@blockcast/mmt-container 2.2.0-main.da2e7cd1dd5d → 2.2.0-main.e1bebe787bc9

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 (97) hide show
  1. package/README.md +5 -2
  2. package/dist/block-policy.d.ts +55 -13
  3. package/dist/block-policy.d.ts.map +1 -1
  4. package/dist/block-policy.js +104 -32
  5. package/dist/block-policy.js.map +2 -2
  6. package/dist/browser-runtime.js +1573 -214
  7. package/dist/browser-runtime.js.map +3 -3
  8. package/dist/carp-catalog.js.map +2 -2
  9. package/dist/catalog-fec-params.d.ts +1 -1
  10. package/dist/catalog-fec-params.d.ts.map +1 -1
  11. package/dist/catalog-fec-params.js +14 -1
  12. package/dist/catalog-fec-params.js.map +2 -2
  13. package/dist/catalog-network-source.js.map +2 -2
  14. package/dist/cmaf-block-assembler.js +92 -1
  15. package/dist/cmaf-block-assembler.js.map +2 -2
  16. package/dist/codec-utils.d.ts.map +1 -1
  17. package/dist/codec-utils.js +92 -1
  18. package/dist/codec-utils.js.map +2 -2
  19. package/dist/delivery-catalog.js +2 -1
  20. package/dist/delivery-catalog.js.map +2 -2
  21. package/dist/delta-fallback-config.js +5 -1
  22. package/dist/delta-fallback-config.js.map +3 -3
  23. package/dist/fec-manager.d.ts +111 -14
  24. package/dist/fec-manager.d.ts.map +1 -1
  25. package/dist/fec-manager.js +613 -91
  26. package/dist/fec-manager.js.map +2 -2
  27. package/dist/fec-state.js +5 -1
  28. package/dist/fec-state.js.map +2 -2
  29. package/dist/fec-worker-setup.js.map +2 -2
  30. package/dist/held-layer-admission.js.map +2 -2
  31. package/dist/index.d.ts +3 -3
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +3 -1
  34. package/dist/index.js.map +2 -2
  35. package/dist/iso-block-locator.d.ts +48 -13
  36. package/dist/iso-block-locator.d.ts.map +1 -1
  37. package/dist/iso-block-locator.js +97 -25
  38. package/dist/iso-block-locator.js.map +2 -2
  39. package/dist/iso-bmff-timing.d.ts +10 -1
  40. package/dist/iso-bmff-timing.d.ts.map +1 -1
  41. package/dist/iso-bmff-timing.js +36 -2
  42. package/dist/iso-bmff-timing.js.map +2 -2
  43. package/dist/media-router.js.map +1 -1
  44. package/dist/mfu-reassembler.js.map +2 -2
  45. package/dist/mmtp-container-parser.d.ts +104 -12
  46. package/dist/mmtp-container-parser.d.ts.map +1 -1
  47. package/dist/mmtp-container-parser.js +308 -27
  48. package/dist/mmtp-container-parser.js.map +2 -2
  49. package/dist/mmtp-container-parser.no-modules.js +329 -32
  50. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  51. package/dist/mmtp-decode-pipeline.js +307 -27
  52. package/dist/mmtp-decode-pipeline.js.map +2 -2
  53. package/dist/mmtp-fec-session.js.map +2 -2
  54. package/dist/mmtp-router.d.ts +36 -8
  55. package/dist/mmtp-router.d.ts.map +1 -1
  56. package/dist/mmtp-router.js +676 -76
  57. package/dist/mmtp-router.js.map +3 -3
  58. package/dist/multicast-auth-catalog.js.map +2 -2
  59. package/dist/multicast-input.js.map +2 -2
  60. package/dist/multicast-manager.d.ts +26 -3
  61. package/dist/multicast-manager.d.ts.map +1 -1
  62. package/dist/multicast-manager.js +1384 -187
  63. package/dist/multicast-manager.js.map +3 -3
  64. package/dist/multicast-transport.js +4 -3
  65. package/dist/multicast-transport.js.map +2 -2
  66. package/dist/multicast-unwrap.js.map +2 -2
  67. package/dist/no-modules.d.ts +1 -0
  68. package/dist/no-modules.d.ts.map +1 -1
  69. package/dist/no-modules.js +329 -31
  70. package/dist/no-modules.js.map +4 -4
  71. package/dist/repair-fetch.d.ts +38 -8
  72. package/dist/repair-fetch.d.ts.map +1 -1
  73. package/dist/repair-fetch.js +286 -27
  74. package/dist/repair-fetch.js.map +3 -3
  75. package/dist/repair-layer-subscriptions.js.map +2 -2
  76. package/dist/signaling.js.map +2 -2
  77. package/dist/timestamp-codec.js.map +2 -2
  78. package/dist/track-session.d.ts.map +1 -1
  79. package/dist/track-session.js +1 -0
  80. package/dist/track-session.js.map +2 -2
  81. package/dist/wasm-mfu-reassembler.js.map +2 -2
  82. package/dist/wasm-mmtp-container-parser.js +307 -27
  83. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  84. package/package.json +5 -5
  85. package/src/block-policy.ts +216 -52
  86. package/src/catalog-fec-params.ts +1 -0
  87. package/src/codec-utils.ts +121 -1
  88. package/src/fec-manager.ts +593 -33
  89. package/src/index.ts +5 -0
  90. package/src/iso-block-locator.ts +133 -31
  91. package/src/iso-bmff-timing.ts +40 -1
  92. package/src/mmtp-container-parser.ts +341 -32
  93. package/src/mmtp-router.ts +614 -61
  94. package/src/multicast-manager.ts +136 -16
  95. package/src/no-modules.ts +3 -0
  96. package/src/repair-fetch.ts +366 -50
  97. package/src/track-session.ts +3 -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({
@@ -1189,6 +1193,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
1189
1193
  this.#heldEvicted = 0;
1190
1194
  /** Pending holes (see `deferIncompleteGaps`): unstated, sources still held. */
1191
1195
  this.#holes = [];
1196
+ /** Holes the horizon passed while pending: sources held until closed. */
1197
+ this.#expired = [];
1198
+ /** Of `#expired`, those `takeExpiredHoles` has not handed out yet. */
1199
+ this.#newlyExpired = [];
1200
+ /**
1201
+ * Spans closed from expired holes: behind the horizon, so kept only for
1202
+ * `locate` while their sources are fed, until the next retirement.
1203
+ */
1204
+ this.#closedBehind = [];
1192
1205
  /**
1193
1206
  * Keep a gap that is missing a source as a pending hole rather than a span,
1194
1207
  * so a repair FETCHed for it (draft-ramadan-moq-fec §7.5) can still state
@@ -1210,7 +1223,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
1210
1223
  #retentionBlocks;
1211
1224
  #heldEvicted;
1212
1225
  #newest;
1226
+ #newestSource;
1213
1227
  #holes;
1228
+ #expired;
1229
+ #newlyExpired;
1230
+ #closedBehind;
1214
1231
  static #checkedRetention(retentionBlocks) {
1215
1232
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
1216
1233
  throw new Error(
@@ -1247,6 +1264,21 @@ var IsoBlockLocator = class _IsoBlockLocator {
1247
1264
  observe(position) {
1248
1265
  if (this.#newest === void 0 || serial32Precedes(this.#newest, position)) this.#newest = position;
1249
1266
  }
1267
+ /**
1268
+ * The newest source SS_ID noted with `noteSource` (RFC 1982 order). Unlike
1269
+ * `newest`, a repair never moves it: a repair can run ahead of its sources,
1270
+ * a source cannot run ahead of the sources sent before it except by
1271
+ * reordering.
1272
+ */
1273
+ get newestSource() {
1274
+ return this.#newestSource;
1275
+ }
1276
+ /** Note a received source's SS_ID; true when it is the newest one yet. */
1277
+ noteSource(ssId) {
1278
+ if (this.#newestSource !== void 0 && !serial32Precedes(this.#newestSource, ssId)) return false;
1279
+ this.#newestSource = ssId;
1280
+ return true;
1281
+ }
1250
1282
  /** Held sources evicted by `heldCapacity` (never by the horizon itself). */
1251
1283
  get heldEvicted() {
1252
1284
  return this.#heldEvicted;
@@ -1265,17 +1297,29 @@ var IsoBlockLocator = class _IsoBlockLocator {
1265
1297
  }
1266
1298
  /** The known block or span containing `ssId`, with its ESI. */
1267
1299
  locate(ssId) {
1268
- for (let i = this.#blocks.length - 1; i >= 0; i--) {
1269
- const block = this.#blocks[i];
1270
- if (isoBlockContains(block.start, block.length, ssId)) {
1271
- return { block, esi: serial32Distance(block.start, ssId) };
1300
+ for (const blocks of [this.#blocks, this.#closedBehind]) {
1301
+ for (let i = blocks.length - 1; i >= 0; i--) {
1302
+ const block = blocks[i];
1303
+ if (isoBlockContains(block.start, block.length, ssId)) {
1304
+ return { block, esi: serial32Distance(block.start, ssId) };
1305
+ }
1272
1306
  }
1273
1307
  }
1274
1308
  return null;
1275
1309
  }
1276
- /** Number of pending holes. */
1310
+ /** Number of holes not closed yet, pending or past the horizon. */
1277
1311
  get holeCount() {
1278
- return this.#holes.length;
1312
+ return this.#holes.length + this.#expired.length;
1313
+ }
1314
+ /**
1315
+ * The pending holes the horizon has passed since the last call, in the
1316
+ * order it passed them. Each is no longer pending: no repair states a block
1317
+ * in it (that repair is `stale`, as for a span the horizon retired) and the
1318
+ * release gate does not wait for it. Its owner must close it
1319
+ * (`closeHolesWithin`), which turns it into a span that is not kept here.
1320
+ */
1321
+ takeExpiredHoles() {
1322
+ return this.#newlyExpired.splice(0);
1279
1323
  }
1280
1324
  /** The stated block (never a span) ending exactly at `end`. */
1281
1325
  blockEndingAt(end) {
@@ -1331,9 +1375,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
1331
1375
  /**
1332
1376
  * Apply one repair symbol's `(SS_Start, SSB_length)`. The first repair of a
1333
1377
  * block states its range and places every held source in it; later repair
1334
- * symbols of the same block change nothing. A range that contradicts a
1335
- * known block (a different length, or an overlap with another block or a
1336
- * span) fails closed: the repair symbol is dropped and no block changes.
1378
+ * symbols of the same block change nothing. A repair whose range is exactly
1379
+ * a repair-less span states that span's one block. A range that contradicts
1380
+ * a known block (a different length, or an overlap with another block or
1381
+ * with part of a span) fails closed: the repair symbol is dropped and no
1382
+ * block changes.
1337
1383
  * A newly stated block retires behind its SS_Start (see the class note).
1338
1384
  * A block so far past `newest` that stating it would retire the position
1339
1385
  * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
@@ -1352,7 +1398,16 @@ var IsoBlockLocator = class _IsoBlockLocator {
1352
1398
  const known = this.blockAt(start);
1353
1399
  if (known !== void 0) {
1354
1400
  if (known.span) {
1355
- return { status: "overlap", reason: `repair block ${start}+${length} falls inside a repair-less span` };
1401
+ if (known.length === length) {
1402
+ const block2 = { start, length, span: false };
1403
+ this.#blocks[this.#blocks.indexOf(known)] = block2;
1404
+ return { status: "placed", block: block2, placed: [] };
1405
+ }
1406
+ return length < known.length ? {
1407
+ status: "overlap",
1408
+ reason: `repair block ${start}+${length} is only the first block of repair-less span ${known.start}+${known.length}`,
1409
+ ofSpan: known
1410
+ } : { status: "overlap", reason: `repair block ${start}+${length} runs past repair-less span ${known.start}+${known.length}` };
1356
1411
  }
1357
1412
  if (known.length !== length) {
1358
1413
  return {
@@ -1420,18 +1475,28 @@ var IsoBlockLocator = class _IsoBlockLocator {
1420
1475
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
1421
1476
  }
1422
1477
  /**
1423
- * Turn every pending hole inside `[start, start + length)` into a
1424
- * repair-less span, claiming its held sources: its range FETCH ended, so
1425
- * nothing more will state its blocks. Returns the spans, in SS_ID order.
1478
+ * Turn every hole inside `[start, start + length)` into a repair-less span,
1479
+ * claiming its held sources: its range FETCH ended, so nothing more will
1480
+ * state its blocks. A hole the horizon passed (`takeExpiredHoles`) leaves a
1481
+ * span that is not kept among the blocks, as the horizon would retire it at
1482
+ * once; only `locate` finds it, until the next retirement, so its sources
1483
+ * can be fed. Returns the spans, in SS_ID order.
1426
1484
  */
1427
1485
  closeHolesWithin(start, length) {
1428
1486
  const closed = [];
1429
- for (const hole of [...this.#holes]) {
1430
- if (!isoBlockContains(start, length, hole.start)) continue;
1431
- this.#holes.splice(this.#holes.indexOf(hole), 1);
1432
- const spanBlock = { start: hole.start, length: hole.length, span: true };
1433
- closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
1434
- this.#blocks.push(spanBlock);
1487
+ for (const holes of [this.#holes, this.#expired]) {
1488
+ for (const hole of [...holes]) {
1489
+ if (!isoBlockContains(start, length, hole.start)) continue;
1490
+ holes.splice(holes.indexOf(hole), 1);
1491
+ const spanBlock = { start: hole.start, length: hole.length, span: true };
1492
+ closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
1493
+ if (holes === this.#holes) {
1494
+ this.#blocks.push(spanBlock);
1495
+ } else {
1496
+ this.#closedBehind.push(spanBlock);
1497
+ if (this.#newlyExpired.includes(hole)) this.#newlyExpired.splice(this.#newlyExpired.indexOf(hole), 1);
1498
+ }
1499
+ }
1435
1500
  }
1436
1501
  return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
1437
1502
  }
@@ -1445,15 +1510,17 @@ var IsoBlockLocator = class _IsoBlockLocator {
1445
1510
  return void 0;
1446
1511
  }
1447
1512
  /**
1448
- * Retire every block and span whose last SS_ID, and every held source,
1449
- * lies more than `retentionBlocks` blocks behind `position`, with the shared
1450
- * lower-bound metric (`isoBlocksBehindLowerBound`) every ISO interleave
1451
- * horizon uses. Returns the retired block starts.
1513
+ * Retire every block and span whose last SS_ID, and every held source
1514
+ * outside a hole, lies more than `retentionBlocks` blocks behind
1515
+ * `position`, with the shared lower-bound metric (`isoBlocksBehindLowerBound`)
1516
+ * every ISO interleave horizon uses; a pending hole so far behind expires
1517
+ * (`takeExpiredHoles`). Returns the retired block starts.
1452
1518
  */
1453
1519
  retireBehind(position) {
1454
1520
  this.observe(position);
1455
1521
  const horizon = this.#retentionBlocks;
1456
1522
  const retired = [];
1523
+ this.#closedBehind.length = 0;
1457
1524
  for (let i = this.#blocks.length - 1; i >= 0; i--) {
1458
1525
  const block = this.#blocks[i];
1459
1526
  const last = serial32Add(block.start, block.length - 1);
@@ -1465,10 +1532,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
1465
1532
  for (let i = this.#holes.length - 1; i >= 0; i--) {
1466
1533
  const hole = this.#holes[i];
1467
1534
  const last = serial32Add(hole.start, hole.length - 1);
1468
- if (isoBlocksBehindLowerBound(last, position, this.#kMax) > horizon) this.#holes.splice(i, 1);
1535
+ if (isoBlocksBehindLowerBound(last, position, this.#kMax) <= horizon) continue;
1536
+ this.#holes.splice(i, 1);
1537
+ this.#expired.push(hole);
1538
+ this.#newlyExpired.push(hole);
1469
1539
  }
1470
1540
  for (const ssId of [...this.#held.keys()]) {
1471
- if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon) this.#held.delete(ssId);
1541
+ 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))) {
1542
+ this.#held.delete(ssId);
1543
+ }
1472
1544
  }
1473
1545
  return retired;
1474
1546
  }
@@ -1476,9 +1548,13 @@ var IsoBlockLocator = class _IsoBlockLocator {
1476
1548
  reset() {
1477
1549
  this.#blocks.length = 0;
1478
1550
  this.#holes.length = 0;
1551
+ this.#expired.length = 0;
1552
+ this.#newlyExpired.length = 0;
1553
+ this.#closedBehind.length = 0;
1479
1554
  this.#held.clear();
1480
1555
  this.#coverageEnd = void 0;
1481
1556
  this.#newest = void 0;
1557
+ this.#newestSource = void 0;
1482
1558
  }
1483
1559
  #claim(block) {
1484
1560
  const placed = [];
@@ -1586,8 +1662,9 @@ function keyframeIntervalMediaTicks(geometry2, mediaTimescale) {
1586
1662
  return scaled / divisor;
1587
1663
  }
1588
1664
  function compareDataUnitStarts(a, b) {
1589
- return a.movieFragment - b.movieFragment || a.idx - b.idx || a.offset - b.offset;
1665
+ return a.movieFragment - b.movieFragment | 0 || a.idx - b.idx || a.offset - b.offset;
1590
1666
  }
1667
+ var UNPLACED = { rapNotMpuStart: false };
1591
1668
  var BlockClassifier = class {
1592
1669
  #geometry;
1593
1670
  #mode;
@@ -1610,8 +1687,23 @@ var BlockClassifier = class {
1610
1687
  #mpuSbnSpans = /* @__PURE__ */ new Map();
1611
1688
  #dataUnitStarts = /* @__PURE__ */ new Map();
1612
1689
  #highestMpu = null;
1613
- /** MPU → movie_fragment_sequence_number observed in it. */
1614
- #mpuFragments = /* @__PURE__ */ new Map();
1690
+ /**
1691
+ * P3 layout, kept for the MPUs within the classification horizon and valid
1692
+ * within one continuous SBN sequence (`noteSourceDiscontinuity`).
1693
+ */
1694
+ #mpus = /* @__PURE__ */ new Map();
1695
+ /** An MPU of this sequence showed two movie fragments: each frame is one. */
1696
+ #fragmentPerFrame = false;
1697
+ /** A DU header of this sequence stated sample_number above 1. */
1698
+ #multiSampleFragment = false;
1699
+ /**
1700
+ * The anchor received last, whether or not its MPU is still in the
1701
+ * horizon. Each new anchor, and the anchor of every DU header's MPU, is
1702
+ * checked against it.
1703
+ */
1704
+ #lastAnchor = null;
1705
+ /** Two anchors were exactly G fragments per MPU apart. */
1706
+ #fragmentsProven = false;
1615
1707
  #lastRap = null;
1616
1708
  constructor(geometry2) {
1617
1709
  this.#geometry = geometry2;
@@ -1641,7 +1733,7 @@ var BlockClassifier = class {
1641
1733
  this.#geometry = geometry2;
1642
1734
  this.#blocks.clear();
1643
1735
  this.#clearContiguityLedger();
1644
- this.#mpuFragments.clear();
1736
+ this.#clearMpuLayout();
1645
1737
  this.#lastRap = null;
1646
1738
  this.#mpuBoundsRaps = true;
1647
1739
  if (geometry2.trackKind === "video" && geometry2.mode === "all-protected") {
@@ -1675,11 +1767,13 @@ var BlockClassifier = class {
1675
1767
  /**
1676
1768
  * The stream's SBN sequence restarted (FECManager source discontinuity:
1677
1769
  * a publisher restart, or the SS_ID space wrapped). Authored order and SBN
1678
- * order are comparable only within one continuous sequence, so the P1
1679
- * ledger starts again.
1770
+ * order are comparable only within one continuous sequence, and a
1771
+ * restarted publisher numbers MPUs and movie fragments again, so the P1
1772
+ * ledger and the P3 layout start again.
1680
1773
  */
1681
1774
  noteSourceDiscontinuity() {
1682
1775
  this.#clearContiguityLedger();
1776
+ this.#clearMpuLayout();
1683
1777
  }
1684
1778
  /** Register a block that exists without evidence (a vanished block). */
1685
1779
  touch(sbn) {
@@ -1698,16 +1792,16 @@ var BlockClassifier = class {
1698
1792
  if (this.#geometry.trackKind === "audio") return [];
1699
1793
  const changes = [];
1700
1794
  const block = this.#blockFor(sbn);
1795
+ const placement = this.#place(evidence);
1701
1796
  if (evidence.rap) block.rapSeen = true;
1702
1797
  if (evidence.mpu !== void 0) block.mpus.add(evidence.mpu);
1703
- if (evidence.idx !== void 0) {
1704
- block.idxMin = block.idxMin === void 0 ? evidence.idx : Math.min(block.idxMin, evidence.idx);
1705
- block.idxMax = block.idxMax === void 0 ? evidence.idx : Math.max(block.idxMax, evidence.idx);
1798
+ const { position } = placement;
1799
+ if (position !== void 0) {
1800
+ block.positionMin = block.positionMin === void 0 ? position : Math.min(block.positionMin, position);
1801
+ block.positionMax = block.positionMax === void 0 ? position : Math.max(block.positionMax, position);
1706
1802
  }
1707
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
1708
- this.#mpuBoundsRaps = false;
1709
- }
1710
- const violation = this.#checkInvariants(sbn, block, evidence);
1803
+ if (placement.rapNotMpuStart) this.#mpuBoundsRaps = false;
1804
+ const violation = this.#checkInvariants(sbn, block, evidence, placement);
1711
1805
  if (violation !== null) changes.push(...this.#disable(violation));
1712
1806
  const next = this.#classify(block);
1713
1807
  if (next !== block.cls && this.#allowed(block.cls, next)) {
@@ -1760,35 +1854,89 @@ var BlockClassifier = class {
1760
1854
  }
1761
1855
  return block;
1762
1856
  }
1763
- #checkInvariants(sbn, block, evidence) {
1857
+ #checkInvariants(sbn, block, evidence, placement) {
1764
1858
  if (this.#mode === "all-protected" || this.#geometry.trackKind !== "video") return null;
1765
1859
  const geometry2 = this.#geometry;
1766
1860
  if (geometry2.mode !== "classifying") return null;
1767
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
1768
- return "rap-not-mpu-start";
1769
- }
1770
- if (evidence.idx !== void 0 && evidence.idx >= geometry2.gopFrames) {
1861
+ if (placement.rapNotMpuStart) return "rap-not-mpu-start";
1862
+ if (placement.position !== void 0 && placement.position >= geometry2.gopFrames) {
1771
1863
  return "mpu-longer-than-gop";
1772
1864
  }
1773
- if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0 && block.idxMax - block.idxMin >= geometry2.interleaveUnits) {
1865
+ if (block.mpus.size === 1 && block.positionMin !== void 0 && block.positionMax !== void 0 && block.positionMax - block.positionMin >= geometry2.interleaveUnits) {
1774
1866
  return "block-wider-than-interleave";
1775
1867
  }
1776
- if (evidence.mpu !== void 0 && evidence.movieFragment !== void 0) {
1777
- const fragment = this.#mpuFragments.get(evidence.mpu);
1778
- if (fragment === void 0) {
1779
- this.#mpuFragments.set(evidence.mpu, evidence.movieFragment);
1780
- for (const mpu of this.#mpuFragments.keys()) {
1781
- if (mpu + 1 < evidence.mpu) this.#mpuFragments.delete(mpu);
1782
- }
1783
- } else if (fragment !== evidence.movieFragment) {
1784
- return "mpu-multiple-fragments";
1785
- }
1786
- }
1868
+ if (placement.violation !== void 0) return placement.violation;
1787
1869
  if (evidence.mpu !== void 0 && this.#contradictsAuthoredOrder(sbn, evidence.mpu, evidence)) {
1788
1870
  return "block-not-contiguous";
1789
1871
  }
1790
1872
  return null;
1791
1873
  }
1874
+ /**
1875
+ * The MPU position a source symbol's DU header proves (P3), and what it
1876
+ * refutes. Runs in every mode: mpuBoundsRaps needs its RAP verdict.
1877
+ */
1878
+ #place(evidence) {
1879
+ const { mpu, idx, movieFragment: fragment } = evidence;
1880
+ if (idx === void 0) return UNPLACED;
1881
+ const bySample = { position: idx, rapNotMpuStart: evidence.rap && idx !== 0 };
1882
+ if (mpu === void 0 || fragment === void 0) {
1883
+ return this.#fragmentPerFrame && !this.#multiSampleFragment ? { rapNotMpuStart: bySample.rapNotMpuStart } : bySample;
1884
+ }
1885
+ let layout = this.#mpus.get(mpu);
1886
+ if (layout === void 0) {
1887
+ layout = { low: fragment };
1888
+ this.#mpus.set(mpu, layout);
1889
+ for (const other of this.#mpus.keys()) {
1890
+ if (other + 1 < mpu) this.#mpus.delete(other);
1891
+ }
1892
+ } else if (fragment !== layout.low) {
1893
+ this.#fragmentPerFrame = true;
1894
+ if ((fragment - layout.low | 0) < 0) layout.low = fragment;
1895
+ }
1896
+ if (idx !== 0) this.#multiSampleFragment = true;
1897
+ let arrival;
1898
+ if (evidence.rap && layout.anchor === void 0) {
1899
+ layout.anchor = fragment;
1900
+ arrival = this.#anchorDrift(mpu, fragment);
1901
+ if (arrival === 0 && this.#lastAnchor?.mpu !== mpu) this.#fragmentsProven = true;
1902
+ this.#lastAnchor = { mpu, fragment };
1903
+ }
1904
+ if (!this.#fragmentPerFrame) return bySample;
1905
+ if (this.#multiSampleFragment) return { ...bySample, violation: "mpu-multiple-fragments" };
1906
+ const { anchor } = layout;
1907
+ if (anchor === void 0) return UNPLACED;
1908
+ const drift = arrival ?? this.#anchorDrift(mpu, anchor);
1909
+ const offset = fragment - anchor | 0;
1910
+ return {
1911
+ ...offset === 0 || offset > 0 && this.#fragmentsProven ? { position: offset } : {},
1912
+ rapNotMpuStart: evidence.rap && offset !== 0 || (layout.low - anchor | 0) < 0 || // Fragments count frames: an anchor arriving past the spacing is a
1913
+ // RAP inside its MPU, or an earlier MPU outran G.
1914
+ arrival !== void 0 && arrival > 0 && this.#fragmentsProven,
1915
+ ...drift === void 0 || drift === 0 ? {} : { violation: "rap-spacing-mismatch" }
1916
+ };
1917
+ }
1918
+ /**
1919
+ * How many fragments MPU m's anchor `fragment` lies past the start that
1920
+ * the anchor received last predicts for MPU m: one frame per fragment and
1921
+ * G frames per MPU put the anchors of MPUs m and m' exactly G * (m - m')
1922
+ * fragments apart, modulo 2^32. Undefined without a last anchor, a
1923
+ * cadence, or this layout.
1924
+ */
1925
+ #anchorDrift(mpu, fragment) {
1926
+ const geometry2 = this.#geometry;
1927
+ const last = this.#lastAnchor;
1928
+ if (last === null || !this.#fragmentPerFrame || this.#multiSampleFragment || geometry2.trackKind !== "video" || geometry2.mode !== "classifying") {
1929
+ return void 0;
1930
+ }
1931
+ return fragment - last.fragment - geometry2.gopFrames * (mpu - last.mpu) | 0;
1932
+ }
1933
+ #clearMpuLayout() {
1934
+ this.#mpus.clear();
1935
+ this.#fragmentPerFrame = false;
1936
+ this.#multiSampleFragment = false;
1937
+ this.#lastAnchor = null;
1938
+ this.#fragmentsProven = false;
1939
+ }
1792
1940
  #clearContiguityLedger() {
1793
1941
  this.#mpuSbnSpans.clear();
1794
1942
  this.#dataUnitStarts.clear();
@@ -1888,9 +2036,9 @@ var BlockClassifier = class {
1888
2036
  if (this.#mode === "all-protected") return "unknown";
1889
2037
  const geometry2 = this.#geometry;
1890
2038
  if (geometry2.trackKind !== "video" || geometry2.mode !== "classifying") return "unknown";
1891
- if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0) {
2039
+ if (block.mpus.size === 1 && block.positionMin !== void 0 && block.positionMax !== void 0) {
1892
2040
  const span = geometry2.interleaveUnits - 1;
1893
- if (block.idxMax - span >= 1 && block.idxMin + span <= geometry2.gopFrames - 1) {
2041
+ if (block.positionMax - span >= 1 && block.positionMin + span <= geometry2.gopFrames - 1) {
1894
2042
  return "delta";
1895
2043
  }
1896
2044
  }
@@ -2067,6 +2215,7 @@ var WORKER_ERROR_LOG_CAP = 5;
2067
2215
  var WORKER_ERROR_KIND_CAP = 32;
2068
2216
  var WORKER_ERROR_OVERFLOW_KIND = "other";
2069
2217
  var STARTUP_REPAIR_WAIT_SOURCE_BOUNDARIES = 2;
2218
+ var NOT_TAKEN = Object.freeze({ taken: false, recovered: null });
2070
2219
  function isMulticastSymbolDelivery(value) {
2071
2220
  return value === "datagram" || value === "ordered-relay";
2072
2221
  }
@@ -2160,10 +2309,18 @@ var FECManager = class _FECManager {
2160
2309
  // 'pending' forever, which would park every later frame of its stream in
2161
2310
  // the in-order release gate. Each entry owns its handle; the callback
2162
2311
  // checks it still owns the key, so a settled or reset key is never touched.
2312
+ /**
2313
+ * Per owed Worker cleanup: the bound on its acknowledgement, when its block
2314
+ * was due, and when its cleanup was asked for (see `onCleanupComplete`).
2315
+ */
2163
2316
  this.#pendingWorkerCleanupBounds = /* @__PURE__ */ new Map();
2164
2317
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
2165
2318
  this.#blockSourceCounts = /* @__PURE__ */ new Map();
2166
2319
  this.#blockSourceEsis = /* @__PURE__ */ new Map();
2320
+ // Source ESIs per block that another FEC instance rebuilt and fed in
2321
+ // (feedRebuiltSourceSymbol). Kept apart from #blockSourceEsis: they are
2322
+ // not network arrivals and never make a block clean.
2323
+ this.#blockRebuiltEsis = /* @__PURE__ */ new Map();
2167
2324
  // Authored SSB_length per block (ISO/IEC 23008-1 §C.5.3), learned from the
2168
2325
  // first repair symbol. The FFmpeg moq_mmt publisher closes a block every D
2169
2326
  // media units, usually before it holds K symbols; under iso-ssbg1-v1
@@ -2172,10 +2329,14 @@ var FECManager = class _FECManager {
2172
2329
  // SSB_length source arrivals and recoverable from SSB_length received
2173
2330
  // symbols; waiting for K fails every one of them.
2174
2331
  this.#blockAuthoredLengths = /* @__PURE__ */ new Map();
2332
+ // Keys whose authored length is a repair-less span's (#openIsoSpan), until
2333
+ // a repair states the block there or the span resolves.
2334
+ this.#isoSpanKeys = /* @__PURE__ */ new Set();
2175
2335
  this.#ssbLengthConflictCount = 0;
2176
2336
  this.#blockRepairRsIds = /* @__PURE__ */ new Map();
2177
2337
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
2178
- // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
2338
+ // symbols its repair group carries; 0 for a repair-less span no repair can
2339
+ // state (#openIsoSpan). Same lifecycle as #blockRepairRsIds.
2179
2340
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
2180
2341
  /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
2181
2342
  this.#heldLayerStates = /* @__PURE__ */ new Map();
@@ -2363,13 +2524,17 @@ var FECManager = class _FECManager {
2363
2524
  this.#workerErrorCounts = /* @__PURE__ */ new Map();
2364
2525
  this.#decoderUnavailableEvents = 0;
2365
2526
  this.#repairSymbolSizeMismatchCount = 0;
2527
+ this.#unlistedRepairTrackRefusals = 0;
2366
2528
  // Event callbacks — block lifecycle notifications for MmtpRouter wiring.
2367
2529
  // NOTE: For sync WASM path, recovery routing is handled by MmtpRouter from
2368
2530
  // feedSourceSymbol/feedRepairSymbol return values. For Worker path, recovery
2369
2531
  // arrives via onBlockRecovered callback.
2370
2532
  this.onBlockStarted = null;
2371
2533
  this.onBlockComplete = null;
2372
- /** A block reached its fail bound. `blockClass` is its class at failure. */
2534
+ /**
2535
+ * A block reached its fail bound. `blockClass` is its class at failure.
2536
+ * `span` is set when what failed is a repair-less span starting at `sbn`.
2537
+ */
2373
2538
  this.onBlockFailed = null;
2374
2539
  /**
2375
2540
  * Fired once per stream when its Worker decoder stops being routable.
@@ -2411,12 +2576,24 @@ var FECManager = class _FECManager {
2411
2576
  * for it, which it must be.
2412
2577
  */
2413
2578
  this.#onUndelimitedLoss = null;
2579
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
2580
+ this.#onIsoHoleExpired = null;
2414
2581
  /** A block every symbol of which vanished was created by SBN evidence. */
2415
2582
  this.onBlockVanished = null;
2416
2583
  /** A block reached a terminal state (completed, recovered, or failed). */
2417
2584
  this.onBlockResolved = null;
2418
2585
  /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
2419
2586
  this.onSourceDiscontinuity = null;
2587
+ /**
2588
+ * The span and tolerance the catalog states for a keyframe overlay
2589
+ * installed over a source track (draft-ramadan-moq-mmt-02 7.4.1: the
2590
+ * overlay instance's own interleaveDepthMs and reorderToleranceMs), or
2591
+ * undefined while none is installed. A stated block only a late source
2592
+ * can complete, and a frame whose gap may hide a RAP behind a span only a
2593
+ * late source can fill, also wait for that overlay's repair
2594
+ * (#overlayLateWaitMs).
2595
+ */
2596
+ this.keyframeOverlayTiming = null;
2420
2597
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
2421
2598
  /**
2422
2599
  * A recovered source symbol. Return false when admission refused the
@@ -2453,7 +2630,9 @@ var FECManager = class _FECManager {
2453
2630
  #pendingWorkerCleanupBounds;
2454
2631
  #blockSourceCounts;
2455
2632
  #blockSourceEsis;
2633
+ #blockRebuiltEsis;
2456
2634
  #blockAuthoredLengths;
2635
+ #isoSpanKeys;
2457
2636
  #ssbLengthConflictCount;
2458
2637
  #blockRepairRsIds;
2459
2638
  #blockRsbLengths;
@@ -2519,7 +2698,9 @@ var FECManager = class _FECManager {
2519
2698
  #workerErrorCounts;
2520
2699
  #decoderUnavailableEvents;
2521
2700
  #repairSymbolSizeMismatchCount;
2701
+ #unlistedRepairTrackRefusals;
2522
2702
  #onUndelimitedLoss;
2703
+ #onIsoHoleExpired;
2523
2704
  #encodeTrackName(catalogTrackName) {
2524
2705
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
2525
2706
  if (encoded === void 0) {
@@ -2991,7 +3172,10 @@ var FECManager = class _FECManager {
2991
3172
  timer.handle = null;
2992
3173
  this.#requestRepair(sbn, packetId, catalogTrackName);
2993
3174
  };
2994
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
3175
+ timer.handle = setTimeout(
3176
+ onFire,
3177
+ this.#receiptAtMs === void 0 ? Math.max(0, deadlineMs - performance.now()) : this.#receiptTimerDelayMs(deadlineMs, 0)
3178
+ );
2995
3179
  this.#repairDeadlines.set(key, timer);
2996
3180
  }
2997
3181
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -3135,8 +3319,14 @@ var FECManager = class _FECManager {
3135
3319
  * Vanished blocks are not enumerated here: their starts are unknown until a
3136
3320
  * repair states them. The SS_IDs between two stated blocks become one
3137
3321
  * repair-less span when the later block's repair arrives (placeIsoRepair).
3322
+ *
3323
+ * A `held` source arrived before its block was known and is fed only now
3324
+ * that a repair, a span or a closed hole placed it: how far its block start
3325
+ * then lies behind the frontier measures how long the receiver held it, not
3326
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
3327
+ * it (BLO-52085).
3138
3328
  */
3139
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
3329
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn, held = false) {
3140
3330
  const streamKey = this.#streamKey(packetId, catalogTrackName);
3141
3331
  const now = performance.now();
3142
3332
  const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
@@ -3175,7 +3365,7 @@ var FECManager = class _FECManager {
3175
3365
  return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
3176
3366
  };
3177
3367
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
3178
- 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))) {
3368
+ 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))) {
3179
3369
  discontinuity();
3180
3370
  return;
3181
3371
  }
@@ -3437,17 +3627,21 @@ var FECManager = class _FECManager {
3437
3627
  this.#blockWaitDeadlinesMs.delete(key);
3438
3628
  this.#repairHoldUntilMs.delete(key);
3439
3629
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
3440
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName);
3630
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs);
3441
3631
  };
3442
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)));
3632
+ timer.handle = setTimeout(
3633
+ onFire,
3634
+ this.#receiptAtMs === void 0 ? Math.max(1, Math.ceil(deadlineMs - nowMs)) : this.#receiptTimerDelayMs(deadlineMs, 1)
3635
+ );
3443
3636
  this.#activeBlocks.set(key, timer);
3444
3637
  this.#indexBlockKey(key, sbn, packetId);
3445
3638
  }
3446
3639
  /**
3447
3640
  * Hand a block whose delivery is over to its decoder for finalization: the
3448
- * datagram deadline fired, or the ordered relay moved past it.
3641
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
3642
+ * is when it was due: its deadline, or now.
3449
3643
  */
3450
- #finalizeExpiredBlock(sbn, packetId, catalogTrackName) {
3644
+ #finalizeExpiredBlock(sbn, packetId, catalogTrackName, dueAtMs = performance.now()) {
3451
3645
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
3452
3646
  if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
3453
3647
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -3463,7 +3657,7 @@ var FECManager = class _FECManager {
3463
3657
  if (workerClient) {
3464
3658
  this.#pendingWorkerCleanups.add(key);
3465
3659
  this.#pendingWorkerCleanupClients.set(key, workerClient);
3466
- this.#boundOwedCleanup(key, packetId, workerClient);
3660
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs);
3467
3661
  workerClient.cleanup(sbn);
3468
3662
  } else {
3469
3663
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
@@ -3673,6 +3867,7 @@ var FECManager = class _FECManager {
3673
3867
  packetId
3674
3868
  })),
3675
3869
  repairSymbolSizeMismatches: this.#repairSymbolSizeMismatchCount,
3870
+ unlistedRepairTrackRefusals: this.#unlistedRepairTrackRefusals,
3676
3871
  repairObjectRejects: [...this.#repairObjectRejects.values()].map((r) => ({ ...r })),
3677
3872
  workerErrors: Object.fromEntries(this.#workerErrorCounts)
3678
3873
  };
@@ -3775,7 +3970,9 @@ var FECManager = class _FECManager {
3775
3970
  }
3776
3971
  resetMap(this.#blockSourceCounts);
3777
3972
  resetMap(this.#blockSourceEsis);
3973
+ resetMap(this.#blockRebuiltEsis);
3778
3974
  resetMap(this.#blockAuthoredLengths);
3975
+ resetSet(this.#isoSpanKeys);
3779
3976
  resetMap(this.#blockRepairRsIds);
3780
3977
  resetMap(this.#blockRsbLengths);
3781
3978
  resetMap(this.#heldLayerStates);
@@ -3899,7 +4096,9 @@ var FECManager = class _FECManager {
3899
4096
  dropMap(this.#pendingWorkerCleanupClients);
3900
4097
  dropMap(this.#blockSourceCounts);
3901
4098
  dropMap(this.#blockSourceEsis);
4099
+ dropMap(this.#blockRebuiltEsis);
3902
4100
  dropMap(this.#blockAuthoredLengths);
4101
+ dropSet(this.#isoSpanKeys);
3903
4102
  dropMap(this.#blockRepairRsIds);
3904
4103
  dropMap(this.#blockRsbLengths);
3905
4104
  dropMap(this.#blockPathCounts);
@@ -4061,6 +4260,9 @@ var FECManager = class _FECManager {
4061
4260
  this.#unindexBlockKey(key);
4062
4261
  }
4063
4262
  }
4263
+ if (isSourceSymbol && source === "multicast") {
4264
+ this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), sbn + esi >>> 0, packetId, catalogTrackName);
4265
+ }
4064
4266
  return true;
4065
4267
  }
4066
4268
  #observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName) {
@@ -4170,8 +4372,10 @@ var FECManager = class _FECManager {
4170
4372
  }
4171
4373
  /**
4172
4374
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
4173
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
4174
- * Undefined for a block that is not open.
4375
+ * (SSB_length) and RSB_length (each undefined until a repair stated it; a
4376
+ * repair-less span states its length, and RSB_length 0 when it is longer
4377
+ * than K, since no repair can reach it). Undefined for a block that is not
4378
+ * open.
4175
4379
  */
4176
4380
  blockSymbolCounts(sbn, packetId, catalogTrackName) {
4177
4381
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -4239,8 +4443,9 @@ var FECManager = class _FECManager {
4239
4443
  return true;
4240
4444
  }
4241
4445
  /**
4242
- * Drop a block's repair hold: its FETCH ended without delivering. The block
4243
- * falls back to its multicast wait, which may already have passed.
4446
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
4447
+ * back only a repair that cannot complete it. The block falls back to its
4448
+ * multicast wait, which may already have passed.
4244
4449
  */
4245
4450
  releaseRepairHold(sbn, packetId, catalogTrackName) {
4246
4451
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -4286,7 +4491,7 @@ var FECManager = class _FECManager {
4286
4491
  }
4287
4492
  const trackConfig = this.#trackConfigs.get(packetId);
4288
4493
  if (trackConfig === void 0) return void 0;
4289
- return Math.max(1, trackConfig.timeoutMs - this.#repairDeadlineMs(trackConfig));
4494
+ return Math.max(1, this.#repairGraceMs(trackConfig, this.#multicastWaitMs(trackConfig)));
4290
4495
  }
4291
4496
  /** True once configureTrack/setFecDecoder/setFecWorker configured this packetId. */
4292
4497
  // -----------------------------------------------------------------------
@@ -4378,6 +4583,8 @@ var FECManager = class _FECManager {
4378
4583
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
4379
4584
  const evictedBefore = locator.heldEvicted;
4380
4585
  const held = locator.hold(ssId, source);
4586
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
4587
+ if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
4381
4588
  const evicted = locator.heldEvicted - evictedBefore;
4382
4589
  if (evicted > 0) {
4383
4590
  const before = this.#isoHeldEvictedCount;
@@ -4398,17 +4605,20 @@ var FECManager = class _FECManager {
4398
4605
  * contradicts a known block is refused (counted) and must be dropped.
4399
4606
  */
4400
4607
  placeIsoRepair(packetId, catalogTrackName, ssStart, ssbLength) {
4401
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength);
4608
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
4609
+ const placement = locator.placeRepair(ssStart, ssbLength);
4610
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
4402
4611
  if (placement.status !== "placed") {
4403
4612
  this.#isoRepairRefusedCount++;
4404
4613
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
4405
4614
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`);
4406
4615
  }
4616
+ if (placement.ofSpan !== void 0) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName);
4407
4617
  return placement;
4408
4618
  }
4619
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName));
4409
4620
  if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
4410
4621
  if (placement.hole !== void 0) {
4411
- const locator = this.#isoLocatorFor(packetId, catalogTrackName);
4412
4622
  const hole = placement.hole.block;
4413
4623
  const previous = locator.blockEndingAt(hole.start);
4414
4624
  const loss = {
@@ -4429,17 +4639,29 @@ var FECManager = class _FECManager {
4429
4639
  * `handler`, instead of a repair-less span; null restores spans. Set by the
4430
4640
  * range repair scheduler; applies to every stream from its next gap. The
4431
4641
  * handler and the deferral are one setting, so no hole is ever created with
4432
- * nobody to close it.
4642
+ * nobody to close it. `onExpired` is told of each pending hole the stream
4643
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
4644
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
4645
+ * reported; otherwise the hole is discarded with its sources.
4433
4646
  */
4434
- setUndelimitedLossHandler(handler) {
4647
+ setUndelimitedLossHandler(handler, onExpired = null) {
4435
4648
  this.#onUndelimitedLoss = handler;
4649
+ this.#onIsoHoleExpired = handler === null ? null : onExpired;
4436
4650
  this.#deferIsoGaps = handler !== null;
4437
4651
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
4438
4652
  }
4653
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
4654
+ #settleExpiredIsoHoles(locator, packetId, catalogTrackName) {
4655
+ for (const hole of locator.takeExpiredHoles()) {
4656
+ const expired = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length };
4657
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length);
4658
+ }
4659
+ }
4439
4660
  /**
4440
- * The range repair for a hole ended: every hole still pending inside
4441
- * `[start, start + length)` becomes a repair-less span. Returns those spans
4442
- * with the held sources they placed, for the caller to feed (MmtpRouter).
4661
+ * The range repair for a hole ended: every hole inside `[start, start +
4662
+ * length)`, pending or expired, becomes a repair-less span. Returns those
4663
+ * spans with the held sources they placed, for the caller to feed
4664
+ * (MmtpRouter).
4443
4665
  */
4444
4666
  closeIsoHoles(packetId, catalogTrackName, start, length) {
4445
4667
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
@@ -4455,10 +4677,25 @@ var FECManager = class _FECManager {
4455
4677
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
4456
4678
  * SS_ID of which vanished resolves through its deadline like any vanished
4457
4679
  * block.
4680
+ *
4681
+ * A span longer than K holds more than one block (SSB_length <= K), and the
4682
+ * locator states no block inside a span, only one exactly its range
4683
+ * (IsoBlockLocator.placeRepair): no repair, multicast or FETCHed, can ever
4684
+ * reach it. Its repair group is empty, so the repair scheduler FETCHes no
4685
+ * Group of it (group-cannot-complete). Every span still keeps its whole
4686
+ * wait (#lateSourceWaitMs): failing it early released the frames behind it
4687
+ * past a keyframe the overlay was still rebuilding (BLO-52085). The release
4688
+ * gate lets those frames go once only a late source can fill the gap
4689
+ * before them, as long after they arrived as the gap's decision allows
4690
+ * (isoRepairlessWaitMs).
4458
4691
  */
4459
4692
  #openIsoSpan(span, packetId, catalogTrackName) {
4460
4693
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
4461
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
4694
+ if (!this.#blockAuthoredLengths.has(key)) {
4695
+ this.#blockAuthoredLengths.set(key, span.block.length);
4696
+ this.#isoSpanKeys.add(key);
4697
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0);
4698
+ }
4462
4699
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
4463
4700
  }
4464
4701
  /**
@@ -4496,6 +4733,62 @@ var FECManager = class _FECManager {
4496
4733
  }
4497
4734
  return lost;
4498
4735
  }
4736
+ /**
4737
+ * The release gate's wait, from a frame's arrival, for the SS_IDs strictly
4738
+ * between two released frames' SS_IDs once only a late source can still
4739
+ * fill them, else undefined. That is when every one missing (neither
4740
+ * arrived nor held) lies in a repair-less span longer than K, which no
4741
+ * repair can state a block of (#openIsoSpan), or in a stated block its
4742
+ * own repair group cannot complete every SS_ID of which it misses lies
4743
+ * between them (so the gap's decision covers all it lost), and a multicast
4744
+ * source at or past `toSsId` arrived, so each is lost or reordered behind
4745
+ * it (a MoQ source shows nothing: MoQ streams overtake one another). The
4746
+ * span or block itself keeps its own wait.
4747
+ *
4748
+ * The wait is the late-symbol allowance, unless `rapMayHide`: the gap may
4749
+ * hold a RAP packet an installed keyframe overlay can still rebuild (its
4750
+ * decision stalls, or it ends at a RAP that may lie past a whole MPU).
4751
+ * Then the frame waits as a stated block its group cannot complete does
4752
+ * (#overlayLateWaitMs): the allowance alone with no overlay installed, the
4753
+ * overlay's span plus the larger of the allowance and its tolerance, or,
4754
+ * for an overlay that states no span, the span's whole wait (undefined).
4755
+ * So does `rapNext` (the gap ends at the RAP that opens the next MPU) when
4756
+ * the gap holds a stated block's loss.
4757
+ */
4758
+ isoRepairlessWaitMs(packetId, catalogTrackName, fromSsId, toSsId, rapMayHide = false, rapNext = false) {
4759
+ const config = this.#trackConfigs.get(packetId);
4760
+ if (config === void 0 || !_FECManager.#hasCatalogTiming(config)) return void 0;
4761
+ const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
4762
+ if (locator === void 0 || !locator.coversBetween(fromSsId, toSsId)) return void 0;
4763
+ const newestSource = locator.newestSource;
4764
+ if (newestSource === void 0 || serial32Precedes(newestSource, toSsId)) return void 0;
4765
+ let repairless = false;
4766
+ let stated = false;
4767
+ for (const block of locator.blocksBetween(fromSsId, toSsId)) {
4768
+ const key = this.#blockKey(block.start, packetId, catalogTrackName);
4769
+ if (this.#completedBlocks.has(key)) continue;
4770
+ if (block.span && block.length > locator.kMax) {
4771
+ repairless = true;
4772
+ continue;
4773
+ }
4774
+ const received = this.#blockSourceEsis.get(key);
4775
+ const rebuilt = this.#blockRebuiltEsis.get(key);
4776
+ let missesInGap = false;
4777
+ let missesOutside = false;
4778
+ for (let esi = 0; esi < block.length; esi++) {
4779
+ const ssId = serial32Add(block.start, esi);
4780
+ if (received?.has(esi) || locator.isHeld(ssId)) continue;
4781
+ if (serial32Precedes(fromSsId, ssId) && serial32Precedes(ssId, toSsId)) missesInGap = true;
4782
+ else if (!rebuilt?.has(esi)) missesOutside = true;
4783
+ }
4784
+ if (!missesInGap) continue;
4785
+ if (missesOutside || block.span || !this.#groupCannotComplete(key)) return void 0;
4786
+ repairless = stated = true;
4787
+ }
4788
+ if (!repairless) return void 0;
4789
+ const waitMs = rapMayHide || stated && rapNext ? this.#overlayLateWaitMs(packetId, catalogTrackName, config) : this.#multicastWaitMs(config) - config.interleaveDepthMs;
4790
+ return waitMs === void 0 ? void 0 : Math.max(0, waitMs);
4791
+ }
4499
4792
  /**
4500
4793
  * iso-ssbg1-v1 block location: repair symbols it refused, oversize sources,
4501
4794
  * the sources held now for a block no repair has stated yet, and the held
@@ -4799,11 +5092,14 @@ var FECManager = class _FECManager {
4799
5092
  });
4800
5093
  client.onCleanupComplete((sbn) => {
4801
5094
  if (this.#releasedWorkerClients.has(client)) return;
4802
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
5095
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
5096
+ const cleanupKeys = owed.filter((key) => {
4803
5097
  const block = this.#parseBlockKey(key);
4804
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
5098
+ return block.packetId === packetId && block.sbn === sbn;
4805
5099
  });
4806
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
5100
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
5101
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
5102
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
4807
5103
  });
4808
5104
  client.onError((msg, code) => {
4809
5105
  const requestedKind = code ?? msg;
@@ -4873,9 +5169,11 @@ var FECManager = class _FECManager {
4873
5169
  * fail deadline already passed, so failing it is the decision that deadline
4874
5170
  * made. A late ack then finds nothing owed and is a no-op.
4875
5171
  */
4876
- #boundOwedCleanup(key, packetId, client) {
5172
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
4877
5173
  this.#clearOwedCleanupBound(key);
4878
5174
  const bound = {
5175
+ dueAtMs,
5176
+ askedAtMs: performance.now(),
4879
5177
  handle: setTimeout(() => {
4880
5178
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
4881
5179
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -4973,7 +5271,15 @@ var FECManager = class _FECManager {
4973
5271
  this.#isoSourceOversizeCount++;
4974
5272
  return null;
4975
5273
  }
4976
- const sbn = located.block.start;
5274
+ return this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, located.block.start);
5275
+ }
5276
+ /**
5277
+ * Hand one placed source symbol to the stream's decoder: its Worker, which
5278
+ * answers through onFrame (null here), or its synchronous decoder, whose
5279
+ * recovered block is returned. `sbn` is the SS_Start of the block a repair
5280
+ * stated for `ssId`.
5281
+ */
5282
+ #feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn) {
4977
5283
  const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
4978
5284
  const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey);
4979
5285
  const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
@@ -5002,6 +5308,74 @@ var FECManager = class _FECManager {
5002
5308
  }
5003
5309
  return recovered;
5004
5310
  }
5311
+ /**
5312
+ * Feed a source symbol of this stream that another FEC instance over the
5313
+ * same packets rebuilt: a keyframe overlay recovery whose base SS_ID the
5314
+ * caller determined (draft-ramadan-moq-mmt-02 7.1, 7.4.4; joint decoding,
5315
+ * BLO-52085). It joins its block's decoder as a received source would, so
5316
+ * it reduces the erasures the block still has to solve, but it is not a
5317
+ * network arrival: no transport accounting, no classification evidence,
5318
+ * no deadline refresh, and it never makes a block clean.
5319
+ *
5320
+ * Only a block a repair stated takes one (a repair-less span has no
5321
+ * decoder block). A block that is terminal, or already holds that source,
5322
+ * does not. The symbol is the exact protected packet, unpadded, as
5323
+ * feedSourceSymbol takes it.
5324
+ *
5325
+ * `recovered` is the block the synchronous decoder completed with it; the
5326
+ * caller routes it and completes the block, as for any recovery. When
5327
+ * every source of the block is then present, received or rebuilt, and no
5328
+ * decoder returned it (a Worker answers asynchronously, and reports such a
5329
+ * block as clean on its own side), the block is completed here as
5330
+ * recovered, with nothing left to route.
5331
+ */
5332
+ feedRebuiltSourceSymbol(packetId, ssId, symbolData, catalogTrackName) {
5333
+ if (!this.#hasBlockProfile(packetId)) return NOT_TAKEN;
5334
+ const located = this.#isoLocatorFor(packetId, catalogTrackName).locate(ssId);
5335
+ if (located === null || located.block.span) return NOT_TAKEN;
5336
+ if (!ssbg1FitsSymbol(symbolData.byteLength, this.#trackConfig(packetId).symbolSize)) return NOT_TAKEN;
5337
+ const sbn = located.block.start;
5338
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
5339
+ if (this.#completedBlocks.has(key) || this.#blockSourceEsis.get(key)?.has(located.esi)) return NOT_TAKEN;
5340
+ let rebuilt = this.#blockRebuiltEsis.get(key);
5341
+ if (rebuilt?.has(located.esi)) return NOT_TAKEN;
5342
+ if (rebuilt === void 0) {
5343
+ rebuilt = /* @__PURE__ */ new Set();
5344
+ this.#blockRebuiltEsis.set(key, rebuilt);
5345
+ }
5346
+ const config = this.#trackConfigs.get(packetId);
5347
+ const wasShort = config !== void 0 && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) !== void 0;
5348
+ rebuilt.add(located.esi);
5349
+ const recovered = this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn);
5350
+ if (recovered === null && !this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName)) {
5351
+ if (wasShort && this.#activeBlocks.has(key) && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) === void 0) {
5352
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, this.#multicastWaitMs(config));
5353
+ }
5354
+ }
5355
+ return { taken: true, recovered };
5356
+ }
5357
+ /**
5358
+ * A block that holds every one of its `length` sources, received or
5359
+ * rebuilt by another instance, with at least one rebuilt, is recovered:
5360
+ * every packet of it was delivered, by its own arrival or by the instance
5361
+ * that rebuilt it, so nothing is routed. Returns whether it completed it.
5362
+ */
5363
+ #completeWhenSourcesPresent(key, sbn, length, packetId, catalogTrackName) {
5364
+ const rebuilt = this.#blockRebuiltEsis.get(key);
5365
+ if (rebuilt === void 0 || this.#completedBlocks.has(key)) return false;
5366
+ let present = rebuilt.size;
5367
+ for (const esi of this.#blockSourceEsis.get(key) ?? []) if (!rebuilt.has(esi)) present++;
5368
+ if (present < length) return false;
5369
+ this.#traceLifecycle("recovered", sbn, packetId, catalogTrackName);
5370
+ this.countRecovery(packetId, sbn, catalogTrackName);
5371
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
5372
+ if (catalogTrackName === void 0) {
5373
+ this.onBlockComplete?.(sbn, packetId);
5374
+ } else {
5375
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName);
5376
+ }
5377
+ return true;
5378
+ }
5005
5379
  /**
5006
5380
  * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
5007
5381
  * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
@@ -5063,7 +5437,10 @@ var FECManager = class _FECManager {
5063
5437
  this.#layerAnchorHorizon(packetId),
5064
5438
  this.#sourceFrontiers.get(streamKey)?.sbn
5065
5439
  );
5066
- if (verdict === "discard") return false;
5440
+ if (verdict === "discard") {
5441
+ this.#unlistedRepairTrackRefusals++;
5442
+ return false;
5443
+ }
5067
5444
  if (verdict !== void 0) {
5068
5445
  this.#failClosed(streamKey, verdict, packetId, catalogTrackName);
5069
5446
  return false;
@@ -5204,8 +5581,115 @@ var FECManager = class _FECManager {
5204
5581
  this.#completeCleanBlock(blockKey, sbn, packetId, catalogTrackName);
5205
5582
  return null;
5206
5583
  }
5584
+ if (recovered === null) this.#shortenUnrecoverableWait(blockKey, sbn, packetId, catalogTrackName);
5207
5585
  return recovered;
5208
5586
  }
5587
+ /**
5588
+ * A first-arrival multicast source, held or placed. A datagram flow keeps
5589
+ * its sources in send order, so one that moves the stream's newest source
5590
+ * position past a block leaves the sources that block still misses
5591
+ * reordered behind it at best: it shortens the wait of every block it
5592
+ * passed that only a late source can complete. MoQ is left out: its streams
5593
+ * can overtake one another, so a MoQ source shows nothing about the sources
5594
+ * sent before it.
5595
+ */
5596
+ #noteMulticastSource(locator, ssId, packetId, catalogTrackName) {
5597
+ const previous = locator.newestSource;
5598
+ if (!locator.noteSource(ssId) || previous === void 0) return;
5599
+ for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
5600
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
5601
+ this.#shortenUnrecoverableWait(
5602
+ this.#blockKey(block.start, packetId, catalogTrackName),
5603
+ block.start,
5604
+ packetId,
5605
+ catalogTrackName
5606
+ );
5607
+ }
5608
+ }
5609
+ /**
5610
+ * The wait of a block that only a late source can complete (BLO-52085): a
5611
+ * repair stated it, its received sources plus every symbol its repair group
5612
+ * carries (RSB_length) are short of K' (the repair scheduler's
5613
+ * group-cannot-complete), and a later source of the stream has arrived, so
5614
+ * a source it misses is lost or reordered behind that one. The span, which
5615
+ * covers repair symbols paced after its sources, buys it nothing: it waits
5616
+ * the late-symbol allowance alone, the multicast wait less the span (the
5617
+ * catalog tolerance or the measured delivery gap). Undefined for any other
5618
+ * block. While a keyframe overlay is installed, the block waits for its
5619
+ * repair too (#overlayLateWaitMs). A repair-less span keeps its whole
5620
+ * wait, even one longer than K whose group is empty (#openIsoSpan): its
5621
+ * resolution is what releases the frames behind it, and failing it early
5622
+ * released them past a keyframe the overlay was still rebuilding, which
5623
+ * then arrived stale. The release gate lets them go instead
5624
+ * (isoRepairlessWaitMs).
5625
+ */
5626
+ #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
5627
+ if (this.#isoSpanKeys.has(key) || !this.#groupCannotComplete(key)) return void 0;
5628
+ const authoredLength = this.#blockAuthoredLengths.get(key);
5629
+ const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
5630
+ if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
5631
+ return void 0;
5632
+ }
5633
+ return this.#overlayLateWaitMs(packetId, catalogTrackName, config);
5634
+ }
5635
+ /**
5636
+ * A repair stated the block, and its sources plus every symbol its repair
5637
+ * group carries (RSB_length) are short of its SSB_length.
5638
+ */
5639
+ #groupCannotComplete(key) {
5640
+ const authoredLength = this.#blockAuthoredLengths.get(key);
5641
+ const rsbLength = this.#blockRsbLengths.get(key);
5642
+ if (authoredLength === void 0 || rsbLength === void 0) return false;
5643
+ let present = this.#blockSourceCounts.get(key) ?? 0;
5644
+ const received = this.#blockSourceEsis.get(key);
5645
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
5646
+ return present + rsbLength < authoredLength;
5647
+ }
5648
+ /**
5649
+ * How long a loss only a late source or an installed keyframe overlay can
5650
+ * still fill waits once a later source passed it: the late-symbol
5651
+ * allowance alone (the multicast wait less the span) while no overlay is
5652
+ * installed. An installed one (keyframeOverlayTiming) may still rebuild a
5653
+ * RAP packet the loss took: a second FEC instance over the same packets
5654
+ * (draft-ramadan-moq-mmt-02 7.4), whose repair is paced across its own
5655
+ * span, unrelated to the base's. That packet can complete a stated block
5656
+ * (feedRebuiltSourceSymbol), or play behind a span; giving the loss up
5657
+ * first lets the release gate pass the keyframe, whose rebuild then lands
5658
+ * stale. The overlay repair of a packet the loss took goes out within the
5659
+ * overlay's span of that packet (fec-core-00 9.3), and the later source was
5660
+ * sent after it, so the loss waits that span plus the larger of the
5661
+ * allowance and the overlay's own tolerance. An overlay that states no
5662
+ * span (its block may then span keyframes), or one whose wait is not
5663
+ * shorter than the whole multicast wait, leaves the whole wait: undefined.
5664
+ */
5665
+ #overlayLateWaitMs(packetId, catalogTrackName, config) {
5666
+ const waitMs = this.#multicastWaitMs(config);
5667
+ const allowanceMs = waitMs - config.interleaveDepthMs;
5668
+ const overlay = this.keyframeOverlayTiming?.(packetId, catalogTrackName);
5669
+ if (overlay === void 0) return allowanceMs;
5670
+ const overlaySpanMs = overlay.interleaveDepthMs ?? 0;
5671
+ const overlayWaitMs = overlaySpanMs + Math.max(allowanceMs, overlay.reorderToleranceMs ?? 0);
5672
+ return overlaySpanMs > 0 && overlayWaitMs < waitMs ? overlayWaitMs : void 0;
5673
+ }
5674
+ /**
5675
+ * Bring an open block's wait in to its late-source wait, when it has one.
5676
+ * Never later than it is armed: only a source can complete such a block,
5677
+ * so a repair of its group (paced across the span) must not keep it open.
5678
+ */
5679
+ #shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName) {
5680
+ if (!this.#activeBlocks.has(key)) return;
5681
+ const config = this.#trackConfigs.get(packetId);
5682
+ if (config === void 0) return;
5683
+ const waitMs = this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config);
5684
+ if (waitMs === void 0) return;
5685
+ const armedAtMs = this.#blockWaitDeadlinesMs.get(key);
5686
+ this.#armBlockTimeout(
5687
+ sbn,
5688
+ packetId,
5689
+ catalogTrackName,
5690
+ armedAtMs === void 0 ? waitMs : Math.min(waitMs, armedAtMs - this.#receiptNow())
5691
+ );
5692
+ }
5209
5693
  /**
5210
5694
  * Record a block's authored SSB_length from a repair symbol. Returns false,
5211
5695
  * leaving the block unchanged, when the symbol contradicts the block: a
@@ -5303,12 +5787,13 @@ var FECManager = class _FECManager {
5303
5787
  * the inactivity deadline on each symbol, records the symbol's in-band
5304
5788
  * classification evidence, and marks the block clean when all of its
5305
5789
  * authored source symbols arrived: the SSB_length a repair symbol declared,
5306
- * otherwise K.
5790
+ * otherwise K. `held` marks a source held unplaced since it arrived and
5791
+ * placed only now (see #noteSbnSeen).
5307
5792
  *
5308
5793
  * Throws for a packetId that was never configured, so a classified block
5309
5794
  * never reads the manager-global K or timeout.
5310
5795
  */
5311
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
5796
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
5312
5797
  const trackConfig = this.#trackConfigs.get(packetId);
5313
5798
  if (trackConfig === void 0) {
5314
5799
  throw new Error(
@@ -5324,7 +5809,8 @@ var FECManager = class _FECManager {
5324
5809
  catalogTrackName,
5325
5810
  "source",
5326
5811
  evidence.packetSequenceNumber,
5327
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
5812
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
5813
+ held
5328
5814
  );
5329
5815
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
5330
5816
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -5360,6 +5846,15 @@ var FECManager = class _FECManager {
5360
5846
  this.#completeCleanBlock(key, sbn, packetId, catalogTrackName);
5361
5847
  return;
5362
5848
  }
5849
+ if (this.#blockRebuiltEsis.has(key) && this.#completeWhenSourcesPresent(
5850
+ key,
5851
+ sbn,
5852
+ this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? authoredLength,
5853
+ packetId,
5854
+ catalogTrackName
5855
+ )) {
5856
+ return;
5857
+ }
5363
5858
  this.noteBlockActivity(sbn, packetId, catalogTrackName, true);
5364
5859
  }
5365
5860
  #completeCleanBlock(key, sbn, packetId, catalogTrackName) {
@@ -5368,7 +5863,9 @@ var FECManager = class _FECManager {
5368
5863
  this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
5369
5864
  this.#blockSourceCounts.delete(key);
5370
5865
  this.#blockSourceEsis.delete(key);
5866
+ this.#blockRebuiltEsis.delete(key);
5371
5867
  this.#blockAuthoredLengths.delete(key);
5868
+ this.#isoSpanKeys.delete(key);
5372
5869
  this.#blockRepairRsIds.delete(key);
5373
5870
  this.#blockRsbLengths.delete(key);
5374
5871
  this.#markTerminal(key, sbn, packetId, true);
@@ -5399,6 +5896,19 @@ var FECManager = class _FECManager {
5399
5896
  #receiptNow() {
5400
5897
  return this.#receiptAtMs ?? performance.now();
5401
5898
  }
5899
+ /**
5900
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
5901
+ * scope: counted from the receipt time, as the timer of a symbol fed when
5902
+ * it was received was, less the whole ms since. So it fires on the tick
5903
+ * that timer would have, never later than a delay counted from now, and
5904
+ * its handler still re-arms a timer that fires before its deadline.
5905
+ * Counted from now, a deadline set from the receipt time is rounded up
5906
+ * from another fraction of a ms (BLO-52085).
5907
+ */
5908
+ #receiptTimerDelayMs(deadlineMs, minMs) {
5909
+ const receivedAtMs = this.#receiptAtMs;
5910
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
5911
+ }
5402
5912
  /**
5403
5913
  * A held packet admitted late arms from its (earlier) receipt time; that
5404
5914
  * never pulls in a deadline later activity already armed. Outside a
@@ -5434,10 +5944,20 @@ var FECManager = class _FECManager {
5434
5944
  this.#repairDeadlineMs(trackConfig)
5435
5945
  );
5436
5946
  }
5437
- this.#armBlockTimeout(sbn, packetId, catalogTrackName, timeoutMs);
5947
+ if (!sourceProgress && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) !== void 0) {
5948
+ this.#shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName);
5949
+ return;
5950
+ }
5951
+ this.#armBlockTimeout(
5952
+ sbn,
5953
+ packetId,
5954
+ catalogTrackName,
5955
+ this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) ?? timeoutMs
5956
+ );
5438
5957
  }
5439
5958
  #failBlock(sbn, packetId, catalogTrackName) {
5440
5959
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
5960
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
5441
5961
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
5442
5962
  this.#clearRepairDeadline(key);
5443
5963
  this.#clearBlockTimer(key);
@@ -5447,6 +5967,7 @@ var FECManager = class _FECManager {
5447
5967
  }
5448
5968
  this.#blockSourceCounts.delete(key);
5449
5969
  this.#blockSourceEsis.delete(key);
5970
+ this.#blockRebuiltEsis.delete(key);
5450
5971
  this.#blockAuthoredLengths.delete(key);
5451
5972
  this.#blockRepairRsIds.delete(key);
5452
5973
  this.#blockRsbLengths.delete(key);
@@ -5456,7 +5977,8 @@ var FECManager = class _FECManager {
5456
5977
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
5457
5978
  this.#fecStats.blocksFailed++;
5458
5979
  this.#statsForPacket(packetId).blocksFailed++;
5459
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5980
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5981
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
5460
5982
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
5461
5983
  }
5462
5984
  /**
@@ -5485,7 +6007,9 @@ var FECManager = class _FECManager {
5485
6007
  this.#retireBlockClass(key, block.sbn, block.packetId, block.catalogTrackName);
5486
6008
  this.#blockSourceCounts.delete(key);
5487
6009
  this.#blockSourceEsis.delete(key);
6010
+ this.#blockRebuiltEsis.delete(key);
5488
6011
  this.#blockAuthoredLengths.delete(key);
6012
+ this.#isoSpanKeys.delete(key);
5489
6013
  this.#blockRepairRsIds.delete(key);
5490
6014
  this.#blockRsbLengths.delete(key);
5491
6015
  this.#clearBlockTimer(key);
@@ -5576,7 +6100,9 @@ var FECManager = class _FECManager {
5576
6100
  this.#blockKeysBySbn.clear();
5577
6101
  this.#blockSourceCounts.clear();
5578
6102
  this.#blockSourceEsis.clear();
6103
+ this.#blockRebuiltEsis.clear();
5579
6104
  this.#blockAuthoredLengths.clear();
6105
+ this.#isoSpanKeys.clear();
5580
6106
  this.#blockRepairRsIds.clear();
5581
6107
  this.#blockRsbLengths.clear();
5582
6108
  this.#heldLayerStates.clear();
@@ -6955,9 +7481,9 @@ async function openSubscription(rx, openedPromise, options, packetIds) {
6955
7481
  } catch (error) {
6956
7482
  throw new MulticastError("subscription-failed", "MulticastReceiver did not open", error);
6957
7483
  }
6958
- if (rx.integrityScheme !== INTEGRITY_SCHEME) {
7484
+ if (opened.integrityScheme !== INTEGRITY_SCHEME) {
6959
7485
  await rx.close();
6960
- throw unsupported(`integrity scheme ${String(rx.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
7486
+ throw unsupported(`integrity scheme ${String(opened.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
6961
7487
  }
6962
7488
  const events = new EventTarget();
6963
7489
  let state = "connected";
@@ -7076,6 +7602,7 @@ var MOQT_PUBLISHER_PRIORITY = Object.freeze({
7076
7602
  });
7077
7603
 
7078
7604
  // node_modules/@blockcast/mmt-transport/dist/amt-gateway.js
7605
+ var MAX_PENDING_PACKETS = 256;
7079
7606
  var AMTGatewayManager = class {
7080
7607
  subscriptions = /* @__PURE__ */ new Map();
7081
7608
  messageHandler;
@@ -7199,7 +7726,7 @@ var AMTGatewayManager = class {
7199
7726
  if (!subscription.handshakeComplete) {
7200
7727
  const queue = this.pendingPackets.get(subscriptionId);
7201
7728
  const packetData2 = data;
7202
- if (queue) {
7729
+ if (queue && queue.length < MAX_PENDING_PACKETS) {
7203
7730
  queue.push({
7204
7731
  data: packetData2.data,
7205
7732
  remoteAddress: packetData2.remoteAddress,
@@ -10292,9 +10819,10 @@ function isH264IntraSlice(nal) {
10292
10819
  const sliceType = readH264SliceType(nal);
10293
10820
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
10294
10821
  }
10822
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
10295
10823
  function readH264SliceType(nal) {
10296
10824
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
10297
- const rbsp = removeEmulationPrevention(nal.subarray(1));
10825
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
10298
10826
  const state = { bitOffset: 0 };
10299
10827
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
10300
10828
  return readUnsignedExpGolomb(rbsp, state);
@@ -10441,6 +10969,96 @@ if (void 0) {
10441
10969
  ]))).toBe(false);
10442
10970
  });
10443
10971
  });
10972
+ describe("readH264SliceType", () => {
10973
+ const wholeNalSliceType = (nal) => {
10974
+ if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
10975
+ const rbsp = removeEmulationPrevention(nal.subarray(1));
10976
+ const state = { bitOffset: 0 };
10977
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null;
10978
+ return readUnsignedExpGolomb(rbsp, state);
10979
+ };
10980
+ const hex2 = (text2) => Uint8Array.from(text2.match(/../g), (byte) => parseInt(byte, 16));
10981
+ const ue = (value) => {
10982
+ const code = (value + 1).toString(2);
10983
+ return "0".repeat(code.length - 1) + code;
10984
+ };
10985
+ const sliceNal = (bits) => {
10986
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, "0").match(/.{8}/g);
10987
+ const nal = [1];
10988
+ let zeros = 0;
10989
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
10990
+ if (zeros >= 2 && byte <= 3) {
10991
+ nal.push(3);
10992
+ zeros = 0;
10993
+ }
10994
+ nal.push(byte);
10995
+ zeros = byte === 0 ? zeros + 1 : 0;
10996
+ }
10997
+ return Uint8Array.from(nal);
10998
+ };
10999
+ const x264Slices = [
11000
+ ["64x48 P", hex2("419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176"), 5, false],
11001
+ ["64x48 B", hex2("419e414212fffeeade283707cb70f7"), 6, false],
11002
+ ["64x48 non-IDR I", hex2(
11003
+ "4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39a527e23eb34c8167fd"
11004
+ ), 7, true],
11005
+ ["1280x720 B, escape at byte 10", hex2(
11006
+ "01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e19b75d92170917306190f262fd58268702db2eff86a9651e48"
11007
+ ), 6, false],
11008
+ ["1280x720 P, escape at byte 15", hex2(
11009
+ "41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f02c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e85302da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3"
11010
+ ), 5, false],
11011
+ ["1280x720 B, escape at byte 22", hex2("01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352"), 6, false],
11012
+ ["7680x4320 IDR, first_mb_in_slice 97440", hex2(
11013
+ "650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9"
11014
+ ), null, true],
11015
+ ["7680x4320 P, first_mb_in_slice 32640", hex2(
11016
+ "410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020"
11017
+ ), 5, false],
11018
+ ["7680x4320 P, first_mb_in_slice 97440", hex2(
11019
+ "410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806"
11020
+ ), 5, false]
11021
+ ];
11022
+ const syntheticSlices = [
11023
+ ["an escape inside first_mb_in_slice", sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
11024
+ ["an escape between the fields", sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
11025
+ ["an escape inside slice_type", sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
11026
+ ["the longest fields, five escapes", sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
11027
+ ["the largest values", sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
11028
+ ["31 leading zeros in first_mb_in_slice", sliceNal(`${"0".repeat(31)}1`), null],
11029
+ ["31 leading zeros in slice_type", sliceNal(`1${"0".repeat(31)}1`), null],
11030
+ ["escapes running past the slice header", sliceNal(ue(0) + ue(5) + "0".repeat(400)), 5]
11031
+ ];
11032
+ test("reads the slice_type of real and synthetic slices", () => {
11033
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
11034
+ expect(readH264SliceType(nal), name).toBe(sliceType);
11035
+ }
11036
+ });
11037
+ test("matches the whole-NAL unescape at every truncation", () => {
11038
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
11039
+ for (let end = 0; end <= nal.length; end++) {
11040
+ const cut = nal.subarray(0, end);
11041
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut));
11042
+ }
11043
+ }
11044
+ });
11045
+ test("matches the whole-NAL unescape on zero-heavy NAL units", () => {
11046
+ const bytes = [0, 0, 0, 3, 1, 2, 128, 255];
11047
+ let seed = 1;
11048
+ const next = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) >>> 16;
11049
+ for (let i = 0; i < 5e3; i++) {
11050
+ const nal = new Uint8Array(2 + next() % 63);
11051
+ nal[0] = 65;
11052
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length];
11053
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal));
11054
+ }
11055
+ });
11056
+ test("classifies the x264 slices as keyframes or not", () => {
11057
+ for (const [name, nal, , keyframe] of x264Slices) {
11058
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe);
11059
+ }
11060
+ });
11061
+ });
10444
11062
  describe("avccToAnnexB", () => {
10445
11063
  test("converts with SPS/PPS on keyframe", () => {
10446
11064
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -13142,9 +13760,21 @@ var IsoBmffTimingResolver = class {
13142
13760
  }
13143
13761
  #track = null;
13144
13762
  #fragments = /* @__PURE__ */ new Map();
13763
+ /** First sample of each pending fragment, kept in `#delivered` with its sample count. */
13764
+ #firstSamples = /* @__PURE__ */ new Map();
13765
+ /**
13766
+ * First sample and sample count of the newest fragments whose every slot was
13767
+ * cleared. Abandonment counts: `releaseSample` clears a slot too, which
13768
+ * matches the combiner, since it retires an abandoned sample as well.
13769
+ */
13770
+ #delivered = /* @__PURE__ */ new Map();
13145
13771
  #pendingSamples = 0;
13146
13772
  #evictedSamples = 0;
13147
13773
  #lastMovieFragmentRejection = null;
13774
+ /** True once an FT=0 has bound the track that FT=1 timing is read against. */
13775
+ get initialized() {
13776
+ return this.#track !== null;
13777
+ }
13148
13778
  get pendingSampleCount() {
13149
13779
  return this.#pendingSamples;
13150
13780
  }
@@ -13168,7 +13798,14 @@ var IsoBmffTimingResolver = class {
13168
13798
  this.#track = timing;
13169
13799
  return true;
13170
13800
  }
13171
- addMovieFragment(mpuSequenceNumber, data, additionalSampleLimit = this.maxPendingSamples) {
13801
+ /**
13802
+ * `recovered` marks an FEC-recovered copy. A recovered block hands back
13803
+ * every FT=1 it holds, the received ones included, so a recovered copy of a
13804
+ * fragment whose samples are all done is a duplicate: admitting it again
13805
+ * would charge stale timing and could displace the live MPU's. A source
13806
+ * copy is still admitted again (a rendition switch re-arms timing that way).
13807
+ */
13808
+ addMovieFragment(mpuSequenceNumber, data, additionalSampleLimit = this.maxPendingSamples, recovered = false) {
13172
13809
  this.#lastMovieFragmentRejection = null;
13173
13810
  if (!Number.isInteger(additionalSampleLimit) || additionalSampleLimit < 0) {
13174
13811
  this.#lastMovieFragmentRejection = "invalid";
@@ -13194,6 +13831,8 @@ var IsoBmffTimingResolver = class {
13194
13831
  (sample, index) => sample !== null && sameSample(sample, parsed.samples[index])
13195
13832
  );
13196
13833
  }
13834
+ const delivered = recovered ? this.#delivered.get(key) : void 0;
13835
+ if (delivered && delivered.sampleCount === parsed.samples.length && sameSample(delivered.first, parsed.samples[0])) return true;
13197
13836
  let freed = 0;
13198
13837
  while (this.#fragments.size > 0 && (this.#pendingSamples + parsed.samples.length > this.maxPendingSamples || parsed.samples.length - freed > additionalSampleLimit)) {
13199
13838
  freed += this.#evictOldestFragment();
@@ -13207,6 +13846,7 @@ var IsoBmffTimingResolver = class {
13207
13846
  return false;
13208
13847
  }
13209
13848
  this.#fragments.set(key, [...parsed.samples]);
13849
+ this.#firstSamples.set(key, parsed.samples[0]);
13210
13850
  this.#pendingSamples += parsed.samples.length;
13211
13851
  return true;
13212
13852
  }
@@ -13264,6 +13904,7 @@ var IsoBmffTimingResolver = class {
13264
13904
  let live = 0;
13265
13905
  for (const sample of samples) if (sample !== null) live++;
13266
13906
  this.#fragments.delete(oldest);
13907
+ this.#firstSamples.delete(oldest);
13267
13908
  this.#pendingSamples -= live;
13268
13909
  this.#evictedSamples += live;
13269
13910
  return live;
@@ -13279,12 +13920,23 @@ var IsoBmffTimingResolver = class {
13279
13920
  if (!samples || !samples[index]) return false;
13280
13921
  samples[index] = null;
13281
13922
  this.#pendingSamples--;
13282
- if (samples.every((value) => value === null)) this.#fragments.delete(key);
13923
+ if (samples.every((value) => value === null)) {
13924
+ this.#fragments.delete(key);
13925
+ const first = this.#firstSamples.get(key);
13926
+ this.#firstSamples.delete(key);
13927
+ this.#delivered.delete(key);
13928
+ this.#delivered.set(key, { first, sampleCount: samples.length });
13929
+ if (this.#delivered.size > this.maxPendingSamples) {
13930
+ this.#delivered.delete(this.#delivered.keys().next().value);
13931
+ }
13932
+ }
13283
13933
  return true;
13284
13934
  }
13285
13935
  reset() {
13286
13936
  this.#track = null;
13287
13937
  this.#fragments.clear();
13938
+ this.#firstSamples.clear();
13939
+ this.#delivered.clear();
13288
13940
  this.#pendingSamples = 0;
13289
13941
  }
13290
13942
  };
@@ -13454,6 +14106,9 @@ function authoredGap(before, after) {
13454
14106
  function ssIdAfter(a, b) {
13455
14107
  return (a - b | 0) > 0;
13456
14108
  }
14109
+ function holdsRebuilt(stream) {
14110
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
14111
+ }
13457
14112
  var FecReleaseSequencer = class {
13458
14113
  #streams = /* @__PURE__ */ new Map();
13459
14114
  #gate;
@@ -13516,6 +14171,7 @@ var FecReleaseSequencer = class {
13516
14171
  stream.lastSbn = void 0;
13517
14172
  stream.discontinuity = false;
13518
14173
  stream.rapSsId = void 0;
14174
+ stream.sourced = false;
13519
14175
  }
13520
14176
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
13521
14177
  this.#recordStat("droppedStale");
@@ -13542,6 +14198,7 @@ var FecReleaseSequencer = class {
13542
14198
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
13543
14199
  else hi = mid;
13544
14200
  }
14201
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
13545
14202
  stream.buf.splice(lo, 0, frame);
13546
14203
  this.#drainUnlessDeferred(stream);
13547
14204
  }
@@ -13577,6 +14234,41 @@ var FecReleaseSequencer = class {
13577
14234
  }
13578
14235
  return false;
13579
14236
  }
14237
+ /**
14238
+ * These streams' sink is being replaced by one that has seen no source
14239
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
14240
+ * release to the sink being replaced the frames the unanchored path had
14241
+ * already released to it (#cursorPassed): there they waited in its queue,
14242
+ * which its replacement flushes. A stream that holds none is not drained:
14243
+ * it holds nothing the anchor kept back, and a drain would still force out
14244
+ * a frame held past the hold limit, which before the anchor waited for the
14245
+ * next push. Then treat the streams as unsourced until a source frame is
14246
+ * released.
14247
+ */
14248
+ unsource(packetId, catalogTrackName) {
14249
+ for (const stream of this.#streams.values()) {
14250
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
14251
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
14252
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
14253
+ else this.#drain(stream, true);
14254
+ }
14255
+ stream.sourced = false;
14256
+ }
14257
+ }
14258
+ }
14259
+ /**
14260
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
14261
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
14262
+ * packetId.
14263
+ */
14264
+ holdsRebuilt(packetId, catalogTrackName) {
14265
+ for (const stream of this.#streams.values()) {
14266
+ if (stream.packetId !== packetId) continue;
14267
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
14268
+ if (holdsRebuilt(stream)) return true;
14269
+ }
14270
+ return false;
14271
+ }
13580
14272
  /** Re-evaluate held gaps after FEC state changed. */
13581
14273
  poke(streamKey) {
13582
14274
  if (streamKey !== void 0) {
@@ -13668,16 +14360,32 @@ var FecReleaseSequencer = class {
13668
14360
  last: null,
13669
14361
  lastSbn: void 0,
13670
14362
  discontinuity: false,
13671
- rapSsId: void 0
14363
+ rapSsId: void 0,
14364
+ sourced: false,
14365
+ draining: 0
13672
14366
  };
13673
14367
  this.#streams.set(streamKey, stream);
13674
14368
  }
13675
14369
  return stream;
13676
14370
  }
13677
- #drain(stream) {
14371
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
14372
+ #drain(stream, asUnanchored = false) {
14373
+ stream.draining++;
14374
+ try {
14375
+ this.#drainLoop(stream, asUnanchored);
14376
+ } finally {
14377
+ stream.draining--;
14378
+ }
14379
+ }
14380
+ #drainLoop(stream, asUnanchored) {
13678
14381
  while (stream.buf.length > 0 && stream.last !== null) {
13679
14382
  const head = stream.buf[0];
13680
14383
  const last = stream.last;
14384
+ if (compareFrameOrder(head, last) <= 0) {
14385
+ stream.buf.shift();
14386
+ this.#release(stream, head, void 0);
14387
+ continue;
14388
+ }
13681
14389
  if (stream.discontinuity) {
13682
14390
  stream.discontinuity = false;
13683
14391
  stream.buf.shift();
@@ -13691,9 +14399,10 @@ var FecReleaseSequencer = class {
13691
14399
  }
13692
14400
  const headSbn = head.meta.fecSbn;
13693
14401
  const from = stream.lastSbn ?? headSbn;
13694
- const to = headSbn ?? stream.lastSbn;
14402
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
13695
14403
  let lost = [];
13696
14404
  const unanchored = from === void 0 && to === void 0;
14405
+ let unresolved = false;
13697
14406
  if (from !== void 0 && to !== void 0) {
13698
14407
  const resolved = this.#gate.resolvedLoss(
13699
14408
  stream.packetId,
@@ -13702,7 +14411,8 @@ var FecReleaseSequencer = class {
13702
14411
  Math.max(from, to),
13703
14412
  from
13704
14413
  );
13705
- if (resolved === null) {
14414
+ unresolved = resolved === null;
14415
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored) && !this.#unrepairableWaitOver(stream, last, head, from, to)) {
13706
14416
  const heldMs = performance.now() - head.arrivedAtMs;
13707
14417
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
13708
14418
  this.#recordStat("forcedWindowFlushes");
@@ -13710,22 +14420,69 @@ var FecReleaseSequencer = class {
13710
14420
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
13711
14421
  continue;
13712
14422
  }
13713
- lost = resolved;
14423
+ lost = resolved ?? [];
13714
14424
  }
13715
14425
  stream.buf.shift();
13716
14426
  this.#release(
13717
14427
  stream,
13718
14428
  head,
13719
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
14429
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
13720
14430
  );
13721
14431
  }
13722
14432
  }
14433
+ /**
14434
+ * The head has waited out a gap only a late source can still fill
14435
+ * (FecReleaseGate.unrepairableWaitMs). Not yet: the gate is asked to poke
14436
+ * the stream when it has (`wakeAt`), since no packet may come by then.
14437
+ */
14438
+ #unrepairableWaitOver(stream, last, head, from, to) {
14439
+ const waitMs = this.#gate.unrepairableWaitMs?.(last, head, from, to);
14440
+ if (waitMs === void 0) return false;
14441
+ const atMs = head.arrivedAtMs + waitMs;
14442
+ if (performance.now() >= atMs) return true;
14443
+ this.#gate.wakeAt?.(stream.packetId, stream.catalogTrackName, atMs);
14444
+ return false;
14445
+ }
14446
+ /**
14447
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
14448
+ * source cursor holds it unanchored, and neither does a later frame behind
14449
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
14450
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
14451
+ * like each frame that arrived in front of it since (stale there). The head
14452
+ * then goes, decided as it would be unanchored, once a frame the base path
14453
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
14454
+ * marked one: the base path has passed that one, so a frame still missing
14455
+ * before it can only come from a repair. It also goes while no source frame
14456
+ * has been released, when the direct path shows a recovered frame at once.
14457
+ * And it goes at once while a staged switch decides on when frames arrive
14458
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
14459
+ * sink being replaced: unanchored, it had already reached the sink.
14460
+ * The scan also writes: the `passed` marks it sets stay on the frames,
14461
+ * and push marks a frame it inserts in front of a marked one from them.
14462
+ */
14463
+ #cursorPassed(stream, asUnanchored) {
14464
+ let at = -1;
14465
+ for (let i = 0; i < stream.buf.length; i++) {
14466
+ const frame = stream.buf[i];
14467
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
14468
+ frame.passed = true;
14469
+ if (at < 0) at = i;
14470
+ } else if (frame.passed !== true) break;
14471
+ }
14472
+ if (at < 0) return false;
14473
+ 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));
14474
+ }
13723
14475
  #release(stream, frame, decision) {
14476
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
14477
+ if (stale) this.#recordStat("droppedStale");
13724
14478
  if (decision) frame.meta.gapBefore = decision;
13725
14479
  stream.last = frame;
13726
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
14480
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
14481
+ stream.lastSbn = frame.meta.fecSbn;
14482
+ }
14483
+ if (frame.meta.recovered !== true) stream.sourced = true;
13727
14484
  this.#gate.onReleased?.(frame.data, frame.meta);
13728
- this.#emit(frame.data, frame.meta);
14485
+ if (!stale) this.#emit(frame.data, frame.meta);
13729
14486
  }
13730
14487
  };
13731
14488
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -13766,6 +14523,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
13766
14523
  this.#reclaimedTimingSamples = 0;
13767
14524
  this.#evictedTimingSamples = 0;
13768
14525
  this.#rejectedMovieFragments = 0;
14526
+ this.#recoveredHeadsAwaitingTiming = {
14527
+ held: 0,
14528
+ expired: 0,
14529
+ discarded: 0,
14530
+ superseded: 0
14531
+ };
13769
14532
  this.#sequencers = /* @__PURE__ */ new Map();
13770
14533
  this.#fecGate = null;
13771
14534
  this.#fecSequencer = null;
@@ -13874,6 +14637,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
13874
14637
  #reclaimedTimingSamples;
13875
14638
  #evictedTimingSamples;
13876
14639
  #rejectedMovieFragments;
14640
+ #recoveredHeadsAwaitingTiming;
13877
14641
  #sequencers;
13878
14642
  #fecGate;
13879
14643
  #fecSequencer;
@@ -13979,11 +14743,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
13979
14743
  /**
13980
14744
  * Typed view of the ISO-BMFF timing-sample budget.
13981
14745
  *
13982
- * This is the acceptance signal for the budget ratchet: `pending` walking
13983
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
13984
- * and it is observable here rather than only as media silently stopping.
13985
- * Per repo policy this is a producer-owned counter -- never infer budget
13986
- * state by parsing logs.
14746
+ * Each stream admits timing against its own window of `capacity` slots
14747
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
14748
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
14749
+ * timing a stream declared and never delivered shows up there. `pending`
14750
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
14751
+ * a producer-owned counter -- never infer budget state by parsing logs.
13987
14752
  */
13988
14753
  get timingBudgetStats() {
13989
14754
  return {
@@ -13994,6 +14759,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
13994
14759
  rejectedMovieFragments: this.#rejectedMovieFragments
13995
14760
  };
13996
14761
  }
14762
+ /** Recovered heads parked for FT=1 timing (BLO-53369). Survives dispose(). */
14763
+ get recoveredHeadsAwaitingTiming() {
14764
+ let pending = 0;
14765
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
14766
+ for (const head of awaitingTiming) if (head.options?.recovered) pending++;
14767
+ }
14768
+ return { ...this.#recoveredHeadsAwaitingTiming, pending };
14769
+ }
13997
14770
  get reorderStats() {
13998
14771
  let bufferedFrames = this.#fecSequencer?.buffered ?? 0;
13999
14772
  for (const { sequencer } of this.#sequencers.values()) bufferedFrames += sequencer.buffered;
@@ -14035,6 +14808,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
14035
14808
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
14036
14809
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
14037
14810
  }
14811
+ /** See FecReleaseSequencer.unsource. */
14812
+ unsourceFecRelease(packetId, catalogTrackName) {
14813
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
14814
+ }
14815
+ /** See FecReleaseSequencer.holdsRebuilt. */
14816
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
14817
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
14818
+ }
14038
14819
  /** Re-evaluate held gaps after FEC block state changed. */
14039
14820
  pokeFecRelease(packetId, catalogTrackName) {
14040
14821
  if (!this.#fecSequencer) return;
@@ -14167,7 +14948,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14167
14948
  const now = Date.now();
14168
14949
  for (const { awaitingTiming } of this.#timingStreams.values()) {
14169
14950
  while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
14170
- awaitingTiming.shift();
14951
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
14171
14952
  }
14172
14953
  }
14173
14954
  }
@@ -14285,11 +15066,16 @@ var MmtpContainerParser = class _MmtpContainerParser {
14285
15066
  if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
14286
15067
  return this.#drop("fragment-unexpected-fragmentation");
14287
15068
  const resolver2 = this.#timingResolver(streamKey, info.packetId, false);
14288
- if (!resolver2) return this.#drop("fragment-no-resolver");
15069
+ if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
14289
15070
  const pendingBefore = resolver2.pendingSampleCount;
14290
15071
  const evictedBefore = resolver2.evictedSampleCount;
14291
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
14292
- const admitted = resolver2.addMovieFragment(mpu.mpuSequenceNumber, data, remaining);
15072
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
15073
+ const admitted = resolver2.addMovieFragment(
15074
+ mpu.mpuSequenceNumber,
15075
+ data,
15076
+ remaining,
15077
+ options?.recovered === true
15078
+ );
14293
15079
  this.#pendingTimingSamples += resolver2.pendingSampleCount - pendingBefore;
14294
15080
  this.#evictedTimingSamples += resolver2.evictedSampleCount - evictedBefore;
14295
15081
  if (!admitted) {
@@ -14309,7 +15095,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14309
15095
  };
14310
15096
  }
14311
15097
  if (fragmentType !== 2) return this.#drop("unknown-fragment-type");
14312
- const resolver = this.#timingResolver(streamKey, info.packetId, false);
15098
+ const resolver = this.#timingResolver(streamKey, info.packetId, true);
14313
15099
  if (!resolver) return this.#drop("mfu-no-resolver");
14314
15100
  if (!Number.isSafeInteger(data.byteLength) || data.byteLength <= 0)
14315
15101
  return this.#drop("mfu-empty-payload");
@@ -14330,6 +15116,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14330
15116
  mpuSequenceNumber: mpu.mpuSequenceNumber,
14331
15117
  movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
14332
15118
  sampleNumber: mfuDuHeader.sampleNumber,
15119
+ sequenceNumber: info.sequenceNumber,
14333
15120
  arrivedAt: Date.now()
14334
15121
  });
14335
15122
  return this.#drop("mfu-sample-timing-missing");
@@ -14355,7 +15142,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14355
15142
  info,
14356
15143
  resolver,
14357
15144
  options?.recovered === true,
14358
- options?.fecSbn
15145
+ options?.fecSbn,
15146
+ options?.fecSbnFirst
14359
15147
  );
14360
15148
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
14361
15149
  }
@@ -14448,7 +15236,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14448
15236
  info,
14449
15237
  resolver,
14450
15238
  options?.recovered === true,
14451
- options?.fecSbn
15239
+ options?.fecSbn,
15240
+ options?.fecSbnFirst
14452
15241
  );
14453
15242
  if (outcome.record !== void 0) return outcome.record;
14454
15243
  return this.#drop(outcome.reason);
@@ -14468,7 +15257,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14468
15257
  * attribution exists to keep readable. Leaving the choice at the call site
14469
15258
  * is what keeps both true.
14470
15259
  */
14471
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
15260
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
14472
15261
  const timing = resolver.sampleTiming(
14473
15262
  combined.mpuSequenceNumber,
14474
15263
  combined.movieFragmentSequenceNumber,
@@ -14485,6 +15274,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14485
15274
  );
14486
15275
  if (!meta) return { reason: "combined-meta-build-failed" };
14487
15276
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
15277
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
14488
15278
  if (!resolver.consumeSample(
14489
15279
  combined.mpuSequenceNumber,
14490
15280
  combined.movieFragmentSequenceNumber,
@@ -14718,6 +15508,9 @@ var MmtpContainerParser = class _MmtpContainerParser {
14718
15508
  for (const { sequencer } of this.#sequencers.values()) sequencer.discard();
14719
15509
  this.#sequencers.clear();
14720
15510
  this.#fecSequencer?.discard();
15511
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
15512
+ for (const head of awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
15513
+ }
14721
15514
  this.#timingStreams.clear();
14722
15515
  this.#pendingTimingSamples = 0;
14723
15516
  this.#reliableMoqStartupGate.clear();
@@ -14736,10 +15529,23 @@ var MmtpContainerParser = class _MmtpContainerParser {
14736
15529
  return resolver;
14737
15530
  }
14738
15531
  #awaitTiming(streamKey, head) {
14739
- const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
14740
- if (!awaitingTiming) return;
15532
+ const state = this.#timingStreams.get(streamKey);
15533
+ if (!state) return;
15534
+ if (!head.options?.recovered) {
15535
+ const kept = state.awaitingTiming.filter((queued) => !queued.options?.recovered || queued.sequenceNumber !== head.sequenceNumber);
15536
+ this.#recoveredHeadsAwaitingTiming.superseded += state.awaitingTiming.length - kept.length;
15537
+ state.awaitingTiming = kept;
15538
+ }
15539
+ const awaitingTiming = state.awaitingTiming;
14741
15540
  awaitingTiming.push(head);
14742
- if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
15541
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming.held++;
15542
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) {
15543
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
15544
+ }
15545
+ }
15546
+ /** Count a recovered head leaving the queue other than by replay or its source copy. */
15547
+ #leaveAwaitingTiming(head, outcome) {
15548
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming[outcome]++;
14743
15549
  }
14744
15550
  /**
14745
15551
  * Feed again the heads whose timing the FT=1 just admitted declares. That
@@ -14767,6 +15573,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14767
15573
  const state = this.#timingStreams.get(streamKey);
14768
15574
  if (!state) return;
14769
15575
  this.#timingStreams.delete(streamKey);
15576
+ for (const head of state.awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
14770
15577
  this.#pendingTimingSamples -= state.resolver.pendingSampleCount;
14771
15578
  if (this.#pendingTimingSamples < 0) {
14772
15579
  throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");
@@ -17972,7 +18779,18 @@ function keyframeOverlaySsId(header) {
17972
18779
  if (ext?.type !== KEYFRAME_OVERLAY_EXTENSION_TYPE || ext.data.length !== 4) return void 0;
17973
18780
  return new DataView(ext.data.buffer, ext.data.byteOffset, 4).getUint32(0);
17974
18781
  }
18782
+ function overlayBaseSsId(anchor, overlaySsId, restoredPsn, headerPsn) {
18783
+ if (anchor.baseSsId === void 0 || headerPsn !== restoredPsn) return void 0;
18784
+ return serial32Add(anchor.baseSsId, overlaySsId - anchor.overlaySsId | 0);
18785
+ }
18786
+ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
18787
+ if (offset === void 0 || offset !== unstampedOffset) return void 0;
18788
+ return headerPsn + offset >>> 0;
18789
+ }
18790
+ var OVERLAY_ROUTED_LIMIT = 1024;
18791
+ var OVERLAY_PENDING_LIMIT = 256;
17975
18792
  var OVERLAY_OFFSET_MPUS = 16;
18793
+ var OVERLAY_REBUILT_LIMIT = 256;
17976
18794
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
17977
18795
  function assertStreamIdentity(role, stream) {
17978
18796
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -18083,6 +18901,7 @@ var MmtpRouter = class {
18083
18901
  #provenance = /* @__PURE__ */ new Map();
18084
18902
  #onFlowProtected = null;
18085
18903
  #unadmittedListedDrops = 0;
18904
+ #admittedSourceDatagrams = 0;
18086
18905
  #unlistedRepairSetAside = 0;
18087
18906
  #assistBlocks = /* @__PURE__ */ new Map();
18088
18907
  #assistFailures = /* @__PURE__ */ new Map();
@@ -18139,6 +18958,26 @@ var MmtpRouter = class {
18139
18958
  * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
18140
18959
  */
18141
18960
  #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18961
+ /**
18962
+ * Per stream, the SS_ID offset at which a base recovery last showed the
18963
+ * sender's own packet_sequence_number: a recovered packet's header psn
18964
+ * equal to its SS_ID minus that offset. While it equals the stream's
18965
+ * current offset, no hop re-stamps the stream, and a packet's protected psn
18966
+ * names its base SS_ID within unstampedBaseSsId's limits (joint decoding of
18967
+ * an MPU no member of which arrived).
18968
+ */
18969
+ #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18970
+ /**
18971
+ * The same, shown by the overlay alone, before any base recovery did: a
18972
+ * packet it rebuilt whose base copy carries its protected psn
18973
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
18974
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
18975
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
18976
+ * make the base drop a late base copy of a keyframe the overlay never
18977
+ * finished, and lift a block's late-source cut, which nothing before
18978
+ * this offset did.
18979
+ */
18980
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18142
18981
  /**
18143
18982
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
18144
18983
  * not parsed, typically because its overlap copy was parsed first
@@ -18184,6 +19023,8 @@ var MmtpRouter = class {
18184
19023
  // end: a synchronous recovery completes its block BEFORE routing the
18185
19024
  // recovered frames, and releasing a held gap in between would strand them.
18186
19025
  #fecPokeDepth = 0;
19026
+ /** FecReleaseGate.wakeAt timers, by media stream key. */
19027
+ #fecWakes = /* @__PURE__ */ new Map();
18187
19028
  #pendingFecPokes = /* @__PURE__ */ new Map();
18188
19029
  // ── Phase 14: per-role packetId dispatch (D-26, D-27, D-28) ───────
18189
19030
  /** Maps packetId → TrackRole. Default: 'single' when absent (legacy path). */
@@ -18208,7 +19049,9 @@ var MmtpRouter = class {
18208
19049
  recovered: 0,
18209
19050
  restarts: 0,
18210
19051
  unsequencedDropped: 0,
18211
- protectedDropped: 0
19052
+ protectedDropped: 0,
19053
+ baseFed: 0,
19054
+ baseUndetermined: 0
18212
19055
  };
18213
19056
  /** Callback fired when a delta-track FEC block completes or fails. */
18214
19057
  #onDeltaBlockCompleteCb = null;
@@ -18381,7 +19224,7 @@ var MmtpRouter = class {
18381
19224
  const cb = this.#getFrameCallback(packetId);
18382
19225
  if (isVideo && !assembler) {
18383
19226
  if (frameMeta.recovered) {
18384
- this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb);
19227
+ this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb, meta.fecSbn);
18385
19228
  } else {
18386
19229
  this.#routeDirectSourceVideo(packetId, data, frameMeta, cb);
18387
19230
  }
@@ -18414,13 +19257,18 @@ var MmtpRouter = class {
18414
19257
  this.#onDeltaBlockCompleteCb?.(packetId, false);
18415
19258
  }
18416
19259
  };
18417
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
19260
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
18418
19261
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
18419
19262
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
18420
19263
  this.#onDeltaBlockCompleteCb?.(packetId, true);
18421
19264
  }
18422
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18423
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19265
+ if (span === void 0) {
19266
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19267
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19268
+ } else {
19269
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
19270
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
19271
+ }
18424
19272
  };
18425
19273
  }
18426
19274
  }
@@ -18465,8 +19313,9 @@ var MmtpRouter = class {
18465
19313
  }
18466
19314
  /**
18467
19315
  * FEC-recovered source symbols whose reconstructed header named a
18468
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
18469
- * a hop re-stamped the sequence after the sender protected the packet.
19316
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
19317
+ * or, rebuilt by the overlay, than their base copy carries: a hop
19318
+ * re-stamped the sequence after the sender protected the packet.
18470
19319
  */
18471
19320
  get restampedRecoveredSequenceCount() {
18472
19321
  return this.#restampedRecoveredSeqs;
@@ -18645,6 +19494,7 @@ var MmtpRouter = class {
18645
19494
  enableMseAssembler(packetId, config, catalogTrackName) {
18646
19495
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
18647
19496
  const previous = this.#mseAssemblers.get(assemblerKey);
19497
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
18648
19498
  if (previous) {
18649
19499
  previous.flush();
18650
19500
  previous.dispose();
@@ -18771,6 +19621,10 @@ var MmtpRouter = class {
18771
19621
  get keyframeOverlayStats() {
18772
19622
  return { ...this.#overlayStats };
18773
19623
  }
19624
+ /** Recovered FT=2 heads held for their FT=1, and how each left the wait (BLO-53369). */
19625
+ get recoveredHeadsAwaitingTiming() {
19626
+ return this.#parser.recoveredHeadsAwaitingTiming;
19627
+ }
18774
19628
  #isOverlayRepair(repairPacketId, repairTrackName) {
18775
19629
  return this.#overlayLegs.has(repairPacketId) || repairTrackName !== void 0 && this.#overlayRepairNames.has(repairTrackName);
18776
19630
  }
@@ -18791,7 +19645,8 @@ var MmtpRouter = class {
18791
19645
  fec,
18792
19646
  k,
18793
19647
  offsets: /* @__PURE__ */ new Map(),
18794
- moqBlocks: /* @__PURE__ */ new Set()
19648
+ moqBlocks: /* @__PURE__ */ new Set(),
19649
+ rebuilt: /* @__PURE__ */ new Map()
18795
19650
  };
18796
19651
  this.#overlays.set(repairPacketId, inst);
18797
19652
  return () => {
@@ -18821,12 +19676,18 @@ var MmtpRouter = class {
18821
19676
  */
18822
19677
  resetKeyframeOverlays(sourcePacketId, catalogTrackName) {
18823
19678
  for (const inst of this.#overlaysForSource(sourcePacketId, catalogTrackName)) this.#resetOverlay(inst);
19679
+ for (const [name, stream] of this.#streams.get(sourcePacketId) ?? []) {
19680
+ if (catalogTrackName !== void 0 && name !== catalogTrackName) continue;
19681
+ stream.overlayToBase.routed.clear();
19682
+ stream.overlayToBase.pending.clear();
19683
+ }
18824
19684
  }
18825
19685
  #resetOverlay(inst) {
18826
19686
  inst.fec.resetTrack(inst.repairPacketId, inst.streamName);
18827
19687
  inst.last = void 0;
18828
19688
  inst.offsets.clear();
18829
19689
  inst.moqBlocks.clear();
19690
+ inst.rebuilt.clear();
18830
19691
  }
18831
19692
  #overlaysForSource(sourcePacketId, catalogTrackName) {
18832
19693
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -18877,18 +19738,33 @@ var MmtpRouter = class {
18877
19738
  * A source packet that carries a 0x8B01 overlay SS_ID is also a symbol of
18878
19739
  * every overlay installed for its source, at that SS_ID, with the bytes the
18879
19740
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
18880
- * included (7.1, 7.4.3).
18881
- */
18882
- #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source) {
19741
+ * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
19742
+ * FEC reads it.
19743
+ *
19744
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
19745
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
19746
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
19747
+ * the stream unstamped at the SS_ID offset it states, for the release gate
19748
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
19749
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
19750
+ */
19751
+ #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
18883
19752
  if (this.#overlays.size === 0) return;
18884
19753
  const ssId = keyframeOverlaySsId(header);
18885
19754
  if (ssId === void 0) return;
19755
+ let rebuiltPsn;
18886
19756
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
18887
19757
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
19758
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
19759
+ inst.rebuilt.delete(ssId);
18888
19760
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
18889
19761
  if (identity !== null) {
18890
19762
  inst.offsets.delete(identity.mpuSequenceNumber);
18891
- inst.offsets.set(identity.mpuSequenceNumber, ssId - sequenceNumber >>> 0);
19763
+ inst.offsets.set(identity.mpuSequenceNumber, {
19764
+ psnOffset: ssId - sequenceNumber >>> 0,
19765
+ overlaySsId: ssId,
19766
+ ...baseSsId === void 0 ? {} : { baseSsId }
19767
+ });
18892
19768
  if (inst.offsets.size > OVERLAY_OFFSET_MPUS) inst.offsets.delete(inst.offsets.keys().next().value);
18893
19769
  }
18894
19770
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -18910,6 +19786,14 @@ var MmtpRouter = class {
18910
19786
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
18911
19787
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
18912
19788
  }
19789
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
19790
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
19791
+ if (rebuiltPsn !== sequenceNumber) {
19792
+ this.#restampedRecoveredSeqs++;
19793
+ } else if (baseSsId !== void 0) {
19794
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19795
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
19796
+ }
18913
19797
  }
18914
19798
  #noteOverlayMoqBlock(inst, blockStart) {
18915
19799
  inst.moqBlocks.add(blockStart);
@@ -18943,11 +19827,16 @@ var MmtpRouter = class {
18943
19827
  }
18944
19828
  /**
18945
19829
  * Route an overlay-recovered block's packets as source media of the
18946
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
18947
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
18948
- * base re-stamp, no block advance. Each packet's wire sequence is restored
18949
- * from its keyframe's own offset; without one, a stream the base never
18950
- * re-stamped keeps the header's sequence and any other drops the packet.
19830
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
19831
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
19832
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
19833
+ * base FEC recovered does, so it waits behind base frames still in flight,
19834
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
19835
+ * longer than unanchored; one whose base SS_ID is undetermined has no
19836
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
19837
+ * advance. Each packet's wire sequence is restored from its keyframe's own
19838
+ * offset; without one, a stream the base never re-stamped keeps the
19839
+ * header's sequence and any other drops the packet.
18951
19840
  */
18952
19841
  #routeOverlayRecovered(inst, blockStart, recovered) {
18953
19842
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -18967,22 +19856,139 @@ var MmtpRouter = class {
18967
19856
  const streamKey = this.#mediaStreamKey(sourcePacketId, sourceName);
18968
19857
  const restamped = this.#restampedStreams.has(streamKey);
18969
19858
  const restored = /* @__PURE__ */ new Set();
19859
+ const baseSsIds = /* @__PURE__ */ new Map();
19860
+ const gateOnly = /* @__PURE__ */ new Set();
18970
19861
  const symbols = result.symbols.flatMap((sym) => {
18971
- const offset = inst.offsets.get(sym.fragment.mpuSequenceNumber);
18972
- if (offset !== void 0) {
18973
- const packetSequenceNumber = serial32Add(blockStart, sym.index) - offset >>> 0;
19862
+ const overlaySsId = serial32Add(blockStart, sym.index);
19863
+ const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
19864
+ if (anchor !== void 0) {
19865
+ const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
18974
19866
  restored.add(packetSequenceNumber);
18975
- return [{ ...sym, packetSequenceNumber }];
19867
+ const out = { ...sym, packetSequenceNumber };
19868
+ const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
19869
+ if (baseSsId !== void 0) {
19870
+ baseSsIds.set(sym.index, baseSsId);
19871
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19872
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
19873
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
19874
+ }
19875
+ }
19876
+ return [out];
19877
+ }
19878
+ if (!restamped) {
19879
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19880
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
19881
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
19882
+ if (baseSsId !== void 0) {
19883
+ baseSsIds.set(sym.index, baseSsId);
19884
+ if (fedSsId === void 0) gateOnly.add(sym.index);
19885
+ } else {
19886
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
19887
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
19888
+ }
19889
+ return [sym];
18976
19890
  }
18977
- if (!restamped) return [sym];
18978
19891
  this.#overlayStats.unsequencedDropped++;
18979
19892
  return [];
18980
19893
  });
18981
19894
  this.#overlayStats.recovered++;
19895
+ const mpuFirst = /* @__PURE__ */ new Map();
19896
+ for (const sym of symbols) {
19897
+ const ssId = baseSsIds.get(sym.index);
19898
+ const mpu = sym.fragment.mpuSequenceNumber;
19899
+ const first = mpuFirst.get(mpu);
19900
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
19901
+ }
19902
+ const firstSsIds = /* @__PURE__ */ new Map();
19903
+ for (const sym of symbols) {
19904
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
19905
+ }
18982
19906
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
18983
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
19907
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
19908
+ baseSsIds,
19909
+ firstSsIds
18984
19910
  });
18985
19911
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
19912
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
19913
+ }
19914
+ /**
19915
+ * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
19916
+ * its base block too, once its base SS_ID is determined (overlayBaseSsId,
19917
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
19918
+ * base recovery showed; `baseSsIds` holds no other),
19919
+ * so it is fed to the base decoder as a rebuilt source
19920
+ * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
19921
+ * fewer to solve, and its repair can recover the block's other packets.
19922
+ * A base block no repair has stated yet takes it when one does
19923
+ * (#feedPendingRebuilt).
19924
+ *
19925
+ * The overlay route already handled each packet fed (delivered it, or
19926
+ * held an untimed head for its FT=1), so a base recovery routes none of
19927
+ * them again (#routeVerifiedFecSymbols): a second recovered copy of a
19928
+ * held head would wait in the parser for timing its first copy consumed.
19929
+ * Only an overlay block decoded from multicast symbols alone is fed: with
19930
+ * a MoQ symbol in it, the base block's recovery would depend on bytes
19931
+ * that crossed no multicast socket, which the provenance counted from the
19932
+ * block's own arrivals cannot show.
19933
+ */
19934
+ #feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds) {
19935
+ const fec = this.#fecManager;
19936
+ const owner = inst.leg.sourcePacketId;
19937
+ const name = inst.leg.sourceCatalogTrackName;
19938
+ if (!fec?.feedRebuiltSourceSymbol || inst.moqBlocks.has(blockStart)) return;
19939
+ if (this.#classifyPacketId(owner) === null || fec.isTrackConfigured?.(owner) === false) return;
19940
+ const { duplicates, overlayToBase: { routed } } = this.#stream(owner, name);
19941
+ const feeds = [];
19942
+ for (const sym of symbols) {
19943
+ if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
19944
+ const ssId = baseSsIds.get(sym.index);
19945
+ if (ssId === void 0) {
19946
+ this.#overlayStats.baseUndetermined++;
19947
+ continue;
19948
+ }
19949
+ routed.delete(ssId);
19950
+ routed.add(ssId);
19951
+ if (routed.size > OVERLAY_ROUTED_LIMIT) routed.delete(routed.values().next().value);
19952
+ feeds.push([ssId, sym.rawSymbol]);
19953
+ }
19954
+ for (const [ssId, symbolData] of feeds) {
19955
+ if (this.#classifyPacketId(owner) === null) return;
19956
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
19957
+ }
19958
+ }
19959
+ /** Feed one rebuilt source to its base block, or keep it until a repair states that block. */
19960
+ #feedRebuiltToBase(owner, name, ssId, symbolData) {
19961
+ const fec = this.#fecManager;
19962
+ if (!fec?.feedRebuiltSourceSymbol) return;
19963
+ const coords = fec.locateIsoSource?.(owner, name, ssId);
19964
+ if (coords == null) {
19965
+ const pending = this.#stream(owner, name).overlayToBase.pending;
19966
+ pending.delete(ssId);
19967
+ pending.set(ssId, symbolData.slice());
19968
+ if (pending.size > OVERLAY_PENDING_LIMIT) pending.delete(pending.keys().next().value);
19969
+ return;
19970
+ }
19971
+ const fed = fec.feedRebuiltSourceSymbol(owner, ssId, symbolData, name);
19972
+ if (!fed.taken) return;
19973
+ this.#overlayStats.baseFed++;
19974
+ if (fed.recovered === null) return;
19975
+ const sbn = coords.sbn;
19976
+ this.#routeRecoveredBlock(sbn, fed.recovered, owner, name, () => {
19977
+ fec.cancelBlockTimeout(sbn, owner, name);
19978
+ fec.countRecovery(owner, sbn, name);
19979
+ fec.markBlockCompleted(sbn, owner, name);
19980
+ });
19981
+ }
19982
+ /** A repair stated `block`: the rebuilt sources that waited for it join it now. */
19983
+ #feedPendingRebuilt(owner, name, block) {
19984
+ const pending = this.#streams.get(owner)?.get(name)?.overlayToBase.pending;
19985
+ if (pending === void 0 || pending.size === 0) return;
19986
+ for (const [ssId, symbolData] of [...pending]) {
19987
+ if (this.#classifyPacketId(owner) === null) return;
19988
+ if (serial32Distance(block.start, ssId) >= block.length) continue;
19989
+ pending.delete(ssId);
19990
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
19991
+ }
18986
19992
  }
18987
19993
  /** fec-multicast-00 §6.6: report each base block whose RAP MFU fragments
18988
19994
  * the overlay restored, when the keyframe's FT=0 and FT=1 are held too. A
@@ -19122,6 +20128,10 @@ var MmtpRouter = class {
19122
20128
  get unadmittedListedDropCount() {
19123
20129
  return this.#unadmittedListedDrops;
19124
20130
  }
20131
+ /** 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. */
20132
+ get admittedSourceDatagramCount() {
20133
+ return this.#admittedSourceDatagrams;
20134
+ }
19125
20135
  /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
19126
20136
  get unlistedRepairSetAsideCount() {
19127
20137
  return this.#unlistedRepairSetAside;
@@ -19608,6 +20618,8 @@ var MmtpRouter = class {
19608
20618
  )) return;
19609
20619
  fec.noteBlockActivity?.(blockStart, ownerPacketId, catalogTrackName);
19610
20620
  fec.noteRepairGroupLength?.(blockStart, ownerPacketId, repair.rsbLength, catalogTrackName);
20621
+ this.#feedPendingRebuilt(ownerPacketId, catalogTrackName, placement.block);
20622
+ if (this.#classifyPacketId(ownerPacketId) === null) return;
19611
20623
  const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
19612
20624
  const recovered = fec.feedRepairSymbol(
19613
20625
  ownerPacketId,
@@ -19658,7 +20670,7 @@ var MmtpRouter = class {
19658
20670
  catalogTrackName
19659
20671
  )) continue;
19660
20672
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
19661
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
20673
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
19662
20674
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
19663
20675
  }
19664
20676
  if (payload.oversized) continue;
@@ -19745,6 +20757,8 @@ var MmtpRouter = class {
19745
20757
  this.#droppedPreSyncVideo.delete(streamKey);
19746
20758
  this.#latestVideoSeqByStream.delete(streamKey);
19747
20759
  this.#ssIdSeqOffsetByStream.delete(streamKey);
20760
+ this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
20761
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
19748
20762
  this.#multicastRapTwinByStream.delete(streamKey);
19749
20763
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
19750
20764
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -19871,6 +20885,12 @@ var MmtpRouter = class {
19871
20885
  * the outgoing stream stops. The hold is bounded by the incoming stream's
19872
20886
  * own RAP cadence, so no timer is involved.
19873
20887
  *
20888
+ * While the switch is staged, the FEC release gate lets a keyframe the
20889
+ * overlay rebuilt reach it, on either side, when the keyframe did before
20890
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
20891
+ * decides on what each side delivered, and the commit discards the gate's
20892
+ * frames of the outgoing stream.
20893
+ *
19874
20894
  * The commit is one synchronous transition inside the frame path: the
19875
20895
  * outgoing stream's already-admitted frames are released (its queued FEC
19876
20896
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -19921,6 +20941,9 @@ var MmtpRouter = class {
19921
20941
  droppedIncomingFrames: 0
19922
20942
  };
19923
20943
  this.#staged = state;
20944
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
20945
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
20946
+ }
19924
20947
  return {
19925
20948
  cancel: () => {
19926
20949
  if (this.#staged !== state) return false;
@@ -20003,7 +21026,17 @@ var MmtpRouter = class {
20003
21026
  */
20004
21027
  #routeParsedFrame(data, meta) {
20005
21028
  if (this.#classifyPacketId(meta.packetId) === null) return;
20006
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
21029
+ if (this.#staged !== null) {
21030
+ let consumed = false;
21031
+ this.#fecPokeDepth++;
21032
+ try {
21033
+ consumed = this.#interceptSwitchFrame(data, meta);
21034
+ } finally {
21035
+ this.#fecPokeDepth--;
21036
+ this.#flushPendingFecPokes();
21037
+ }
21038
+ if (consumed) return;
21039
+ }
20007
21040
  this.#deliverParsedFrame(data, meta);
20008
21041
  }
20009
21042
  #commitStreamSwitch(state, rap, reason) {
@@ -20052,6 +21085,8 @@ var MmtpRouter = class {
20052
21085
  this.#disposed = true;
20053
21086
  this.#staged = null;
20054
21087
  this.cancelKeyframeLostTimer();
21088
+ for (const { timer } of this.#fecWakes.values()) clearTimeout(timer);
21089
+ this.#fecWakes.clear();
20055
21090
  this.#parser.dispose();
20056
21091
  this.#streams.clear();
20057
21092
  this.#trackPacketCallbacks.clear();
@@ -20155,12 +21190,16 @@ var MmtpRouter = class {
20155
21190
  this.#parser.deferFecRelease(work);
20156
21191
  } finally {
20157
21192
  this.#fecPokeDepth--;
20158
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
20159
- const pokes = [...this.#pendingFecPokes.values()];
20160
- this.#pendingFecPokes.clear();
20161
- for (const poke of pokes) {
20162
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20163
- }
21193
+ this.#flushPendingFecPokes();
21194
+ }
21195
+ }
21196
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
21197
+ #flushPendingFecPokes() {
21198
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
21199
+ const pokes = [...this.#pendingFecPokes.values()];
21200
+ this.#pendingFecPokes.clear();
21201
+ for (const poke of pokes) {
21202
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20164
21203
  }
20165
21204
  }
20166
21205
  }
@@ -20229,6 +21268,31 @@ var MmtpRouter = class {
20229
21268
  if (!fec?.terminalRetentionMsForPacket) return Infinity;
20230
21269
  return fec.terminalRetentionMsForPacket(packetId) ?? 0;
20231
21270
  },
21271
+ // Once no repair can fill a gap (FECManager.isoRepairlessWaitMs: only a
21272
+ // late source can), its frame waits the late-symbol allowance when the
21273
+ // gap holds no RAP an installed keyframe overlay could still rebuild:
21274
+ // lost deltas of one MPU (delta-lost), the tail of the MPU before a RAP
21275
+ // that opens the next one while MPU boundaries bound RAPs (rap-next,
21276
+ // unless the gap holds a stated block's loss: the overlay may rebuild
21277
+ // that MPU's FT=0, and the block's group then complete it), or
21278
+ // an audio gap. A gap that may hold one (rap-lost, rap-unknown, or any
21279
+ // other rap-next, whose gap may hold a whole MPU and the keyframe the
21280
+ // overlay protects) waits for that overlay's repair too (BLO-52085
21281
+ // D4). The FEC check comes first: most held gaps are not behind such a
21282
+ // span, and deciding one scans both frames' bitstreams.
21283
+ unrepairableWaitMs: (before, after, fromSbn, toSbn) => {
21284
+ const fec = this.#fecManager;
21285
+ const { packetId, catalogTrackName } = after.meta;
21286
+ const allowanceMs = fec?.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn);
21287
+ if (!fec || allowanceMs === void 0) return void 0;
21288
+ const decision = this.#decideGap(before, after, [], false);
21289
+ const mpu = before.meta.mpuSequenceNumber;
21290
+ const intoNextMpu = decision.reason === "rap-next" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu + 1 >>> 0 && fec.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
21291
+ if (decision.action === "stall" || decision.reason === "rap-next" && !intoNextMpu) {
21292
+ return fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, true);
21293
+ }
21294
+ return decision.reason === "rap-next" ? fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, true) : allowanceMs;
21295
+ },
20232
21296
  decide: (before, after, lostBlocks, discontinuity) => {
20233
21297
  const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
20234
21298
  this.#onFrameGap?.(decision);
@@ -20238,6 +21302,28 @@ var MmtpRouter = class {
20238
21302
  onRap: (packetId, catalogTrackName, ssId) => {
20239
21303
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
20240
21304
  },
21305
+ // One timer per stream, at the earliest wake asked: its drain re-arms
21306
+ // for the next frame still waiting.
21307
+ wakeAt: (packetId, catalogTrackName, atMs) => {
21308
+ if (this.#disposed) return;
21309
+ const key = this.#mediaStreamKey(packetId, catalogTrackName);
21310
+ const armed = this.#fecWakes.get(key);
21311
+ if (armed !== void 0 && armed.atMs <= atMs) return;
21312
+ if (armed !== void 0) clearTimeout(armed.timer);
21313
+ const timer = setTimeout(() => {
21314
+ this.#fecWakes.delete(key);
21315
+ this.#requestFecPoke(packetId, catalogTrackName);
21316
+ }, Math.max(0, Math.ceil(atMs - performance.now())));
21317
+ this.#fecWakes.set(key, { atMs, timer });
21318
+ },
21319
+ // A staged switch commits on when each side's frames reach it
21320
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
21321
+ // they did unanchored.
21322
+ releaseUnanchored: (packetId, catalogTrackName) => {
21323
+ const staged = this.#staged;
21324
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
21325
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
21326
+ },
20241
21327
  onReleased: (data, meta) => {
20242
21328
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
20243
21329
  const timing = meta.authoredTiming;
@@ -20265,7 +21351,7 @@ var MmtpRouter = class {
20265
21351
  #decideGap(before, after, lostBlocks, discontinuity) {
20266
21352
  const { packetId, catalogTrackName } = after.meta;
20267
21353
  const trackKind = this.#classifyPacketId(packetId) === false ? "audio" : "video";
20268
- const positionsTrusted = this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying";
21354
+ const positionsTrusted = this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying" && before.meta.movieFragmentSequenceNumber === after.meta.movieFragmentSequenceNumber;
20269
21355
  const mpuTrusted = this.#fecManager?.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
20270
21356
  const evidence = (frame) => {
20271
21357
  const timing = frame.meta.authoredTiming;
@@ -20379,6 +21465,7 @@ var MmtpRouter = class {
20379
21465
  const parsed = this.#parser.parsePacket(packet);
20380
21466
  if (!parsed) return;
20381
21467
  const info = parsed.info;
21468
+ if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
20382
21469
  if (source === "multicast" && !manifestAdmitted) {
20383
21470
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
20384
21471
  }
@@ -20660,7 +21747,8 @@ var MmtpRouter = class {
20660
21747
  parsed.header,
20661
21748
  info.sequenceNumber,
20662
21749
  info.rapFlag,
20663
- source
21750
+ source,
21751
+ fecPayloadId?.ssId
20664
21752
  );
20665
21753
  }
20666
21754
  }
@@ -20686,7 +21774,8 @@ var MmtpRouter = class {
20686
21774
  source: parserOptions?.source,
20687
21775
  deliveryProvenance: parserOptions?.deliveryProvenance,
20688
21776
  catalogTrackName: parserOptions?.catalogTrackName,
20689
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
21777
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
21778
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
20690
21779
  };
20691
21780
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
20692
21781
  else this.#parser.feed(packet, feedOptions);
@@ -20810,7 +21899,8 @@ var MmtpRouter = class {
20810
21899
  if (stream === void 0) {
20811
21900
  stream = {
20812
21901
  key: JSON.stringify([packetId, catalogTrackName ?? null]),
20813
- duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId))
21902
+ duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId)),
21903
+ overlayToBase: { routed: /* @__PURE__ */ new Set(), pending: /* @__PURE__ */ new Map() }
20814
21904
  };
20815
21905
  byName.set(catalogTrackName, stream);
20816
21906
  }
@@ -20925,8 +22015,16 @@ var MmtpRouter = class {
20925
22015
  this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
20926
22016
  this.#emitDirectVideo(packetId, data, meta, cb);
20927
22017
  }
20928
- #routeDirectRecoveredVideo(packetId, data, meta, cb) {
22018
+ #routeDirectRecoveredVideo(packetId, data, meta, cb, fecSbn) {
20929
22019
  const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);
22020
+ if (this.#isFecTrack(packetId)) {
22021
+ const high = this.#deliveredVideoHighWaterByStream.get(streamKey);
22022
+ if (fecSbn !== void 0 || high !== void 0 && authoredAdjacent(high, meta)) {
22023
+ this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
22024
+ this.#emitDirectVideo(packetId, data, meta, cb);
22025
+ return;
22026
+ }
22027
+ }
20930
22028
  this.#enqueueDirectRecoveredVideo(packetId, data, meta);
20931
22029
  const lastSourceTs = this.#lastDirectSourceVideoTsByStream.get(streamKey);
20932
22030
  this.#drainDirectRecoveredVideo(
@@ -21080,6 +22178,13 @@ var MmtpRouter = class {
21080
22178
  * frames by epoch only if pre-protection input ever matters.
21081
22179
  */
21082
22180
  #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete, assisted = false) {
22181
+ const overlayRouted = ownerPacketId == null ? void 0 : this.#streams.get(ownerPacketId)?.get(catalogTrackName)?.overlayToBase.routed;
22182
+ if (overlayRouted !== void 0 && overlayRouted.size > 0) {
22183
+ result = {
22184
+ ...result,
22185
+ symbols: result.symbols.filter((sym) => !overlayRouted.has(this.#fecAnchorForRecovered(blockId, sym.index)))
22186
+ };
22187
+ }
21083
22188
  const entry = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
21084
22189
  const receiver = entry === void 0 || entry === "ambiguous" ? entry : entry.receiver;
21085
22190
  const userAgent = !assisted && entry !== void 0 && entry !== "ambiguous" && entry.protected === true && entry.userAgent === true;
@@ -21136,7 +22241,12 @@ var MmtpRouter = class {
21136
22241
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
21137
22242
  if (ownerPacketId == null) return;
21138
22243
  if (this.#classifyPacketId(ownerPacketId) === null) return;
21139
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
22244
+ const fecSbnOf = (index) => {
22245
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
22246
+ const fecSbn = overlay.baseSsIds.get(index);
22247
+ const fecSbnFirst = overlay.firstSsIds.get(index);
22248
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
22249
+ };
21140
22250
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
21141
22251
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
21142
22252
  if (ssIdSeqOffset !== void 0) {
@@ -21144,7 +22254,10 @@ var MmtpRouter = class {
21144
22254
  ...result,
21145
22255
  symbols: result.symbols.map((sym) => {
21146
22256
  const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
21147
- if (wire === sym.packetSequenceNumber) return sym;
22257
+ if (wire === sym.packetSequenceNumber) {
22258
+ this.#unstampedSsIdSeqOffsetByStream.set(streamKey, ssIdSeqOffset);
22259
+ return sym;
22260
+ }
21148
22261
  this.#restampedRecoveredSeqs++;
21149
22262
  this.#restampedStreams.add(streamKey);
21150
22263
  return { ...sym, packetSequenceNumber: wire };
@@ -21180,16 +22293,29 @@ var MmtpRouter = class {
21180
22293
  }
21181
22294
  );
21182
22295
  }
21183
- result = {
21184
- ...result,
21185
- symbols: result.symbols.filter((sym) => sym.fragmentType !== 2 || sym.fragment.fragmentationIndicator !== 1 || sym.fragment.movieFragmentSequenceNumber === void 0 || sym.fragment.sampleNumber === void 0 || this.#parser.hasAuthoredTimingFor(
21186
- ownerPacketId,
21187
- sym.fragment.mpuSequenceNumber,
21188
- sym.fragment.movieFragmentSequenceNumber,
21189
- sym.fragment.sampleNumber,
21190
- catalogTrackName
21191
- ))
21192
- };
22296
+ const untimedHead = (sym) => sym.fragmentType === 2 && sym.fragment.fragmentationIndicator === 1 && sym.fragment.movieFragmentSequenceNumber !== void 0 && sym.fragment.sampleNumber !== void 0 && !this.#parser.hasAuthoredTimingFor(
22297
+ ownerPacketId,
22298
+ sym.fragment.mpuSequenceNumber,
22299
+ sym.fragment.movieFragmentSequenceNumber,
22300
+ sym.fragment.sampleNumber,
22301
+ catalogTrackName
22302
+ );
22303
+ for (const sym of result.symbols) {
22304
+ if (!untimedHead(sym) || this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) continue;
22305
+ this.#feedViaParser(
22306
+ sym.rawSymbol,
22307
+ { packetId: ownerPacketId, sequenceNumber: sym.packetSequenceNumber },
22308
+ void 0,
22309
+ {
22310
+ skipFecPayloadId: true,
22311
+ recovered: true,
22312
+ deliveryProvenance,
22313
+ ...fecSbnOf(sym.index),
22314
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
22315
+ }
22316
+ );
22317
+ }
22318
+ result = { ...result, symbols: result.symbols.filter((sym) => !untimedHead(sym)) };
21193
22319
  const gated = this.#isFecTrack(ownerPacketId);
21194
22320
  const assembler = this.#mseAssemblerFor(ownerPacketId, catalogTrackName);
21195
22321
  if (assembler) {
@@ -22666,6 +23792,12 @@ function isNonNegativeSafeInteger(value) {
22666
23792
  function isSymbolCounts(value) {
22667
23793
  return isRecord(value) && hasExactKeys(value, ["multicast", "moq"]) && isNonNegativeSafeInteger(value["multicast"]) && isNonNegativeSafeInteger(value["moq"]);
22668
23794
  }
23795
+ function isSpanFailure(value) {
23796
+ if (!isRecord(value) || !hasExactKeys(value, ["length", "sources"])) return false;
23797
+ const length = value["length"];
23798
+ const sources = value["sources"];
23799
+ return Number.isSafeInteger(length) && length > 0 && isNonNegativeSafeInteger(sources) && sources < length;
23800
+ }
22669
23801
  function isNullableNonNegative(value) {
22670
23802
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
22671
23803
  }
@@ -22685,7 +23817,10 @@ function isRepairLifecycleEvent(value) {
22685
23817
  case "recovered":
22686
23818
  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"]);
22687
23819
  case "failed":
22688
- return hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]);
23820
+ return hasExactKeys(
23821
+ value,
23822
+ "span" in value ? ["version", "type", "block", "blockClass", "symbols", "span"] : ["version", "type", "block", "blockClass", "symbols"]
23823
+ ) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]) && (!("span" in value) || isSpanFailure(value["span"]));
22689
23824
  case "repair-preempted":
22690
23825
  case "repair-deferred":
22691
23826
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
@@ -22894,6 +24029,8 @@ var MulticastManager = class {
22894
24029
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
22895
24030
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
22896
24031
  #repairReleases = /* @__PURE__ */ new Map();
24032
+ /** Protected repair flows owned by each live repair-endpoint release. */
24033
+ #repairProvenanceFlows = /* @__PURE__ */ new Map();
22897
24034
  /** Each source's catalog keyframe overlay, from its `ok` binding. */
22898
24035
  #overlayBindings = /* @__PURE__ */ new Map();
22899
24036
  /** Installed overlay decoders (`setKeyframeOverlayDecoder`), by source. */
@@ -22951,7 +24088,7 @@ var MulticastManager = class {
22951
24088
  onPublisherRestart: (packetId, catalogTrackName) => {
22952
24089
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
22953
24090
  },
22954
- onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
24091
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass, span) => {
22955
24092
  const pathCount = this.#fec.blockPathCount(
22956
24093
  sbn,
22957
24094
  packetId,
@@ -22969,7 +24106,8 @@ var MulticastManager = class {
22969
24106
  symbols: {
22970
24107
  multicast: pathCount?.multicastSymbols ?? 0,
22971
24108
  moq: pathCount?.moqSymbols ?? 0
22972
- }
24109
+ },
24110
+ ...span === void 0 ? {} : { span }
22973
24111
  });
22974
24112
  },
22975
24113
  onFrameGap: (decision) => {
@@ -23057,6 +24195,11 @@ var MulticastManager = class {
23057
24195
  this.#fec.onBlockVanished = (_sbn, packetId, catalogTrackName) => {
23058
24196
  this.#statsFor(packetId, catalogTrackName).vanishedBlocks++;
23059
24197
  };
24198
+ this.#fec.keyframeOverlayTiming = (packetId, catalogTrackName) => {
24199
+ const binding = this.#overlayInstalls.has(packetId) ? this.#overlayBindings.get(packetId) : void 0;
24200
+ if (binding === void 0) return void 0;
24201
+ return catalogTrackName === void 0 || catalogTrackName === binding.sourceCatalogTrackName ? binding.geometry : void 0;
24202
+ };
23060
24203
  this.#fec.onDecoderUnavailable = (event) => {
23061
24204
  this.#emitRepairLifecycle({
23062
24205
  version: 2,
@@ -23559,6 +24702,9 @@ var MulticastManager = class {
23559
24702
  this.#transport.onFailback((reason) => {
23560
24703
  const joined = this.#provenanceJoin;
23561
24704
  if (joined !== null) this.#router.unprotectProvenanceFlow(joined.flow);
24705
+ for (const flows of this.#repairProvenanceFlows.values()) {
24706
+ for (const flow of flows) this.#router.unprotectProvenanceFlow(flow);
24707
+ }
23562
24708
  this.#onFailback?.(reason);
23563
24709
  });
23564
24710
  }
@@ -23593,6 +24739,12 @@ var MulticastManager = class {
23593
24739
  "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
23594
24740
  );
23595
24741
  }
24742
+ if (provenanceFlow !== void 0) {
24743
+ const flow = multicastProvenanceFlowKey(provenanceFlow);
24744
+ if ([...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
24745
+ throw new TypeError(`[MulticastManager] join: provenance flow already registered by a repair endpoint: ${flow}`);
24746
+ }
24747
+ }
23596
24748
  const staged = this.#renditionSwitch;
23597
24749
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
23598
24750
  this.configureFec(config);
@@ -23600,8 +24752,8 @@ var MulticastManager = class {
23600
24752
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
23601
24753
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
23602
24754
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
23603
- this.#releaseProvenanceJoin();
23604
24755
  const provenance = config.provenance;
24756
+ this.#releaseProvenanceJoin();
23605
24757
  const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
23606
24758
  const ingress = protectedTracks === void 0 ? void 0 : {
23607
24759
  tracks: Object.freeze(
@@ -23654,8 +24806,13 @@ var MulticastManager = class {
23654
24806
  * feeds the flow's receiver; media datagrams are held until one admits them.
23655
24807
  */
23656
24808
  #joinProvenance(provenance, ingress) {
24809
+ this.#router.registerProvenanceFlow(ingress, this.#provenanceReceiver(provenance));
24810
+ this.#hookFailback();
24811
+ this.#provenanceJoin = { flow: ingress.flow };
24812
+ }
24813
+ #provenanceReceiver(provenance) {
23657
24814
  const { flow, auth } = provenance;
23658
- const receiver = new BcProvenanceV2Receiver({
24815
+ return new BcProvenanceV2Receiver({
23659
24816
  ...provenance.receiver,
23660
24817
  // The caller's ctx when it passes one, else the catalog's: an explicit
23661
24818
  // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
@@ -23672,9 +24829,6 @@ var MulticastManager = class {
23672
24829
  maxAuthDelayMs: flow.maxAuthDelayMs,
23673
24830
  manifestTimerMs: flow.manifestTimerMs
23674
24831
  });
23675
- this.#router.registerProvenanceFlow(ingress, receiver);
23676
- this.#hookFailback();
23677
- this.#provenanceJoin = { flow: ingress.flow };
23678
24832
  }
23679
24833
  /** Un-protect: drop the flow's hold queues (no expiry counted). */
23680
24834
  #releaseProvenanceJoin() {
@@ -23705,8 +24859,25 @@ var MulticastManager = class {
23705
24859
  * callback delivers must come from a subscription opened on
23706
24860
  * `options.gateway`. A callback that also merges another source (a MoQ or
23707
24861
  * WebSocket repair feed) must not name a native provider here.
24862
+ *
24863
+ * An endpoint's `provenance` makes its group a protected flow of its own
24864
+ * (multicast-02 7.2.7), registered here and released with the group; its
24865
+ * records ride in band on the group's port. On the user-agent path a
24866
+ * flow-less repair group of a protected track is set aside, never read, so
24867
+ * a player joining a protected catalog's repair groups passes it.
23708
24868
  */
23709
24869
  joinRepairEndpoints(endpoints, provider, options) {
24870
+ for (const { provenance, flow, source, group, port } of endpoints) {
24871
+ if (provenance === void 0) continue;
24872
+ if (flow !== void 0) {
24873
+ throw new TypeError("[MulticastManager] joinRepairEndpoints: an endpoint names provenance or flow, never both");
24874
+ }
24875
+ if (!sameIpAddress(source, provenance.flow.source) || !sameIpAddress(group, provenance.flow.groupAddress) || port !== provenance.flow.port) {
24876
+ throw new RangeError(
24877
+ "[MulticastManager] joinRepairEndpoints: provenance flow (S, G, port) must match the endpoint's source, group and port"
24878
+ );
24879
+ }
24880
+ }
23710
24881
  const releases = [];
23711
24882
  let released = false;
23712
24883
  const safely = (each) => {
@@ -23716,17 +24887,36 @@ var MulticastManager = class {
23716
24887
  console.warn("[MulticastManager] repair group release failed", error);
23717
24888
  }
23718
24889
  };
24890
+ const usedFlows = new Set(endpoints.flatMap(({ flow }) => flow === void 0 ? [] : [flow]));
24891
+ const preparedProvenance = endpoints.map((endpoint) => {
24892
+ if (endpoint.provenance === void 0) return void 0;
24893
+ const flow = multicastProvenanceFlowKey(endpoint.provenance.flow);
24894
+ if (usedFlows.has(flow) || this.#provenanceJoin?.flow === flow || [...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
24895
+ throw new TypeError(`[MulticastManager] joinRepairEndpoints: provenance flow already registered: ${flow}`);
24896
+ }
24897
+ usedFlows.add(flow);
24898
+ return { flow, receiver: this.#provenanceReceiver(endpoint.provenance) };
24899
+ });
24900
+ const provenanceFlows = [];
23719
24901
  const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners.map((owner) => owner.instance !== "keyframe" ? owner : {
23720
24902
  ...owner,
23721
24903
  ownerTrackName: endpoint.tracks.find((t) => t.packetId === owner.ownerPacketId)?.name,
23722
24904
  repairTrackName: endpoint.tracks.find((t) => t.packetId === owner.packetId)?.name
23723
24905
  }));
23724
24906
  this.#applyRepairOwners(repairOwners);
23725
- for (const endpoint of endpoints) {
24907
+ for (const [index, endpoint] of endpoints.entries()) {
24908
+ const flow = endpoint.provenance === void 0 ? endpoint.flow : multicastProvenanceFlowKey(endpoint.provenance.flow);
23726
24909
  const ingress = {
23727
24910
  tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
23728
- ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
24911
+ ...flow === void 0 ? {} : { flow }
23729
24912
  };
24913
+ if (endpoint.provenance !== void 0) {
24914
+ const prepared = preparedProvenance[index];
24915
+ if (prepared === void 0) throw new Error("[MulticastManager] repair provenance preparation missing");
24916
+ this.#router.registerProvenanceFlow(ingress, prepared.receiver);
24917
+ provenanceFlows.push(prepared.flow);
24918
+ releases.push(() => this.#router.releaseProvenanceFlow(flow));
24919
+ }
23730
24920
  let sender;
23731
24921
  const feed = (packet, sourceAddress, ingressToFeed) => {
23732
24922
  if (released) return;
@@ -23756,7 +24946,7 @@ var MulticastManager = class {
23756
24946
  packetIds: endpoint.packetIds,
23757
24947
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
23758
24948
  // A protected repair group's records ride in band on its port (7.2.3).
23759
- ...endpoint.flow === void 0 ? {} : { protected: true }
24949
+ ...flow === void 0 ? {} : { protected: true }
23760
24950
  }, ingress).then((joined) => {
23761
24951
  if (!joined && !released) fail(transport.lastJoinOutcome);
23762
24952
  });
@@ -23765,9 +24955,12 @@ var MulticastManager = class {
23765
24955
  if (released) return;
23766
24956
  released = true;
23767
24957
  this.#repairReleases.delete(release);
24958
+ this.#repairProvenanceFlows.delete(release);
23768
24959
  for (const each of releases.splice(0)) safely(each);
23769
24960
  };
23770
24961
  this.#repairReleases.set(release, repairOwners);
24962
+ this.#repairProvenanceFlows.set(release, provenanceFlows);
24963
+ if (provenanceFlows.length) this.#hookFailback();
23771
24964
  return release;
23772
24965
  }
23773
24966
  #applyRepairOwners(owners) {
@@ -24253,7 +25446,8 @@ var MulticastManager = class {
24253
25446
  blockProfile: parseFecBlockProfile(
24254
25447
  geometry2.blockProfile,
24255
25448
  `tracks[${JSON.stringify(track.name)}].fec keyframe overlay blockProfile`
24256
- )
25449
+ ),
25450
+ geometry: geometry2
24257
25451
  });
24258
25452
  }
24259
25453
  }
@@ -24292,7 +25486,7 @@ var MulticastManager = class {
24292
25486
  for (const [sourcePacketId, install] of [...this.#overlayInstalls]) {
24293
25487
  const before = this.#overlayBindings.get(sourcePacketId);
24294
25488
  const after = overlayBindings.get(sourcePacketId);
24295
- const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => after[key] === before[key]);
25489
+ const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => key === "geometry" || after[key] === before[key]);
24296
25490
  if (!same) install.dispose();
24297
25491
  else if (this.#router.hasKeyframeOverlay(after.repairPacketId)) this.#router.resetKeyframeOverlays(sourcePacketId);
24298
25492
  else install.reattach();
@@ -24349,10 +25543,12 @@ var MulticastManager = class {
24349
25543
  * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
24350
25544
  * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
24351
25545
  * pending hole and reported here, and `closeIsoHoles` must be called for it
24352
- * once its range FETCH ends (or none is sent).
25546
+ * once its range FETCH ends (or none is sent). `onExpired` is told of a
25547
+ * pending hole the stream runs past the locator's horizon: returning true,
25548
+ * the caller closes it (`closeIsoHoles`); otherwise it is discarded.
24353
25549
  */
24354
- onUndelimitedLoss(cb) {
24355
- this.#fec.setUndelimitedLossHandler(cb);
25550
+ onUndelimitedLoss(cb, onExpired) {
25551
+ this.#fec.setUndelimitedLossHandler(cb, onExpired ?? null);
24356
25552
  }
24357
25553
  /**
24358
25554
  * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
@@ -24588,7 +25784,8 @@ var MulticastManager = class {
24588
25784
  "stream" in event ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
24589
25785
  ...event,
24590
25786
  block: Object.freeze({ ...event.block }),
24591
- ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {}
25787
+ ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {},
25788
+ ..."span" in event && event.span !== void 0 ? { span: Object.freeze({ ...event.span }) } : {}
24592
25789
  }
24593
25790
  );
24594
25791
  if (this.#logRepairLifecycle) {