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

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 (54) hide show
  1. package/dist/browser-runtime.js +891 -141
  2. package/dist/browser-runtime.js.map +3 -3
  3. package/dist/delta-fallback-config.js.map +1 -1
  4. package/dist/fec-manager.d.ts +67 -11
  5. package/dist/fec-manager.d.ts.map +1 -1
  6. package/dist/fec-manager.js +283 -54
  7. package/dist/fec-manager.js.map +2 -2
  8. package/dist/fec-worker-setup.js.map +1 -1
  9. package/dist/index.d.ts +1 -1
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js.map +2 -2
  12. package/dist/iso-block-locator.d.ts +39 -13
  13. package/dist/iso-block-locator.d.ts.map +1 -1
  14. package/dist/iso-block-locator.js +80 -25
  15. package/dist/iso-block-locator.js.map +2 -2
  16. package/dist/media-router.js.map +1 -1
  17. package/dist/mmtp-container-parser.d.ts +42 -8
  18. package/dist/mmtp-container-parser.d.ts.map +1 -1
  19. package/dist/mmtp-container-parser.js +121 -17
  20. package/dist/mmtp-container-parser.js.map +2 -2
  21. package/dist/mmtp-container-parser.no-modules.js +120 -18
  22. package/dist/mmtp-container-parser.no-modules.js.map +2 -2
  23. package/dist/mmtp-decode-pipeline.js +121 -17
  24. package/dist/mmtp-decode-pipeline.js.map +2 -2
  25. package/dist/mmtp-router.d.ts +28 -8
  26. package/dist/mmtp-router.d.ts.map +1 -1
  27. package/dist/mmtp-router.js +407 -52
  28. package/dist/mmtp-router.js.map +2 -2
  29. package/dist/multicast-manager.d.ts +13 -3
  30. package/dist/multicast-manager.d.ts.map +1 -1
  31. package/dist/multicast-manager.js +712 -115
  32. package/dist/multicast-manager.js.map +2 -2
  33. package/dist/multicast-transport.js +2 -2
  34. package/dist/multicast-transport.js.map +2 -2
  35. package/dist/no-modules.js +121 -17
  36. package/dist/no-modules.js.map +2 -2
  37. package/dist/repair-fetch.d.ts +36 -8
  38. package/dist/repair-fetch.d.ts.map +1 -1
  39. package/dist/repair-fetch.js +285 -26
  40. package/dist/repair-fetch.js.map +3 -3
  41. package/dist/track-session.d.ts.map +1 -1
  42. package/dist/track-session.js +1 -0
  43. package/dist/track-session.js.map +2 -2
  44. package/dist/wasm-mmtp-container-parser.js +121 -17
  45. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  46. package/package.json +5 -5
  47. package/src/fec-manager.ts +304 -28
  48. package/src/index.ts +2 -0
  49. package/src/iso-block-locator.ts +114 -31
  50. package/src/mmtp-container-parser.ts +210 -21
  51. package/src/mmtp-router.ts +488 -45
  52. package/src/multicast-manager.ts +44 -6
  53. package/src/repair-fetch.ts +363 -49
  54. package/src/track-session.ts +3 -0
@@ -1189,6 +1189,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
1189
1189
  this.#heldEvicted = 0;
1190
1190
  /** Pending holes (see `deferIncompleteGaps`): unstated, sources still held. */
1191
1191
  this.#holes = [];
1192
+ /** Holes the horizon passed while pending: sources held until closed. */
1193
+ this.#expired = [];
1194
+ /** Of `#expired`, those `takeExpiredHoles` has not handed out yet. */
1195
+ this.#newlyExpired = [];
1196
+ /**
1197
+ * Spans closed from expired holes: behind the horizon, so kept only for
1198
+ * `locate` while their sources are fed, until the next retirement.
1199
+ */
1200
+ this.#closedBehind = [];
1192
1201
  /**
1193
1202
  * Keep a gap that is missing a source as a pending hole rather than a span,
1194
1203
  * so a repair FETCHed for it (draft-ramadan-moq-fec §7.5) can still state
@@ -1212,6 +1221,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
1212
1221
  #newest;
1213
1222
  #newestSource;
1214
1223
  #holes;
1224
+ #expired;
1225
+ #newlyExpired;
1226
+ #closedBehind;
1215
1227
  static #checkedRetention(retentionBlocks) {
1216
1228
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
1217
1229
  throw new Error(
@@ -1281,17 +1293,29 @@ var IsoBlockLocator = class _IsoBlockLocator {
1281
1293
  }
1282
1294
  /** The known block or span containing `ssId`, with its ESI. */
