@blockcast/mmt-container 2.2.0-main.e75bbd7576a6 → 2.2.0-main.ef09fa701ea8

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 +994 -162
  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 +75 -14
  10. package/dist/fec-manager.d.ts.map +1 -1
  11. package/dist/fec-manager.js +315 -65
  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 +69 -10
  23. package/dist/mmtp-container-parser.d.ts.map +1 -1
  24. package/dist/mmtp-container-parser.js +226 -18
  25. package/dist/mmtp-container-parser.js.map +2 -2
  26. package/dist/mmtp-container-parser.no-modules.js +225 -19
  27. package/dist/mmtp-container-parser.no-modules.js.map +3 -3
  28. package/dist/mmtp-decode-pipeline.js +226 -18
  29. package/dist/mmtp-decode-pipeline.js.map +2 -2
  30. package/dist/mmtp-router.d.ts +20 -9
  31. package/dist/mmtp-router.d.ts.map +1 -1
  32. package/dist/mmtp-router.js +409 -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 +814 -135
  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 +226 -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 +226 -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 +329 -39
  54. package/src/index.ts +2 -0
  55. package/src/iso-block-locator.ts +114 -31
  56. package/src/mmtp-container-parser.ts +257 -24
  57. package/src/mmtp-router.ts +287 -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);
@@ -4314,7 +4412,7 @@ var FECManager = class _FECManager {
4314
4412
  }
4315
4413
  const trackConfig = this.#trackConfigs.get(packetId);
4316
4414
  if (trackConfig === void 0) return void 0;
