@blockcast/mmt-container 2.2.0-main.2c4d96d3ffc2 → 2.2.0-main.34b53d33bace

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 (60) hide show
  1. package/dist/browser-runtime.js +954 -157
  2. package/dist/browser-runtime.js.map +3 -3
  3. package/dist/cmaf-block-assembler.js +92 -1
  4. package/dist/cmaf-block-assembler.js.map +2 -2
  5. package/dist/codec-utils.d.ts.map +1 -1
  6. package/dist/codec-utils.js +92 -1
  7. package/dist/codec-utils.js.map +2 -2
  8. package/dist/delta-fallback-config.js.map +1 -1
  9. package/dist/fec-manager.d.ts +71 -14
  10. package/dist/fec-manager.d.ts.map +1 -1
  11. package/dist/fec-manager.js +300 -60
  12. package/dist/fec-manager.js.map +2 -2
  13. package/dist/fec-worker-setup.js.map +1 -1
  14. package/dist/index.d.ts +1 -1
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js.map +2 -2
  17. package/dist/iso-block-locator.d.ts +39 -13
  18. package/dist/iso-block-locator.d.ts.map +1 -1
  19. package/dist/iso-block-locator.js +80 -25
  20. package/dist/iso-block-locator.js.map +2 -2
  21. package/dist/media-router.js.map +1 -1
  22. package/dist/mmtp-container-parser.d.ts +63 -10
  23. package/dist/mmtp-container-parser.d.ts.map +1 -1
  24. package/dist/mmtp-container-parser.js +218 -18
  25. package/dist/mmtp-container-parser.js.map +2 -2
  26. package/dist/mmtp-container-parser.no-modules.js +217 -19
  27. package/dist/mmtp-container-parser.no-modules.js.map +3 -3
  28. package/dist/mmtp-decode-pipeline.js +218 -18
  29. package/dist/mmtp-decode-pipeline.js.map +2 -2
  30. package/dist/mmtp-router.d.ts +22 -9
  31. package/dist/mmtp-router.d.ts.map +1 -1
  32. package/dist/mmtp-router.js +384 -51
  33. package/dist/mmtp-router.js.map +3 -3
  34. package/dist/multicast-manager.d.ts +26 -3
  35. package/dist/multicast-manager.d.ts.map +1 -1
  36. package/dist/multicast-manager.js +774 -130
  37. package/dist/multicast-manager.js.map +3 -3
  38. package/dist/multicast-transport.js +2 -2
  39. package/dist/multicast-transport.js.map +2 -2
  40. package/dist/no-modules.js +218 -18
  41. package/dist/no-modules.js.map +3 -3
  42. package/dist/repair-fetch.d.ts +38 -8
  43. package/dist/repair-fetch.d.ts.map +1 -1
  44. package/dist/repair-fetch.js +286 -27
  45. package/dist/repair-fetch.js.map +3 -3
  46. package/dist/track-session.d.ts.map +1 -1
  47. package/dist/track-session.js +1 -0
  48. package/dist/track-session.js.map +2 -2
  49. package/dist/wasm-mmtp-container-parser.js +218 -18
  50. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  51. package/package.json +5 -5
  52. package/src/codec-utils.ts +121 -1
  53. package/src/fec-manager.ts +316 -34
  54. package/src/index.ts +2 -0
  55. package/src/iso-block-locator.ts +114 -31
  56. package/src/mmtp-container-parser.ts +238 -21
  57. package/src/mmtp-router.ts +271 -58
  58. package/src/multicast-manager.ts +136 -16
  59. package/src/repair-fetch.ts +366 -50
  60. 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;
@@ -2178,6 +2233,10 @@ var FECManager = class _FECManager {
2178
2233
  // 'pending' forever, which would park every later frame of its stream in
2179
2234
  // the in-order release gate. Each entry owns its handle; the callback
2180
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
+ */
2181
2240
  this.#pendingWorkerCleanupBounds = /* @__PURE__ */ new Map();
2182
2241
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
2183
2242
  this.#blockSourceCounts = /* @__PURE__ */ new Map();
@@ -2194,10 +2253,14 @@ var FECManager = class _FECManager {
2194
2253
  // SSB_length source arrivals and recoverable from SSB_length received
2195
2254
  // symbols; waiting for K fails every one of them.
2196
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();
2197
2259
  this.#ssbLengthConflictCount = 0;
2198
2260
  this.#blockRepairRsIds = /* @__PURE__ */ new Map();
2199
2261
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
2200
- // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
2262
+ // symbols its repair group carries; 0 for a repair-less span no repair can
2263
+ // state (#openIsoSpan). Same lifecycle as #blockRepairRsIds.
2201
2264
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
2202
2265
  /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
2203
2266
  this.#heldLayerStates = /* @__PURE__ */ new Map();
@@ -2391,7 +2454,10 @@ var FECManager = class _FECManager {
2391
2454
  // arrives via onBlockRecovered callback.
2392
2455
  this.onBlockStarted = null;
2393
2456
  this.onBlockComplete = null;
2394
- /** A block reached its fail bound. `blockClass` is its class at failure. */
2457
+ /**
2458
+ * A block reached its fail bound. `blockClass` is its class at failure.
2459
+ * `span` is set when what failed is a repair-less span starting at `sbn`.
2460
+ */
2395
2461
  this.onBlockFailed = null;
2396
2462
  /**
2397
2463
  * Fired once per stream when its Worker decoder stops being routable.
@@ -2433,12 +2499,24 @@ var FECManager = class _FECManager {
2433
2499
  * for it, which it must be.
2434
2500
  */
2435
2501
  this.#onUndelimitedLoss = null;
2502
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
2503
+ this.#onIsoHoleExpired = null;
2436
2504
  /** A block every symbol of which vanished was created by SBN evidence. */
2437
2505
  this.onBlockVanished = null;
2438
2506
  /** A block reached a terminal state (completed, recovered, or failed). */
2439
2507
  this.onBlockResolved = null;
2440
2508
  /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
2441
2509
  this.onSourceDiscontinuity = null;
2510
+ /**
2511
+ * The span and tolerance the catalog states for a keyframe overlay
2512
+ * installed over a source track (draft-ramadan-moq-mmt-02 7.4.1: the
2513
+ * overlay instance's own interleaveDepthMs and reorderToleranceMs), or
2514
+ * undefined while none is installed. A stated block only a late source
2515
+ * can complete, and a frame whose gap may hide a RAP behind a span only a
2516
+ * late source can fill, also wait for that overlay's repair
2517
+ * (#overlayLateWaitMs).
2518
+ */
2519
+ this.keyframeOverlayTiming = null;
2442
2520
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
2443
2521
  /**
2444
2522
  * A recovered source symbol. Return false when admission refused the
@@ -2477,6 +2555,7 @@ var FECManager = class _FECManager {
2477
2555
  #blockSourceEsis;
2478
2556
  #blockRebuiltEsis;
2479
2557
  #blockAuthoredLengths;
2558
+ #isoSpanKeys;
2480
2559
  #ssbLengthConflictCount;
2481
2560
  #blockRepairRsIds;
2482
2561
  #blockRsbLengths;
@@ -2543,6 +2622,7 @@ var FECManager = class _FECManager {
2543
2622
  #decoderUnavailableEvents;
2544
2623
  #repairSymbolSizeMismatchCount;
2545
2624
  #onUndelimitedLoss;
2625
+ #onIsoHoleExpired;
2546
2626
  #encodeTrackName(catalogTrackName) {
2547
2627
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
2548
2628
  if (encoded === void 0) {
@@ -3014,7 +3094,10 @@ var FECManager = class _FECManager {
3014
3094
  timer.handle = null;
3015
3095
  this.#requestRepair(sbn, packetId, catalogTrackName);
3016
3096
  };
3017
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
3097
+ timer.handle = setTimeout(
3098
+ onFire,
3099
+ this.#receiptAtMs === void 0 ? Math.max(0, deadlineMs - performance.now()) : this.#receiptTimerDelayMs(deadlineMs, 0)
3100
+ );
3018
3101
  this.#repairDeadlines.set(key, timer);
3019
3102
  }
3020
3103
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -3158,8 +3241,14 @@ var FECManager = class _FECManager {
3158
3241
  * Vanished blocks are not enumerated here: their starts are unknown until a
3159
3242
  * repair states them. The SS_IDs between two stated blocks become one
3160
3243
  * repair-less span when the later block's repair arrives (placeIsoRepair).
3244
+ *
3245
+ * A `held` source arrived before its block was known and is fed only now
3246
+ * that a repair, a span or a closed hole placed it: how far its block start
3247
+ * then lies behind the frontier measures how long the receiver held it, not
3248
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
3249
+ * it (BLO-52085).
3161
3250
  */
3162
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
3251
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn, held = false) {
3163
3252
  const streamKey = this.#streamKey(packetId, catalogTrackName);
3164
3253
  const now = performance.now();
3165
3254
  const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
@@ -3198,7 +3287,7 @@ var FECManager = class _FECManager {
3198
3287
  return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
3199
3288
  };
3200
3289
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
3201
- 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))) {
3290
+ 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))) {
3202
3291
  discontinuity();
3203
3292
  return;
3204
3293
  }
@@ -3460,17 +3549,21 @@ var FECManager = class _FECManager {
3460
3549
  this.#blockWaitDeadlinesMs.delete(key);
3461
3550
  this.#repairHoldUntilMs.delete(key);
3462
3551
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
3463
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName);
3552
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs);
3464
3553
  };
3465
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)));
3554
+ timer.handle = setTimeout(
3555
+ onFire,
3556
+ this.#receiptAtMs === void 0 ? Math.max(1, Math.ceil(deadlineMs - nowMs)) : this.#receiptTimerDelayMs(deadlineMs, 1)
3557
+ );
3466
3558
  this.#activeBlocks.set(key, timer);
3467
3559
  this.#indexBlockKey(key, sbn, packetId);
3468
3560
  }