1283
1295
  locate(ssId) {
1284
- for (let i = this.#blocks.length - 1; i >= 0; i--) {
1285
- const block = this.#blocks[i];
1286
- if (isoBlockContains(block.start, block.length, ssId)) {
1287
- return { block, esi: serial32Distance(block.start, ssId) };
1296
+ for (const blocks of [this.#blocks, this.#closedBehind]) {
1297
+ for (let i = blocks.length - 1; i >= 0; i--) {
1298
+ const block = blocks[i];
1299
+ if (isoBlockContains(block.start, block.length, ssId)) {
1300
+ return { block, esi: serial32Distance(block.start, ssId) };
1301
+ }
1288
1302
  }
1289
1303
  }
1290
1304
  return null;
1291
1305
  }
1292
- /** Number of pending holes. */
1306
+ /** Number of holes not closed yet, pending or past the horizon. */
1293
1307
  get holeCount() {
1294
- return this.#holes.length;
1308
+ return this.#holes.length + this.#expired.length;
1309
+ }
1310
+ /**
1311
+ * The pending holes the horizon has passed since the last call, in the
1312
+ * order it passed them. Each is no longer pending: no repair states a block
1313
+ * in it (that repair is `stale`, as for a span the horizon retired) and the
1314
+ * release gate does not wait for it. Its owner must close it
1315
+ * (`closeHolesWithin`), which turns it into a span that is not kept here.
1316
+ */
1317
+ takeExpiredHoles() {
1318
+ return this.#newlyExpired.splice(0);
1295
1319
  }
1296
1320
  /** The stated block (never a span) ending exactly at `end`. */
1297
1321
  blockEndingAt(end) {
@@ -1347,9 +1371,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
1347
1371
  /**
1348
1372
  * Apply one repair symbol's `(SS_Start, SSB_length)`. The first repair of a
1349
1373
  * block states its range and places every held source in it; later repair
1350
- * symbols of the same block change nothing. A range that contradicts a
1351
- * known block (a different length, or an overlap with another block or a
1352
- * span) fails closed: the repair symbol is dropped and no block changes.
1374
+ * symbols of the same block change nothing. A repair whose range is exactly
1375
+ * a repair-less span states that span's one block. A range that contradicts
1376
+ * a known block (a different length, or an overlap with another block or
1377
+ * with part of a span) fails closed: the repair symbol is dropped and no
1378
+ * block changes.
1353
1379
  * A newly stated block retires behind its SS_Start (see the class note).
1354
1380
  * A block so far past `newest` that stating it would retire the position
1355
1381
  * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
@@ -1368,7 +1394,16 @@ var IsoBlockLocator = class _IsoBlockLocator {
1368
1394
  const known = this.blockAt(start);
1369
1395
  if (known !== void 0) {
1370
1396
  if (known.span) {
1371
- return { status: "overlap", reason: `repair block ${start}+${length} falls inside a repair-less span` };
1397
+ if (known.length === length) {
1398
+ const block2 = { start, length, span: false };
1399
+ this.#blocks[this.#blocks.indexOf(known)] = block2;
1400
+ return { status: "placed", block: block2, placed: [] };
1401
+ }
1402
+ return length < known.length ? {
1403
+ status: "overlap",
1404
+ reason: `repair block ${start}+${length} is only the first block of repair-less span ${known.start}+${known.length}`,
1405
+ ofSpan: known
1406
+ } : { status: "overlap", reason: `repair block ${start}+${length} runs past repair-less span ${known.start}+${known.length}` };
1372
1407
  }
1373
1408
  if (known.length !== length) {
1374
1409
  return {
@@ -1436,18 +1471,28 @@ var IsoBlockLocator = class _IsoBlockLocator {
1436
1471
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
1437
1472
  }
1438
1473
  /**
1439
- * Turn every pending hole inside `[start, start + length)` into a
1440
- * repair-less span, claiming its held sources: its range FETCH ended, so
1441
- * nothing more will state its blocks. Returns the spans, in SS_ID order.
1474
+ * Turn every hole inside `[start, start + length)` into a repair-less span,
1475
+ * claiming its held sources: its range FETCH ended, so nothing more will
1476
+ * state its blocks. A hole the horizon passed (`takeExpiredHoles`) leaves a
1477
+ * span that is not kept among the blocks, as the horizon would retire it at
1478
+ * once; only `locate` finds it, until the next retirement, so its sources
1479
+ * can be fed. Returns the spans, in SS_ID order.
1442
1480
  */
1443
1481
  closeHolesWithin(start, length) {
1444
1482
  const closed = [];
1445
- for (const hole of [...this.#holes]) {
1446
- if (!isoBlockContains(start, length, hole.start)) continue;
1447
- this.#holes.splice(this.#holes.indexOf(hole), 1);
1448
- const spanBlock = { start: hole.start, length: hole.length, span: true };
1449
- closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
1450
- this.#blocks.push(spanBlock);
1483
+ for (const holes of [this.#holes, this.#expired]) {
1484
+ for (const hole of [...holes]) {
1485
+ if (!isoBlockContains(start, length, hole.start)) continue;
1486
+ holes.splice(holes.indexOf(hole), 1);
1487
+ const spanBlock = { start: hole.start, length: hole.length, span: true };
1488
+ closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
1489
+ if (holes === this.#holes) {
1490
+ this.#blocks.push(spanBlock);
1491
+ } else {
1492
+ this.#closedBehind.push(spanBlock);
1493
+ if (this.#newlyExpired.includes(hole)) this.#newlyExpired.splice(this.#newlyExpired.indexOf(hole), 1);
1494
+ }
1495
+ }
1451
1496
  }
1452
1497
  return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
1453
1498
  }
@@ -1461,15 +1506,17 @@ var IsoBlockLocator = class _IsoBlockLocator {
1461
1506
  return void 0;
1462
1507
  }
1463
1508
  /**
1464
- * Retire every block and span whose last SS_ID, and every held source,
1465
- * lies more than `retentionBlocks` blocks behind `position`, with the shared
1466
- * lower-bound metric (`isoBlocksBehindLowerBound`) every ISO interleave
1467
- * horizon uses. Returns the retired block starts.
1509
+ * Retire every block and span whose last SS_ID, and every held source
1510
+ * outside a hole, lies more than `retentionBlocks` blocks behind
1511
+ * `position`, with the shared lower-bound metric (`isoBlocksBehindLowerBound`)
1512
+ * every ISO interleave horizon uses; a pending hole so far behind expires
1513
+ * (`takeExpiredHoles`). Returns the retired block starts.
1468
1514
  */
1469
1515
  retireBehind(position) {
1470
1516
  this.observe(position);
1471
1517
  const horizon = this.#retentionBlocks;
1472
1518
  const retired = [];
1519
+ this.#closedBehind.length = 0;
1473
1520
  for (let i = this.#blocks.length - 1; i >= 0; i--) {
1474
1521
  const block = this.#blocks[i];
1475
1522
  const last = serial32Add(block.start, block.length - 1);
@@ -1481,10 +1528,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
1481
1528
  for (let i = this.#holes.length - 1; i >= 0; i--) {
1482
1529
  const hole = this.#holes[i];
1483
1530
  const last = serial32Add(hole.start, hole.length - 1);
1484
- if (isoBlocksBehindLowerBound(last, position, this.#kMax) > horizon) this.#holes.splice(i, 1);
1531
+ if (isoBlocksBehindLowerBound(last, position, this.#kMax) <= horizon) continue;
1532
+ this.#holes.splice(i, 1);
1533
+ this.#expired.push(hole);
1534
+ this.#newlyExpired.push(hole);
1485
1535
  }
1486
1536
  for (const ssId of [...this.#held.keys()]) {
1487
- if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon) this.#held.delete(ssId);
1537
+ 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))) {
1538
+ this.#held.delete(ssId);
1539
+ }
1488
1540
  }
1489
1541
  return retired;
1490
1542
  }
@@ -1492,6 +1544,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
1492
1544
  reset() {
1493
1545
  this.#blocks.length = 0;
1494
1546
  this.#holes.length = 0;
1547
+ this.#expired.length = 0;
1548
+ this.#newlyExpired.length = 0;
1549
+ this.#closedBehind.length = 0;
1495
1550
  this.#held.clear();
1496
1551
  this.#coverageEnd = void 0;
1497
1552
  this.#newest = void 0;
@@ -2084,6 +2139,7 @@ var WORKER_ERROR_LOG_CAP = 5;
2084
2139
  var WORKER_ERROR_KIND_CAP = 32;
2085
2140
  var WORKER_ERROR_OVERFLOW_KIND = "other";
2086
2141
  var STARTUP_REPAIR_WAIT_SOURCE_BOUNDARIES = 2;
2142
+ var NOT_TAKEN = Object.freeze({ taken: false, recovered: null });
2087
2143
  function isMulticastSymbolDelivery(value) {
2088
2144
  return value === "datagram" || value === "ordered-relay";
2089
2145
  }
@@ -2177,10 +2233,18 @@ var FECManager = class _FECManager {
2177
2233
  // 'pending' forever, which would park every later frame of its stream in
2178
2234
  // the in-order release gate. Each entry owns its handle; the callback
2179
2235
  // checks it still owns the key, so a settled or reset key is never touched.
2236
+ /**
2237
+ * Per owed Worker cleanup: the bound on its acknowledgement, when its block
2238
+ * was due, and when its cleanup was asked for (see `onCleanupComplete`).
2239
+ */
2180
2240
  this.#pendingWorkerCleanupBounds = /* @__PURE__ */ new Map();
2181
2241
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
2182
2242
  this.#blockSourceCounts = /* @__PURE__ */ new Map();
2183
2243
  this.#blockSourceEsis = /* @__PURE__ */ new Map();
2244
+ // Source ESIs per block that another FEC instance rebuilt and fed in
2245
+ // (feedRebuiltSourceSymbol). Kept apart from #blockSourceEsis: they are
2246
+ // not network arrivals and never make a block clean.
2247
+ this.#blockRebuiltEsis = /* @__PURE__ */ new Map();
2184
2248
  // Authored SSB_length per block (ISO/IEC 23008-1 §C.5.3), learned from the
2185
2249
  // first repair symbol. The FFmpeg moq_mmt publisher closes a block every D
2186
2250
  // media units, usually before it holds K symbols; under iso-ssbg1-v1
@@ -2189,6 +2253,9 @@ var FECManager = class _FECManager {
2189
2253
  // SSB_length source arrivals and recoverable from SSB_length received
2190
2254
  // symbols; waiting for K fails every one of them.
2191
2255
  this.#blockAuthoredLengths = /* @__PURE__ */ new Map();
2256
+ // Keys whose authored length is a repair-less span's (#openIsoSpan), until
2257
+ // a repair states the block there or the span resolves.
2258
+ this.#isoSpanKeys = /* @__PURE__ */ new Set();
2192
2259
  this.#ssbLengthConflictCount = 0;
2193
2260
  this.#blockRepairRsIds = /* @__PURE__ */ new Map();
2194
2261
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
@@ -2386,7 +2453,10 @@ var FECManager = class _FECManager {
2386
2453
  // arrives via onBlockRecovered callback.
2387
2454
  this.onBlockStarted = null;
2388
2455
  this.onBlockComplete = null;
2389
- /** A block reached its fail bound. `blockClass` is its class at failure. */
2456
+ /**
2457
+ * A block reached its fail bound. `blockClass` is its class at failure.
2458
+ * `span` is set when what failed is a repair-less span starting at `sbn`.
2459
+ */
2390
2460
  this.onBlockFailed = null;
2391
2461
  /**
2392
2462
  * Fired once per stream when its Worker decoder stops being routable.
@@ -2428,6 +2498,8 @@ var FECManager = class _FECManager {
2428
2498
  * for it, which it must be.
2429
2499
  */
2430
2500
  this.#onUndelimitedLoss = null;
2501
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
2502
+ this.#onIsoHoleExpired = null;
2431
2503
  /** A block every symbol of which vanished was created by SBN evidence. */
2432
2504
  this.onBlockVanished = null;
2433
2505
  /** A block reached a terminal state (completed, recovered, or failed). */
@@ -2470,7 +2542,9 @@ var FECManager = class _FECManager {
2470
2542
  #pendingWorkerCleanupBounds;
2471
2543
  #blockSourceCounts;
2472
2544
  #blockSourceEsis;
2545
+ #blockRebuiltEsis;
2473
2546
  #blockAuthoredLengths;
2547
+ #isoSpanKeys;
2474
2548
  #ssbLengthConflictCount;
2475
2549
  #blockRepairRsIds;
2476
2550
  #blockRsbLengths;
@@ -2537,6 +2611,7 @@ var FECManager = class _FECManager {
2537
2611
  #decoderUnavailableEvents;
2538
2612
  #repairSymbolSizeMismatchCount;
2539
2613
  #onUndelimitedLoss;
2614
+ #onIsoHoleExpired;
2540
2615
  #encodeTrackName(catalogTrackName) {
2541
2616
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
2542
2617
  if (encoded === void 0) {
@@ -3008,7 +3083,10 @@ var FECManager = class _FECManager {
3008
3083
  timer.handle = null;
3009
3084
  this.#requestRepair(sbn, packetId, catalogTrackName);
3010
3085
  };
3011
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
3086
+ timer.handle = setTimeout(
3087
+ onFire,
3088
+ this.#receiptAtMs === void 0 ? Math.max(0, deadlineMs - performance.now()) : this.#receiptTimerDelayMs(deadlineMs, 0)
3089
+ );
3012
3090
  this.#repairDeadlines.set(key, timer);
3013
3091
  }
3014
3092
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -3152,8 +3230,14 @@ var FECManager = class _FECManager {
3152
3230
  * Vanished blocks are not enumerated here: their starts are unknown until a
3153
3231
  * repair states them. The SS_IDs between two stated blocks become one
3154
3232
  * repair-less span when the later block's repair arrives (placeIsoRepair).
3233
+ *
3234
+ * A `held` source arrived before its block was known and is fed only now
3235
+ * that a repair, a span or a closed hole placed it: how far its block start
3236
+ * then lies behind the frontier measures how long the receiver held it, not
3237
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
3238
+ * it (BLO-52085).
3155
3239
  */
3156
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
3240
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn, held = false) {
3157
3241
  const streamKey = this.#streamKey(packetId, catalogTrackName);
3158
3242
  const now = performance.now();
3159
3243
  const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
@@ -3192,7 +3276,7 @@ var FECManager = class _FECManager {
3192
3276
  return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
3193
3277
  };
3194
3278
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
3195
- if (symbol === "source" && window2 !== null && this.#blockPrecedes(sbn, previous.sbn) && (this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId) || psn !== void 0 && anchor !== void 0 && serial32Precedes(ssId, anchor.ssId) && psn !== anchor.psn && !sentInOrder({ ssId, psn }, anchor))) {
3279
+ if (symbol === "source" && window2 !== null && this.#blockPrecedes(sbn, previous.sbn) && (!held && this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId) || psn !== void 0 && anchor !== void 0 && serial32Precedes(ssId, anchor.ssId) && psn !== anchor.psn && !sentInOrder({ ssId, psn }, anchor))) {
3196
3280
  discontinuity();
3197
3281
  return;
3198
3282
  }
@@ -3454,17 +3538,21 @@ var FECManager = class _FECManager {
3454
3538
  this.#blockWaitDeadlinesMs.delete(key);
3455
3539
  this.#repairHoldUntilMs.delete(key);
3456
3540
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
3457
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName);
3541
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs);
3458
3542
  };
3459
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)));
3543
+ timer.handle = setTimeout(
3544
+ onFire,
3545
+ this.#receiptAtMs === void 0 ? Math.max(1, Math.ceil(deadlineMs - nowMs)) : this.#receiptTimerDelayMs(deadlineMs, 1)
3546
+ );
3460
3547
  this.#activeBlocks.set(key, timer);
3461
3548
  this.#indexBlockKey(key, sbn, packetId);
3462
3549
  }
3463
3550
  /**
3464
3551
  * Hand a block whose delivery is over to its decoder for finalization: the
3465
- * datagram deadline fired, or the ordered relay moved past it.
3552
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
3553
+ * is when it was due: its deadline, or now.
3466
3554
  */
3467
- #finalizeExpiredBlock(sbn, packetId, catalogTrackName) {
3555
+ #finalizeExpiredBlock(sbn, packetId, catalogTrackName, dueAtMs = performance.now()) {
3468
3556
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
3469
3557
  if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
3470
3558
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -3480,7 +3568,7 @@ var FECManager = class _FECManager {
3480
3568
  if (workerClient) {
3481
3569
  this.#pendingWorkerCleanups.add(key);
3482
3570
  this.#pendingWorkerCleanupClients.set(key, workerClient);
3483
- this.#boundOwedCleanup(key, packetId, workerClient);
3571
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs);
3484
3572
  workerClient.cleanup(sbn);
3485
3573
  } else {
3486
3574
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
@@ -3792,7 +3880,9 @@ var FECManager = class _FECManager {
3792
3880
  }
3793
3881
  resetMap(this.#blockSourceCounts);
3794
3882
  resetMap(this.#blockSourceEsis);
3883
+ resetMap(this.#blockRebuiltEsis);
3795
3884
  resetMap(this.#blockAuthoredLengths);
3885
+ resetSet(this.#isoSpanKeys);
3796
3886
  resetMap(this.#blockRepairRsIds);
3797
3887
  resetMap(this.#blockRsbLengths);
3798
3888
  resetMap(this.#heldLayerStates);
@@ -3916,7 +4006,9 @@ var FECManager = class _FECManager {
3916
4006
  dropMap(this.#pendingWorkerCleanupClients);
3917
4007
  dropMap(this.#blockSourceCounts);
3918
4008
  dropMap(this.#blockSourceEsis);
4009
+ dropMap(this.#blockRebuiltEsis);
3919
4010
  dropMap(this.#blockAuthoredLengths);
4011
+ dropSet(this.#isoSpanKeys);
3920
4012
  dropMap(this.#blockRepairRsIds);
3921
4013
  dropMap(this.#blockRsbLengths);
3922
4014
  dropMap(this.#blockPathCounts);
@@ -4259,8 +4351,9 @@ var FECManager = class _FECManager {
4259
4351
  return true;
4260
4352
  }
4261
4353
  /**
4262
- * Drop a block's repair hold: its FETCH ended without delivering. The block
4263
- * falls back to its multicast wait, which may already have passed.
4354
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
4355
+ * back only a repair that cannot complete it. The block falls back to its
4356
+ * multicast wait, which may already have passed.
4264
4357
  */
4265
4358
  releaseRepairHold(sbn, packetId, catalogTrackName) {
4266
4359
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -4398,6 +4491,7 @@ var FECManager = class _FECManager {
4398
4491
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
4399
4492
  const evictedBefore = locator.heldEvicted;
4400
4493
  const held = locator.hold(ssId, source);
4494
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
4401
4495
  if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
4402
4496
  const evicted = locator.heldEvicted - evictedBefore;
4403
4497
  if (evicted > 0) {
@@ -4419,17 +4513,20 @@ var FECManager = class _FECManager {
4419
4513
  * contradicts a known block is refused (counted) and must be dropped.
4420
4514
  */
4421
4515
  placeIsoRepair(packetId, catalogTrackName, ssStart, ssbLength) {
4422
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength);
4516
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
4517
+ const placement = locator.placeRepair(ssStart, ssbLength);
4518
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
4423
4519
  if (placement.status !== "placed") {
4424
4520
  this.#isoRepairRefusedCount++;
4425
4521
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
4426
4522
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`);
4427
4523
  }
4524
+ if (placement.ofSpan !== void 0) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName);
4428
4525
  return placement;
4429
4526
  }
4527
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName));
4430
4528
  if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
4431
4529
  if (placement.hole !== void 0) {
4432
- const locator = this.#isoLocatorFor(packetId, catalogTrackName);
4433
4530
  const hole = placement.hole.block;
4434
4531
  const previous = locator.blockEndingAt(hole.start);
4435
4532
  const loss = {
@@ -4450,17 +4547,29 @@ var FECManager = class _FECManager {
4450
4547
  * `handler`, instead of a repair-less span; null restores spans. Set by the
4451
4548
  * range repair scheduler; applies to every stream from its next gap. The
4452
4549
  * handler and the deferral are one setting, so no hole is ever created with
4453
- * nobody to close it.
4550
+ * nobody to close it. `onExpired` is told of each pending hole the stream
4551
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
4552
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
4553
+ * reported; otherwise the hole is discarded with its sources.
4454
4554
  */
4455
- setUndelimitedLossHandler(handler) {
4555
+ setUndelimitedLossHandler(handler, onExpired = null) {
4456
4556
  this.#onUndelimitedLoss = handler;
4557
+ this.#onIsoHoleExpired = handler === null ? null : onExpired;
4457
4558
  this.#deferIsoGaps = handler !== null;
4458
4559
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
4459
4560
  }
4561
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
4562
+ #settleExpiredIsoHoles(locator, packetId, catalogTrackName) {
4563
+ for (const hole of locator.takeExpiredHoles()) {
4564
+ const expired = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length };
4565
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length);
4566
+ }
4567
+ }
4460
4568
  /**
4461
- * The range repair for a hole ended: every hole still pending inside
4462
- * `[start, start + length)` becomes a repair-less span. Returns those spans
4463
- * with the held sources they placed, for the caller to feed (MmtpRouter).
4569
+ * The range repair for a hole ended: every hole inside `[start, start +
4570
+ * length)`, pending or expired, becomes a repair-less span. Returns those
4571
+ * spans with the held sources they placed, for the caller to feed
4572
+ * (MmtpRouter).
4464
4573
  */
4465
4574
  closeIsoHoles(packetId, catalogTrackName, start, length) {
4466
4575
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
@@ -4479,7 +4588,10 @@ var FECManager = class _FECManager {
4479
4588
  */
4480
4589
  #openIsoSpan(span, packetId, catalogTrackName) {
4481
4590
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
4482
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
4591
+ if (!this.#blockAuthoredLengths.has(key)) {
4592
+ this.#blockAuthoredLengths.set(key, span.block.length);
4593
+ this.#isoSpanKeys.add(key);
4594
+ }
4483
4595
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
4484
4596
  }
4485
4597
  /**
@@ -4820,11 +4932,14 @@ var FECManager = class _FECManager {
4820
4932
  });
4821
4933
  client.onCleanupComplete((sbn) => {
4822
4934
  if (this.#releasedWorkerClients.has(client)) return;
4823
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
4935
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
4936
+ const cleanupKeys = owed.filter((key) => {
4824
4937
  const block = this.#parseBlockKey(key);
4825
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
4938
+ return block.packetId === packetId && block.sbn === sbn;
4826
4939
  });
4827
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
4940
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
4941
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
4942
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
4828
4943
  });
4829
4944
  client.onError((msg, code) => {
4830
4945
  const requestedKind = code ?? msg;
@@ -4894,9 +5009,11 @@ var FECManager = class _FECManager {
4894
5009
  * fail deadline already passed, so failing it is the decision that deadline
4895
5010
  * made. A late ack then finds nothing owed and is a no-op.
4896
5011
  */
4897
- #boundOwedCleanup(key, packetId, client) {
5012
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
4898
5013
  this.#clearOwedCleanupBound(key);
4899
5014
  const bound = {
5015
+ dueAtMs,
5016
+ askedAtMs: performance.now(),
4900
5017
  handle: setTimeout(() => {
4901
5018
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
4902
5019
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -4994,7 +5111,15 @@ var FECManager = class _FECManager {
4994
5111
  this.#isoSourceOversizeCount++;
4995
5112
  return null;
4996
5113
  }
4997
- const sbn = located.block.start;
5114
+ return this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, located.block.start);
5115
+ }
5116
+ /**
5117
+ * Hand one placed source symbol to the stream's decoder: its Worker, which
5118
+ * answers through onFrame (null here), or its synchronous decoder, whose
5119
+ * recovered block is returned. `sbn` is the SS_Start of the block a repair
5120
+ * stated for `ssId`.
5121
+ */
5122
+ #feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn) {
4998
5123
  const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
4999
5124
  const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey);
5000
5125
  const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
@@ -5023,6 +5148,74 @@ var FECManager = class _FECManager {
5023
5148
  }
5024
5149
  return recovered;
5025
5150
  }
5151
+ /**
5152
+ * Feed a source symbol of this stream that another FEC instance over the
5153
+ * same packets rebuilt: a keyframe overlay recovery whose base SS_ID the
5154
+ * caller determined (draft-ramadan-moq-mmt-02 7.1, 7.4.4; joint decoding,
5155
+ * BLO-52085). It joins its block's decoder as a received source would, so
5156
+ * it reduces the erasures the block still has to solve, but it is not a
5157
+ * network arrival: no transport accounting, no classification evidence,
5158
+ * no deadline refresh, and it never makes a block clean.
5159
+ *
5160
+ * Only a block a repair stated takes one (a repair-less span has no
5161
+ * decoder block). A block that is terminal, or already holds that source,
5162
+ * does not. The symbol is the exact protected packet, unpadded, as
5163
+ * feedSourceSymbol takes it.
5164
+ *
5165
+ * `recovered` is the block the synchronous decoder completed with it; the
5166
+ * caller routes it and completes the block, as for any recovery. When
5167
+ * every source of the block is then present, received or rebuilt, and no
5168
+ * decoder returned it (a Worker answers asynchronously, and reports such a
5169
+ * block as clean on its own side), the block is completed here as
5170
+ * recovered, with nothing left to route.
5171
+ */
5172
+ feedRebuiltSourceSymbol(packetId, ssId, symbolData, catalogTrackName) {
5173
+ if (!this.#hasBlockProfile(packetId)) return NOT_TAKEN;
5174
+ const located = this.#isoLocatorFor(packetId, catalogTrackName).locate(ssId);
5175
+ if (located === null || located.block.span) return NOT_TAKEN;
5176
+ if (!ssbg1FitsSymbol(symbolData.byteLength, this.#trackConfig(packetId).symbolSize)) return NOT_TAKEN;
5177
+ const sbn = located.block.start;
5178
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
5179
+ if (this.#completedBlocks.has(key) || this.#blockSourceEsis.get(key)?.has(located.esi)) return NOT_TAKEN;
5180
+ let rebuilt = this.#blockRebuiltEsis.get(key);
5181
+ if (rebuilt?.has(located.esi)) return NOT_TAKEN;
5182
+ if (rebuilt === void 0) {
5183
+ rebuilt = /* @__PURE__ */ new Set();
5184
+ this.#blockRebuiltEsis.set(key, rebuilt);
5185
+ }
5186
+ const config = this.#trackConfigs.get(packetId);
5187
+ const wasShort = config !== void 0 && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) !== void 0;
5188
+ rebuilt.add(located.esi);
5189
+ const recovered = this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn);
5190
+ if (recovered === null && !this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName)) {
5191
+ if (wasShort && this.#activeBlocks.has(key) && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) === void 0) {
5192
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, this.#multicastWaitMs(config));
5193
+ }
5194
+ }
5195
+ return { taken: true, recovered };
5196
+ }
5197
+ /**
5198
+ * A block that holds every one of its `length` sources, received or
5199
+ * rebuilt by another instance, with at least one rebuilt, is recovered:
5200
+ * every packet of it was delivered, by its own arrival or by the instance
5201
+ * that rebuilt it, so nothing is routed. Returns whether it completed it.
5202
+ */
5203
+ #completeWhenSourcesPresent(key, sbn, length, packetId, catalogTrackName) {
5204
+ const rebuilt = this.#blockRebuiltEsis.get(key);
5205
+ if (rebuilt === void 0 || this.#completedBlocks.has(key)) return false;
5206
+ let present = rebuilt.size;
5207
+ for (const esi of this.#blockSourceEsis.get(key) ?? []) if (!rebuilt.has(esi)) present++;
5208
+ if (present < length) return false;
5209
+ this.#traceLifecycle("recovered", sbn, packetId, catalogTrackName);
5210
+ this.countRecovery(packetId, sbn, catalogTrackName);
5211
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
5212
+ if (catalogTrackName === void 0) {
5213
+ this.onBlockComplete?.(sbn, packetId);
5214
+ } else {
5215
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName);
5216
+ }
5217
+ return true;
5218
+ }
5026
5219
  /**
5027
5220
  * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
5028
5221
  * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
@@ -5265,7 +5458,10 @@ var FECManager = class _FECManager {
5265
5458
  const authoredLength = this.#blockAuthoredLengths.get(key);
5266
5459
  const rsbLength = this.#blockRsbLengths.get(key);
5267
5460
  if (authoredLength === void 0 || rsbLength === void 0) return void 0;
5268
- if ((this.#blockSourceCounts.get(key) ?? 0) + rsbLength >= authoredLength) return void 0;
5461
+ let present = this.#blockSourceCounts.get(key) ?? 0;
5462
+ const received = this.#blockSourceEsis.get(key);
5463
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
5464
+ if (present + rsbLength >= authoredLength) return void 0;
5269
5465
  const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
5270
5466
  if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
5271
5467
  return void 0;
@@ -5388,12 +5584,13 @@ var FECManager = class _FECManager {
5388
5584
  * the inactivity deadline on each symbol, records the symbol's in-band
5389
5585
  * classification evidence, and marks the block clean when all of its
5390
5586
  * authored source symbols arrived: the SSB_length a repair symbol declared,
5391
- * otherwise K.
5587
+ * otherwise K. `held` marks a source held unplaced since it arrived and
5588
+ * placed only now (see #noteSbnSeen).
5392
5589
  *
5393
5590
  * Throws for a packetId that was never configured, so a classified block
5394
5591
  * never reads the manager-global K or timeout.
5395
5592
  */
5396
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
5593
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
5397
5594
  const trackConfig = this.#trackConfigs.get(packetId);
5398
5595
  if (trackConfig === void 0) {
5399
5596
  throw new Error(
@@ -5409,7 +5606,8 @@ var FECManager = class _FECManager {
5409
5606
  catalogTrackName,
5410
5607
  "source",
5411
5608
  evidence.packetSequenceNumber,
5412
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
5609
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
5610
+ held
5413
5611
  );
5414
5612
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
5415
5613
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -5445,6 +5643,15 @@ var FECManager = class _FECManager {
5445
5643
  this.#completeCleanBlock(key, sbn, packetId, catalogTrackName);
5446
5644
  return;
5447
5645
  }
5646
+ if (this.#blockRebuiltEsis.has(key) && this.#completeWhenSourcesPresent(
5647
+ key,
5648
+ sbn,
5649
+ this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? authoredLength,
5650
+ packetId,
5651
+ catalogTrackName
5652
+ )) {
5653
+ return;
5654
+ }
5448
5655
  this.noteBlockActivity(sbn, packetId, catalogTrackName, true);
5449
5656
  }
5450
5657
  #completeCleanBlock(key, sbn, packetId, catalogTrackName) {
@@ -5453,7 +5660,9 @@ var FECManager = class _FECManager {
5453
5660
  this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
5454
5661
  this.#blockSourceCounts.delete(key);
5455
5662
  this.#blockSourceEsis.delete(key);
5663
+ this.#blockRebuiltEsis.delete(key);
5456
5664
  this.#blockAuthoredLengths.delete(key);
5665
+ this.#isoSpanKeys.delete(key);
5457
5666
  this.#blockRepairRsIds.delete(key);
5458
5667
  this.#blockRsbLengths.delete(key);
5459
5668
  this.#markTerminal(key, sbn, packetId, true);
@@ -5484,6 +5693,19 @@ var FECManager = class _FECManager {
5484
5693
  #receiptNow() {
5485
5694
  return this.#receiptAtMs ?? performance.now();
5486
5695
  }
5696
+ /**
5697
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
5698
+ * scope: counted from the receipt time, as the timer of a symbol fed when
5699
+ * it was received was, less the whole ms since. So it fires on the tick
5700
+ * that timer would have, never later than a delay counted from now, and
5701
+ * its handler still re-arms a timer that fires before its deadline.
5702
+ * Counted from now, a deadline set from the receipt time is rounded up
5703
+ * from another fraction of a ms (BLO-52085).
5704
+ */
5705
+ #receiptTimerDelayMs(deadlineMs, minMs) {
5706
+ const receivedAtMs = this.#receiptAtMs;
5707
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
5708
+ }
5487
5709
  /**
5488
5710
  * A held packet admitted late arms from its (earlier) receipt time; that
5489
5711
  * never pulls in a deadline later activity already armed. Outside a
@@ -5532,6 +5754,7 @@ var FECManager = class _FECManager {
5532
5754
  }
5533
5755
  #failBlock(sbn, packetId, catalogTrackName) {
5534
5756
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
5757
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
5535
5758
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
5536
5759
  this.#clearRepairDeadline(key);
5537
5760
  this.#clearBlockTimer(key);
@@ -5541,6 +5764,7 @@ var FECManager = class _FECManager {
5541
5764
  }
5542
5765
  this.#blockSourceCounts.delete(key);
5543
5766
  this.#blockSourceEsis.delete(key);
5767
+ this.#blockRebuiltEsis.delete(key);
5544
5768
  this.#blockAuthoredLengths.delete(key);
5545
5769
  this.#blockRepairRsIds.delete(key);
5546
5770
  this.#blockRsbLengths.delete(key);
@@ -5550,7 +5774,8 @@ var FECManager = class _FECManager {
5550
5774
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
5551
5775
  this.#fecStats.blocksFailed++;
5552
5776
  this.#statsForPacket(packetId).blocksFailed++;
5553
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5777
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5778
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
5554
5779
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
5555
5780
  }
5556
5781
  /**
@@ -5579,7 +5804,9 @@ var FECManager = class _FECManager {
5579
5804
  this.#retireBlockClass(key, block.sbn, block.packetId, block.catalogTrackName);
5580
5805
  this.#blockSourceCounts.delete(key);
5581
5806
  this.#blockSourceEsis.delete(key);
5807
+ this.#blockRebuiltEsis.delete(key);
5582
5808
  this.#blockAuthoredLengths.delete(key);
5809
+ this.#isoSpanKeys.delete(key);
5583
5810
  this.#blockRepairRsIds.delete(key);
5584
5811
  this.#blockRsbLengths.delete(key);
5585
5812
  this.#clearBlockTimer(key);
@@ -5670,7 +5897,9 @@ var FECManager = class _FECManager {
5670
5897
  this.#blockKeysBySbn.clear();
5671
5898
  this.#blockSourceCounts.clear();
5672
5899
  this.#blockSourceEsis.clear();
5900
+ this.#blockRebuiltEsis.clear();
5673
5901
  this.#blockAuthoredLengths.clear();
5902
+ this.#isoSpanKeys.clear();
5674
5903
  this.#blockRepairRsIds.clear();
5675
5904
  this.#blockRsbLengths.clear();
5676
5905
  this.#heldLayerStates.clear();
@@ -7049,9 +7278,9 @@ async function openSubscription(rx, openedPromise, options, packetIds) {
7049
7278
  } catch (error) {
7050
7279
  throw new MulticastError("subscription-failed", "MulticastReceiver did not open", error);
7051
7280
  }
7052
- if (rx.integrityScheme !== INTEGRITY_SCHEME) {
7281
+ if (opened.integrityScheme !== INTEGRITY_SCHEME) {
7053
7282
  await rx.close();
7054
- throw unsupported(`integrity scheme ${String(rx.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
7283
+ throw unsupported(`integrity scheme ${String(opened.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
7055
7284
  }
7056
7285
  const events = new EventTarget();
7057
7286
  let state = "connected";
@@ -13583,6 +13812,9 @@ function authoredGap(before, after) {
13583
13812
  function ssIdAfter(a, b) {
13584
13813
  return (a - b | 0) > 0;
13585
13814
  }
13815
+ function holdsRebuilt(stream) {
13816
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
13817
+ }
13586
13818
  var FecReleaseSequencer = class {
13587
13819
  #streams = /* @__PURE__ */ new Map();
13588
13820
  #gate;
@@ -13645,6 +13877,7 @@ var FecReleaseSequencer = class {
13645
13877
  stream.lastSbn = void 0;
13646
13878
  stream.discontinuity = false;
13647
13879
  stream.rapSsId = void 0;
13880
+ stream.sourced = false;
13648
13881
  }
13649
13882
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
13650
13883
  this.#recordStat("droppedStale");
@@ -13671,6 +13904,7 @@ var FecReleaseSequencer = class {
13671
13904
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
13672
13905
  else hi = mid;
13673
13906
  }
13907
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
13674
13908
  stream.buf.splice(lo, 0, frame);
13675
13909
  this.#drainUnlessDeferred(stream);
13676
13910
  }
@@ -13706,6 +13940,41 @@ var FecReleaseSequencer = class {
13706
13940
  }
13707
13941
  return false;
13708
13942
  }
13943
+ /**
13944
+ * These streams' sink is being replaced by one that has seen no source
13945
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
13946
+ * release to the sink being replaced the frames the unanchored path had
13947
+ * already released to it (#cursorPassed): there they waited in its queue,
13948
+ * which its replacement flushes. A stream that holds none is not drained:
13949
+ * it holds nothing the anchor kept back, and a drain would still force out
13950
+ * a frame held past the hold limit, which before the anchor waited for the
13951
+ * next push. Then treat the streams as unsourced until a source frame is
13952
+ * released.
13953
+ */
13954
+ unsource(packetId, catalogTrackName) {
13955
+ for (const stream of this.#streams.values()) {
13956
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
13957
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
13958
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
13959
+ else this.#drain(stream, true);
13960
+ }
13961
+ stream.sourced = false;
13962
+ }
13963
+ }
13964
+ }
13965
+ /**
13966
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
13967
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
13968
+ * packetId.
13969
+ */
13970
+ holdsRebuilt(packetId, catalogTrackName) {
13971
+ for (const stream of this.#streams.values()) {
13972
+ if (stream.packetId !== packetId) continue;
13973
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
13974
+ if (holdsRebuilt(stream)) return true;
13975
+ }
13976
+ return false;
13977
+ }
13709
13978
  /** Re-evaluate held gaps after FEC state changed. */
13710
13979
  poke(streamKey) {
13711
13980
  if (streamKey !== void 0) {
@@ -13797,16 +14066,32 @@ var FecReleaseSequencer = class {
13797
14066
  last: null,
13798
14067
  lastSbn: void 0,
13799
14068
  discontinuity: false,
13800
- rapSsId: void 0
14069
+ rapSsId: void 0,
14070
+ sourced: false,
14071
+ draining: 0
13801
14072
  };
13802
14073
  this.#streams.set(streamKey, stream);
13803
14074
  }
13804
14075
  return stream;
13805
14076
  }
13806
- #drain(stream) {
14077
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
14078
+ #drain(stream, asUnanchored = false) {
14079
+ stream.draining++;
14080
+ try {
14081
+ this.#drainLoop(stream, asUnanchored);
14082
+ } finally {
14083
+ stream.draining--;
14084
+ }
14085
+ }
14086
+ #drainLoop(stream, asUnanchored) {
13807
14087
  while (stream.buf.length > 0 && stream.last !== null) {
13808
14088
  const head = stream.buf[0];
13809
14089
  const last = stream.last;
14090
+ if (compareFrameOrder(head, last) <= 0) {
14091
+ stream.buf.shift();
14092
+ this.#release(stream, head, void 0);
14093
+ continue;
14094
+ }
13810
14095
  if (stream.discontinuity) {
13811
14096
  stream.discontinuity = false;
13812
14097
  stream.buf.shift();
@@ -13820,9 +14105,10 @@ var FecReleaseSequencer = class {
13820
14105
  }
13821
14106
  const headSbn = head.meta.fecSbn;
13822
14107
  const from = stream.lastSbn ?? headSbn;
13823
- const to = headSbn ?? stream.lastSbn;
14108
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
13824
14109
  let lost = [];
13825
14110
  const unanchored = from === void 0 && to === void 0;
14111
+ let unresolved = false;
13826
14112
  if (from !== void 0 && to !== void 0) {
13827
14113
  const resolved = this.#gate.resolvedLoss(
13828
14114
  stream.packetId,
@@ -13831,7 +14117,8 @@ var FecReleaseSequencer = class {
13831
14117
  Math.max(from, to),
13832
14118
  from
13833
14119
  );
13834
- if (resolved === null) {
14120
+ unresolved = resolved === null;
14121
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored)) {
13835
14122
  const heldMs = performance.now() - head.arrivedAtMs;
13836
14123
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
13837
14124
  this.#recordStat("forcedWindowFlushes");
@@ -13839,22 +14126,56 @@ var FecReleaseSequencer = class {
13839
14126
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
13840
14127
  continue;
13841
14128
  }
13842
- lost = resolved;
14129
+ lost = resolved ?? [];
13843
14130
  }
13844
14131
  stream.buf.shift();
13845
14132
  this.#release(
13846
14133
  stream,
13847
14134
  head,
13848
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
14135
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
13849
14136
  );
13850
14137
  }
13851
14138
  }
14139
+ /**
14140
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
14141
+ * source cursor holds it unanchored, and neither does a later frame behind
14142
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
14143
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
14144
+ * like each frame that arrived in front of it since (stale there). The head
14145
+ * then goes, decided as it would be unanchored, once a frame the base path
14146
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
14147
+ * marked one: the base path has passed that one, so a frame still missing
14148
+ * before it can only come from a repair. It also goes while no source frame
14149
+ * has been released, when the direct path shows a recovered frame at once.
14150
+ * And it goes at once while a staged switch decides on when frames arrive
14151
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
14152
+ * sink being replaced: unanchored, it had already reached the sink.
14153
+ * The scan also writes: the `passed` marks it sets stay on the frames,
14154
+ * and push marks a frame it inserts in front of a marked one from them.
14155
+ */
14156
+ #cursorPassed(stream, asUnanchored) {
14157
+ let at = -1;
14158
+ for (let i = 0; i < stream.buf.length; i++) {
14159
+ const frame = stream.buf[i];
14160
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
14161
+ frame.passed = true;
14162
+ if (at < 0) at = i;
14163
+ } else if (frame.passed !== true) break;
14164
+ }
14165
+ if (at < 0) return false;
14166
+ 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));
14167
+ }
13852
14168
  #release(stream, frame, decision) {
14169
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
14170
+ if (stale) this.#recordStat("droppedStale");
13853
14171
  if (decision) frame.meta.gapBefore = decision;
13854
14172
  stream.last = frame;
13855
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
14173
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
14174
+ stream.lastSbn = frame.meta.fecSbn;
14175
+ }
14176
+ if (frame.meta.recovered !== true) stream.sourced = true;
13856
14177
  this.#gate.onReleased?.(frame.data, frame.meta);
13857
- this.#emit(frame.data, frame.meta);
14178
+ if (!stale) this.#emit(frame.data, frame.meta);
13858
14179
  }
13859
14180
  };
13860
14181
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -14115,11 +14436,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
14115
14436
  /**
14116
14437
  * Typed view of the ISO-BMFF timing-sample budget.
14117
14438
  *
14118
- * This is the acceptance signal for the budget ratchet: `pending` walking
14119
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
14120
- * and it is observable here rather than only as media silently stopping.
14121
- * Per repo policy this is a producer-owned counter -- never infer budget
14122
- * state by parsing logs.
14439
+ * Each stream admits timing against its own window of `capacity` slots
14440
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
14441
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
14442
+ * timing a stream declared and never delivered shows up there. `pending`
14443
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
14444
+ * a producer-owned counter -- never infer budget state by parsing logs.
14123
14445
  */
14124
14446
  get timingBudgetStats() {
14125
14447
  return {
@@ -14179,6 +14501,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
14179
14501
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
14180
14502
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
14181
14503
  }
14504
+ /** See FecReleaseSequencer.unsource. */
14505
+ unsourceFecRelease(packetId, catalogTrackName) {
14506
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
14507
+ }
14508
+ /** See FecReleaseSequencer.holdsRebuilt. */
14509
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
14510
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
14511
+ }
14182
14512
  /** Re-evaluate held gaps after FEC block state changed. */
14183
14513
  pokeFecRelease(packetId, catalogTrackName) {
14184
14514
  if (!this.#fecSequencer) return;
@@ -14432,7 +14762,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14432
14762
  if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
14433
14763
  const pendingBefore = resolver2.pendingSampleCount;
14434
14764
  const evictedBefore = resolver2.evictedSampleCount;
14435
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
14765
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
14436
14766
  const admitted = resolver2.addMovieFragment(
14437
14767
  mpu.mpuSequenceNumber,
14438
14768
  data,
@@ -14505,7 +14835,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14505
14835
  info,
14506
14836
  resolver,
14507
14837
  options?.recovered === true,
14508
- options?.fecSbn
14838
+ options?.fecSbn,
14839
+ options?.fecSbnFirst
14509
14840
  );
14510
14841
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
14511
14842
  }
@@ -14598,7 +14929,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14598
14929
  info,
14599
14930
  resolver,
14600
14931
  options?.recovered === true,
14601
- options?.fecSbn
14932
+ options?.fecSbn,
14933
+ options?.fecSbnFirst
14602
14934
  );
14603
14935
  if (outcome.record !== void 0) return outcome.record;
14604
14936
  return this.#drop(outcome.reason);
@@ -14618,7 +14950,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14618
14950
  * attribution exists to keep readable. Leaving the choice at the call site
14619
14951
  * is what keeps both true.
14620
14952
  */
14621
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
14953
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
14622
14954
  const timing = resolver.sampleTiming(
14623
14955
  combined.mpuSequenceNumber,
14624
14956
  combined.movieFragmentSequenceNumber,
@@ -14635,6 +14967,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14635
14967
  );
14636
14968
  if (!meta) return { reason: "combined-meta-build-failed" };
14637
14969
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
14970
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
14638
14971
  if (!resolver.consumeSample(
14639
14972
  combined.mpuSequenceNumber,
14640
14973
  combined.movieFragmentSequenceNumber,
@@ -18139,7 +18472,18 @@ function keyframeOverlaySsId(header) {
18139
18472
  if (ext?.type !== KEYFRAME_OVERLAY_EXTENSION_TYPE || ext.data.length !== 4) return void 0;
18140
18473
  return new DataView(ext.data.buffer, ext.data.byteOffset, 4).getUint32(0);
18141
18474
  }
18475
+ function overlayBaseSsId(anchor, overlaySsId, restoredPsn, headerPsn) {
18476
+ if (anchor.baseSsId === void 0 || headerPsn !== restoredPsn) return void 0;
18477
+ return serial32Add(anchor.baseSsId, overlaySsId - anchor.overlaySsId | 0);
18478
+ }
18479
+ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
18480
+ if (offset === void 0 || offset !== unstampedOffset) return void 0;
18481
+ return headerPsn + offset >>> 0;
18482
+ }
18483
+ var OVERLAY_ROUTED_LIMIT = 1024;
18484
+ var OVERLAY_PENDING_LIMIT = 256;
18142
18485
  var OVERLAY_OFFSET_MPUS = 16;
18486
+ var OVERLAY_REBUILT_LIMIT = 256;
18143
18487
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
18144
18488
  function assertStreamIdentity(role, stream) {
18145
18489
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -18250,6 +18594,7 @@ var MmtpRouter = class {
18250
18594
  #provenance = /* @__PURE__ */ new Map();
18251
18595
  #onFlowProtected = null;
18252
18596
  #unadmittedListedDrops = 0;
18597
+ #admittedSourceDatagrams = 0;
18253
18598
  #unlistedRepairSetAside = 0;
18254
18599
  #assistBlocks = /* @__PURE__ */ new Map();
18255
18600
  #assistFailures = /* @__PURE__ */ new Map();
@@ -18306,6 +18651,26 @@ var MmtpRouter = class {
18306
18651
  * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
18307
18652
  */
18308
18653
  #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18654
+ /**
18655
+ * Per stream, the SS_ID offset at which a base recovery last showed the
18656
+ * sender's own packet_sequence_number: a recovered packet's header psn
18657
+ * equal to its SS_ID minus that offset. While it equals the stream's
18658
+ * current offset, no hop re-stamps the stream, and a packet's protected psn
18659
+ * names its base SS_ID within unstampedBaseSsId's limits (joint decoding of
18660
+ * an MPU no member of which arrived).
18661
+ */
18662
+ #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18663
+ /**
18664
+ * The same, shown by the overlay alone, before any base recovery did: a
18665
+ * packet it rebuilt whose base copy carries its protected psn
18666
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
18667
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
18668
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
18669
+ * make the base drop a late base copy of a keyframe the overlay never
18670
+ * finished, and lift a block's late-source cut, which nothing before
18671
+ * this offset did.
18672
+ */
18673
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18309
18674
  /**
18310
18675
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
18311
18676
  * not parsed, typically because its overlap copy was parsed first
@@ -18375,7 +18740,9 @@ var MmtpRouter = class {
18375
18740
  recovered: 0,
18376
18741
  restarts: 0,
18377
18742
  unsequencedDropped: 0,
18378
- protectedDropped: 0
18743
+ protectedDropped: 0,
18744
+ baseFed: 0,
18745
+ baseUndetermined: 0
18379
18746
  };
18380
18747
  /** Callback fired when a delta-track FEC block completes or fails. */
18381
18748
  #onDeltaBlockCompleteCb = null;
@@ -18581,13 +18948,18 @@ var MmtpRouter = class {
18581
18948
  this.#onDeltaBlockCompleteCb?.(packetId, false);
18582
18949
  }
18583
18950
  };
18584
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
18951
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
18585
18952
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
18586
18953
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
18587
18954
  this.#onDeltaBlockCompleteCb?.(packetId, true);
18588
18955
  }
18589
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18590
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18956
+ if (span === void 0) {
18957
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18958
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18959
+ } else {
18960
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
18961
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
18962
+ }
18591
18963
  };
18592
18964
  }
18593
18965
  }
@@ -18632,8 +19004,9 @@ var MmtpRouter = class {
18632
19004
  }
18633
19005
  /**
18634
19006
  * FEC-recovered source symbols whose reconstructed header named a
18635
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
18636
- * a hop re-stamped the sequence after the sender protected the packet.
19007
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
19008
+ * or, rebuilt by the overlay, than their base copy carries: a hop
19009
+ * re-stamped the sequence after the sender protected the packet.
18637
19010
  */
18638
19011
  get restampedRecoveredSequenceCount() {
18639
19012
  return this.#restampedRecoveredSeqs;
@@ -18812,6 +19185,7 @@ var MmtpRouter = class {
18812
19185
  enableMseAssembler(packetId, config, catalogTrackName) {
18813
19186
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
18814
19187
  const previous = this.#mseAssemblers.get(assemblerKey);
19188
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
18815
19189
  if (previous) {
18816
19190
  previous.flush();
18817
19191
  previous.dispose();
@@ -18962,7 +19336,8 @@ var MmtpRouter = class {
18962
19336
  fec,
18963
19337
  k,
18964
19338
  offsets: /* @__PURE__ */ new Map(),
18965
- moqBlocks: /* @__PURE__ */ new Set()
19339
+ moqBlocks: /* @__PURE__ */ new Set(),
19340
+ rebuilt: /* @__PURE__ */ new Map()
18966
19341
  };
18967
19342
  this.#overlays.set(repairPacketId, inst);
18968
19343
  return () => {
@@ -18992,12 +19367,18 @@ var MmtpRouter = class {
18992
19367
  */
18993
19368
  resetKeyframeOverlays(sourcePacketId, catalogTrackName) {
18994
19369
  for (const inst of this.#overlaysForSource(sourcePacketId, catalogTrackName)) this.#resetOverlay(inst);
19370
+ for (const [name, stream] of this.#streams.get(sourcePacketId) ?? []) {
19371
+ if (catalogTrackName !== void 0 && name !== catalogTrackName) continue;
19372
+ stream.overlayToBase.routed.clear();
19373
+ stream.overlayToBase.pending.clear();
19374
+ }
18995
19375
  }
18996
19376
  #resetOverlay(inst) {
18997
19377
  inst.fec.resetTrack(inst.repairPacketId, inst.streamName);
18998
19378
  inst.last = void 0;
18999
19379
  inst.offsets.clear();
19000
19380
  inst.moqBlocks.clear();
19381
+ inst.rebuilt.clear();
19001
19382
  }
19002
19383
  #overlaysForSource(sourcePacketId, catalogTrackName) {
19003
19384
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -19048,18 +19429,33 @@ var MmtpRouter = class {
19048
19429
  * A source packet that carries a 0x8B01 overlay SS_ID is also a symbol of
19049
19430
  * every overlay installed for its source, at that SS_ID, with the bytes the
19050
19431
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
19051
- * included (7.1, 7.4.3).
19052
- */
19053
- #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source) {
19432
+ * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
19433
+ * FEC reads it.
19434
+ *
19435
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
19436
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
19437
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
19438
+ * the stream unstamped at the SS_ID offset it states, for the release gate
19439
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
19440
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
19441
+ */
19442
+ #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
19054
19443
  if (this.#overlays.size === 0) return;
19055
19444
  const ssId = keyframeOverlaySsId(header);
19056
19445
  if (ssId === void 0) return;
19446
+ let rebuiltPsn;
19057
19447
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
19058
19448
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
19449
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
19450
+ inst.rebuilt.delete(ssId);
19059
19451
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
19060
19452
  if (identity !== null) {
19061
19453
  inst.offsets.delete(identity.mpuSequenceNumber);
19062
- inst.offsets.set(identity.mpuSequenceNumber, ssId - sequenceNumber >>> 0);
19454
+ inst.offsets.set(identity.mpuSequenceNumber, {
19455
+ psnOffset: ssId - sequenceNumber >>> 0,
19456
+ overlaySsId: ssId,
19457
+ ...baseSsId === void 0 ? {} : { baseSsId }
19458
+ });
19063
19459
  if (inst.offsets.size > OVERLAY_OFFSET_MPUS) inst.offsets.delete(inst.offsets.keys().next().value);
19064
19460
  }
19065
19461
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -19081,6 +19477,14 @@ var MmtpRouter = class {
19081
19477
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
19082
19478
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
19083
19479
  }
19480
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
19481
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
19482
+ if (rebuiltPsn !== sequenceNumber) {
19483
+ this.#restampedRecoveredSeqs++;
19484
+ } else if (baseSsId !== void 0) {
19485
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19486
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
19487
+ }
19084
19488
  }
19085
19489
  #noteOverlayMoqBlock(inst, blockStart) {
19086
19490
  inst.moqBlocks.add(blockStart);
@@ -19114,11 +19518,16 @@ var MmtpRouter = class {
19114
19518
  }
19115
19519
  /**
19116
19520
  * Route an overlay-recovered block's packets as source media of the
19117
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
19118
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
19119
- * base re-stamp, no block advance. Each packet's wire sequence is restored
19120
- * from its keyframe's own offset; without one, a stream the base never
19121
- * re-stamped keeps the header's sequence and any other drops the packet.
19521
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
19522
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
19523
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
19524
+ * base FEC recovered does, so it waits behind base frames still in flight,
19525
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
19526
+ * longer than unanchored; one whose base SS_ID is undetermined has no
19527
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
19528
+ * advance. Each packet's wire sequence is restored from its keyframe's own
19529
+ * offset; without one, a stream the base never re-stamped keeps the
19530
+ * header's sequence and any other drops the packet.
19122
19531
  */
19123
19532
  #routeOverlayRecovered(inst, blockStart, recovered) {
19124
19533
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -19138,22 +19547,139 @@ var MmtpRouter = class {
19138
19547
  const streamKey = this.#mediaStreamKey(sourcePacketId, sourceName);
19139
19548
  const restamped = this.#restampedStreams.has(streamKey);
19140
19549
  const restored = /* @__PURE__ */ new Set();
19550
+ const baseSsIds = /* @__PURE__ */ new Map();
19551
+ const gateOnly = /* @__PURE__ */ new Set();
19141
19552
  const symbols = result.symbols.flatMap((sym) => {
19142
- const offset = inst.offsets.get(sym.fragment.mpuSequenceNumber);
19143
- if (offset !== void 0) {
19144
- const packetSequenceNumber = serial32Add(blockStart, sym.index) - offset >>> 0;
19553
+ const overlaySsId = serial32Add(blockStart, sym.index);
19554
+ const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
19555
+ if (anchor !== void 0) {
19556
+ const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
19145
19557
  restored.add(packetSequenceNumber);
19146
- return [{ ...sym, packetSequenceNumber }];
19558
+ const out = { ...sym, packetSequenceNumber };
19559
+ const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
19560
+ if (baseSsId !== void 0) {
19561
+ baseSsIds.set(sym.index, baseSsId);
19562
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19563
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
19564
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
19565
+ }
19566
+ }
19567
+ return [out];
19568
+ }
19569
+ if (!restamped) {
19570
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19571
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
19572
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
19573
+ if (baseSsId !== void 0) {
19574
+ baseSsIds.set(sym.index, baseSsId);
19575
+ if (fedSsId === void 0) gateOnly.add(sym.index);
19576
+ } else {
19577
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
19578
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
19579
+ }
19580
+ return [sym];
19147
19581
  }
19148
- if (!restamped) return [sym];
19149
19582
  this.#overlayStats.unsequencedDropped++;
19150
19583
  return [];
19151
19584
  });
19152
19585
  this.#overlayStats.recovered++;
19586
+ const mpuFirst = /* @__PURE__ */ new Map();
19587
+ for (const sym of symbols) {
19588
+ const ssId = baseSsIds.get(sym.index);
19589
+ const mpu = sym.fragment.mpuSequenceNumber;
19590
+ const first = mpuFirst.get(mpu);
19591
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
19592
+ }
19593
+ const firstSsIds = /* @__PURE__ */ new Map();
19594
+ for (const sym of symbols) {
19595
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
19596
+ }
19153
19597
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
19154
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
19598
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
19599
+ baseSsIds,
19600
+ firstSsIds
19155
19601
  });
19156
19602
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
19603
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
19604
+ }
19605
+ /**
19606
+ * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
19607
+ * its base block too, once its base SS_ID is determined (overlayBaseSsId,
19608
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
19609
+ * base recovery showed; `baseSsIds` holds no other),
19610
+ * so it is fed to the base decoder as a rebuilt source
19611
+ * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
19612
+ * fewer to solve, and its repair can recover the block's other packets.
19613
+ * A base block no repair has stated yet takes it when one does
19614
+ * (#feedPendingRebuilt).
19615
+ *
19616
+ * The overlay route already handled each packet fed (delivered it, or
19617
+ * held an untimed head for its FT=1), so a base recovery routes none of
19618
+ * them again (#routeVerifiedFecSymbols): a second recovered copy of a
19619
+ * held head would wait in the parser for timing its first copy consumed.
19620
+ * Only an overlay block decoded from multicast symbols alone is fed: with
19621
+ * a MoQ symbol in it, the base block's recovery would depend on bytes
19622
+ * that crossed no multicast socket, which the provenance counted from the
19623
+ * block's own arrivals cannot show.
19624
+ */
19625
+ #feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds) {
19626
+ const fec = this.#fecManager;
19627
+ const owner = inst.leg.sourcePacketId;
19628
+ const name = inst.leg.sourceCatalogTrackName;
19629
+ if (!fec?.feedRebuiltSourceSymbol || inst.moqBlocks.has(blockStart)) return;
19630
+ if (this.#classifyPacketId(owner) === null || fec.isTrackConfigured?.(owner) === false) return;
19631
+ const { duplicates, overlayToBase: { routed } } = this.#stream(owner, name);
19632
+ const feeds = [];
19633
+ for (const sym of symbols) {
19634
+ if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
19635
+ const ssId = baseSsIds.get(sym.index);
19636
+ if (ssId === void 0) {
19637
+ this.#overlayStats.baseUndetermined++;
19638
+ continue;
19639
+ }
19640
+ routed.delete(ssId);
19641
+ routed.add(ssId);
19642
+ if (routed.size > OVERLAY_ROUTED_LIMIT) routed.delete(routed.values().next().value);
19643
+ feeds.push([ssId, sym.rawSymbol]);
19644
+ }
19645
+ for (const [ssId, symbolData] of feeds) {
19646
+ if (this.#classifyPacketId(owner) === null) return;
19647
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
19648
+ }
19649
+ }
19650
+ /** Feed one rebuilt source to its base block, or keep it until a repair states that block. */
19651
+ #feedRebuiltToBase(owner, name, ssId, symbolData) {
19652
+ const fec = this.#fecManager;
19653
+ if (!fec?.feedRebuiltSourceSymbol) return;
19654
+ const coords = fec.locateIsoSource?.(owner, name, ssId);
19655
+ if (coords == null) {
19656
+ const pending = this.#stream(owner, name).overlayToBase.pending;
19657
+ pending.delete(ssId);
19658
+ pending.set(ssId, symbolData.slice());
19659
+ if (pending.size > OVERLAY_PENDING_LIMIT) pending.delete(pending.keys().next().value);
19660
+ return;
19661
+ }
19662
+ const fed = fec.feedRebuiltSourceSymbol(owner, ssId, symbolData, name);
19663
+ if (!fed.taken) return;
19664
+ this.#overlayStats.baseFed++;
19665
+ if (fed.recovered === null) return;
19666
+ const sbn = coords.sbn;
19667
+ this.#routeRecoveredBlock(sbn, fed.recovered, owner, name, () => {
19668
+ fec.cancelBlockTimeout(sbn, owner, name);
19669
+ fec.countRecovery(owner, sbn, name);
19670
+ fec.markBlockCompleted(sbn, owner, name);
19671
+ });
19672
+ }
19673
+ /** A repair stated `block`: the rebuilt sources that waited for it join it now. */
19674
+ #feedPendingRebuilt(owner, name, block) {
19675
+ const pending = this.#streams.get(owner)?.get(name)?.overlayToBase.pending;
19676
+ if (pending === void 0 || pending.size === 0) return;
19677
+ for (const [ssId, symbolData] of [...pending]) {
19678
+ if (this.#classifyPacketId(owner) === null) return;
19679
+ if (serial32Distance(block.start, ssId) >= block.length) continue;
19680
+ pending.delete(ssId);
19681
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
19682
+ }
19157
19683
  }
19158
19684
  /** fec-multicast-00 §6.6: report each base block whose RAP MFU fragments
19159
19685
  * the overlay restored, when the keyframe's FT=0 and FT=1 are held too. A
@@ -19293,6 +19819,10 @@ var MmtpRouter = class {
19293
19819
  get unadmittedListedDropCount() {
19294
19820
  return this.#unadmittedListedDrops;
19295
19821
  }
19822
+ /** 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. */
19823
+ get admittedSourceDatagramCount() {
19824
+ return this.#admittedSourceDatagrams;
19825
+ }
19296
19826
  /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
19297
19827
  get unlistedRepairSetAsideCount() {
19298
19828
  return this.#unlistedRepairSetAside;
@@ -19779,6 +20309,8 @@ var MmtpRouter = class {
19779
20309
  )) return;
19780
20310
  fec.noteBlockActivity?.(blockStart, ownerPacketId, catalogTrackName);
19781
20311
  fec.noteRepairGroupLength?.(blockStart, ownerPacketId, repair.rsbLength, catalogTrackName);
20312
+ this.#feedPendingRebuilt(ownerPacketId, catalogTrackName, placement.block);
20313
+ if (this.#classifyPacketId(ownerPacketId) === null) return;
19782
20314
  const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
19783
20315
  const recovered = fec.feedRepairSymbol(
19784
20316
  ownerPacketId,
@@ -19829,7 +20361,7 @@ var MmtpRouter = class {
19829
20361
  catalogTrackName
19830
20362
  )) continue;
19831
20363
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
19832
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
20364
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
19833
20365
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
19834
20366
  }
19835
20367
  if (payload.oversized) continue;
@@ -19916,6 +20448,8 @@ var MmtpRouter = class {
19916
20448
  this.#droppedPreSyncVideo.delete(streamKey);
19917
20449
  this.#latestVideoSeqByStream.delete(streamKey);
19918
20450
  this.#ssIdSeqOffsetByStream.delete(streamKey);
20451
+ this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
20452
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
19919
20453
  this.#multicastRapTwinByStream.delete(streamKey);
19920
20454
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
19921
20455
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -20042,6 +20576,12 @@ var MmtpRouter = class {
20042
20576
  * the outgoing stream stops. The hold is bounded by the incoming stream's
20043
20577
  * own RAP cadence, so no timer is involved.
20044
20578
  *
20579
+ * While the switch is staged, the FEC release gate lets a keyframe the
20580
+ * overlay rebuilt reach it, on either side, when the keyframe did before
20581
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
20582
+ * decides on what each side delivered, and the commit discards the gate's
20583
+ * frames of the outgoing stream.
20584
+ *
20045
20585
  * The commit is one synchronous transition inside the frame path: the
20046
20586
  * outgoing stream's already-admitted frames are released (its queued FEC
20047
20587
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -20092,6 +20632,9 @@ var MmtpRouter = class {
20092
20632
  droppedIncomingFrames: 0
20093
20633
  };
20094
20634
  this.#staged = state;
20635
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
20636
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
20637
+ }
20095
20638
  return {
20096
20639
  cancel: () => {
20097
20640
  if (this.#staged !== state) return false;
@@ -20174,7 +20717,17 @@ var MmtpRouter = class {
20174
20717
  */
20175
20718
  #routeParsedFrame(data, meta) {
20176
20719
  if (this.#classifyPacketId(meta.packetId) === null) return;
20177
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
20720
+ if (this.#staged !== null) {
20721
+ let consumed = false;
20722
+ this.#fecPokeDepth++;
20723
+ try {
20724
+ consumed = this.#interceptSwitchFrame(data, meta);
20725
+ } finally {
20726
+ this.#fecPokeDepth--;
20727
+ this.#flushPendingFecPokes();
20728
+ }
20729
+ if (consumed) return;
20730
+ }
20178
20731
  this.#deliverParsedFrame(data, meta);
20179
20732
  }
20180
20733
  #commitStreamSwitch(state, rap, reason) {
@@ -20326,12 +20879,16 @@ var MmtpRouter = class {
20326
20879
  this.#parser.deferFecRelease(work);
20327
20880
  } finally {
20328
20881
  this.#fecPokeDepth--;
20329
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
20330
- const pokes = [...this.#pendingFecPokes.values()];
20331
- this.#pendingFecPokes.clear();
20332
- for (const poke of pokes) {
20333
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20334
- }
20882
+ this.#flushPendingFecPokes();
20883
+ }
20884
+ }
20885
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
20886
+ #flushPendingFecPokes() {
20887
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
20888
+ const pokes = [...this.#pendingFecPokes.values()];
20889
+ this.#pendingFecPokes.clear();
20890
+ for (const poke of pokes) {
20891
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20335
20892
  }
20336
20893
  }
20337
20894
  }
@@ -20409,6 +20966,14 @@ var MmtpRouter = class {
20409
20966
  onRap: (packetId, catalogTrackName, ssId) => {
20410
20967
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
20411
20968
  },
20969
+ // A staged switch commits on when each side's frames reach it
20970
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
20971
+ // they did unanchored.
20972
+ releaseUnanchored: (packetId, catalogTrackName) => {
20973
+ const staged = this.#staged;
20974
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
20975
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
20976
+ },
20412
20977
  onReleased: (data, meta) => {
20413
20978
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
20414
20979
  const timing = meta.authoredTiming;
@@ -20550,6 +21115,7 @@ var MmtpRouter = class {
20550
21115
  const parsed = this.#parser.parsePacket(packet);
20551
21116
  if (!parsed) return;
20552
21117
  const info = parsed.info;
21118
+ if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
20553
21119
  if (source === "multicast" && !manifestAdmitted) {
20554
21120
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
20555
21121
  }
@@ -20831,7 +21397,8 @@ var MmtpRouter = class {
20831
21397
  parsed.header,
20832
21398
  info.sequenceNumber,
20833
21399
  info.rapFlag,
20834
- source
21400
+ source,
21401
+ fecPayloadId?.ssId
20835
21402
  );
20836
21403
  }
20837
21404
  }
@@ -20857,7 +21424,8 @@ var MmtpRouter = class {
20857
21424
  source: parserOptions?.source,
20858
21425
  deliveryProvenance: parserOptions?.deliveryProvenance,
20859
21426
  catalogTrackName: parserOptions?.catalogTrackName,
20860
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
21427
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
21428
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
20861
21429
  };
20862
21430
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
20863
21431
  else this.#parser.feed(packet, feedOptions);
@@ -20981,7 +21549,8 @@ var MmtpRouter = class {
20981
21549
  if (stream === void 0) {
20982
21550
  stream = {
20983
21551
  key: JSON.stringify([packetId, catalogTrackName ?? null]),
20984
- duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId))
21552
+ duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId)),
21553
+ overlayToBase: { routed: /* @__PURE__ */ new Set(), pending: /* @__PURE__ */ new Map() }
20985
21554
  };
20986
21555
  byName.set(catalogTrackName, stream);
20987
21556
  }
@@ -21259,6 +21828,13 @@ var MmtpRouter = class {
21259
21828
  * frames by epoch only if pre-protection input ever matters.
21260
21829
  */
21261
21830
  #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete, assisted = false) {
21831
+ const overlayRouted = ownerPacketId == null ? void 0 : this.#streams.get(ownerPacketId)?.get(catalogTrackName)?.overlayToBase.routed;
21832
+ if (overlayRouted !== void 0 && overlayRouted.size > 0) {
21833
+ result = {
21834
+ ...result,
21835
+ symbols: result.symbols.filter((sym) => !overlayRouted.has(this.#fecAnchorForRecovered(blockId, sym.index)))
21836
+ };
21837
+ }
21262
21838
  const entry = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
21263
21839
  const receiver = entry === void 0 || entry === "ambiguous" ? entry : entry.receiver;
21264
21840
  const userAgent = !assisted && entry !== void 0 && entry !== "ambiguous" && entry.protected === true && entry.userAgent === true;
@@ -21315,7 +21891,12 @@ var MmtpRouter = class {
21315
21891
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
21316
21892
  if (ownerPacketId == null) return;
21317
21893
  if (this.#classifyPacketId(ownerPacketId) === null) return;
21318
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
21894
+ const fecSbnOf = (index) => {
21895
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
21896
+ const fecSbn = overlay.baseSsIds.get(index);
21897
+ const fecSbnFirst = overlay.firstSsIds.get(index);
21898
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
21899
+ };
21319
21900
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
21320
21901
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
21321
21902
  if (ssIdSeqOffset !== void 0) {
@@ -21323,7 +21904,10 @@ var MmtpRouter = class {
21323
21904
  ...result,
21324
21905
  symbols: result.symbols.map((sym) => {
21325
21906
  const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
21326
- if (wire === sym.packetSequenceNumber) return sym;
21907
+ if (wire === sym.packetSequenceNumber) {
21908
+ this.#unstampedSsIdSeqOffsetByStream.set(streamKey, ssIdSeqOffset);
21909
+ return sym;
21910
+ }
21327
21911
  this.#restampedRecoveredSeqs++;
21328
21912
  this.#restampedStreams.add(streamKey);
21329
21913
  return { ...sym, packetSequenceNumber: wire };
@@ -22858,6 +23442,12 @@ function isNonNegativeSafeInteger(value) {
22858
23442
  function isSymbolCounts(value) {
22859
23443
  return isRecord(value) && hasExactKeys(value, ["multicast", "moq"]) && isNonNegativeSafeInteger(value["multicast"]) && isNonNegativeSafeInteger(value["moq"]);
22860
23444
  }
23445
+ function isSpanFailure(value) {
23446
+ if (!isRecord(value) || !hasExactKeys(value, ["length", "sources"])) return false;
23447
+ const length = value["length"];
23448
+ const sources = value["sources"];
23449
+ return Number.isSafeInteger(length) && length > 0 && isNonNegativeSafeInteger(sources) && sources < length;
23450
+ }
22861
23451
  function isNullableNonNegative(value) {
22862
23452
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
22863
23453
  }
@@ -22877,7 +23467,10 @@ function isRepairLifecycleEvent(value) {
22877
23467
  case "recovered":
22878
23468
  return hasExactKeys(value, ["version", "type", "block", "blockClass", "via", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && (value["via"] === "inband" || value["via"] === "quic") && isSymbolCounts(value["symbols"]);
22879
23469
  case "failed":
22880
- return hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]);
23470
+ return hasExactKeys(
23471
+ value,
23472
+ "span" in value ? ["version", "type", "block", "blockClass", "symbols", "span"] : ["version", "type", "block", "blockClass", "symbols"]
23473
+ ) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]) && (!("span" in value) || isSpanFailure(value["span"]));
22881
23474
  case "repair-preempted":
22882
23475
  case "repair-deferred":
22883
23476
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
@@ -23143,7 +23736,7 @@ var MulticastManager = class {
23143
23736
  onPublisherRestart: (packetId, catalogTrackName) => {
23144
23737
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
23145
23738
  },
23146
- onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
23739
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass, span) => {
23147
23740
  const pathCount = this.#fec.blockPathCount(
23148
23741
  sbn,
23149
23742
  packetId,
@@ -23161,7 +23754,8 @@ var MulticastManager = class {
23161
23754
  symbols: {
23162
23755
  multicast: pathCount?.multicastSymbols ?? 0,
23163
23756
  moq: pathCount?.moqSymbols ?? 0
23164
- }
23757
+ },
23758
+ ...span === void 0 ? {} : { span }
23165
23759
  });
23166
23760
  },
23167
23761
  onFrameGap: (decision) => {
@@ -24541,10 +25135,12 @@ var MulticastManager = class {
24541
25135
  * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
24542
25136
  * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
24543
25137
  * pending hole and reported here, and `closeIsoHoles` must be called for it
24544
- * once its range FETCH ends (or none is sent).
25138
+ * once its range FETCH ends (or none is sent). `onExpired` is told of a
25139
+ * pending hole the stream runs past the locator's horizon: returning true,
25140
+ * the caller closes it (`closeIsoHoles`); otherwise it is discarded.
24545
25141
  */
24546
- onUndelimitedLoss(cb) {
24547
- this.#fec.setUndelimitedLossHandler(cb);
25142
+ onUndelimitedLoss(cb, onExpired) {
25143
+ this.#fec.setUndelimitedLossHandler(cb, onExpired ?? null);
24548
25144
  }
24549
25145
  /**
24550
25146
  * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
@@ -24780,7 +25376,8 @@ var MulticastManager = class {
24780
25376
  "stream" in event ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
24781
25377
  ...event,
24782
25378
  block: Object.freeze({ ...event.block }),
24783
- ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {}
25379
+ ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {},
25380
+ ..."span" in event && event.span !== void 0 ? { span: Object.freeze({ ...event.span }) } : {}
24784
25381
  }
24785
25382
  );
24786
25383
  if (this.#logRepairLifecycle) {