4317
- return Math.max(1, trackConfig.timeoutMs - this.#repairDeadlineMs(trackConfig));
4415
+ return Math.max(1, this.#repairGraceMs(trackConfig, this.#multicastWaitMs(trackConfig)));
4318
4416
  }
4319
4417
  /** True once configureTrack/setFecDecoder/setFecWorker configured this packetId. */
4320
4418
  // -----------------------------------------------------------------------
@@ -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,62 @@ 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), or in a stated block its
4663
+ * own repair group cannot complete every SS_ID of which it misses lies
4664
+ * between them (so the gap's decision covers all it lost), and a multicast
4665
+ * source at or past `toSsId` arrived, so each is lost or reordered behind
4666
+ * it (a MoQ source shows nothing: MoQ streams overtake one another). The
4667
+ * span or block itself keeps its own wait.
4668
+ *
4669
+ * The wait is the late-symbol allowance, unless `rapMayHide`: the gap may
4670
+ * hold a RAP packet an installed keyframe overlay can still rebuild (its
4671
+ * decision stalls, or it ends at a RAP that may lie past a whole MPU).
4672
+ * Then the frame waits as a stated block its group cannot complete does
4673
+ * (#overlayLateWaitMs): the allowance alone with no overlay installed, the
4674
+ * overlay's span plus the larger of the allowance and its tolerance, or,
4675
+ * for an overlay that states no span, the span's whole wait (undefined).
4676
+ * So does `rapNext` (the gap ends at the RAP that opens the next MPU) when
4677
+ * the gap holds a stated block's loss.
4678
+ */
4679
+ isoRepairlessWaitMs(packetId, catalogTrackName, fromSsId, toSsId, rapMayHide = false, rapNext = false) {
4680
+ const config = this.#trackConfigs.get(packetId);
4681
+ if (config === void 0 || !_FECManager.#hasCatalogTiming(config)) return void 0;
4682
+ const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
4683
+ if (locator === void 0 || !locator.coversBetween(fromSsId, toSsId)) return void 0;
4684
+ const newestSource = locator.newestSource;
4685
+ if (newestSource === void 0 || serial32Precedes(newestSource, toSsId)) return void 0;
4686
+ let repairless = false;
4687
+ let stated = false;
4688
+ for (const block of locator.blocksBetween(fromSsId, toSsId)) {
4689
+ const key = this.#blockKey(block.start, packetId, catalogTrackName);
4690
+ if (this.#completedBlocks.has(key)) continue;
4691
+ if (block.span && block.length > locator.kMax) {
4692
+ repairless = true;
4693
+ continue;
4694
+ }
4695
+ const received = this.#blockSourceEsis.get(key);
4696
+ const rebuilt = this.#blockRebuiltEsis.get(key);
4697
+ let missesInGap = false;
4698
+ let missesOutside = false;
4699
+ for (let esi = 0; esi < block.length; esi++) {
4700
+ const ssId = serial32Add(block.start, esi);
4701
+ if (received?.has(esi) || locator.isHeld(ssId)) continue;
4702
+ if (serial32Precedes(fromSsId, ssId) && serial32Precedes(ssId, toSsId)) missesInGap = true;
4703
+ else if (!rebuilt?.has(esi)) missesOutside = true;
4704
+ }
4705
+ if (!missesInGap) continue;
4706
+ if (missesOutside || block.span || !this.#groupCannotComplete(key)) return void 0;
4707
+ repairless = stated = true;
4708
+ }
4709
+ if (!repairless) return void 0;
4710
+ const waitMs = rapMayHide || stated && rapNext ? this.#overlayLateWaitMs(packetId, catalogTrackName, config) : this.#multicastWaitMs(config) - config.interleaveDepthMs;
4711
+ return waitMs === void 0 ? void 0 : Math.max(0, waitMs);
4712
+ }
4528
4713
  /**
4529
4714
  * iso-ssbg1-v1 block location: repair symbols it refused, oversize sources,
4530
4715
  * the sources held now for a block no repair has stated yet, and the held
@@ -4828,11 +5013,14 @@ var FECManager = class _FECManager {
4828
5013
  });
4829
5014
  client.onCleanupComplete((sbn) => {
4830
5015
  if (this.#releasedWorkerClients.has(client)) return;
4831
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
5016
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
5017
+ const cleanupKeys = owed.filter((key) => {
4832
5018
  const block = this.#parseBlockKey(key);
4833
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
5019
+ return block.packetId === packetId && block.sbn === sbn;
4834
5020
  });
4835
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
5021
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
5022
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
5023
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
4836
5024
  });
4837
5025
  client.onError((msg, code) => {
4838
5026
  const requestedKind = code ?? msg;
@@ -4902,9 +5090,11 @@ var FECManager = class _FECManager {
4902
5090
  * fail deadline already passed, so failing it is the decision that deadline
4903
5091
  * made. A late ack then finds nothing owed and is a no-op.
4904
5092
  */
4905
- #boundOwedCleanup(key, packetId, client) {
5093
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
4906
5094
  this.#clearOwedCleanupBound(key);
4907
5095
  const bound = {
5096
+ dueAtMs,
5097
+ askedAtMs: performance.now(),
4908
5098
  handle: setTimeout(() => {
4909
5099
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
4910
5100
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -5325,7 +5515,7 @@ var FECManager = class _FECManager {
5325
5515
  const previous = locator.newestSource;
5326
5516
  if (!locator.noteSource(ssId) || previous === void 0) return;
5327
5517
  for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
5328
- if (block.span || !serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
5518
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
5329
5519
  this.#shortenUnrecoverableWait(
5330
5520
  this.#blockKey(block.start, packetId, catalogTrackName),
5331
5521
  block.start,
@@ -5343,21 +5533,61 @@ var FECManager = class _FECManager {
5343
5533
  * covers repair symbols paced after its sources, buys it nothing: it waits
5344
5534
  * the late-symbol allowance alone, the multicast wait less the span (the
5345
5535
  * catalog tolerance or the measured delivery gap). Undefined for any other
5346
- * block.
5536
+ * block. While a keyframe overlay is installed, the block waits for its
5537
+ * repair too (#overlayLateWaitMs). A repair-less span keeps its whole
5538
+ * wait, even one longer than K whose group is empty (#openIsoSpan): its
5539
+ * resolution is what releases the frames behind it, and failing it early
5540
+ * released them past a keyframe the overlay was still rebuilding, which
5541
+ * then arrived stale. The release gate lets them go instead
5542
+ * (isoRepairlessWaitMs).
5347
5543
  */
5348
5544
  #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
5545
+ if (this.#isoSpanKeys.has(key) || !this.#groupCannotComplete(key)) return void 0;
5349
5546
  const authoredLength = this.#blockAuthoredLengths.get(key);
5350
- const rsbLength = this.#blockRsbLengths.get(key);
5351
- if (authoredLength === void 0 || rsbLength === void 0) return void 0;
5352
- let present = this.#blockSourceCounts.get(key) ?? 0;
5353
- const received = this.#blockSourceEsis.get(key);
5354
- for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
5355
- if (present + rsbLength >= authoredLength) return void 0;
5356
5547
  const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
5357
5548
  if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
5358
5549
  return void 0;
5359
5550
  }
5360
- return this.#multicastWaitMs(config) - config.interleaveDepthMs;
5551
+ return this.#overlayLateWaitMs(packetId, catalogTrackName, config);
5552
+ }
5553
+ /**
5554
+ * A repair stated the block, and its sources plus every symbol its repair
5555
+ * group carries (RSB_length) are short of its SSB_length.
5556
+ */
5557
+ #groupCannotComplete(key) {
5558
+ const authoredLength = this.#blockAuthoredLengths.get(key);
5559
+ const rsbLength = this.#blockRsbLengths.get(key);
5560
+ if (authoredLength === void 0 || rsbLength === void 0) return false;
5561
+ let present = this.#blockSourceCounts.get(key) ?? 0;
5562
+ const received = this.#blockSourceEsis.get(key);
5563
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
5564
+ return present + rsbLength < authoredLength;
5565
+ }
5566
+ /**
5567
+ * How long a loss only a late source or an installed keyframe overlay can
5568
+ * still fill waits once a later source passed it: the late-symbol
5569
+ * allowance alone (the multicast wait less the span) while no overlay is
5570
+ * installed. An installed one (keyframeOverlayTiming) may still rebuild a
5571
+ * RAP packet the loss took: a second FEC instance over the same packets
5572
+ * (draft-ramadan-moq-mmt-02 7.4), whose repair is paced across its own
5573
+ * span, unrelated to the base's. That packet can complete a stated block
5574
+ * (feedRebuiltSourceSymbol), or play behind a span; giving the loss up
5575
+ * first lets the release gate pass the keyframe, whose rebuild then lands
5576
+ * stale. The overlay repair of a packet the loss took goes out within the
5577
+ * overlay's span of that packet (fec-core-00 9.3), and the later source was
5578
+ * sent after it, so the loss waits that span plus the larger of the
5579
+ * allowance and the overlay's own tolerance. An overlay that states no
5580
+ * span (its block may then span keyframes), or one whose wait is not
5581
+ * shorter than the whole multicast wait, leaves the whole wait: undefined.
5582
+ */
5583
+ #overlayLateWaitMs(packetId, catalogTrackName, config) {
5584
+ const waitMs = this.#multicastWaitMs(config);
5585
+ const allowanceMs = waitMs - config.interleaveDepthMs;
5586
+ const overlay = this.keyframeOverlayTiming?.(packetId, catalogTrackName);
5587
+ if (overlay === void 0) return allowanceMs;
5588
+ const overlaySpanMs = overlay.interleaveDepthMs ?? 0;
5589
+ const overlayWaitMs = overlaySpanMs + Math.max(allowanceMs, overlay.reorderToleranceMs ?? 0);
5590
+ return overlaySpanMs > 0 && overlayWaitMs < waitMs ? overlayWaitMs : void 0;
5361
5591
  }
5362
5592
  /**
5363
5593
  * Bring an open block's wait in to its late-source wait, when it has one.
@@ -5475,12 +5705,13 @@ var FECManager = class _FECManager {
5475
5705
  * the inactivity deadline on each symbol, records the symbol's in-band
5476
5706
  * classification evidence, and marks the block clean when all of its
5477
5707
  * authored source symbols arrived: the SSB_length a repair symbol declared,
5478
- * otherwise K.
5708
+ * otherwise K. `held` marks a source held unplaced since it arrived and
5709
+ * placed only now (see #noteSbnSeen).
5479
5710
  *
5480
5711
  * Throws for a packetId that was never configured, so a classified block
5481
5712
  * never reads the manager-global K or timeout.
5482
5713
  */
5483
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
5714
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
5484
5715
  const trackConfig = this.#trackConfigs.get(packetId);
5485
5716
  if (trackConfig === void 0) {
5486
5717
  throw new Error(
@@ -5496,7 +5727,8 @@ var FECManager = class _FECManager {
5496
5727
  catalogTrackName,
5497
5728
  "source",
5498
5729
  evidence.packetSequenceNumber,
5499
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
5730
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
5731
+ held
5500
5732
  );
5501
5733
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
5502
5734
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -5551,6 +5783,7 @@ var FECManager = class _FECManager {
5551
5783
  this.#blockSourceEsis.delete(key);
5552
5784
  this.#blockRebuiltEsis.delete(key);
5553
5785
  this.#blockAuthoredLengths.delete(key);
5786
+ this.#isoSpanKeys.delete(key);
5554
5787
  this.#blockRepairRsIds.delete(key);
5555
5788
  this.#blockRsbLengths.delete(key);
5556
5789
  this.#markTerminal(key, sbn, packetId, true);
@@ -5581,6 +5814,19 @@ var FECManager = class _FECManager {
5581
5814
  #receiptNow() {
5582
5815
  return this.#receiptAtMs ?? performance.now();
5583
5816
  }
5817
+ /**
5818
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
5819
+ * scope: counted from the receipt time, as the timer of a symbol fed when
5820
+ * it was received was, less the whole ms since. So it fires on the tick
5821
+ * that timer would have, never later than a delay counted from now, and
5822
+ * its handler still re-arms a timer that fires before its deadline.
5823
+ * Counted from now, a deadline set from the receipt time is rounded up
5824
+ * from another fraction of a ms (BLO-52085).
5825
+ */
5826
+ #receiptTimerDelayMs(deadlineMs, minMs) {
5827
+ const receivedAtMs = this.#receiptAtMs;
5828
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
5829
+ }
5584
5830
  /**
5585
5831
  * A held packet admitted late arms from its (earlier) receipt time; that
5586
5832
  * never pulls in a deadline later activity already armed. Outside a
@@ -5629,6 +5875,7 @@ var FECManager = class _FECManager {
5629
5875
  }
5630
5876
  #failBlock(sbn, packetId, catalogTrackName) {
5631
5877
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
5878
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
5632
5879
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
5633
5880
  this.#clearRepairDeadline(key);
5634
5881
  this.#clearBlockTimer(key);
@@ -5648,7 +5895,8 @@ var FECManager = class _FECManager {
5648
5895
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
5649
5896
  this.#fecStats.blocksFailed++;
5650
5897
  this.#statsForPacket(packetId).blocksFailed++;
5651
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5898
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5899
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
5652
5900
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
5653
5901
  }
5654
5902
  /**
@@ -5679,6 +5927,7 @@ var FECManager = class _FECManager {
5679
5927
  this.#blockSourceEsis.delete(key);
5680
5928
  this.#blockRebuiltEsis.delete(key);
5681
5929
  this.#blockAuthoredLengths.delete(key);
5930
+ this.#isoSpanKeys.delete(key);
5682
5931
  this.#blockRepairRsIds.delete(key);
5683
5932
  this.#blockRsbLengths.delete(key);
5684
5933
  this.#clearBlockTimer(key);
@@ -5771,6 +6020,7 @@ var FECManager = class _FECManager {
5771
6020
  this.#blockSourceEsis.clear();
5772
6021
  this.#blockRebuiltEsis.clear();
5773
6022
  this.#blockAuthoredLengths.clear();
6023
+ this.#isoSpanKeys.clear();
5774
6024
  this.#blockRepairRsIds.clear();
5775
6025
  this.#blockRsbLengths.clear();
5776
6026
  this.#heldLayerStates.clear();
@@ -7149,9 +7399,9 @@ async function openSubscription(rx, openedPromise, options, packetIds) {
7149
7399
  } catch (error) {
7150
7400
  throw new MulticastError("subscription-failed", "MulticastReceiver did not open", error);
7151
7401
  }
7152
- if (rx.integrityScheme !== INTEGRITY_SCHEME) {
7402
+ if (opened.integrityScheme !== INTEGRITY_SCHEME) {
7153
7403
  await rx.close();
7154
- throw unsupported(`integrity scheme ${String(rx.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
7404
+ throw unsupported(`integrity scheme ${String(opened.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
7155
7405
  }
7156
7406
  const events = new EventTarget();
7157
7407
  let state = "connected";
@@ -10487,9 +10737,10 @@ function isH264IntraSlice(nal) {
10487
10737
  const sliceType = readH264SliceType(nal);
10488
10738
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
10489
10739
  }
10740
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
10490
10741
  function readH264SliceType(nal) {
10491
10742
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
10492
- const rbsp = removeEmulationPrevention(nal.subarray(1));
10743
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
10493
10744
  const state = { bitOffset: 0 };
10494
10745
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
10495
10746
  return readUnsignedExpGolomb(rbsp, state);
@@ -10636,6 +10887,96 @@ if (void 0) {
10636
10887
  ]))).toBe(false);
10637
10888
  });
10638
10889
  });
10890
+ describe("readH264SliceType", () => {
10891
+ const wholeNalSliceType = (nal) => {
10892
+ if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
10893
+ const rbsp = removeEmulationPrevention(nal.subarray(1));
10894
+ const state = { bitOffset: 0 };
10895
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null;
10896
+ return readUnsignedExpGolomb(rbsp, state);
10897
+ };
10898
+ const hex2 = (text2) => Uint8Array.from(text2.match(/../g), (byte) => parseInt(byte, 16));
10899
+ const ue = (value) => {
10900
+ const code = (value + 1).toString(2);
10901
+ return "0".repeat(code.length - 1) + code;
10902
+ };
10903
+ const sliceNal = (bits) => {
10904
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, "0").match(/.{8}/g);
10905
+ const nal = [1];
10906
+ let zeros = 0;
10907
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
10908
+ if (zeros >= 2 && byte <= 3) {
10909
+ nal.push(3);
10910
+ zeros = 0;
10911
+ }
10912
+ nal.push(byte);
10913
+ zeros = byte === 0 ? zeros + 1 : 0;
10914
+ }
10915
+ return Uint8Array.from(nal);
10916
+ };
10917
+ const x264Slices = [
10918
+ ["64x48 P", hex2("419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176"), 5, false],
10919
+ ["64x48 B", hex2("419e414212fffeeade283707cb70f7"), 6, false],
10920
+ ["64x48 non-IDR I", hex2(
10921
+ "4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39a527e23eb34c8167fd"
10922
+ ), 7, true],
10923
+ ["1280x720 B, escape at byte 10", hex2(
10924
+ "01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e19b75d92170917306190f262fd58268702db2eff86a9651e48"
10925
+ ), 6, false],
10926
+ ["1280x720 P, escape at byte 15", hex2(
10927
+ "41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f02c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e85302da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3"
10928
+ ), 5, false],
10929
+ ["1280x720 B, escape at byte 22", hex2("01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352"), 6, false],
10930
+ ["7680x4320 IDR, first_mb_in_slice 97440", hex2(
10931
+ "650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9"
10932
+ ), null, true],
10933
+ ["7680x4320 P, first_mb_in_slice 32640", hex2(
10934
+ "410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020"
10935
+ ), 5, false],
10936
+ ["7680x4320 P, first_mb_in_slice 97440", hex2(
10937
+ "410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806"
10938
+ ), 5, false]
10939
+ ];
10940
+ const syntheticSlices = [
10941
+ ["an escape inside first_mb_in_slice", sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
10942
+ ["an escape between the fields", sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
10943
+ ["an escape inside slice_type", sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
10944
+ ["the longest fields, five escapes", sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
10945
+ ["the largest values", sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
10946
+ ["31 leading zeros in first_mb_in_slice", sliceNal(`${"0".repeat(31)}1`), null],
10947
+ ["31 leading zeros in slice_type", sliceNal(`1${"0".repeat(31)}1`), null],
10948
+ ["escapes running past the slice header", sliceNal(ue(0) + ue(5) + "0".repeat(400)), 5]
10949
+ ];
10950
+ test("reads the slice_type of real and synthetic slices", () => {
10951
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
10952
+ expect(readH264SliceType(nal), name).toBe(sliceType);
10953
+ }
10954
+ });
10955
+ test("matches the whole-NAL unescape at every truncation", () => {
10956
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
10957
+ for (let end = 0; end <= nal.length; end++) {
10958
+ const cut = nal.subarray(0, end);
10959
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut));
10960
+ }
10961
+ }
10962
+ });
10963
+ test("matches the whole-NAL unescape on zero-heavy NAL units", () => {
10964
+ const bytes = [0, 0, 0, 3, 1, 2, 128, 255];
10965
+ let seed = 1;
10966
+ const next = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) >>> 16;
10967
+ for (let i = 0; i < 5e3; i++) {
10968
+ const nal = new Uint8Array(2 + next() % 63);
10969
+ nal[0] = 65;
10970
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length];
10971
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal));
10972
+ }
10973
+ });
10974
+ test("classifies the x264 slices as keyframes or not", () => {
10975
+ for (const [name, nal, , keyframe] of x264Slices) {
10976
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe);
10977
+ }
10978
+ });
10979
+ });
10639
10980
  describe("avccToAnnexB", () => {
10640
10981
  test("converts with SPS/PPS on keyframe", () => {
10641
10982
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -13683,6 +14024,9 @@ function authoredGap(before, after) {
13683
14024
  function ssIdAfter(a, b) {
13684
14025
  return (a - b | 0) > 0;
13685
14026
  }
14027
+ function holdsRebuilt(stream) {
14028
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
14029
+ }
13686
14030
  var FecReleaseSequencer = class {
13687
14031
  #streams = /* @__PURE__ */ new Map();
13688
14032
  #gate;
@@ -13745,6 +14089,7 @@ var FecReleaseSequencer = class {
13745
14089
  stream.lastSbn = void 0;
13746
14090
  stream.discontinuity = false;
13747
14091
  stream.rapSsId = void 0;
14092
+ stream.sourced = false;
13748
14093
  }
13749
14094
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
13750
14095
  this.#recordStat("droppedStale");
@@ -13771,6 +14116,7 @@ var FecReleaseSequencer = class {
13771
14116
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
13772
14117
  else hi = mid;
13773
14118
  }
14119
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
13774
14120
  stream.buf.splice(lo, 0, frame);
13775
14121
  this.#drainUnlessDeferred(stream);
13776
14122
  }
@@ -13806,6 +14152,41 @@ var FecReleaseSequencer = class {
13806
14152
  }
13807
14153
  return false;
13808
14154
  }
14155
+ /**
14156
+ * These streams' sink is being replaced by one that has seen no source
14157
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
14158
+ * release to the sink being replaced the frames the unanchored path had
14159
+ * already released to it (#cursorPassed): there they waited in its queue,
14160
+ * which its replacement flushes. A stream that holds none is not drained:
14161
+ * it holds nothing the anchor kept back, and a drain would still force out
14162
+ * a frame held past the hold limit, which before the anchor waited for the
14163
+ * next push. Then treat the streams as unsourced until a source frame is
14164
+ * released.
14165
+ */
14166
+ unsource(packetId, catalogTrackName) {
14167
+ for (const stream of this.#streams.values()) {
14168
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
14169
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
14170
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
14171
+ else this.#drain(stream, true);
14172
+ }
14173
+ stream.sourced = false;
14174
+ }
14175
+ }
14176
+ }
14177
+ /**
14178
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
14179
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
14180
+ * packetId.
14181
+ */
14182
+ holdsRebuilt(packetId, catalogTrackName) {
14183
+ for (const stream of this.#streams.values()) {
14184
+ if (stream.packetId !== packetId) continue;
14185
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
14186
+ if (holdsRebuilt(stream)) return true;
14187
+ }
14188
+ return false;
14189
+ }
13809
14190
  /** Re-evaluate held gaps after FEC state changed. */
13810
14191
  poke(streamKey) {
13811
14192
  if (streamKey !== void 0) {
@@ -13897,16 +14278,32 @@ var FecReleaseSequencer = class {
13897
14278
  last: null,
13898
14279
  lastSbn: void 0,
13899
14280
  discontinuity: false,
13900
- rapSsId: void 0
14281
+ rapSsId: void 0,
14282
+ sourced: false,
14283
+ draining: 0
13901
14284
  };
13902
14285
  this.#streams.set(streamKey, stream);
13903
14286
  }
13904
14287
  return stream;
13905
14288
  }
13906
- #drain(stream) {
14289
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
14290
+ #drain(stream, asUnanchored = false) {
14291
+ stream.draining++;
14292
+ try {
14293
+ this.#drainLoop(stream, asUnanchored);
14294
+ } finally {
14295
+ stream.draining--;
14296
+ }
14297
+ }
14298
+ #drainLoop(stream, asUnanchored) {
13907
14299
  while (stream.buf.length > 0 && stream.last !== null) {
13908
14300
  const head = stream.buf[0];
13909
14301
  const last = stream.last;
14302
+ if (compareFrameOrder(head, last) <= 0) {
14303
+ stream.buf.shift();
14304
+ this.#release(stream, head, void 0);
14305
+ continue;
14306
+ }
13910
14307
  if (stream.discontinuity) {
13911
14308
  stream.discontinuity = false;
13912
14309
  stream.buf.shift();
@@ -13920,9 +14317,10 @@ var FecReleaseSequencer = class {
13920
14317
  }
13921
14318
  const headSbn = head.meta.fecSbn;
13922
14319
  const from = stream.lastSbn ?? headSbn;
13923
- const to = headSbn ?? stream.lastSbn;
14320
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
13924
14321
  let lost = [];
13925
14322
  const unanchored = from === void 0 && to === void 0;
14323
+ let unresolved = false;
13926
14324
  if (from !== void 0 && to !== void 0) {
13927
14325
  const resolved = this.#gate.resolvedLoss(
13928
14326
  stream.packetId,
@@ -13931,7 +14329,8 @@ var FecReleaseSequencer = class {
13931
14329
  Math.max(from, to),
13932
14330
  from
13933
14331
  );
13934
- if (resolved === null) {
14332
+ unresolved = resolved === null;
14333
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored) && !this.#unrepairableWaitOver(stream, last, head, from, to)) {
13935
14334
  const heldMs = performance.now() - head.arrivedAtMs;
13936
14335
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
13937
14336
  this.#recordStat("forcedWindowFlushes");
@@ -13939,22 +14338,69 @@ var FecReleaseSequencer = class {
13939
14338
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
13940
14339
  continue;
13941
14340
  }
13942
- lost = resolved;
14341
+ lost = resolved ?? [];
13943
14342
  }
13944
14343
  stream.buf.shift();
13945
14344
  this.#release(
13946
14345
  stream,
13947
14346
  head,
13948
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
14347
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
13949
14348
  );
13950
14349
  }
13951
14350
  }
14351
+ /**
14352
+ * The head has waited out a gap only a late source can still fill
14353
+ * (FecReleaseGate.unrepairableWaitMs). Not yet: the gate is asked to poke
14354
+ * the stream when it has (`wakeAt`), since no packet may come by then.
14355
+ */
14356
+ #unrepairableWaitOver(stream, last, head, from, to) {
14357
+ const waitMs = this.#gate.unrepairableWaitMs?.(last, head, from, to);
14358
+ if (waitMs === void 0) return false;
14359
+ const atMs = head.arrivedAtMs + waitMs;
14360
+ if (performance.now() >= atMs) return true;
14361
+ this.#gate.wakeAt?.(stream.packetId, stream.catalogTrackName, atMs);
14362
+ return false;
14363
+ }
14364
+ /**
14365
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
14366
+ * source cursor holds it unanchored, and neither does a later frame behind
14367
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
14368
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
14369
+ * like each frame that arrived in front of it since (stale there). The head
14370
+ * then goes, decided as it would be unanchored, once a frame the base path
14371
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
14372
+ * marked one: the base path has passed that one, so a frame still missing
14373
+ * before it can only come from a repair. It also goes while no source frame
14374
+ * has been released, when the direct path shows a recovered frame at once.
14375
+ * And it goes at once while a staged switch decides on when frames arrive
14376
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
14377
+ * sink being replaced: unanchored, it had already reached the sink.
14378
+ * The scan also writes: the `passed` marks it sets stay on the frames,
14379
+ * and push marks a frame it inserts in front of a marked one from them.
14380
+ */
14381
+ #cursorPassed(stream, asUnanchored) {
14382
+ let at = -1;
14383
+ for (let i = 0; i < stream.buf.length; i++) {
14384
+ const frame = stream.buf[i];
14385
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
14386
+ frame.passed = true;
14387
+ if (at < 0) at = i;
14388
+ } else if (frame.passed !== true) break;
14389
+ }
14390
+ if (at < 0) return false;
14391
+ 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));
14392
+ }
13952
14393
  #release(stream, frame, decision) {
14394
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
14395
+ if (stale) this.#recordStat("droppedStale");
13953
14396
  if (decision) frame.meta.gapBefore = decision;
13954
14397
  stream.last = frame;
13955
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
14398
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
14399
+ stream.lastSbn = frame.meta.fecSbn;
14400
+ }
14401
+ if (frame.meta.recovered !== true) stream.sourced = true;
13956
14402
  this.#gate.onReleased?.(frame.data, frame.meta);