3469
3561
  /**
3470
3562
  * Hand a block whose delivery is over to its decoder for finalization: the
3471
- * datagram deadline fired, or the ordered relay moved past it.
3563
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
3564
+ * is when it was due: its deadline, or now.
3472
3565
  */
3473
- #finalizeExpiredBlock(sbn, packetId, catalogTrackName) {
3566
+ #finalizeExpiredBlock(sbn, packetId, catalogTrackName, dueAtMs = performance.now()) {
3474
3567
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
3475
3568
  if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
3476
3569
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -3486,7 +3579,7 @@ var FECManager = class _FECManager {
3486
3579
  if (workerClient) {
3487
3580
  this.#pendingWorkerCleanups.add(key);
3488
3581
  this.#pendingWorkerCleanupClients.set(key, workerClient);
3489
- this.#boundOwedCleanup(key, packetId, workerClient);
3582
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs);
3490
3583
  workerClient.cleanup(sbn);
3491
3584
  } else {
3492
3585
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
@@ -3800,6 +3893,7 @@ var FECManager = class _FECManager {
3800
3893
  resetMap(this.#blockSourceEsis);
3801
3894
  resetMap(this.#blockRebuiltEsis);
3802
3895
  resetMap(this.#blockAuthoredLengths);
3896
+ resetSet(this.#isoSpanKeys);
3803
3897
  resetMap(this.#blockRepairRsIds);
3804
3898
  resetMap(this.#blockRsbLengths);
3805
3899
  resetMap(this.#heldLayerStates);
@@ -3925,6 +4019,7 @@ var FECManager = class _FECManager {
3925
4019
  dropMap(this.#blockSourceEsis);
3926
4020
  dropMap(this.#blockRebuiltEsis);
3927
4021
  dropMap(this.#blockAuthoredLengths);
4022
+ dropSet(this.#isoSpanKeys);
3928
4023
  dropMap(this.#blockRepairRsIds);
3929
4024
  dropMap(this.#blockRsbLengths);
3930
4025
  dropMap(this.#blockPathCounts);
@@ -4198,8 +4293,10 @@ var FECManager = class _FECManager {
4198
4293
  }
4199
4294
  /**
4200
4295
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
4201
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
4202
- * Undefined for a block that is not open.
4296
+ * (SSB_length) and RSB_length (each undefined until a repair stated it; a
4297
+ * repair-less span states its length, and RSB_length 0 when it is longer
4298
+ * than K, since no repair can reach it). Undefined for a block that is not
4299
+ * open.
4203
4300
  */
4204
4301
  blockSymbolCounts(sbn, packetId, catalogTrackName) {
4205
4302
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -4267,8 +4364,9 @@ var FECManager = class _FECManager {
4267
4364
  return true;
4268
4365
  }
4269
4366
  /**
4270
- * Drop a block's repair hold: its FETCH ended without delivering. The block
4271
- * falls back to its multicast wait, which may already have passed.
4367
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
4368
+ * back only a repair that cannot complete it. The block falls back to its
4369
+ * multicast wait, which may already have passed.
4272
4370
  */
4273
4371
  releaseRepairHold(sbn, packetId, catalogTrackName) {
4274
4372
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -4406,6 +4504,7 @@ var FECManager = class _FECManager {
4406
4504
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
4407
4505
  const evictedBefore = locator.heldEvicted;
4408
4506
  const held = locator.hold(ssId, source);
4507
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
4409
4508
  if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
4410
4509
  const evicted = locator.heldEvicted - evictedBefore;
4411
4510
  if (evicted > 0) {
@@ -4427,17 +4526,20 @@ var FECManager = class _FECManager {
4427
4526
  * contradicts a known block is refused (counted) and must be dropped.
4428
4527
  */
4429
4528
  placeIsoRepair(packetId, catalogTrackName, ssStart, ssbLength) {
4430
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength);
4529
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
4530
+ const placement = locator.placeRepair(ssStart, ssbLength);
4531
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
4431
4532
  if (placement.status !== "placed") {
4432
4533
  this.#isoRepairRefusedCount++;
4433
4534
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
4434
4535
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`);
4435
4536
  }
4537
+ if (placement.ofSpan !== void 0) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName);
4436
4538
  return placement;
4437
4539
  }
4540
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName));
4438
4541
  if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
4439
4542
  if (placement.hole !== void 0) {
4440
- const locator = this.#isoLocatorFor(packetId, catalogTrackName);
4441
4543
  const hole = placement.hole.block;
4442
4544
  const previous = locator.blockEndingAt(hole.start);
4443
4545
  const loss = {
@@ -4458,17 +4560,29 @@ var FECManager = class _FECManager {
4458
4560
  * `handler`, instead of a repair-less span; null restores spans. Set by the
4459
4561
  * range repair scheduler; applies to every stream from its next gap. The
4460
4562
  * handler and the deferral are one setting, so no hole is ever created with
4461
- * nobody to close it.
4563
+ * nobody to close it. `onExpired` is told of each pending hole the stream
4564
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
4565
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
4566
+ * reported; otherwise the hole is discarded with its sources.
4462
4567
  */
4463
- setUndelimitedLossHandler(handler) {
4568
+ setUndelimitedLossHandler(handler, onExpired = null) {
4464
4569
  this.#onUndelimitedLoss = handler;
4570
+ this.#onIsoHoleExpired = handler === null ? null : onExpired;
4465
4571
  this.#deferIsoGaps = handler !== null;
4466
4572
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
4467
4573
  }
4574
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
4575
+ #settleExpiredIsoHoles(locator, packetId, catalogTrackName) {
4576
+ for (const hole of locator.takeExpiredHoles()) {
4577
+ const expired = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length };
4578
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length);
4579
+ }
4580
+ }
4468
4581
  /**
4469
- * The range repair for a hole ended: every hole still pending inside
4470
- * `[start, start + length)` becomes a repair-less span. Returns those spans
4471
- * with the held sources they placed, for the caller to feed (MmtpRouter).
4582
+ * The range repair for a hole ended: every hole inside `[start, start +
4583
+ * length)`, pending or expired, becomes a repair-less span. Returns those
4584
+ * spans with the held sources they placed, for the caller to feed
4585
+ * (MmtpRouter).
4472
4586
  */
4473
4587
  closeIsoHoles(packetId, catalogTrackName, start, length) {
4474
4588
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
@@ -4484,10 +4598,25 @@ var FECManager = class _FECManager {
4484
4598
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
4485
4599
  * SS_ID of which vanished resolves through its deadline like any vanished
4486
4600
  * block.
4601
+ *
4602
+ * A span longer than K holds more than one block (SSB_length <= K), and the
4603
+ * locator states no block inside a span, only one exactly its range
4604
+ * (IsoBlockLocator.placeRepair): no repair, multicast or FETCHed, can ever
4605
+ * reach it. Its repair group is empty, so the repair scheduler FETCHes no
4606
+ * Group of it (group-cannot-complete). Every span still keeps its whole
4607
+ * wait (#lateSourceWaitMs): failing it early released the frames behind it
4608
+ * past a keyframe the overlay was still rebuilding (BLO-52085). The release
4609
+ * gate lets those frames go once only a late source can fill the gap
4610
+ * before them, as long after they arrived as the gap's decision allows
4611
+ * (isoRepairlessWaitMs).
4487
4612
  */
4488
4613
  #openIsoSpan(span, packetId, catalogTrackName) {
4489
4614
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
4490
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
4615
+ if (!this.#blockAuthoredLengths.has(key)) {
4616
+ this.#blockAuthoredLengths.set(key, span.block.length);
4617
+ this.#isoSpanKeys.add(key);
4618
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0);
4619
+ }
4491
4620
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
4492
4621
  }
4493
4622
  /**
@@ -4525,6 +4654,50 @@ var FECManager = class _FECManager {
4525
4654
  }
4526
4655
  return lost;
4527
4656
  }
4657
+ /**
4658
+ * The release gate's wait, from a frame's arrival, for the SS_IDs strictly
4659
+ * between two released frames' SS_IDs once only a late source can still
4660
+ * fill them, else undefined. That is when every one missing (neither
4661
+ * arrived nor held) lies in a repair-less span longer than K, which no
4662
+ * repair can state a block of (#openIsoSpan), and a multicast source at or
4663
+ * past `toSsId` arrived, so each is lost or reordered behind it (a MoQ
4664
+ * source shows nothing: MoQ streams overtake one another). The span itself
4665
+ * keeps its whole wait.
4666
+ *
4667
+ * The wait is the late-symbol allowance, unless `rapMayHide`: the gap may
4668
+ * hold a RAP packet an installed keyframe overlay can still rebuild (its
4669
+ * decision stalls, or it ends at a RAP that may lie past a whole MPU).
4670
+ * Then the frame waits as a stated block its group cannot complete does
4671
+ * (#overlayLateWaitMs): the allowance alone with no overlay installed, the
4672
+ * overlay's span plus the larger of the allowance and its tolerance, or,
4673
+ * for an overlay that states no span, the span's whole wait (undefined).
4674
+ */
4675
+ isoRepairlessWaitMs(packetId, catalogTrackName, fromSsId, toSsId, rapMayHide = false) {
4676
+ const config = this.#trackConfigs.get(packetId);
4677
+ if (config === void 0 || !_FECManager.#hasCatalogTiming(config)) return void 0;
4678
+ const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
4679
+ if (locator === void 0 || !locator.coversBetween(fromSsId, toSsId)) return void 0;
4680
+ const newestSource = locator.newestSource;
4681
+ if (newestSource === void 0 || serial32Precedes(newestSource, toSsId)) return void 0;
4682
+ let repairless = false;
4683
+ for (const block of locator.blocksBetween(fromSsId, toSsId)) {
4684
+ const key = this.#blockKey(block.start, packetId, catalogTrackName);
4685
+ if (this.#completedBlocks.has(key)) continue;
4686
+ if (block.span && block.length > locator.kMax) {
4687
+ repairless = true;
4688
+ continue;
4689
+ }
4690
+ const received = this.#blockSourceEsis.get(key);
4691
+ for (let esi = 0; esi < block.length; esi++) {
4692
+ const ssId = serial32Add(block.start, esi);
4693
+ if (!serial32Precedes(fromSsId, ssId) || !serial32Precedes(ssId, toSsId)) continue;
4694
+ if (!received?.has(esi) && !locator.isHeld(ssId)) return void 0;
4695
+ }
4696
+ }
4697
+ if (!repairless) return void 0;
4698
+ const waitMs = rapMayHide ? this.#overlayLateWaitMs(packetId, catalogTrackName, config) : this.#multicastWaitMs(config) - config.interleaveDepthMs;
4699
+ return waitMs === void 0 ? void 0 : Math.max(0, waitMs);
4700
+ }
4528
4701
  /**
4529
4702
  * iso-ssbg1-v1 block location: repair symbols it refused, oversize sources,
4530
4703
  * the sources held now for a block no repair has stated yet, and the held
@@ -4828,11 +5001,14 @@ var FECManager = class _FECManager {
4828
5001
  });
4829
5002
  client.onCleanupComplete((sbn) => {
4830
5003
  if (this.#releasedWorkerClients.has(client)) return;
4831
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
5004
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
5005
+ const cleanupKeys = owed.filter((key) => {
4832
5006
  const block = this.#parseBlockKey(key);
4833
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
5007
+ return block.packetId === packetId && block.sbn === sbn;
4834
5008
  });
4835
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
5009
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
5010
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
5011
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
4836
5012
  });
4837
5013
  client.onError((msg, code) => {
4838
5014
  const requestedKind = code ?? msg;
@@ -4902,9 +5078,11 @@ var FECManager = class _FECManager {
4902
5078
  * fail deadline already passed, so failing it is the decision that deadline
4903
5079
  * made. A late ack then finds nothing owed and is a no-op.
4904
5080
  */
4905
- #boundOwedCleanup(key, packetId, client) {
5081
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
4906
5082
  this.#clearOwedCleanupBound(key);
4907
5083
  const bound = {
5084
+ dueAtMs,
5085
+ askedAtMs: performance.now(),
4908
5086
  handle: setTimeout(() => {
4909
5087
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
4910
5088
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -5074,9 +5252,15 @@ var FECManager = class _FECManager {
5074
5252
  rebuilt = /* @__PURE__ */ new Set();
5075
5253
  this.#blockRebuiltEsis.set(key, rebuilt);
5076
5254
  }
5255
+ const config = this.#trackConfigs.get(packetId);
5256
+ const wasShort = config !== void 0 && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) !== void 0;
5077
5257
  rebuilt.add(located.esi);
5078
5258
  const recovered = this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn);
5079
- if (recovered === null) this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName);
5259
+ if (recovered === null && !this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName)) {
5260
+ if (wasShort && this.#activeBlocks.has(key) && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) === void 0) {
5261
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, this.#multicastWaitMs(config));
5262
+ }
5263
+ }
5080
5264
  return { taken: true, recovered };
5081
5265
  }
5082
5266
  /**
@@ -5319,7 +5503,7 @@ var FECManager = class _FECManager {
5319
5503
  const previous = locator.newestSource;
5320
5504
  if (!locator.noteSource(ssId) || previous === void 0) return;
5321
5505
  for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
5322
- if (block.span || !serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
5506
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
5323
5507
  this.#shortenUnrecoverableWait(
5324
5508
  this.#blockKey(block.start, packetId, catalogTrackName),
5325
5509
  block.start,
@@ -5337,18 +5521,54 @@ var FECManager = class _FECManager {
5337
5521
  * covers repair symbols paced after its sources, buys it nothing: it waits
5338
5522
  * the late-symbol allowance alone, the multicast wait less the span (the
5339
5523
  * catalog tolerance or the measured delivery gap). Undefined for any other
5340
- * block.
5524
+ * block. While a keyframe overlay is installed, the block waits for its
5525
+ * repair too (#overlayLateWaitMs). A repair-less span keeps its whole
5526
+ * wait, even one longer than K whose group is empty (#openIsoSpan): its
5527
+ * resolution is what releases the frames behind it, and failing it early
5528
+ * released them past a keyframe the overlay was still rebuilding, which
5529
+ * then arrived stale. The release gate lets them go instead
5530
+ * (isoRepairlessWaitMs).
5341
5531
  */
5342
5532
  #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
5533
+ if (this.#isoSpanKeys.has(key)) return void 0;
5343
5534
  const authoredLength = this.#blockAuthoredLengths.get(key);
5344
5535
  const rsbLength = this.#blockRsbLengths.get(key);
5345
5536
  if (authoredLength === void 0 || rsbLength === void 0) return void 0;
5346
- if ((this.#blockSourceCounts.get(key) ?? 0) + rsbLength >= authoredLength) return void 0;
5537
+ let present = this.#blockSourceCounts.get(key) ?? 0;
5538
+ const received = this.#blockSourceEsis.get(key);
5539
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
5540
+ if (present + rsbLength >= authoredLength) return void 0;
5347
5541
  const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
5348
5542
  if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
5349
5543
  return void 0;
5350
5544
  }
5351
- return this.#multicastWaitMs(config) - config.interleaveDepthMs;
5545
+ return this.#overlayLateWaitMs(packetId, catalogTrackName, config);
5546
+ }
5547
+ /**
5548
+ * How long a loss only a late source or an installed keyframe overlay can
5549
+ * still fill waits once a later source passed it: the late-symbol
5550
+ * allowance alone (the multicast wait less the span) while no overlay is
5551
+ * installed. An installed one (keyframeOverlayTiming) may still rebuild a
5552
+ * RAP packet the loss took: a second FEC instance over the same packets
5553
+ * (draft-ramadan-moq-mmt-02 7.4), whose repair is paced across its own
5554
+ * span, unrelated to the base's. That packet can complete a stated block
5555
+ * (feedRebuiltSourceSymbol), or play behind a span; giving the loss up
5556
+ * first lets the release gate pass the keyframe, whose rebuild then lands
5557
+ * stale. The overlay repair of a packet the loss took goes out within the
5558
+ * overlay's span of that packet (fec-core-00 9.3), and the later source was
5559
+ * sent after it, so the loss waits that span plus the larger of the
5560
+ * allowance and the overlay's own tolerance. An overlay that states no
5561
+ * span (its block may then span keyframes), or one whose wait is not
5562
+ * shorter than the whole multicast wait, leaves the whole wait: undefined.
5563
+ */
5564
+ #overlayLateWaitMs(packetId, catalogTrackName, config) {
5565
+ const waitMs = this.#multicastWaitMs(config);
5566
+ const allowanceMs = waitMs - config.interleaveDepthMs;
5567
+ const overlay = this.keyframeOverlayTiming?.(packetId, catalogTrackName);
5568
+ if (overlay === void 0) return allowanceMs;
5569
+ const overlaySpanMs = overlay.interleaveDepthMs ?? 0;
5570
+ const overlayWaitMs = overlaySpanMs + Math.max(allowanceMs, overlay.reorderToleranceMs ?? 0);
5571
+ return overlaySpanMs > 0 && overlayWaitMs < waitMs ? overlayWaitMs : void 0;
5352
5572
  }
5353
5573
  /**
5354
5574
  * Bring an open block's wait in to its late-source wait, when it has one.
@@ -5466,12 +5686,13 @@ var FECManager = class _FECManager {
5466
5686
  * the inactivity deadline on each symbol, records the symbol's in-band
5467
5687
  * classification evidence, and marks the block clean when all of its
5468
5688
  * authored source symbols arrived: the SSB_length a repair symbol declared,
5469
- * otherwise K.
5689
+ * otherwise K. `held` marks a source held unplaced since it arrived and
5690
+ * placed only now (see #noteSbnSeen).
5470
5691
  *
5471
5692
  * Throws for a packetId that was never configured, so a classified block
5472
5693
  * never reads the manager-global K or timeout.
5473
5694
  */
5474
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
5695
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
5475
5696
  const trackConfig = this.#trackConfigs.get(packetId);
5476
5697
  if (trackConfig === void 0) {
5477
5698
  throw new Error(
@@ -5487,7 +5708,8 @@ var FECManager = class _FECManager {
5487
5708
  catalogTrackName,
5488
5709
  "source",
5489
5710
  evidence.packetSequenceNumber,
5490
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
5711
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
5712
+ held
5491
5713
  );
5492
5714
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
5493
5715
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -5542,6 +5764,7 @@ var FECManager = class _FECManager {
5542
5764
  this.#blockSourceEsis.delete(key);
5543
5765
  this.#blockRebuiltEsis.delete(key);
5544
5766
  this.#blockAuthoredLengths.delete(key);
5767
+ this.#isoSpanKeys.delete(key);
5545
5768
  this.#blockRepairRsIds.delete(key);
5546
5769
  this.#blockRsbLengths.delete(key);
5547
5770
  this.#markTerminal(key, sbn, packetId, true);
@@ -5572,6 +5795,19 @@ var FECManager = class _FECManager {
5572
5795
  #receiptNow() {
5573
5796
  return this.#receiptAtMs ?? performance.now();
5574
5797
  }
5798
+ /**
5799
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
5800
+ * scope: counted from the receipt time, as the timer of a symbol fed when
5801
+ * it was received was, less the whole ms since. So it fires on the tick
5802
+ * that timer would have, never later than a delay counted from now, and
5803
+ * its handler still re-arms a timer that fires before its deadline.
5804
+ * Counted from now, a deadline set from the receipt time is rounded up
5805
+ * from another fraction of a ms (BLO-52085).
5806
+ */
5807
+ #receiptTimerDelayMs(deadlineMs, minMs) {
5808
+ const receivedAtMs = this.#receiptAtMs;
5809
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
5810
+ }
5575
5811
  /**
5576
5812
  * A held packet admitted late arms from its (earlier) receipt time; that
5577
5813
  * never pulls in a deadline later activity already armed. Outside a
@@ -5620,6 +5856,7 @@ var FECManager = class _FECManager {
5620
5856
  }
5621
5857
  #failBlock(sbn, packetId, catalogTrackName) {
5622
5858
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
5859
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
5623
5860
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
5624
5861
  this.#clearRepairDeadline(key);
5625
5862
  this.#clearBlockTimer(key);
@@ -5639,7 +5876,8 @@ var FECManager = class _FECManager {
5639
5876
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
5640
5877
  this.#fecStats.blocksFailed++;
5641
5878
  this.#statsForPacket(packetId).blocksFailed++;
5642
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5879
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5880
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
5643
5881
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
5644
5882
  }
5645
5883
  /**
@@ -5670,6 +5908,7 @@ var FECManager = class _FECManager {
5670
5908
  this.#blockSourceEsis.delete(key);
5671
5909
  this.#blockRebuiltEsis.delete(key);
5672
5910
  this.#blockAuthoredLengths.delete(key);
5911
+ this.#isoSpanKeys.delete(key);
5673
5912
  this.#blockRepairRsIds.delete(key);
5674
5913
  this.#blockRsbLengths.delete(key);
5675
5914
  this.#clearBlockTimer(key);
@@ -5762,6 +6001,7 @@ var FECManager = class _FECManager {
5762
6001
  this.#blockSourceEsis.clear();
5763
6002
  this.#blockRebuiltEsis.clear();
5764
6003
  this.#blockAuthoredLengths.clear();
6004
+ this.#isoSpanKeys.clear();
5765
6005
  this.#blockRepairRsIds.clear();
5766
6006
  this.#blockRsbLengths.clear();
5767
6007
  this.#heldLayerStates.clear();
@@ -7140,9 +7380,9 @@ async function openSubscription(rx, openedPromise, options, packetIds) {
7140
7380
  } catch (error) {
7141
7381
  throw new MulticastError("subscription-failed", "MulticastReceiver did not open", error);
7142
7382
  }
7143
- if (rx.integrityScheme !== INTEGRITY_SCHEME) {
7383
+ if (opened.integrityScheme !== INTEGRITY_SCHEME) {
7144
7384
  await rx.close();
7145
- throw unsupported(`integrity scheme ${String(rx.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
7385
+ throw unsupported(`integrity scheme ${String(opened.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
7146
7386
  }
7147
7387
  const events = new EventTarget();
7148
7388
  let state = "connected";
@@ -10478,9 +10718,10 @@ function isH264IntraSlice(nal) {
10478
10718
  const sliceType = readH264SliceType(nal);
10479
10719
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
10480
10720
  }
10721
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
10481
10722
  function readH264SliceType(nal) {
10482
10723
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
10483
- const rbsp = removeEmulationPrevention(nal.subarray(1));
10724
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
10484
10725
  const state = { bitOffset: 0 };
10485
10726
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
10486
10727
  return readUnsignedExpGolomb(rbsp, state);
@@ -10627,6 +10868,96 @@ if (void 0) {
10627
10868
  ]))).toBe(false);
10628
10869
  });
10629
10870
  });
10871
+ describe("readH264SliceType", () => {
10872
+ const wholeNalSliceType = (nal) => {
10873
+ if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
10874
+ const rbsp = removeEmulationPrevention(nal.subarray(1));
10875
+ const state = { bitOffset: 0 };
10876
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null;
10877
+ return readUnsignedExpGolomb(rbsp, state);
10878
+ };
10879
+ const hex2 = (text2) => Uint8Array.from(text2.match(/../g), (byte) => parseInt(byte, 16));
10880
+ const ue = (value) => {
10881
+ const code = (value + 1).toString(2);
10882
+ return "0".repeat(code.length - 1) + code;
10883
+ };
10884
+ const sliceNal = (bits) => {
10885
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, "0").match(/.{8}/g);
10886
+ const nal = [1];
10887
+ let zeros = 0;
10888
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
10889
+ if (zeros >= 2 && byte <= 3) {
10890
+ nal.push(3);
10891
+ zeros = 0;
10892
+ }
10893
+ nal.push(byte);
10894
+ zeros = byte === 0 ? zeros + 1 : 0;
10895
+ }
10896
+ return Uint8Array.from(nal);
10897
+ };
10898
+ const x264Slices = [
10899
+ ["64x48 P", hex2("419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176"), 5, false],
10900
+ ["64x48 B", hex2("419e414212fffeeade283707cb70f7"), 6, false],
10901
+ ["64x48 non-IDR I", hex2(
10902
+ "4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39a527e23eb34c8167fd"
10903
+ ), 7, true],
10904
+ ["1280x720 B, escape at byte 10", hex2(
10905
+ "01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e19b75d92170917306190f262fd58268702db2eff86a9651e48"
10906
+ ), 6, false],
10907
+ ["1280x720 P, escape at byte 15", hex2(
10908
+ "41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f02c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e85302da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3"
10909
+ ), 5, false],
10910
+ ["1280x720 B, escape at byte 22", hex2("01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352"), 6, false],
10911
+ ["7680x4320 IDR, first_mb_in_slice 97440", hex2(
10912
+ "650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9"
10913
+ ), null, true],
10914
+ ["7680x4320 P, first_mb_in_slice 32640", hex2(
10915
+ "410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020"
10916
+ ), 5, false],
10917
+ ["7680x4320 P, first_mb_in_slice 97440", hex2(
10918
+ "410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806"
10919
+ ), 5, false]
10920
+ ];
10921
+ const syntheticSlices = [
10922
+ ["an escape inside first_mb_in_slice", sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
10923
+ ["an escape between the fields", sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
10924
+ ["an escape inside slice_type", sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
10925
+ ["the longest fields, five escapes", sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
10926
+ ["the largest values", sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
10927
+ ["31 leading zeros in first_mb_in_slice", sliceNal(`${"0".repeat(31)}1`), null],
10928
+ ["31 leading zeros in slice_type", sliceNal(`1${"0".repeat(31)}1`), null],
10929
+ ["escapes running past the slice header", sliceNal(ue(0) + ue(5) + "0".repeat(400)), 5]
10930
+ ];
10931
+ test("reads the slice_type of real and synthetic slices", () => {
10932
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
10933
+ expect(readH264SliceType(nal), name).toBe(sliceType);
10934
+ }
10935
+ });
10936
+ test("matches the whole-NAL unescape at every truncation", () => {
10937
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
10938
+ for (let end = 0; end <= nal.length; end++) {
10939
+ const cut = nal.subarray(0, end);
10940
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut));
10941
+ }
10942
+ }
10943
+ });
10944
+ test("matches the whole-NAL unescape on zero-heavy NAL units", () => {
10945
+ const bytes = [0, 0, 0, 3, 1, 2, 128, 255];
10946
+ let seed = 1;
10947
+ const next = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) >>> 16;
10948
+ for (let i = 0; i < 5e3; i++) {
10949
+ const nal = new Uint8Array(2 + next() % 63);
10950
+ nal[0] = 65;
10951
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length];
10952
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal));
10953
+ }
10954
+ });
10955
+ test("classifies the x264 slices as keyframes or not", () => {
10956
+ for (const [name, nal, , keyframe] of x264Slices) {
10957
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe);
10958
+ }
10959
+ });
10960
+ });
10630
10961
  describe("avccToAnnexB", () => {
10631
10962
  test("converts with SPS/PPS on keyframe", () => {
10632
10963
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -13674,6 +14005,9 @@ function authoredGap(before, after) {
13674
14005
  function ssIdAfter(a, b) {
13675
14006
  return (a - b | 0) > 0;
13676
14007
  }
14008
+ function holdsRebuilt(stream) {
14009
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
14010
+ }
13677
14011
  var FecReleaseSequencer = class {
13678
14012
  #streams = /* @__PURE__ */ new Map();
13679
14013
  #gate;
@@ -13736,6 +14070,7 @@ var FecReleaseSequencer = class {
13736
14070
  stream.lastSbn = void 0;
13737
14071
  stream.discontinuity = false;
13738
14072
  stream.rapSsId = void 0;
14073
+ stream.sourced = false;
13739
14074
  }
13740
14075
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
13741
14076
  this.#recordStat("droppedStale");
@@ -13762,6 +14097,7 @@ var FecReleaseSequencer = class {
13762
14097
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
13763
14098
  else hi = mid;
13764
14099
  }
14100
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
13765
14101
  stream.buf.splice(lo, 0, frame);
13766
14102
  this.#drainUnlessDeferred(stream);
13767
14103
  }
@@ -13797,6 +14133,41 @@ var FecReleaseSequencer = class {
13797
14133
  }
13798
14134
  return false;
13799
14135
  }
14136
+ /**
14137
+ * These streams' sink is being replaced by one that has seen no source
14138
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
14139
+ * release to the sink being replaced the frames the unanchored path had
14140
+ * already released to it (#cursorPassed): there they waited in its queue,
14141
+ * which its replacement flushes. A stream that holds none is not drained:
14142
+ * it holds nothing the anchor kept back, and a drain would still force out
14143
+ * a frame held past the hold limit, which before the anchor waited for the
14144
+ * next push. Then treat the streams as unsourced until a source frame is
14145
+ * released.
14146
+ */
14147
+ unsource(packetId, catalogTrackName) {
14148
+ for (const stream of this.#streams.values()) {
14149
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
14150
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
14151
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
14152
+ else this.#drain(stream, true);
14153
+ }
14154
+ stream.sourced = false;
14155
+ }
14156
+ }
14157
+ }
14158
+ /**
14159
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
14160
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
14161
+ * packetId.
14162
+ */
14163
+ holdsRebuilt(packetId, catalogTrackName) {
14164
+ for (const stream of this.#streams.values()) {
14165
+ if (stream.packetId !== packetId) continue;
14166
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
14167
+ if (holdsRebuilt(stream)) return true;
14168
+ }
14169
+ return false;
14170
+ }
13800
14171
  /** Re-evaluate held gaps after FEC state changed. */
13801
14172
  poke(streamKey) {
13802
14173
  if (streamKey !== void 0) {
@@ -13888,16 +14259,32 @@ var FecReleaseSequencer = class {
13888
14259
  last: null,
13889
14260
  lastSbn: void 0,
13890
14261
  discontinuity: false,
13891
- rapSsId: void 0
14262
+ rapSsId: void 0,
14263
+ sourced: false,
14264
+ draining: 0
13892
14265
  };
13893
14266
  this.#streams.set(streamKey, stream);
13894
14267
  }
13895
14268
  return stream;
13896
14269
  }
13897
- #drain(stream) {
14270
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
14271
+ #drain(stream, asUnanchored = false) {
14272
+ stream.draining++;
14273
+ try {
14274
+ this.#drainLoop(stream, asUnanchored);
14275
+ } finally {
14276
+ stream.draining--;
14277
+ }
14278
+ }
14279
+ #drainLoop(stream, asUnanchored) {
13898
14280
  while (stream.buf.length > 0 && stream.last !== null) {
13899
14281
  const head = stream.buf[0];
13900
14282
  const last = stream.last;
14283
+ if (compareFrameOrder(head, last) <= 0) {
14284
+ stream.buf.shift();
14285
+ this.#release(stream, head, void 0);
14286
+ continue;
14287
+ }
13901
14288
  if (stream.discontinuity) {
13902
14289
  stream.discontinuity = false;
13903
14290
  stream.buf.shift();
@@ -13911,9 +14298,10 @@ var FecReleaseSequencer = class {
13911
14298
  }
13912
14299
  const headSbn = head.meta.fecSbn;
13913
14300
  const from = stream.lastSbn ?? headSbn;
13914
- const to = headSbn ?? stream.lastSbn;
14301
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
13915
14302
  let lost = [];
13916
14303
  const unanchored = from === void 0 && to === void 0;
14304
+ let unresolved = false;
13917
14305
  if (from !== void 0 && to !== void 0) {
13918
14306
  const resolved = this.#gate.resolvedLoss(
13919
14307
  stream.packetId,
@@ -13922,7 +14310,8 @@ var FecReleaseSequencer = class {
13922
14310
  Math.max(from, to),
13923
14311
  from
13924
14312
  );
13925
- if (resolved === null) {
14313
+ unresolved = resolved === null;
14314
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored) && !this.#unrepairableWaitOver(last, head, from, to)) {
13926
14315
  const heldMs = performance.now() - head.arrivedAtMs;
13927
14316
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
13928
14317
  this.#recordStat("forcedWindowFlushes");
@@ -13930,22 +14319,61 @@ var FecReleaseSequencer = class {
13930
14319
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
13931
14320
  continue;
13932
14321
  }
13933
- lost = resolved;
14322
+ lost = resolved ?? [];
13934
14323
  }
13935
14324
  stream.buf.shift();
13936
14325
  this.#release(
13937
14326
  stream,
13938
14327
  head,
13939
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
14328
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
13940
14329
  );
13941
14330
  }
13942
14331
  }
14332
+ /** The head has waited out a gap only a late source can still fill (FecReleaseGate.unrepairableWaitMs). */
14333
+ #unrepairableWaitOver(last, head, from, to) {
14334
+ const waitMs = this.#gate.unrepairableWaitMs?.(last, head, from, to);
14335
+ return waitMs !== void 0 && performance.now() - head.arrivedAtMs >= waitMs;
14336
+ }
14337
+ /**
14338
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
14339
+ * source cursor holds it unanchored, and neither does a later frame behind
14340
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
14341
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
14342
+ * like each frame that arrived in front of it since (stale there). The head
14343
+ * then goes, decided as it would be unanchored, once a frame the base path
14344
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
14345
+ * marked one: the base path has passed that one, so a frame still missing
14346
+ * before it can only come from a repair. It also goes while no source frame
14347
+ * has been released, when the direct path shows a recovered frame at once.
14348
+ * And it goes at once while a staged switch decides on when frames arrive
14349
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
14350
+ * sink being replaced: unanchored, it had already reached the sink.
14351
+ * The scan also writes: the `passed` marks it sets stay on the frames,
14352
+ * and push marks a frame it inserts in front of a marked one from them.
14353
+ */
14354
+ #cursorPassed(stream, asUnanchored) {
14355
+ let at = -1;
14356
+ for (let i = 0; i < stream.buf.length; i++) {
14357
+ const frame = stream.buf[i];
14358
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
14359
+ frame.passed = true;
14360
+ if (at < 0) at = i;
14361
+ } else if (frame.passed !== true) break;
14362
+ }
14363
+ if (at < 0) return false;
14364
+ 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));
14365
+ }
13943
14366
  #release(stream, frame, decision) {
14367
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
14368
+ if (stale) this.#recordStat("droppedStale");
13944
14369
  if (decision) frame.meta.gapBefore = decision;
13945
14370
  stream.last = frame;
13946
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
14371
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
14372
+ stream.lastSbn = frame.meta.fecSbn;
14373
+ }
14374
+ if (frame.meta.recovered !== true) stream.sourced = true;
13947
14375
  this.#gate.onReleased?.(frame.data, frame.meta);
13948
- this.#emit(frame.data, frame.meta);
14376
+ if (!stale) this.#emit(frame.data, frame.meta);
13949
14377
  }
13950
14378
  };
13951
14379
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -14206,11 +14634,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
14206
14634
  /**
14207
14635
  * Typed view of the ISO-BMFF timing-sample budget.
14208
14636
  *
14209
- * This is the acceptance signal for the budget ratchet: `pending` walking
14210
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
14211
- * and it is observable here rather than only as media silently stopping.
14212
- * Per repo policy this is a producer-owned counter -- never infer budget
14213
- * state by parsing logs.
14637
+ * Each stream admits timing against its own window of `capacity` slots
14638
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
14639
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
14640
+ * timing a stream declared and never delivered shows up there. `pending`
14641
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
14642
+ * a producer-owned counter -- never infer budget state by parsing logs.
14214
14643
  */
14215
14644
  get timingBudgetStats() {
14216
14645
  return {
@@ -14270,6 +14699,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
14270
14699
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
14271
14700
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
14272
14701
  }
14702
+ /** See FecReleaseSequencer.unsource. */
14703
+ unsourceFecRelease(packetId, catalogTrackName) {
14704
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
14705
+ }
14706
+ /** See FecReleaseSequencer.holdsRebuilt. */
14707
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
14708
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
14709
+ }
14273
14710
  /** Re-evaluate held gaps after FEC block state changed. */
14274
14711
  pokeFecRelease(packetId, catalogTrackName) {
14275
14712
  if (!this.#fecSequencer) return;
@@ -14523,7 +14960,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14523
14960
  if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
14524
14961
  const pendingBefore = resolver2.pendingSampleCount;
14525
14962
  const evictedBefore = resolver2.evictedSampleCount;
14526
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
14963
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
14527
14964
  const admitted = resolver2.addMovieFragment(
14528
14965
  mpu.mpuSequenceNumber,
14529
14966
  data,
@@ -14596,7 +15033,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14596
15033
  info,
14597
15034
  resolver,
14598
15035
  options?.recovered === true,
14599
- options?.fecSbn
15036
+ options?.fecSbn,
15037
+ options?.fecSbnFirst
14600
15038
  );
14601
15039
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
14602
15040
  }
@@ -14689,7 +15127,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14689
15127
  info,
14690
15128
  resolver,
14691
15129
  options?.recovered === true,
14692
- options?.fecSbn
15130
+ options?.fecSbn,
15131
+ options?.fecSbnFirst
14693
15132
  );
14694
15133
  if (outcome.record !== void 0) return outcome.record;
14695
15134
  return this.#drop(outcome.reason);
@@ -14709,7 +15148,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14709
15148
  * attribution exists to keep readable. Leaving the choice at the call site
14710
15149
  * is what keeps both true.
14711
15150
  */
14712
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
15151
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
14713
15152
  const timing = resolver.sampleTiming(
14714
15153
  combined.mpuSequenceNumber,
14715
15154
  combined.movieFragmentSequenceNumber,
@@ -14726,6 +15165,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14726
15165
  );
14727
15166
  if (!meta) return { reason: "combined-meta-build-failed" };
14728
15167
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
15168
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
14729
15169
  if (!resolver.consumeSample(
14730
15170
  combined.mpuSequenceNumber,
14731
15171
  combined.movieFragmentSequenceNumber,
@@ -18241,6 +18681,7 @@ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
18241
18681
  var OVERLAY_ROUTED_LIMIT = 1024;
18242
18682
  var OVERLAY_PENDING_LIMIT = 256;
18243
18683
  var OVERLAY_OFFSET_MPUS = 16;
18684
+ var OVERLAY_REBUILT_LIMIT = 256;
18244
18685
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
18245
18686
  function assertStreamIdentity(role, stream) {
18246
18687
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -18351,6 +18792,7 @@ var MmtpRouter = class {
18351
18792
  #provenance = /* @__PURE__ */ new Map();
18352
18793
  #onFlowProtected = null;
18353
18794
  #unadmittedListedDrops = 0;
18795
+ #admittedSourceDatagrams = 0;
18354
18796
  #unlistedRepairSetAside = 0;
18355
18797
  #assistBlocks = /* @__PURE__ */ new Map();
18356
18798
  #assistFailures = /* @__PURE__ */ new Map();
@@ -18416,6 +18858,17 @@ var MmtpRouter = class {
18416
18858
  * an MPU no member of which arrived).
18417
18859
  */
18418
18860
  #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18861
+ /**
18862
+ * The same, shown by the overlay alone, before any base recovery did: a
18863
+ * packet it rebuilt whose base copy carries its protected psn
18864
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
18865
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
18866
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
18867
+ * make the base drop a late base copy of a keyframe the overlay never
18868
+ * finished, and lift a block's late-source cut, which nothing before
18869
+ * this offset did.
18870
+ */
18871
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18419
18872
  /**
18420
18873
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
18421
18874
  * not parsed, typically because its overlap copy was parsed first
@@ -18693,13 +19146,18 @@ var MmtpRouter = class {
18693
19146
  this.#onDeltaBlockCompleteCb?.(packetId, false);
18694
19147
  }
18695
19148
  };
18696
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
19149
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
18697
19150
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
18698
19151
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
18699
19152
  this.#onDeltaBlockCompleteCb?.(packetId, true);
18700
19153
  }
18701
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18702
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19154
+ if (span === void 0) {
19155
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19156
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19157
+ } else {
19158
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
19159
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
19160
+ }
18703
19161
  };
18704
19162
  }
18705
19163
  }
@@ -18744,8 +19202,9 @@ var MmtpRouter = class {
18744
19202
  }
18745
19203
  /**
18746
19204
  * FEC-recovered source symbols whose reconstructed header named a
18747
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
18748
- * a hop re-stamped the sequence after the sender protected the packet.
19205
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
19206
+ * or, rebuilt by the overlay, than their base copy carries: a hop
19207
+ * re-stamped the sequence after the sender protected the packet.
18749
19208
  */
18750
19209
  get restampedRecoveredSequenceCount() {
18751
19210
  return this.#restampedRecoveredSeqs;
@@ -18924,6 +19383,7 @@ var MmtpRouter = class {
18924
19383
  enableMseAssembler(packetId, config, catalogTrackName) {
18925
19384
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
18926
19385
  const previous = this.#mseAssemblers.get(assemblerKey);
19386
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
18927
19387
  if (previous) {
18928
19388
  previous.flush();
18929
19389
  previous.dispose();
@@ -19074,7 +19534,8 @@ var MmtpRouter = class {
19074
19534
  fec,
19075
19535
  k,
19076
19536
  offsets: /* @__PURE__ */ new Map(),
19077
- moqBlocks: /* @__PURE__ */ new Set()
19537
+ moqBlocks: /* @__PURE__ */ new Set(),
19538
+ rebuilt: /* @__PURE__ */ new Map()
19078
19539
  };
19079
19540
  this.#overlays.set(repairPacketId, inst);
19080
19541
  return () => {
@@ -19115,6 +19576,7 @@ var MmtpRouter = class {
19115
19576
  inst.last = void 0;
19116
19577
  inst.offsets.clear();
19117
19578
  inst.moqBlocks.clear();
19579
+ inst.rebuilt.clear();
19118
19580
  }
19119
19581
  #overlaysForSource(sourcePacketId, catalogTrackName) {
19120
19582
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -19167,13 +19629,23 @@ var MmtpRouter = class {
19167
19629
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
19168
19630
  * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
19169
19631
  * FEC reads it.
19632
+ *
19633
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
19634
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
19635
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
19636
+ * the stream unstamped at the SS_ID offset it states, for the release gate
19637
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
19638
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
19170
19639
  */
19171
19640
  #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
19172
19641
  if (this.#overlays.size === 0) return;
19173
19642
  const ssId = keyframeOverlaySsId(header);
19174
19643
  if (ssId === void 0) return;
19644
+ let rebuiltPsn;
19175
19645
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
19176
19646
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
19647
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
19648
+ inst.rebuilt.delete(ssId);
19177
19649
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
19178
19650
  if (identity !== null) {
19179
19651
  inst.offsets.delete(identity.mpuSequenceNumber);
@@ -19203,6 +19675,14 @@ var MmtpRouter = class {
19203
19675
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
19204
19676
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
19205
19677
  }
19678
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
19679
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
19680
+ if (rebuiltPsn !== sequenceNumber) {
19681
+ this.#restampedRecoveredSeqs++;
19682
+ } else if (baseSsId !== void 0) {
19683
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19684
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
19685
+ }
19206
19686
  }
19207
19687
  #noteOverlayMoqBlock(inst, blockStart) {
19208
19688
  inst.moqBlocks.add(blockStart);
@@ -19236,11 +19716,16 @@ var MmtpRouter = class {
19236
19716
  }
19237
19717
  /**
19238
19718
  * Route an overlay-recovered block's packets as source media of the
19239
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
19240
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
19241
- * base re-stamp, no block advance. Each packet's wire sequence is restored
19242
- * from its keyframe's own offset; without one, a stream the base never
19243
- * re-stamped keeps the header's sequence and any other drops the packet.
19719
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
19720
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
19721
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
19722
+ * base FEC recovered does, so it waits behind base frames still in flight,
19723
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
19724
+ * longer than unanchored; one whose base SS_ID is undetermined has no
19725
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
19726
+ * advance. Each packet's wire sequence is restored from its keyframe's own
19727
+ * offset; without one, a stream the base never re-stamped keeps the
19728
+ * header's sequence and any other drops the packet.
19244
19729
  */
19245
19730
  #routeOverlayRecovered(inst, blockStart, recovered) {
19246
19731
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -19261,40 +19746,65 @@ var MmtpRouter = class {
19261
19746
  const restamped = this.#restampedStreams.has(streamKey);
19262
19747
  const restored = /* @__PURE__ */ new Set();
19263
19748
  const baseSsIds = /* @__PURE__ */ new Map();
19749
+ const gateOnly = /* @__PURE__ */ new Set();
19264
19750
  const symbols = result.symbols.flatMap((sym) => {
19751
+ const overlaySsId = serial32Add(blockStart, sym.index);
19265
19752
  const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
19266
19753
  if (anchor !== void 0) {
19267
- const overlaySsId = serial32Add(blockStart, sym.index);
19268
19754
  const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
19269
19755
  restored.add(packetSequenceNumber);
19270
19756
  const out = { ...sym, packetSequenceNumber };
19271
19757
  const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
19272
- if (baseSsId !== void 0) baseSsIds.set(out, baseSsId);
19758
+ if (baseSsId !== void 0) {
19759
+ baseSsIds.set(sym.index, baseSsId);
19760
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19761
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
19762
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
19763
+ }
19764
+ }
19273
19765
  return [out];
19274
19766
  }
19275
19767
  if (!restamped) {
19276
- const baseSsId = unstampedBaseSsId(
19277
- this.#ssIdSeqOffsetByStream.get(streamKey),
19278
- this.#unstampedSsIdSeqOffsetByStream.get(streamKey),
19279
- sym.packetSequenceNumber
19280
- );
19281
- if (baseSsId !== void 0) baseSsIds.set(sym, baseSsId);
19768
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19769
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
19770
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
19771
+ if (baseSsId !== void 0) {
19772
+ baseSsIds.set(sym.index, baseSsId);
19773
+ if (fedSsId === void 0) gateOnly.add(sym.index);
19774
+ } else {
19775
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
19776
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
19777
+ }
19282
19778
  return [sym];
19283
19779
  }
19284
19780
  this.#overlayStats.unsequencedDropped++;
19285
19781
  return [];
19286
19782
  });
19287
19783
  this.#overlayStats.recovered++;
19784
+ const mpuFirst = /* @__PURE__ */ new Map();
19785
+ for (const sym of symbols) {
19786
+ const ssId = baseSsIds.get(sym.index);
19787
+ const mpu = sym.fragment.mpuSequenceNumber;
19788
+ const first = mpuFirst.get(mpu);
19789
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
19790
+ }
19791
+ const firstSsIds = /* @__PURE__ */ new Map();
19792
+ for (const sym of symbols) {
19793
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
19794
+ }
19288
19795
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
19289
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
19796
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
19797
+ baseSsIds,
19798
+ firstSsIds
19290
19799
  });
19291
19800
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
19292
- this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds);
19801
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
19293
19802
  }
19294
19803
  /**
19295
19804
  * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
19296
19805
  * its base block too, once its base SS_ID is determined (overlayBaseSsId,
19297
- * from a received member of its MPU, else unstampedBaseSsId),
19806
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
19807
+ * base recovery showed; `baseSsIds` holds no other),
19298
19808
  * so it is fed to the base decoder as a rebuilt source
19299
19809
  * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
19300
19810
  * fewer to solve, and its repair can recover the block's other packets.
@@ -19320,7 +19830,7 @@ var MmtpRouter = class {
19320
19830
  const feeds = [];
19321
19831
  for (const sym of symbols) {
19322
19832
  if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
19323
- const ssId = baseSsIds.get(sym);
19833
+ const ssId = baseSsIds.get(sym.index);
19324
19834
  if (ssId === void 0) {
19325
19835
  this.#overlayStats.baseUndetermined++;
19326
19836
  continue;
@@ -19507,6 +20017,10 @@ var MmtpRouter = class {
19507
20017
  get unadmittedListedDropCount() {
19508
20018
  return this.#unadmittedListedDrops;
19509
20019
  }
20020
+ /** 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. */
20021
+ get admittedSourceDatagramCount() {
20022
+ return this.#admittedSourceDatagrams;
20023
+ }
19510
20024
  /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
19511
20025
  get unlistedRepairSetAsideCount() {
19512
20026
  return this.#unlistedRepairSetAside;
@@ -20045,7 +20559,7 @@ var MmtpRouter = class {
20045
20559
  catalogTrackName
20046
20560
  )) continue;
20047
20561
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
20048
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
20562
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
20049
20563
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
20050
20564
  }
20051
20565
  if (payload.oversized) continue;
@@ -20133,6 +20647,7 @@ var MmtpRouter = class {
20133
20647
  this.#latestVideoSeqByStream.delete(streamKey);
20134
20648
  this.#ssIdSeqOffsetByStream.delete(streamKey);
20135
20649
  this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
20650
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
20136
20651
  this.#multicastRapTwinByStream.delete(streamKey);
20137
20652
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
20138
20653
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -20259,6 +20774,12 @@ var MmtpRouter = class {
20259
20774
  * the outgoing stream stops. The hold is bounded by the incoming stream's
20260
20775
  * own RAP cadence, so no timer is involved.
20261
20776
  *
20777
+ * While the switch is staged, the FEC release gate lets a keyframe the
20778
+ * overlay rebuilt reach it, on either side, when the keyframe did before
20779
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
20780
+ * decides on what each side delivered, and the commit discards the gate's
20781
+ * frames of the outgoing stream.
20782
+ *
20262
20783
  * The commit is one synchronous transition inside the frame path: the
20263
20784
  * outgoing stream's already-admitted frames are released (its queued FEC
20264
20785
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -20309,6 +20830,9 @@ var MmtpRouter = class {
20309
20830
  droppedIncomingFrames: 0
20310
20831
  };
20311
20832
  this.#staged = state;
20833
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
20834
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
20835
+ }
20312
20836
  return {
20313
20837
  cancel: () => {
20314
20838
  if (this.#staged !== state) return false;
@@ -20391,7 +20915,17 @@ var MmtpRouter = class {
20391
20915
  */
20392
20916
  #routeParsedFrame(data, meta) {
20393
20917
  if (this.#classifyPacketId(meta.packetId) === null) return;
20394
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
20918
+ if (this.#staged !== null) {
20919
+ let consumed = false;
20920
+ this.#fecPokeDepth++;
20921
+ try {
20922
+ consumed = this.#interceptSwitchFrame(data, meta);
20923
+ } finally {
20924
+ this.#fecPokeDepth--;
20925
+ this.#flushPendingFecPokes();
20926
+ }
20927
+ if (consumed) return;
20928
+ }
20395
20929
  this.#deliverParsedFrame(data, meta);
20396
20930
  }
20397
20931
  #commitStreamSwitch(state, rap, reason) {
@@ -20543,12 +21077,16 @@ var MmtpRouter = class {
20543
21077
  this.#parser.deferFecRelease(work);
20544
21078
  } finally {
20545
21079
  this.#fecPokeDepth--;
20546
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
20547
- const pokes = [...this.#pendingFecPokes.values()];
20548
- this.#pendingFecPokes.clear();
20549
- for (const poke of pokes) {
20550
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20551
- }
21080
+ this.#flushPendingFecPokes();
21081
+ }
21082
+ }
21083
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
21084
+ #flushPendingFecPokes() {
21085
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
21086
+ const pokes = [...this.#pendingFecPokes.values()];
21087
+ this.#pendingFecPokes.clear();
21088
+ for (const poke of pokes) {
21089
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20552
21090
  }
20553
21091
  }
20554
21092
  }
@@ -20617,6 +21155,26 @@ var MmtpRouter = class {
20617
21155
  if (!fec?.terminalRetentionMsForPacket) return Infinity;
20618
21156
  return fec.terminalRetentionMsForPacket(packetId) ?? 0;
20619
21157
  },
21158
+ // Once no repair can fill a gap (FECManager.isoRepairlessWaitMs: only a
21159
+ // late source can), its frame waits the late-symbol allowance when the
21160
+ // gap holds no RAP an installed keyframe overlay could still rebuild:
21161
+ // lost deltas of one MPU (delta-lost), the tail of the MPU before a RAP
21162
+ // that opens the next one while MPU boundaries bound RAPs (rap-next), or
21163
+ // an audio gap. A gap that may hold one (rap-lost, rap-unknown, or any
21164
+ // other rap-next, whose gap may hold a whole MPU and the keyframe the
21165
+ // overlay protects) waits for that overlay's repair too (BLO-52085
21166
+ // D4). The FEC check comes first: most held gaps are not behind such a
21167
+ // span, and deciding one scans both frames' bitstreams.
21168
+ unrepairableWaitMs: (before, after, fromSbn, toSbn) => {
21169
+ const fec = this.#fecManager;
21170
+ const { packetId, catalogTrackName } = after.meta;
21171
+ const allowanceMs = fec?.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn);
21172
+ if (!fec || allowanceMs === void 0) return void 0;
21173
+ const decision = this.#decideGap(before, after, [], false);
21174
+ const mpu = before.meta.mpuSequenceNumber;
21175
+ const intoNextMpu = decision.reason === "rap-next" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu + 1 >>> 0 && fec.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
21176
+ return decision.action === "stall" || decision.reason === "rap-next" && !intoNextMpu ? fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, true) : allowanceMs;
21177
+ },
20620
21178
  decide: (before, after, lostBlocks, discontinuity) => {
20621
21179
  const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
20622
21180
  this.#onFrameGap?.(decision);
@@ -20626,6 +21184,14 @@ var MmtpRouter = class {
20626
21184
  onRap: (packetId, catalogTrackName, ssId) => {
20627
21185
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
20628
21186
  },
21187
+ // A staged switch commits on when each side's frames reach it
21188
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
21189
+ // they did unanchored.
21190
+ releaseUnanchored: (packetId, catalogTrackName) => {
21191
+ const staged = this.#staged;
21192
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
21193
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
21194
+ },
20629
21195
  onReleased: (data, meta) => {
20630
21196
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
20631
21197
  const timing = meta.authoredTiming;
@@ -20767,6 +21333,7 @@ var MmtpRouter = class {
20767
21333
  const parsed = this.#parser.parsePacket(packet);
20768
21334
  if (!parsed) return;
20769
21335
  const info = parsed.info;
21336
+ if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
20770
21337
  if (source === "multicast" && !manifestAdmitted) {
20771
21338
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
20772
21339
  }
@@ -21075,7 +21642,8 @@ var MmtpRouter = class {
21075
21642
  source: parserOptions?.source,
21076
21643
  deliveryProvenance: parserOptions?.deliveryProvenance,
21077
21644
  catalogTrackName: parserOptions?.catalogTrackName,
21078
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
21645
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
21646
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
21079
21647
  };
21080
21648
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
21081
21649
  else this.#parser.feed(packet, feedOptions);
@@ -21541,7 +22109,12 @@ var MmtpRouter = class {
21541
22109
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
21542
22110
  if (ownerPacketId == null) return;
21543
22111
  if (this.#classifyPacketId(ownerPacketId) === null) return;
21544
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
22112
+ const fecSbnOf = (index) => {
22113
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
22114
+ const fecSbn = overlay.baseSsIds.get(index);
22115
+ const fecSbnFirst = overlay.firstSsIds.get(index);
22116
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
22117
+ };
21545
22118
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
21546
22119
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
21547
22120
  if (ssIdSeqOffset !== void 0) {
@@ -23087,6 +23660,12 @@ function isNonNegativeSafeInteger(value) {
23087
23660
  function isSymbolCounts(value) {
23088
23661
  return isRecord(value) && hasExactKeys(value, ["multicast", "moq"]) && isNonNegativeSafeInteger(value["multicast"]) && isNonNegativeSafeInteger(value["moq"]);
23089
23662
  }
23663
+ function isSpanFailure(value) {
23664
+ if (!isRecord(value) || !hasExactKeys(value, ["length", "sources"])) return false;
23665
+ const length = value["length"];
23666
+ const sources = value["sources"];
23667
+ return Number.isSafeInteger(length) && length > 0 && isNonNegativeSafeInteger(sources) && sources < length;
23668
+ }
23090
23669
  function isNullableNonNegative(value) {
23091
23670
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
23092
23671
  }
@@ -23106,7 +23685,10 @@ function isRepairLifecycleEvent(value) {
23106
23685
  case "recovered":
23107
23686
  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"]);
23108
23687
  case "failed":
23109
- return hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]);
23688
+ return hasExactKeys(
23689
+ value,
23690
+ "span" in value ? ["version", "type", "block", "blockClass", "symbols", "span"] : ["version", "type", "block", "blockClass", "symbols"]
23691
+ ) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]) && (!("span" in value) || isSpanFailure(value["span"]));
23110
23692
  case "repair-preempted":
23111
23693
  case "repair-deferred":
23112
23694
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
@@ -23315,6 +23897,8 @@ var MulticastManager = class {
23315
23897
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
23316
23898
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
23317
23899
  #repairReleases = /* @__PURE__ */ new Map();
23900
+ /** Protected repair flows owned by each live repair-endpoint release. */
23901
+ #repairProvenanceFlows = /* @__PURE__ */ new Map();
23318
23902
  /** Each source's catalog keyframe overlay, from its `ok` binding. */
23319
23903
  #overlayBindings = /* @__PURE__ */ new Map();
23320
23904
  /** Installed overlay decoders (`setKeyframeOverlayDecoder`), by source. */
@@ -23372,7 +23956,7 @@ var MulticastManager = class {
23372
23956
  onPublisherRestart: (packetId, catalogTrackName) => {
23373
23957
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
23374
23958
  },
23375
- onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
23959
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass, span) => {
23376
23960
  const pathCount = this.#fec.blockPathCount(
23377
23961
  sbn,
23378
23962
  packetId,
@@ -23390,7 +23974,8 @@ var MulticastManager = class {
23390
23974
  symbols: {
23391
23975
  multicast: pathCount?.multicastSymbols ?? 0,
23392
23976
  moq: pathCount?.moqSymbols ?? 0
23393
- }
23977
+ },
23978
+ ...span === void 0 ? {} : { span }
23394
23979
  });
23395
23980
  },
23396
23981
  onFrameGap: (decision) => {
@@ -23478,6 +24063,11 @@ var MulticastManager = class {
23478
24063
  this.#fec.onBlockVanished = (_sbn, packetId, catalogTrackName) => {
23479
24064
  this.#statsFor(packetId, catalogTrackName).vanishedBlocks++;
23480
24065
  };
24066
+ this.#fec.keyframeOverlayTiming = (packetId, catalogTrackName) => {
24067
+ const binding = this.#overlayInstalls.has(packetId) ? this.#overlayBindings.get(packetId) : void 0;
24068
+ if (binding === void 0) return void 0;
24069
+ return catalogTrackName === void 0 || catalogTrackName === binding.sourceCatalogTrackName ? binding.geometry : void 0;
24070
+ };
23481
24071
  this.#fec.onDecoderUnavailable = (event) => {
23482
24072
  this.#emitRepairLifecycle({
23483
24073
  version: 2,
@@ -23980,6 +24570,9 @@ var MulticastManager = class {
23980
24570
  this.#transport.onFailback((reason) => {
23981
24571
  const joined = this.#provenanceJoin;
23982
24572
  if (joined !== null) this.#router.unprotectProvenanceFlow(joined.flow);
24573
+ for (const flows of this.#repairProvenanceFlows.values()) {
24574
+ for (const flow of flows) this.#router.unprotectProvenanceFlow(flow);
24575
+ }
23983
24576
  this.#onFailback?.(reason);
23984
24577
  });
23985
24578
  }
@@ -24014,6 +24607,12 @@ var MulticastManager = class {
24014
24607
  "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
24015
24608
  );
24016
24609
  }
24610
+ if (provenanceFlow !== void 0) {
24611
+ const flow = multicastProvenanceFlowKey(provenanceFlow);
24612
+ if ([...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
24613
+ throw new TypeError(`[MulticastManager] join: provenance flow already registered by a repair endpoint: ${flow}`);
24614
+ }
24615
+ }
24017
24616
  const staged = this.#renditionSwitch;
24018
24617
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
24019
24618
  this.configureFec(config);
@@ -24021,8 +24620,8 @@ var MulticastManager = class {
24021
24620
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
24022
24621
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
24023
24622
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
24024
- this.#releaseProvenanceJoin();
24025
24623
  const provenance = config.provenance;
24624
+ this.#releaseProvenanceJoin();
24026
24625
  const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
24027
24626
  const ingress = protectedTracks === void 0 ? void 0 : {
24028
24627
  tracks: Object.freeze(
@@ -24075,8 +24674,13 @@ var MulticastManager = class {
24075
24674
  * feeds the flow's receiver; media datagrams are held until one admits them.
24076
24675
  */
24077
24676
  #joinProvenance(provenance, ingress) {
24677
+ this.#router.registerProvenanceFlow(ingress, this.#provenanceReceiver(provenance));
24678
+ this.#hookFailback();
24679
+ this.#provenanceJoin = { flow: ingress.flow };
24680
+ }
24681
+ #provenanceReceiver(provenance) {
24078
24682
  const { flow, auth } = provenance;
24079
- const receiver = new BcProvenanceV2Receiver({
24683
+ return new BcProvenanceV2Receiver({
24080
24684
  ...provenance.receiver,
24081
24685
  // The caller's ctx when it passes one, else the catalog's: an explicit
24082
24686
  // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
@@ -24093,9 +24697,6 @@ var MulticastManager = class {
24093
24697
  maxAuthDelayMs: flow.maxAuthDelayMs,
24094
24698
  manifestTimerMs: flow.manifestTimerMs
24095
24699
  });
24096
- this.#router.registerProvenanceFlow(ingress, receiver);
24097
- this.#hookFailback();
24098
- this.#provenanceJoin = { flow: ingress.flow };
24099
24700
  }
24100
24701
  /** Un-protect: drop the flow's hold queues (no expiry counted). */
24101
24702
  #releaseProvenanceJoin() {
@@ -24126,8 +24727,25 @@ var MulticastManager = class {
24126
24727
  * callback delivers must come from a subscription opened on
24127
24728
  * `options.gateway`. A callback that also merges another source (a MoQ or
24128
24729
  * WebSocket repair feed) must not name a native provider here.
24730
+ *
24731
+ * An endpoint's `provenance` makes its group a protected flow of its own
24732
+ * (multicast-02 7.2.7), registered here and released with the group; its
24733
+ * records ride in band on the group's port. On the user-agent path a
24734
+ * flow-less repair group of a protected track is set aside, never read, so
24735
+ * a player joining a protected catalog's repair groups passes it.
24129
24736
  */
24130
24737
  joinRepairEndpoints(endpoints, provider, options) {
24738
+ for (const { provenance, flow, source, group, port } of endpoints) {
24739
+ if (provenance === void 0) continue;
24740
+ if (flow !== void 0) {
24741
+ throw new TypeError("[MulticastManager] joinRepairEndpoints: an endpoint names provenance or flow, never both");
24742
+ }
24743
+ if (!sameIpAddress(source, provenance.flow.source) || !sameIpAddress(group, provenance.flow.groupAddress) || port !== provenance.flow.port) {
24744
+ throw new RangeError(
24745
+ "[MulticastManager] joinRepairEndpoints: provenance flow (S, G, port) must match the endpoint's source, group and port"
24746
+ );
24747
+ }
24748
+ }
24131
24749
  const releases = [];
24132
24750
  let released = false;
24133
24751
  const safely = (each) => {
@@ -24137,17 +24755,36 @@ var MulticastManager = class {
24137
24755
  console.warn("[MulticastManager] repair group release failed", error);
24138
24756
  }
24139
24757
  };
24758
+ const usedFlows = new Set(endpoints.flatMap(({ flow }) => flow === void 0 ? [] : [flow]));
24759
+ const preparedProvenance = endpoints.map((endpoint) => {
24760
+ if (endpoint.provenance === void 0) return void 0;
24761
+ const flow = multicastProvenanceFlowKey(endpoint.provenance.flow);
24762
+ if (usedFlows.has(flow) || this.#provenanceJoin?.flow === flow || [...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
24763
+ throw new TypeError(`[MulticastManager] joinRepairEndpoints: provenance flow already registered: ${flow}`);
24764
+ }
24765
+ usedFlows.add(flow);
24766
+ return { flow, receiver: this.#provenanceReceiver(endpoint.provenance) };
24767
+ });
24768
+ const provenanceFlows = [];
24140
24769
  const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners.map((owner) => owner.instance !== "keyframe" ? owner : {
24141
24770
  ...owner,
24142
24771
  ownerTrackName: endpoint.tracks.find((t) => t.packetId === owner.ownerPacketId)?.name,
24143
24772
  repairTrackName: endpoint.tracks.find((t) => t.packetId === owner.packetId)?.name
24144
24773
  }));
24145
24774
  this.#applyRepairOwners(repairOwners);
24146
- for (const endpoint of endpoints) {
24775
+ for (const [index, endpoint] of endpoints.entries()) {
24776
+ const flow = endpoint.provenance === void 0 ? endpoint.flow : multicastProvenanceFlowKey(endpoint.provenance.flow);
24147
24777
  const ingress = {
24148
24778
  tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
24149
- ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
24779
+ ...flow === void 0 ? {} : { flow }
24150
24780
  };
24781
+ if (endpoint.provenance !== void 0) {
24782
+ const prepared = preparedProvenance[index];
24783
+ if (prepared === void 0) throw new Error("[MulticastManager] repair provenance preparation missing");
24784
+ this.#router.registerProvenanceFlow(ingress, prepared.receiver);
24785
+ provenanceFlows.push(prepared.flow);
24786
+ releases.push(() => this.#router.releaseProvenanceFlow(flow));
24787
+ }
24151
24788
  let sender;
24152
24789
  const feed = (packet, sourceAddress, ingressToFeed) => {
24153
24790
  if (released) return;
@@ -24177,7 +24814,7 @@ var MulticastManager = class {
24177
24814
  packetIds: endpoint.packetIds,
24178
24815
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
24179
24816
  // A protected repair group's records ride in band on its port (7.2.3).
24180
- ...endpoint.flow === void 0 ? {} : { protected: true }
24817
+ ...flow === void 0 ? {} : { protected: true }
24181
24818
  }, ingress).then((joined) => {
24182
24819
  if (!joined && !released) fail(transport.lastJoinOutcome);
24183
24820
  });
@@ -24186,9 +24823,12 @@ var MulticastManager = class {
24186
24823
  if (released) return;
24187
24824
  released = true;
24188
24825
  this.#repairReleases.delete(release);
24826
+ this.#repairProvenanceFlows.delete(release);
24189
24827
  for (const each of releases.splice(0)) safely(each);
24190
24828
  };
24191
24829
  this.#repairReleases.set(release, repairOwners);
24830
+ this.#repairProvenanceFlows.set(release, provenanceFlows);
24831
+ if (provenanceFlows.length) this.#hookFailback();
24192
24832
  return release;
24193
24833
  }
24194
24834
  #applyRepairOwners(owners) {
@@ -24674,7 +25314,8 @@ var MulticastManager = class {
24674
25314
  blockProfile: parseFecBlockProfile(
24675
25315
  geometry2.blockProfile,
24676
25316
  `tracks[${JSON.stringify(track.name)}].fec keyframe overlay blockProfile`
24677
- )
25317
+ ),
25318
+ geometry: geometry2
24678
25319
  });
24679
25320
  }
24680
25321
  }
@@ -24713,7 +25354,7 @@ var MulticastManager = class {
24713
25354
  for (const [sourcePacketId, install] of [...this.#overlayInstalls]) {
24714
25355
  const before = this.#overlayBindings.get(sourcePacketId);
24715
25356
  const after = overlayBindings.get(sourcePacketId);
24716
- const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => after[key] === before[key]);
25357
+ const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => key === "geometry" || after[key] === before[key]);
24717
25358
  if (!same) install.dispose();
24718
25359
  else if (this.#router.hasKeyframeOverlay(after.repairPacketId)) this.#router.resetKeyframeOverlays(sourcePacketId);
24719
25360
  else install.reattach();
@@ -24770,10 +25411,12 @@ var MulticastManager = class {
24770
25411
  * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
24771
25412
  * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
24772
25413
  * pending hole and reported here, and `closeIsoHoles` must be called for it
24773
- * once its range FETCH ends (or none is sent).
25414
+ * once its range FETCH ends (or none is sent). `onExpired` is told of a
25415
+ * pending hole the stream runs past the locator's horizon: returning true,
25416
+ * the caller closes it (`closeIsoHoles`); otherwise it is discarded.
24774
25417
  */
24775
- onUndelimitedLoss(cb) {
24776
- this.#fec.setUndelimitedLossHandler(cb);
25418
+ onUndelimitedLoss(cb, onExpired) {
25419
+ this.#fec.setUndelimitedLossHandler(cb, onExpired ?? null);
24777
25420
  }
24778
25421
  /**
24779
25422
  * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
@@ -25009,7 +25652,8 @@ var MulticastManager = class {
25009
25652
  "stream" in event ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
25010
25653
  ...event,
25011
25654
  block: Object.freeze({ ...event.block }),
25012
- ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {}
25655
+ ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {},
25656
+ ..."span" in event && event.span !== void 0 ? { span: Object.freeze({ ...event.span }) } : {}
25013
25657
  }
25014
25658
  );
25015
25659
  if (this.#logRepairLifecycle) {