13957
- this.#emit(frame.data, frame.meta);
14403
+ if (!stale) this.#emit(frame.data, frame.meta);
13958
14404
  }
13959
14405
  };
13960
14406
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -14215,11 +14661,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
14215
14661
  /**
14216
14662
  * Typed view of the ISO-BMFF timing-sample budget.
14217
14663
  *
14218
- * This is the acceptance signal for the budget ratchet: `pending` walking
14219
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
14220
- * and it is observable here rather than only as media silently stopping.
14221
- * Per repo policy this is a producer-owned counter -- never infer budget
14222
- * state by parsing logs.
14664
+ * Each stream admits timing against its own window of `capacity` slots
14665
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
14666
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
14667
+ * timing a stream declared and never delivered shows up there. `pending`
14668
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
14669
+ * a producer-owned counter -- never infer budget state by parsing logs.
14223
14670
  */
14224
14671
  get timingBudgetStats() {
14225
14672
  return {
@@ -14279,6 +14726,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
14279
14726
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
14280
14727
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
14281
14728
  }
14729
+ /** See FecReleaseSequencer.unsource. */
14730
+ unsourceFecRelease(packetId, catalogTrackName) {
14731
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
14732
+ }
14733
+ /** See FecReleaseSequencer.holdsRebuilt. */
14734
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
14735
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
14736
+ }
14282
14737
  /** Re-evaluate held gaps after FEC block state changed. */
14283
14738
  pokeFecRelease(packetId, catalogTrackName) {
14284
14739
  if (!this.#fecSequencer) return;
@@ -14532,7 +14987,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14532
14987
  if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
14533
14988
  const pendingBefore = resolver2.pendingSampleCount;
14534
14989
  const evictedBefore = resolver2.evictedSampleCount;
14535
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
14990
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
14536
14991
  const admitted = resolver2.addMovieFragment(
14537
14992
  mpu.mpuSequenceNumber,
14538
14993
  data,
@@ -14605,7 +15060,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14605
15060
  info,
14606
15061
  resolver,
14607
15062
  options?.recovered === true,
14608
- options?.fecSbn
15063
+ options?.fecSbn,
15064
+ options?.fecSbnFirst
14609
15065
  );
14610
15066
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
14611
15067
  }
@@ -14698,7 +15154,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14698
15154
  info,
14699
15155
  resolver,
14700
15156
  options?.recovered === true,
14701
- options?.fecSbn
15157
+ options?.fecSbn,
15158
+ options?.fecSbnFirst
14702
15159
  );
14703
15160
  if (outcome.record !== void 0) return outcome.record;
14704
15161
  return this.#drop(outcome.reason);
@@ -14718,7 +15175,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14718
15175
  * attribution exists to keep readable. Leaving the choice at the call site
14719
15176
  * is what keeps both true.
14720
15177
  */
14721
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
15178
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
14722
15179
  const timing = resolver.sampleTiming(
14723
15180
  combined.mpuSequenceNumber,
14724
15181
  combined.movieFragmentSequenceNumber,
@@ -14735,6 +15192,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14735
15192
  );
14736
15193
  if (!meta) return { reason: "combined-meta-build-failed" };
14737
15194
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
15195
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
14738
15196
  if (!resolver.consumeSample(
14739
15197
  combined.mpuSequenceNumber,
14740
15198
  combined.movieFragmentSequenceNumber,
@@ -18250,6 +18708,7 @@ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
18250
18708
  var OVERLAY_ROUTED_LIMIT = 1024;
18251
18709
  var OVERLAY_PENDING_LIMIT = 256;
18252
18710
  var OVERLAY_OFFSET_MPUS = 16;
18711
+ var OVERLAY_REBUILT_LIMIT = 256;
18253
18712
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
18254
18713
  function assertStreamIdentity(role, stream) {
18255
18714
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -18426,6 +18885,17 @@ var MmtpRouter = class {
18426
18885
  * an MPU no member of which arrived).
18427
18886
  */
18428
18887
  #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18888
+ /**
18889
+ * The same, shown by the overlay alone, before any base recovery did: a
18890
+ * packet it rebuilt whose base copy carries its protected psn
18891
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
18892
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
18893
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
18894
+ * make the base drop a late base copy of a keyframe the overlay never
18895
+ * finished, and lift a block's late-source cut, which nothing before
18896
+ * this offset did.
18897
+ */
18898
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18429
18899
  /**
18430
18900
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
18431
18901
  * not parsed, typically because its overlap copy was parsed first
@@ -18471,6 +18941,8 @@ var MmtpRouter = class {
18471
18941
  // end: a synchronous recovery completes its block BEFORE routing the
18472
18942
  // recovered frames, and releasing a held gap in between would strand them.
18473
18943
  #fecPokeDepth = 0;
18944
+ /** FecReleaseGate.wakeAt timers, by media stream key. */
18945
+ #fecWakes = /* @__PURE__ */ new Map();
18474
18946
  #pendingFecPokes = /* @__PURE__ */ new Map();
18475
18947
  // ── Phase 14: per-role packetId dispatch (D-26, D-27, D-28) ───────
18476
18948
  /** Maps packetId → TrackRole. Default: 'single' when absent (legacy path). */
@@ -18703,13 +19175,18 @@ var MmtpRouter = class {
18703
19175
  this.#onDeltaBlockCompleteCb?.(packetId, false);
18704
19176
  }
18705
19177
  };
18706
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
19178
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
18707
19179
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
18708
19180
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
18709
19181
  this.#onDeltaBlockCompleteCb?.(packetId, true);
18710
19182
  }
18711
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18712
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19183
+ if (span === void 0) {
19184
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19185
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19186
+ } else {
19187
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
19188
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
19189
+ }
18713
19190
  };
18714
19191
  }
18715
19192
  }
@@ -18754,8 +19231,9 @@ var MmtpRouter = class {
18754
19231
  }
18755
19232
  /**
18756
19233
  * FEC-recovered source symbols whose reconstructed header named a
18757
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
18758
- * a hop re-stamped the sequence after the sender protected the packet.
19234
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
19235
+ * or, rebuilt by the overlay, than their base copy carries: a hop
19236
+ * re-stamped the sequence after the sender protected the packet.
18759
19237
  */
18760
19238
  get restampedRecoveredSequenceCount() {
18761
19239
  return this.#restampedRecoveredSeqs;
@@ -18934,6 +19412,7 @@ var MmtpRouter = class {
18934
19412
  enableMseAssembler(packetId, config, catalogTrackName) {
18935
19413
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
18936
19414
  const previous = this.#mseAssemblers.get(assemblerKey);
19415
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
18937
19416
  if (previous) {
18938
19417
  previous.flush();
18939
19418
  previous.dispose();
@@ -19084,7 +19563,8 @@ var MmtpRouter = class {
19084
19563
  fec,
19085
19564
  k,
19086
19565
  offsets: /* @__PURE__ */ new Map(),
19087
- moqBlocks: /* @__PURE__ */ new Set()
19566
+ moqBlocks: /* @__PURE__ */ new Set(),
19567
+ rebuilt: /* @__PURE__ */ new Map()
19088
19568
  };
19089
19569
  this.#overlays.set(repairPacketId, inst);
19090
19570
  return () => {
@@ -19125,6 +19605,7 @@ var MmtpRouter = class {
19125
19605
  inst.last = void 0;
19126
19606
  inst.offsets.clear();
19127
19607
  inst.moqBlocks.clear();
19608
+ inst.rebuilt.clear();
19128
19609
  }
19129
19610
  #overlaysForSource(sourcePacketId, catalogTrackName) {
19130
19611
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -19177,13 +19658,23 @@ var MmtpRouter = class {
19177
19658
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
19178
19659
  * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
19179
19660
  * FEC reads it.
19661
+ *
19662
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
19663
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
19664
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
19665
+ * the stream unstamped at the SS_ID offset it states, for the release gate
19666
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
19667
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
19180
19668
  */
19181
19669
  #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
19182
19670
  if (this.#overlays.size === 0) return;
19183
19671
  const ssId = keyframeOverlaySsId(header);
19184
19672
  if (ssId === void 0) return;
19673
+ let rebuiltPsn;
19185
19674
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
19186
19675
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
19676
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
19677
+ inst.rebuilt.delete(ssId);
19187
19678
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
19188
19679
  if (identity !== null) {
19189
19680
  inst.offsets.delete(identity.mpuSequenceNumber);
@@ -19213,6 +19704,14 @@ var MmtpRouter = class {
19213
19704
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
19214
19705
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
19215
19706
  }
19707
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
19708
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
19709
+ if (rebuiltPsn !== sequenceNumber) {
19710
+ this.#restampedRecoveredSeqs++;
19711
+ } else if (baseSsId !== void 0) {
19712
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19713
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
19714
+ }
19216
19715
  }
19217
19716
  #noteOverlayMoqBlock(inst, blockStart) {
19218
19717
  inst.moqBlocks.add(blockStart);
@@ -19246,11 +19745,16 @@ var MmtpRouter = class {
19246
19745
  }
19247
19746
  /**
19248
19747
  * Route an overlay-recovered block's packets as source media of the
19249
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
19250
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
19251
- * base re-stamp, no block advance. Each packet's wire sequence is restored
19252
- * from its keyframe's own offset; without one, a stream the base never
19253
- * re-stamped keeps the header's sequence and any other drops the packet.
19748
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
19749
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
19750
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
19751
+ * base FEC recovered does, so it waits behind base frames still in flight,
19752
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
19753
+ * longer than unanchored; one whose base SS_ID is undetermined has no
19754
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
19755
+ * advance. Each packet's wire sequence is restored from its keyframe's own
19756
+ * offset; without one, a stream the base never re-stamped keeps the
19757
+ * header's sequence and any other drops the packet.
19254
19758
  */
19255
19759
  #routeOverlayRecovered(inst, blockStart, recovered) {
19256
19760
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -19271,40 +19775,65 @@ var MmtpRouter = class {
19271
19775
  const restamped = this.#restampedStreams.has(streamKey);
19272
19776
  const restored = /* @__PURE__ */ new Set();
19273
19777
  const baseSsIds = /* @__PURE__ */ new Map();
19778
+ const gateOnly = /* @__PURE__ */ new Set();
19274
19779
  const symbols = result.symbols.flatMap((sym) => {
19780
+ const overlaySsId = serial32Add(blockStart, sym.index);
19275
19781
  const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
19276
19782
  if (anchor !== void 0) {
19277
- const overlaySsId = serial32Add(blockStart, sym.index);
19278
19783
  const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
19279
19784
  restored.add(packetSequenceNumber);
19280
19785
  const out = { ...sym, packetSequenceNumber };
19281
19786
  const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
19282
- if (baseSsId !== void 0) baseSsIds.set(out, baseSsId);
19787
+ if (baseSsId !== void 0) {
19788
+ baseSsIds.set(sym.index, baseSsId);
19789
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19790
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
19791
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
19792
+ }
19793
+ }
19283
19794
  return [out];
19284
19795
  }
19285
19796
  if (!restamped) {
19286
- const baseSsId = unstampedBaseSsId(
19287
- this.#ssIdSeqOffsetByStream.get(streamKey),
19288
- this.#unstampedSsIdSeqOffsetByStream.get(streamKey),
19289
- sym.packetSequenceNumber
19290
- );
19291
- if (baseSsId !== void 0) baseSsIds.set(sym, baseSsId);
19797
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19798
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
19799
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
19800
+ if (baseSsId !== void 0) {
19801
+ baseSsIds.set(sym.index, baseSsId);
19802
+ if (fedSsId === void 0) gateOnly.add(sym.index);
19803
+ } else {
19804
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
19805
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
19806
+ }
19292
19807
  return [sym];
19293
19808
  }
19294
19809
  this.#overlayStats.unsequencedDropped++;
19295
19810
  return [];
19296
19811
  });
19297
19812
  this.#overlayStats.recovered++;
19813
+ const mpuFirst = /* @__PURE__ */ new Map();
19814
+ for (const sym of symbols) {
19815
+ const ssId = baseSsIds.get(sym.index);
19816
+ const mpu = sym.fragment.mpuSequenceNumber;
19817
+ const first = mpuFirst.get(mpu);
19818
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
19819
+ }
19820
+ const firstSsIds = /* @__PURE__ */ new Map();
19821
+ for (const sym of symbols) {
19822
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
19823
+ }
19298
19824
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
19299
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
19825
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
19826
+ baseSsIds,
19827
+ firstSsIds
19300
19828
  });
19301
19829
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
19302
- this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds);
19830
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
19303
19831
  }
19304
19832
  /**
19305
19833
  * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
19306
19834
  * its base block too, once its base SS_ID is determined (overlayBaseSsId,
19307
- * from a received member of its MPU, else unstampedBaseSsId),
19835
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
19836
+ * base recovery showed; `baseSsIds` holds no other),
19308
19837
  * so it is fed to the base decoder as a rebuilt source
19309
19838
  * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
19310
19839
  * fewer to solve, and its repair can recover the block's other packets.
@@ -19330,7 +19859,7 @@ var MmtpRouter = class {
19330
19859
  const feeds = [];
19331
19860
  for (const sym of symbols) {
19332
19861
  if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
19333
- const ssId = baseSsIds.get(sym);
19862
+ const ssId = baseSsIds.get(sym.index);
19334
19863
  if (ssId === void 0) {
19335
19864
  this.#overlayStats.baseUndetermined++;
19336
19865
  continue;
@@ -20059,7 +20588,7 @@ var MmtpRouter = class {
20059
20588
  catalogTrackName
20060
20589
  )) continue;
20061
20590
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
20062
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
20591
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
20063
20592
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
20064
20593
  }
20065
20594
  if (payload.oversized) continue;
@@ -20147,6 +20676,7 @@ var MmtpRouter = class {
20147
20676
  this.#latestVideoSeqByStream.delete(streamKey);
20148
20677
  this.#ssIdSeqOffsetByStream.delete(streamKey);
20149
20678
  this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
20679
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
20150
20680
  this.#multicastRapTwinByStream.delete(streamKey);
20151
20681
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
20152
20682
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -20273,6 +20803,12 @@ var MmtpRouter = class {
20273
20803
  * the outgoing stream stops. The hold is bounded by the incoming stream's
20274
20804
  * own RAP cadence, so no timer is involved.
20275
20805
  *
20806
+ * While the switch is staged, the FEC release gate lets a keyframe the
20807
+ * overlay rebuilt reach it, on either side, when the keyframe did before
20808
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
20809
+ * decides on what each side delivered, and the commit discards the gate's
20810
+ * frames of the outgoing stream.
20811
+ *
20276
20812
  * The commit is one synchronous transition inside the frame path: the
20277
20813
  * outgoing stream's already-admitted frames are released (its queued FEC
20278
20814
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -20323,6 +20859,9 @@ var MmtpRouter = class {
20323
20859
  droppedIncomingFrames: 0
20324
20860
  };
20325
20861
  this.#staged = state;
20862
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
20863
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
20864
+ }
20326
20865
  return {
20327
20866
  cancel: () => {
20328
20867
  if (this.#staged !== state) return false;
@@ -20405,7 +20944,17 @@ var MmtpRouter = class {
20405
20944
  */
20406
20945
  #routeParsedFrame(data, meta) {
20407
20946
  if (this.#classifyPacketId(meta.packetId) === null) return;
20408
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
20947
+ if (this.#staged !== null) {
20948
+ let consumed = false;
20949
+ this.#fecPokeDepth++;
20950
+ try {
20951
+ consumed = this.#interceptSwitchFrame(data, meta);
20952
+ } finally {
20953
+ this.#fecPokeDepth--;
20954
+ this.#flushPendingFecPokes();
20955
+ }
20956
+ if (consumed) return;
20957
+ }
20409
20958
  this.#deliverParsedFrame(data, meta);
20410
20959
  }
20411
20960
  #commitStreamSwitch(state, rap, reason) {
@@ -20454,6 +21003,8 @@ var MmtpRouter = class {
20454
21003
  this.#disposed = true;
20455
21004
  this.#staged = null;
20456
21005
  this.cancelKeyframeLostTimer();
21006
+ for (const { timer } of this.#fecWakes.values()) clearTimeout(timer);
21007
+ this.#fecWakes.clear();
20457
21008
  this.#parser.dispose();
20458
21009
  this.#streams.clear();
20459
21010
  this.#trackPacketCallbacks.clear();
@@ -20557,12 +21108,16 @@ var MmtpRouter = class {
20557
21108
  this.#parser.deferFecRelease(work);
20558
21109
  } finally {
20559
21110
  this.#fecPokeDepth--;
20560
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
20561
- const pokes = [...this.#pendingFecPokes.values()];
20562
- this.#pendingFecPokes.clear();
20563
- for (const poke of pokes) {
20564
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20565
- }
21111
+ this.#flushPendingFecPokes();
21112
+ }
21113
+ }
21114
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
21115
+ #flushPendingFecPokes() {
21116
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
21117
+ const pokes = [...this.#pendingFecPokes.values()];
21118
+ this.#pendingFecPokes.clear();
21119
+ for (const poke of pokes) {
21120
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20566
21121
  }
20567
21122
  }
20568
21123
  }
@@ -20631,6 +21186,31 @@ var MmtpRouter = class {
20631
21186
  if (!fec?.terminalRetentionMsForPacket) return Infinity;
20632
21187
  return fec.terminalRetentionMsForPacket(packetId) ?? 0;
20633
21188
  },
21189
+ // Once no repair can fill a gap (FECManager.isoRepairlessWaitMs: only a
21190
+ // late source can), its frame waits the late-symbol allowance when the
21191
+ // gap holds no RAP an installed keyframe overlay could still rebuild:
21192
+ // lost deltas of one MPU (delta-lost), the tail of the MPU before a RAP
21193
+ // that opens the next one while MPU boundaries bound RAPs (rap-next,
21194
+ // unless the gap holds a stated block's loss: the overlay may rebuild
21195
+ // that MPU's FT=0, and the block's group then complete it), or
21196
+ // an audio gap. A gap that may hold one (rap-lost, rap-unknown, or any
21197
+ // other rap-next, whose gap may hold a whole MPU and the keyframe the
21198
+ // overlay protects) waits for that overlay's repair too (BLO-52085
21199
+ // D4). The FEC check comes first: most held gaps are not behind such a
21200
+ // span, and deciding one scans both frames' bitstreams.
21201
+ unrepairableWaitMs: (before, after, fromSbn, toSbn) => {
21202
+ const fec = this.#fecManager;
21203
+ const { packetId, catalogTrackName } = after.meta;
21204
+ const allowanceMs = fec?.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn);
21205
+ if (!fec || allowanceMs === void 0) return void 0;
21206
+ const decision = this.#decideGap(before, after, [], false);
21207
+ const mpu = before.meta.mpuSequenceNumber;
21208
+ const intoNextMpu = decision.reason === "rap-next" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu + 1 >>> 0 && fec.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
21209
+ if (decision.action === "stall" || decision.reason === "rap-next" && !intoNextMpu) {
21210
+ return fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, true);
21211
+ }
21212
+ return decision.reason === "rap-next" ? fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, true) : allowanceMs;
21213
+ },
20634
21214
  decide: (before, after, lostBlocks, discontinuity) => {
20635
21215
  const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
20636
21216
  this.#onFrameGap?.(decision);
@@ -20640,6 +21220,28 @@ var MmtpRouter = class {
20640
21220
  onRap: (packetId, catalogTrackName, ssId) => {
20641
21221
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
20642
21222
  },
21223
+ // One timer per stream, at the earliest wake asked: its drain re-arms
21224
+ // for the next frame still waiting.
21225
+ wakeAt: (packetId, catalogTrackName, atMs) => {
21226
+ if (this.#disposed) return;
21227
+ const key = this.#mediaStreamKey(packetId, catalogTrackName);
21228
+ const armed = this.#fecWakes.get(key);
21229
+ if (armed !== void 0 && armed.atMs <= atMs) return;
21230
+ if (armed !== void 0) clearTimeout(armed.timer);
21231
+ const timer = setTimeout(() => {
21232
+ this.#fecWakes.delete(key);
21233
+ this.#requestFecPoke(packetId, catalogTrackName);
21234
+ }, Math.max(0, Math.ceil(atMs - performance.now())));
21235
+ this.#fecWakes.set(key, { atMs, timer });
21236
+ },
21237
+ // A staged switch commits on when each side's frames reach it
21238
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
21239
+ // they did unanchored.
21240
+ releaseUnanchored: (packetId, catalogTrackName) => {
21241
+ const staged = this.#staged;
21242
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
21243
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
21244
+ },
20643
21245
  onReleased: (data, meta) => {
20644
21246
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
20645
21247
  const timing = meta.authoredTiming;
@@ -21090,7 +21692,8 @@ var MmtpRouter = class {
21090
21692
  source: parserOptions?.source,
21091
21693
  deliveryProvenance: parserOptions?.deliveryProvenance,
21092
21694
  catalogTrackName: parserOptions?.catalogTrackName,
21093
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
21695
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
21696
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
21094
21697
  };
21095
21698
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
21096
21699
  else this.#parser.feed(packet, feedOptions);
@@ -21556,7 +22159,12 @@ var MmtpRouter = class {
21556
22159
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
21557
22160
  if (ownerPacketId == null) return;
21558
22161
  if (this.#classifyPacketId(ownerPacketId) === null) return;
21559
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
22162
+ const fecSbnOf = (index) => {
22163
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
22164
+ const fecSbn = overlay.baseSsIds.get(index);
22165
+ const fecSbnFirst = overlay.firstSsIds.get(index);
22166
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
22167
+ };
21560
22168
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
21561
22169
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
21562
22170
  if (ssIdSeqOffset !== void 0) {
@@ -23102,6 +23710,12 @@ function isNonNegativeSafeInteger(value) {
23102
23710
  function isSymbolCounts(value) {
23103
23711
  return isRecord(value) && hasExactKeys(value, ["multicast", "moq"]) && isNonNegativeSafeInteger(value["multicast"]) && isNonNegativeSafeInteger(value["moq"]);
23104
23712
  }
23713
+ function isSpanFailure(value) {
23714
+ if (!isRecord(value) || !hasExactKeys(value, ["length", "sources"])) return false;
23715
+ const length = value["length"];
23716
+ const sources = value["sources"];
23717
+ return Number.isSafeInteger(length) && length > 0 && isNonNegativeSafeInteger(sources) && sources < length;
23718
+ }
23105
23719
  function isNullableNonNegative(value) {
23106
23720
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
23107
23721
  }
@@ -23121,7 +23735,10 @@ function isRepairLifecycleEvent(value) {
23121
23735
  case "recovered":
23122
23736
  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"]);
23123
23737
  case "failed":
23124
- return hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]);
23738
+ return hasExactKeys(
23739
+ value,
23740
+ "span" in value ? ["version", "type", "block", "blockClass", "symbols", "span"] : ["version", "type", "block", "blockClass", "symbols"]
23741
+ ) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]) && (!("span" in value) || isSpanFailure(value["span"]));
23125
23742
  case "repair-preempted":
23126
23743
  case "repair-deferred":
23127
23744
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
@@ -23330,6 +23947,8 @@ var MulticastManager = class {
23330
23947
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
23331
23948
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
23332
23949
  #repairReleases = /* @__PURE__ */ new Map();
23950
+ /** Protected repair flows owned by each live repair-endpoint release. */
23951
+ #repairProvenanceFlows = /* @__PURE__ */ new Map();
23333
23952
  /** Each source's catalog keyframe overlay, from its `ok` binding. */
23334
23953
  #overlayBindings = /* @__PURE__ */ new Map();
23335
23954
  /** Installed overlay decoders (`setKeyframeOverlayDecoder`), by source. */
@@ -23387,7 +24006,7 @@ var MulticastManager = class {
23387
24006
  onPublisherRestart: (packetId, catalogTrackName) => {
23388
24007
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
23389
24008
  },
23390
- onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
24009
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass, span) => {
23391
24010
  const pathCount = this.#fec.blockPathCount(
23392
24011
  sbn,
23393
24012
  packetId,
@@ -23405,7 +24024,8 @@ var MulticastManager = class {
23405
24024
  symbols: {
23406
24025
  multicast: pathCount?.multicastSymbols ?? 0,
23407
24026
  moq: pathCount?.moqSymbols ?? 0
23408
- }
24027
+ },
24028
+ ...span === void 0 ? {} : { span }
23409
24029
  });
23410
24030
  },
23411
24031
  onFrameGap: (decision) => {
@@ -23493,6 +24113,11 @@ var MulticastManager = class {
23493
24113
  this.#fec.onBlockVanished = (_sbn, packetId, catalogTrackName) => {
23494
24114
  this.#statsFor(packetId, catalogTrackName).vanishedBlocks++;
23495
24115
  };
24116
+ this.#fec.keyframeOverlayTiming = (packetId, catalogTrackName) => {
24117
+ const binding = this.#overlayInstalls.has(packetId) ? this.#overlayBindings.get(packetId) : void 0;
24118
+ if (binding === void 0) return void 0;
24119
+ return catalogTrackName === void 0 || catalogTrackName === binding.sourceCatalogTrackName ? binding.geometry : void 0;
24120
+ };
23496
24121
  this.#fec.onDecoderUnavailable = (event) => {
23497
24122
  this.#emitRepairLifecycle({
23498
24123
  version: 2,
@@ -23995,6 +24620,9 @@ var MulticastManager = class {
23995
24620
  this.#transport.onFailback((reason) => {
23996
24621
  const joined = this.#provenanceJoin;
23997
24622
  if (joined !== null) this.#router.unprotectProvenanceFlow(joined.flow);
24623
+ for (const flows of this.#repairProvenanceFlows.values()) {
24624
+ for (const flow of flows) this.#router.unprotectProvenanceFlow(flow);
24625
+ }
23998
24626
  this.#onFailback?.(reason);
23999
24627
  });
24000
24628
  }
@@ -24029,6 +24657,12 @@ var MulticastManager = class {
24029
24657
  "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
24030
24658
  );
24031
24659
  }
24660
+ if (provenanceFlow !== void 0) {
24661
+ const flow = multicastProvenanceFlowKey(provenanceFlow);
24662
+ if ([...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
24663
+ throw new TypeError(`[MulticastManager] join: provenance flow already registered by a repair endpoint: ${flow}`);
24664
+ }
24665
+ }
24032
24666
  const staged = this.#renditionSwitch;
24033
24667
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
24034
24668
  this.configureFec(config);
@@ -24036,8 +24670,8 @@ var MulticastManager = class {
24036
24670
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
24037
24671
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
24038
24672
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
24039
- this.#releaseProvenanceJoin();
24040
24673
  const provenance = config.provenance;
24674
+ this.#releaseProvenanceJoin();
24041
24675
  const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
24042
24676
  const ingress = protectedTracks === void 0 ? void 0 : {
24043
24677
  tracks: Object.freeze(
@@ -24090,8 +24724,13 @@ var MulticastManager = class {
24090
24724
  * feeds the flow's receiver; media datagrams are held until one admits them.
24091
24725
  */
24092
24726
  #joinProvenance(provenance, ingress) {
24727
+ this.#router.registerProvenanceFlow(ingress, this.#provenanceReceiver(provenance));
24728
+ this.#hookFailback();
24729
+ this.#provenanceJoin = { flow: ingress.flow };
24730
+ }
24731
+ #provenanceReceiver(provenance) {
24093
24732
  const { flow, auth } = provenance;
24094
- const receiver = new BcProvenanceV2Receiver({
24733
+ return new BcProvenanceV2Receiver({
24095
24734
  ...provenance.receiver,
24096
24735
  // The caller's ctx when it passes one, else the catalog's: an explicit
24097
24736
  // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
@@ -24108,9 +24747,6 @@ var MulticastManager = class {
24108
24747
  maxAuthDelayMs: flow.maxAuthDelayMs,
24109
24748
  manifestTimerMs: flow.manifestTimerMs
24110
24749
  });
24111
- this.#router.registerProvenanceFlow(ingress, receiver);
24112
- this.#hookFailback();
24113
- this.#provenanceJoin = { flow: ingress.flow };
24114
24750
  }
24115
24751
  /** Un-protect: drop the flow's hold queues (no expiry counted). */
24116
24752
  #releaseProvenanceJoin() {
@@ -24141,8 +24777,25 @@ var MulticastManager = class {
24141
24777
  * callback delivers must come from a subscription opened on
24142
24778
  * `options.gateway`. A callback that also merges another source (a MoQ or
24143
24779
  * WebSocket repair feed) must not name a native provider here.
24780
+ *
24781
+ * An endpoint's `provenance` makes its group a protected flow of its own
24782
+ * (multicast-02 7.2.7), registered here and released with the group; its
24783
+ * records ride in band on the group's port. On the user-agent path a
24784
+ * flow-less repair group of a protected track is set aside, never read, so
24785
+ * a player joining a protected catalog's repair groups passes it.
24144
24786
  */
24145
24787
  joinRepairEndpoints(endpoints, provider, options) {
24788
+ for (const { provenance, flow, source, group, port } of endpoints) {
24789
+ if (provenance === void 0) continue;
24790
+ if (flow !== void 0) {
24791
+ throw new TypeError("[MulticastManager] joinRepairEndpoints: an endpoint names provenance or flow, never both");
24792
+ }
24793
+ if (!sameIpAddress(source, provenance.flow.source) || !sameIpAddress(group, provenance.flow.groupAddress) || port !== provenance.flow.port) {
24794
+ throw new RangeError(
24795
+ "[MulticastManager] joinRepairEndpoints: provenance flow (S, G, port) must match the endpoint's source, group and port"
24796
+ );
24797
+ }
24798
+ }
24146
24799
  const releases = [];
24147
24800
  let released = false;
24148
24801
  const safely = (each) => {
@@ -24152,17 +24805,36 @@ var MulticastManager = class {
24152
24805
  console.warn("[MulticastManager] repair group release failed", error);
24153
24806
  }
24154
24807
  };
24808
+ const usedFlows = new Set(endpoints.flatMap(({ flow }) => flow === void 0 ? [] : [flow]));
24809
+ const preparedProvenance = endpoints.map((endpoint) => {
24810
+ if (endpoint.provenance === void 0) return void 0;
24811
+ const flow = multicastProvenanceFlowKey(endpoint.provenance.flow);
24812
+ if (usedFlows.has(flow) || this.#provenanceJoin?.flow === flow || [...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
24813
+ throw new TypeError(`[MulticastManager] joinRepairEndpoints: provenance flow already registered: ${flow}`);
24814
+ }
24815
+ usedFlows.add(flow);
24816
+ return { flow, receiver: this.#provenanceReceiver(endpoint.provenance) };
24817
+ });
24818
+ const provenanceFlows = [];
24155
24819
  const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners.map((owner) => owner.instance !== "keyframe" ? owner : {
24156
24820
  ...owner,
24157
24821
  ownerTrackName: endpoint.tracks.find((t) => t.packetId === owner.ownerPacketId)?.name,
24158
24822
  repairTrackName: endpoint.tracks.find((t) => t.packetId === owner.packetId)?.name
24159
24823
  }));
24160
24824
  this.#applyRepairOwners(repairOwners);
24161
- for (const endpoint of endpoints) {
24825
+ for (const [index, endpoint] of endpoints.entries()) {
24826
+ const flow = endpoint.provenance === void 0 ? endpoint.flow : multicastProvenanceFlowKey(endpoint.provenance.flow);
24162
24827
  const ingress = {
24163
24828
  tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
24164
- ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
24829
+ ...flow === void 0 ? {} : { flow }
24165
24830
  };
24831
+ if (endpoint.provenance !== void 0) {
24832
+ const prepared = preparedProvenance[index];
24833
+ if (prepared === void 0) throw new Error("[MulticastManager] repair provenance preparation missing");
24834
+ this.#router.registerProvenanceFlow(ingress, prepared.receiver);
24835
+ provenanceFlows.push(prepared.flow);
24836
+ releases.push(() => this.#router.releaseProvenanceFlow(flow));
24837
+ }
24166
24838
  let sender;
24167
24839
  const feed = (packet, sourceAddress, ingressToFeed) => {
24168
24840
  if (released) return;
@@ -24192,7 +24864,7 @@ var MulticastManager = class {
24192
24864
  packetIds: endpoint.packetIds,
24193
24865
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
24194
24866
  // A protected repair group's records ride in band on its port (7.2.3).
24195
- ...endpoint.flow === void 0 ? {} : { protected: true }
24867
+ ...flow === void 0 ? {} : { protected: true }
24196
24868
  }, ingress).then((joined) => {
24197
24869
  if (!joined && !released) fail(transport.lastJoinOutcome);
24198
24870
  });
@@ -24201,9 +24873,12 @@ var MulticastManager = class {
24201
24873
  if (released) return;
24202
24874
  released = true;
24203
24875
  this.#repairReleases.delete(release);
24876
+ this.#repairProvenanceFlows.delete(release);
24204
24877
  for (const each of releases.splice(0)) safely(each);
24205
24878
  };
24206
24879
  this.#repairReleases.set(release, repairOwners);
24880
+ this.#repairProvenanceFlows.set(release, provenanceFlows);
24881
+ if (provenanceFlows.length) this.#hookFailback();
24207
24882
  return release;
24208
24883
  }
24209
24884
  #applyRepairOwners(owners) {
@@ -24689,7 +25364,8 @@ var MulticastManager = class {
24689
25364
  blockProfile: parseFecBlockProfile(
24690
25365
  geometry2.blockProfile,
24691
25366
  `tracks[${JSON.stringify(track.name)}].fec keyframe overlay blockProfile`
24692
- )
25367
+ ),
25368
+ geometry: geometry2
24693
25369
  });
24694
25370
  }
24695
25371
  }
@@ -24728,7 +25404,7 @@ var MulticastManager = class {
24728
25404
  for (const [sourcePacketId, install] of [...this.#overlayInstalls]) {
24729
25405
  const before = this.#overlayBindings.get(sourcePacketId);
24730
25406
  const after = overlayBindings.get(sourcePacketId);
24731
- const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => after[key] === before[key]);
25407
+ const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => key === "geometry" || after[key] === before[key]);
24732
25408
  if (!same) install.dispose();
24733
25409
  else if (this.#router.hasKeyframeOverlay(after.repairPacketId)) this.#router.resetKeyframeOverlays(sourcePacketId);
24734
25410
  else install.reattach();
@@ -24785,10 +25461,12 @@ var MulticastManager = class {
24785
25461
  * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
24786
25462
  * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
24787
25463
  * pending hole and reported here, and `closeIsoHoles` must be called for it
24788
- * once its range FETCH ends (or none is sent).
25464
+ * once its range FETCH ends (or none is sent). `onExpired` is told of a
25465
+ * pending hole the stream runs past the locator's horizon: returning true,
25466
+ * the caller closes it (`closeIsoHoles`); otherwise it is discarded.
24789
25467
  */
24790
- onUndelimitedLoss(cb) {
24791
- this.#fec.setUndelimitedLossHandler(cb);
25468
+ onUndelimitedLoss(cb, onExpired) {
25469
+ this.#fec.setUndelimitedLossHandler(cb, onExpired ?? null);
24792
25470
  }
24793
25471
  /**
24794
25472
  * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
@@ -25024,7 +25702,8 @@ var MulticastManager = class {
25024
25702
  "stream" in event ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
25025
25703
  ...event,
25026
25704
  block: Object.freeze({ ...event.block }),
25027
- ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {}
25705
+ ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {},
25706
+ ..."span" in event && event.span !== void 0 ? { span: Object.freeze({ ...event.span }) } : {}
25028
25707
  }
25029
25708
  );
25030
25709
  if (this.#logRepairLifecycle) {