@blockcast/mmt-container 2.2.0-main.4a79a288e69e → 2.2.0-main.4ccba0f2f32a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/browser-runtime.js +1119 -165
  2. package/dist/browser-runtime.js.map +3 -3
  3. package/dist/delta-fallback-config.js.map +1 -1
  4. package/dist/fec-manager.d.ts +67 -11
  5. package/dist/fec-manager.d.ts.map +1 -1
  6. package/dist/fec-manager.js +377 -54
  7. package/dist/fec-manager.js.map +2 -2
  8. package/dist/fec-worker-setup.js.map +1 -1
  9. package/dist/index.d.ts +2 -2
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js.map +2 -2
  12. package/dist/iso-block-locator.d.ts +48 -13
  13. package/dist/iso-block-locator.d.ts.map +1 -1
  14. package/dist/iso-block-locator.js +97 -25
  15. package/dist/iso-block-locator.js.map +2 -2
  16. package/dist/media-router.js.map +1 -1
  17. package/dist/mmtp-container-parser.d.ts +64 -8
  18. package/dist/mmtp-container-parser.d.ts.map +1 -1
  19. package/dist/mmtp-container-parser.js +159 -21
  20. package/dist/mmtp-container-parser.js.map +2 -2
  21. package/dist/mmtp-container-parser.no-modules.js +158 -23
  22. package/dist/mmtp-container-parser.no-modules.js.map +2 -2
  23. package/dist/mmtp-decode-pipeline.js +158 -21
  24. package/dist/mmtp-decode-pipeline.js.map +2 -2
  25. package/dist/mmtp-router.d.ts +31 -8
  26. package/dist/mmtp-router.d.ts.map +1 -1
  27. package/dist/mmtp-router.js +481 -68
  28. package/dist/mmtp-router.js.map +2 -2
  29. package/dist/multicast-manager.d.ts +26 -3
  30. package/dist/multicast-manager.d.ts.map +1 -1
  31. package/dist/multicast-manager.js +940 -139
  32. package/dist/multicast-manager.js.map +2 -2
  33. package/dist/multicast-transport.js +2 -2
  34. package/dist/multicast-transport.js.map +2 -2
  35. package/dist/no-modules.js +158 -21
  36. package/dist/no-modules.js.map +2 -2
  37. package/dist/repair-fetch.d.ts +36 -8
  38. package/dist/repair-fetch.d.ts.map +1 -1
  39. package/dist/repair-fetch.js +285 -26
  40. package/dist/repair-fetch.js.map +3 -3
  41. package/dist/track-session.d.ts.map +1 -1
  42. package/dist/track-session.js +1 -0
  43. package/dist/track-session.js.map +2 -2
  44. package/dist/wasm-mmtp-container-parser.js +158 -21
  45. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  46. package/package.json +5 -5
  47. package/src/fec-manager.ts +407 -28
  48. package/src/index.ts +3 -0
  49. package/src/iso-block-locator.ts +133 -31
  50. package/src/mmtp-container-parser.ts +273 -26
  51. package/src/mmtp-router.ts +541 -55
  52. package/src/multicast-manager.ts +118 -14
  53. package/src/repair-fetch.ts +363 -49
  54. package/src/track-session.ts +3 -0
@@ -1189,6 +1189,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
1189
1189
  this.#heldEvicted = 0;
1190
1190
  /** Pending holes (see `deferIncompleteGaps`): unstated, sources still held. */
1191
1191
  this.#holes = [];
1192
+ /** Holes the horizon passed while pending: sources held until closed. */
1193
+ this.#expired = [];
1194
+ /** Of `#expired`, those `takeExpiredHoles` has not handed out yet. */
1195
+ this.#newlyExpired = [];
1196
+ /**
1197
+ * Spans closed from expired holes: behind the horizon, so kept only for
1198
+ * `locate` while their sources are fed, until the next retirement.
1199
+ */
1200
+ this.#closedBehind = [];
1192
1201
  /**
1193
1202
  * Keep a gap that is missing a source as a pending hole rather than a span,
1194
1203
  * so a repair FETCHed for it (draft-ramadan-moq-fec §7.5) can still state
@@ -1210,7 +1219,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
1210
1219
  #retentionBlocks;
1211
1220
  #heldEvicted;
1212
1221
  #newest;
1222
+ #newestSource;
1213
1223
  #holes;
1224
+ #expired;
1225
+ #newlyExpired;
1226
+ #closedBehind;
1214
1227
  static #checkedRetention(retentionBlocks) {
1215
1228
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
1216
1229
  throw new Error(
@@ -1247,6 +1260,21 @@ var IsoBlockLocator = class _IsoBlockLocator {
1247
1260
  observe(position) {
1248
1261
  if (this.#newest === void 0 || serial32Precedes(this.#newest, position)) this.#newest = position;
1249
1262
  }
1263
+ /**
1264
+ * The newest source SS_ID noted with `noteSource` (RFC 1982 order). Unlike
1265
+ * `newest`, a repair never moves it: a repair can run ahead of its sources,
1266
+ * a source cannot run ahead of the sources sent before it except by
1267
+ * reordering.
1268
+ */
1269
+ get newestSource() {
1270
+ return this.#newestSource;
1271
+ }
1272
+ /** Note a received source's SS_ID; true when it is the newest one yet. */
1273
+ noteSource(ssId) {
1274
+ if (this.#newestSource !== void 0 && !serial32Precedes(this.#newestSource, ssId)) return false;
1275
+ this.#newestSource = ssId;
1276
+ return true;
1277
+ }
1250
1278
  /** Held sources evicted by `heldCapacity` (never by the horizon itself). */
1251
1279
  get heldEvicted() {
1252
1280
  return this.#heldEvicted;
@@ -1265,17 +1293,29 @@ var IsoBlockLocator = class _IsoBlockLocator {
1265
1293
  }
1266
1294
  /** The known block or span containing `ssId`, with its ESI. */
1267
1295
  locate(ssId) {
1268
- for (let i = this.#blocks.length - 1; i >= 0; i--) {
1269
- const block = this.#blocks[i];
1270
- if (isoBlockContains(block.start, block.length, ssId)) {
1271
- return { block, esi: serial32Distance(block.start, ssId) };
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
+ }
1272
1302
  }
1273
1303
  }
1274
1304
  return null;
1275
1305
  }
1276
- /** Number of pending holes. */
1306
+ /** Number of holes not closed yet, pending or past the horizon. */
1277
1307
  get holeCount() {
1278
- 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);
1279
1319
  }
1280
1320
  /** The stated block (never a span) ending exactly at `end`. */
1281
1321
  blockEndingAt(end) {
@@ -1331,9 +1371,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
1331
1371
  /**
1332
1372
  * Apply one repair symbol's `(SS_Start, SSB_length)`. The first repair of a
1333
1373
  * block states its range and places every held source in it; later repair
1334
- * symbols of the same block change nothing. A range that contradicts a
1335
- * known block (a different length, or an overlap with another block or a
1336
- * span) fails closed: the repair symbol is dropped and no block changes.
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.
1337
1379
  * A newly stated block retires behind its SS_Start (see the class note).
1338
1380
  * A block so far past `newest` that stating it would retire the position
1339
1381
  * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
@@ -1352,7 +1394,16 @@ var IsoBlockLocator = class _IsoBlockLocator {
1352
1394
  const known = this.blockAt(start);
1353
1395
  if (known !== void 0) {
1354
1396
  if (known.span) {
1355
- 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}` };
1356
1407
  }
1357
1408
  if (known.length !== length) {
1358
1409
  return {
@@ -1420,18 +1471,28 @@ var IsoBlockLocator = class _IsoBlockLocator {
1420
1471
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
1421
1472
  }
1422
1473
  /**
1423
- * Turn every pending hole inside `[start, start + length)` into a
1424
- * repair-less span, claiming its held sources: its range FETCH ended, so
1425
- * nothing more will state its blocks. Returns the spans, in SS_ID order.
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.
1426
1480
  */
1427
1481
  closeHolesWithin(start, length) {
1428
1482
  const closed = [];
1429
- for (const hole of [...this.#holes]) {
1430
- if (!isoBlockContains(start, length, hole.start)) continue;
1431
- this.#holes.splice(this.#holes.indexOf(hole), 1);
1432
- const spanBlock = { start: hole.start, length: hole.length, span: true };
1433
- closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
1434
- this.#blocks.push(spanBlock);
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
+ }
1435
1496
  }
1436
1497
  return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
1437
1498
  }
@@ -1445,15 +1506,17 @@ var IsoBlockLocator = class _IsoBlockLocator {
1445
1506
  return void 0;
1446
1507
  }
1447
1508
  /**
1448
- * Retire every block and span whose last SS_ID, and every held source,
1449
- * lies more than `retentionBlocks` blocks behind `position`, with the shared
1450
- * lower-bound metric (`isoBlocksBehindLowerBound`) every ISO interleave
1451
- * horizon uses. Returns the retired block starts.
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.
1452
1514
  */
1453
1515
  retireBehind(position) {
1454
1516
  this.observe(position);
1455
1517
  const horizon = this.#retentionBlocks;
1456
1518
  const retired = [];
1519
+ this.#closedBehind.length = 0;
1457
1520
  for (let i = this.#blocks.length - 1; i >= 0; i--) {
1458
1521
  const block = this.#blocks[i];
1459
1522
  const last = serial32Add(block.start, block.length - 1);
@@ -1465,10 +1528,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
1465
1528
  for (let i = this.#holes.length - 1; i >= 0; i--) {
1466
1529
  const hole = this.#holes[i];
1467
1530
  const last = serial32Add(hole.start, hole.length - 1);
1468
- 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);
1469
1535
  }
1470
1536
  for (const ssId of [...this.#held.keys()]) {
1471
- 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
+ }
1472
1540
  }
1473
1541
  return retired;
1474
1542
  }
@@ -1476,9 +1544,13 @@ var IsoBlockLocator = class _IsoBlockLocator {
1476
1544
  reset() {
1477
1545
  this.#blocks.length = 0;
1478
1546
  this.#holes.length = 0;
1547
+ this.#expired.length = 0;
1548
+ this.#newlyExpired.length = 0;
1549
+ this.#closedBehind.length = 0;
1479
1550
  this.#held.clear();
1480
1551
  this.#coverageEnd = void 0;
1481
1552
  this.#newest = void 0;
1553
+ this.#newestSource = void 0;
1482
1554
  }
1483
1555
  #claim(block) {
1484
1556
  const placed = [];
@@ -2067,6 +2139,7 @@ var WORKER_ERROR_LOG_CAP = 5;
2067
2139
  var WORKER_ERROR_KIND_CAP = 32;
2068
2140
  var WORKER_ERROR_OVERFLOW_KIND = "other";
2069
2141
  var STARTUP_REPAIR_WAIT_SOURCE_BOUNDARIES = 2;
2142
+ var NOT_TAKEN = Object.freeze({ taken: false, recovered: null });
2070
2143
  function isMulticastSymbolDelivery(value) {
2071
2144
  return value === "datagram" || value === "ordered-relay";
2072
2145
  }
@@ -2160,10 +2233,18 @@ var FECManager = class _FECManager {
2160
2233
  // 'pending' forever, which would park every later frame of its stream in
2161
2234
  // the in-order release gate. Each entry owns its handle; the callback
2162
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
+ */
2163
2240
  this.#pendingWorkerCleanupBounds = /* @__PURE__ */ new Map();
2164
2241
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
2165
2242
  this.#blockSourceCounts = /* @__PURE__ */ new Map();
2166
2243
  this.#blockSourceEsis = /* @__PURE__ */ new Map();
2244
+ // Source ESIs per block that another FEC instance rebuilt and fed in
2245
+ // (feedRebuiltSourceSymbol). Kept apart from #blockSourceEsis: they are
2246
+ // not network arrivals and never make a block clean.
2247
+ this.#blockRebuiltEsis = /* @__PURE__ */ new Map();
2167
2248
  // Authored SSB_length per block (ISO/IEC 23008-1 §C.5.3), learned from the
2168
2249
  // first repair symbol. The FFmpeg moq_mmt publisher closes a block every D
2169
2250
  // media units, usually before it holds K symbols; under iso-ssbg1-v1
@@ -2172,6 +2253,9 @@ var FECManager = class _FECManager {
2172
2253
  // SSB_length source arrivals and recoverable from SSB_length received
2173
2254
  // symbols; waiting for K fails every one of them.
2174
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();
2175
2259
  this.#ssbLengthConflictCount = 0;
2176
2260
  this.#blockRepairRsIds = /* @__PURE__ */ new Map();
2177
2261
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
@@ -2369,7 +2453,10 @@ var FECManager = class _FECManager {
2369
2453
  // arrives via onBlockRecovered callback.
2370
2454
  this.onBlockStarted = null;
2371
2455
  this.onBlockComplete = null;
2372
- /** A block reached its fail bound. `blockClass` is its class at failure. */
2456
+ /**
2457
+ * A block reached its fail bound. `blockClass` is its class at failure.
2458
+ * `span` is set when what failed is a repair-less span starting at `sbn`.
2459
+ */
2373
2460
  this.onBlockFailed = null;
2374
2461
  /**
2375
2462
  * Fired once per stream when its Worker decoder stops being routable.
@@ -2411,6 +2498,8 @@ var FECManager = class _FECManager {
2411
2498
  * for it, which it must be.
2412
2499
  */
2413
2500
  this.#onUndelimitedLoss = null;
2501
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
2502
+ this.#onIsoHoleExpired = null;
2414
2503
  /** A block every symbol of which vanished was created by SBN evidence. */
2415
2504
  this.onBlockVanished = null;
2416
2505
  /** A block reached a terminal state (completed, recovered, or failed). */
@@ -2453,7 +2542,9 @@ var FECManager = class _FECManager {
2453
2542
  #pendingWorkerCleanupBounds;
2454
2543
  #blockSourceCounts;
2455
2544
  #blockSourceEsis;
2545
+ #blockRebuiltEsis;
2456
2546
  #blockAuthoredLengths;
2547
+ #isoSpanKeys;
2457
2548
  #ssbLengthConflictCount;
2458
2549
  #blockRepairRsIds;
2459
2550
  #blockRsbLengths;
@@ -2520,6 +2611,7 @@ var FECManager = class _FECManager {
2520
2611
  #decoderUnavailableEvents;
2521
2612
  #repairSymbolSizeMismatchCount;
2522
2613
  #onUndelimitedLoss;
2614
+ #onIsoHoleExpired;
2523
2615
  #encodeTrackName(catalogTrackName) {
2524
2616
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
2525
2617
  if (encoded === void 0) {
@@ -2991,7 +3083,10 @@ var FECManager = class _FECManager {
2991
3083
  timer.handle = null;
2992
3084
  this.#requestRepair(sbn, packetId, catalogTrackName);
2993
3085
  };
2994
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
3086
+ timer.handle = setTimeout(
3087
+ onFire,
3088
+ this.#receiptAtMs === void 0 ? Math.max(0, deadlineMs - performance.now()) : this.#receiptTimerDelayMs(deadlineMs, 0)
3089
+ );
2995
3090
  this.#repairDeadlines.set(key, timer);
2996
3091
  }
2997
3092
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -3135,8 +3230,14 @@ var FECManager = class _FECManager {
3135
3230
  * Vanished blocks are not enumerated here: their starts are unknown until a
3136
3231
  * repair states them. The SS_IDs between two stated blocks become one
3137
3232
  * repair-less span when the later block's repair arrives (placeIsoRepair).
3233
+ *
3234
+ * A `held` source arrived before its block was known and is fed only now
3235
+ * that a repair, a span or a closed hole placed it: how far its block start
3236
+ * then lies behind the frontier measures how long the receiver held it, not
3237
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
3238
+ * it (BLO-52085).
3138
3239
  */
3139
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
3240
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn, held = false) {
3140
3241
  const streamKey = this.#streamKey(packetId, catalogTrackName);
3141
3242
  const now = performance.now();
3142
3243
  const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
@@ -3175,7 +3276,7 @@ var FECManager = class _FECManager {
3175
3276
  return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
3176
3277
  };
3177
3278
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
3178
- if (symbol === "source" && window2 !== null && this.#blockPrecedes(sbn, previous.sbn) && (this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId) || psn !== void 0 && anchor !== void 0 && serial32Precedes(ssId, anchor.ssId) && psn !== anchor.psn && !sentInOrder({ ssId, psn }, anchor))) {
3279
+ if (symbol === "source" && window2 !== null && this.#blockPrecedes(sbn, previous.sbn) && (!held && this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId) || psn !== void 0 && anchor !== void 0 && serial32Precedes(ssId, anchor.ssId) && psn !== anchor.psn && !sentInOrder({ ssId, psn }, anchor))) {
3179
3280
  discontinuity();
3180
3281
  return;
3181
3282
  }
@@ -3437,17 +3538,21 @@ var FECManager = class _FECManager {
3437
3538
  this.#blockWaitDeadlinesMs.delete(key);
3438
3539
  this.#repairHoldUntilMs.delete(key);
3439
3540
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
3440
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName);
3541
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs);
3441
3542
  };
3442
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)));
3543
+ timer.handle = setTimeout(
3544
+ onFire,
3545
+ this.#receiptAtMs === void 0 ? Math.max(1, Math.ceil(deadlineMs - nowMs)) : this.#receiptTimerDelayMs(deadlineMs, 1)
3546
+ );
3443
3547
  this.#activeBlocks.set(key, timer);
3444
3548
  this.#indexBlockKey(key, sbn, packetId);
3445
3549
  }
3446
3550
  /**
3447
3551
  * Hand a block whose delivery is over to its decoder for finalization: the
3448
- * datagram deadline fired, or the ordered relay moved past it.
3552
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
3553
+ * is when it was due: its deadline, or now.
3449
3554
  */
3450
- #finalizeExpiredBlock(sbn, packetId, catalogTrackName) {
3555
+ #finalizeExpiredBlock(sbn, packetId, catalogTrackName, dueAtMs = performance.now()) {
3451
3556
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
3452
3557
  if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
3453
3558
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -3463,7 +3568,7 @@ var FECManager = class _FECManager {
3463
3568
  if (workerClient) {
3464
3569
  this.#pendingWorkerCleanups.add(key);
3465
3570
  this.#pendingWorkerCleanupClients.set(key, workerClient);
3466
- this.#boundOwedCleanup(key, packetId, workerClient);
3571
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs);
3467
3572
  workerClient.cleanup(sbn);
3468
3573
  } else {
3469
3574
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
@@ -3775,7 +3880,9 @@ var FECManager = class _FECManager {
3775
3880
  }
3776
3881
  resetMap(this.#blockSourceCounts);
3777
3882
  resetMap(this.#blockSourceEsis);
3883
+ resetMap(this.#blockRebuiltEsis);
3778
3884
  resetMap(this.#blockAuthoredLengths);
3885
+ resetSet(this.#isoSpanKeys);
3779
3886
  resetMap(this.#blockRepairRsIds);
3780
3887
  resetMap(this.#blockRsbLengths);
3781
3888
  resetMap(this.#heldLayerStates);
@@ -3899,7 +4006,9 @@ var FECManager = class _FECManager {
3899
4006
  dropMap(this.#pendingWorkerCleanupClients);
3900
4007
  dropMap(this.#blockSourceCounts);
3901
4008
  dropMap(this.#blockSourceEsis);
4009
+ dropMap(this.#blockRebuiltEsis);
3902
4010
  dropMap(this.#blockAuthoredLengths);
4011
+ dropSet(this.#isoSpanKeys);
3903
4012
  dropMap(this.#blockRepairRsIds);
3904
4013
  dropMap(this.#blockRsbLengths);
3905
4014
  dropMap(this.#blockPathCounts);
@@ -4061,6 +4170,9 @@ var FECManager = class _FECManager {
4061
4170
  this.#unindexBlockKey(key);
4062
4171
  }
4063
4172
  }
4173
+ if (isSourceSymbol && source === "multicast") {
4174
+ this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), sbn + esi >>> 0, packetId, catalogTrackName);
4175
+ }
4064
4176
  return true;
4065
4177
  }
4066
4178
  #observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName) {
@@ -4239,8 +4351,9 @@ var FECManager = class _FECManager {
4239
4351
  return true;
4240
4352
  }
4241
4353
  /**
4242
- * Drop a block's repair hold: its FETCH ended without delivering. The block
4243
- * falls back to its multicast wait, which may already have passed.
4354
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
4355
+ * back only a repair that cannot complete it. The block falls back to its
4356
+ * multicast wait, which may already have passed.
4244
4357
  */
4245
4358
  releaseRepairHold(sbn, packetId, catalogTrackName) {
4246
4359
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -4378,6 +4491,8 @@ var FECManager = class _FECManager {
4378
4491
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
4379
4492
  const evictedBefore = locator.heldEvicted;
4380
4493
  const held = locator.hold(ssId, source);
4494
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
4495
+ if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
4381
4496
  const evicted = locator.heldEvicted - evictedBefore;
4382
4497
  if (evicted > 0) {
4383
4498
  const before = this.#isoHeldEvictedCount;
@@ -4398,17 +4513,20 @@ var FECManager = class _FECManager {
4398
4513
  * contradicts a known block is refused (counted) and must be dropped.
4399
4514
  */
4400
4515
  placeIsoRepair(packetId, catalogTrackName, ssStart, ssbLength) {
4401
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength);
4516
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
4517
+ const placement = locator.placeRepair(ssStart, ssbLength);
4518
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
4402
4519
  if (placement.status !== "placed") {
4403
4520
  this.#isoRepairRefusedCount++;
4404
4521
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
4405
4522
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`);
4406
4523
  }
4524
+ if (placement.ofSpan !== void 0) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName);
4407
4525
  return placement;
4408
4526
  }
4527
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName));
4409
4528
  if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
4410
4529
  if (placement.hole !== void 0) {
4411
- const locator = this.#isoLocatorFor(packetId, catalogTrackName);
4412
4530
  const hole = placement.hole.block;
4413
4531
  const previous = locator.blockEndingAt(hole.start);
4414
4532
  const loss = {
@@ -4429,17 +4547,29 @@ var FECManager = class _FECManager {
4429
4547
  * `handler`, instead of a repair-less span; null restores spans. Set by the
4430
4548
  * range repair scheduler; applies to every stream from its next gap. The
4431
4549
  * handler and the deferral are one setting, so no hole is ever created with
4432
- * nobody to close it.
4550
+ * nobody to close it. `onExpired` is told of each pending hole the stream
4551
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
4552
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
4553
+ * reported; otherwise the hole is discarded with its sources.
4433
4554
  */
4434
- setUndelimitedLossHandler(handler) {
4555
+ setUndelimitedLossHandler(handler, onExpired = null) {
4435
4556
  this.#onUndelimitedLoss = handler;
4557
+ this.#onIsoHoleExpired = handler === null ? null : onExpired;
4436
4558
  this.#deferIsoGaps = handler !== null;
4437
4559
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
4438
4560
  }
4561
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
4562
+ #settleExpiredIsoHoles(locator, packetId, catalogTrackName) {
4563
+ for (const hole of locator.takeExpiredHoles()) {
4564
+ const expired = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length };
4565
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length);
4566
+ }
4567
+ }
4439
4568
  /**
4440
- * The range repair for a hole ended: every hole still pending inside
4441
- * `[start, start + length)` becomes a repair-less span. Returns those spans
4442
- * with the held sources they placed, for the caller to feed (MmtpRouter).
4569
+ * The range repair for a hole ended: every hole inside `[start, start +
4570
+ * length)`, pending or expired, becomes a repair-less span. Returns those
4571
+ * spans with the held sources they placed, for the caller to feed
4572
+ * (MmtpRouter).
4443
4573
  */
4444
4574
  closeIsoHoles(packetId, catalogTrackName, start, length) {
4445
4575
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
@@ -4458,7 +4588,10 @@ var FECManager = class _FECManager {
4458
4588
  */
4459
4589
  #openIsoSpan(span, packetId, catalogTrackName) {
4460
4590
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
4461
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
4591
+ if (!this.#blockAuthoredLengths.has(key)) {
4592
+ this.#blockAuthoredLengths.set(key, span.block.length);
4593
+ this.#isoSpanKeys.add(key);
4594
+ }
4462
4595
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
4463
4596
  }
4464
4597
  /**
@@ -4799,11 +4932,14 @@ var FECManager = class _FECManager {
4799
4932
  });
4800
4933
  client.onCleanupComplete((sbn) => {
4801
4934
  if (this.#releasedWorkerClients.has(client)) return;
4802
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
4935
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
4936
+ const cleanupKeys = owed.filter((key) => {
4803
4937
  const block = this.#parseBlockKey(key);
4804
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
4938
+ return block.packetId === packetId && block.sbn === sbn;
4805
4939
  });
4806
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
4940
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
4941
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
4942
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
4807
4943
  });
4808
4944
  client.onError((msg, code) => {
4809
4945
  const requestedKind = code ?? msg;
@@ -4873,9 +5009,11 @@ var FECManager = class _FECManager {
4873
5009
  * fail deadline already passed, so failing it is the decision that deadline
4874
5010
  * made. A late ack then finds nothing owed and is a no-op.
4875
5011
  */
4876
- #boundOwedCleanup(key, packetId, client) {
5012
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
4877
5013
  this.#clearOwedCleanupBound(key);
4878
5014
  const bound = {
5015
+ dueAtMs,
5016
+ askedAtMs: performance.now(),
4879
5017
  handle: setTimeout(() => {
4880
5018
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
4881
5019
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -4973,7 +5111,15 @@ var FECManager = class _FECManager {
4973
5111
  this.#isoSourceOversizeCount++;
4974
5112
  return null;
4975
5113
  }
4976
- const sbn = located.block.start;
5114
+ return this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, located.block.start);
5115
+ }
5116
+ /**
5117
+ * Hand one placed source symbol to the stream's decoder: its Worker, which
5118
+ * answers through onFrame (null here), or its synchronous decoder, whose
5119
+ * recovered block is returned. `sbn` is the SS_Start of the block a repair
5120
+ * stated for `ssId`.
5121
+ */
5122
+ #feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn) {
4977
5123
  const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
4978
5124
  const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey);
4979
5125
  const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
@@ -5002,6 +5148,74 @@ var FECManager = class _FECManager {
5002
5148
  }
5003
5149
  return recovered;
5004
5150
  }
5151
+ /**
5152
+ * Feed a source symbol of this stream that another FEC instance over the
5153
+ * same packets rebuilt: a keyframe overlay recovery whose base SS_ID the
5154
+ * caller determined (draft-ramadan-moq-mmt-02 7.1, 7.4.4; joint decoding,
5155
+ * BLO-52085). It joins its block's decoder as a received source would, so
5156
+ * it reduces the erasures the block still has to solve, but it is not a
5157
+ * network arrival: no transport accounting, no classification evidence,
5158
+ * no deadline refresh, and it never makes a block clean.
5159
+ *
5160
+ * Only a block a repair stated takes one (a repair-less span has no
5161
+ * decoder block). A block that is terminal, or already holds that source,
5162
+ * does not. The symbol is the exact protected packet, unpadded, as
5163
+ * feedSourceSymbol takes it.
5164
+ *
5165
+ * `recovered` is the block the synchronous decoder completed with it; the
5166
+ * caller routes it and completes the block, as for any recovery. When
5167
+ * every source of the block is then present, received or rebuilt, and no
5168
+ * decoder returned it (a Worker answers asynchronously, and reports such a
5169
+ * block as clean on its own side), the block is completed here as
5170
+ * recovered, with nothing left to route.
5171
+ */
5172
+ feedRebuiltSourceSymbol(packetId, ssId, symbolData, catalogTrackName) {
5173
+ if (!this.#hasBlockProfile(packetId)) return NOT_TAKEN;
5174
+ const located = this.#isoLocatorFor(packetId, catalogTrackName).locate(ssId);
5175
+ if (located === null || located.block.span) return NOT_TAKEN;
5176
+ if (!ssbg1FitsSymbol(symbolData.byteLength, this.#trackConfig(packetId).symbolSize)) return NOT_TAKEN;
5177
+ const sbn = located.block.start;
5178
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
5179
+ if (this.#completedBlocks.has(key) || this.#blockSourceEsis.get(key)?.has(located.esi)) return NOT_TAKEN;
5180
+ let rebuilt = this.#blockRebuiltEsis.get(key);
5181
+ if (rebuilt?.has(located.esi)) return NOT_TAKEN;
5182
+ if (rebuilt === void 0) {
5183
+ rebuilt = /* @__PURE__ */ new Set();
5184
+ this.#blockRebuiltEsis.set(key, rebuilt);
5185
+ }
5186
+ const config = this.#trackConfigs.get(packetId);
5187
+ const wasShort = config !== void 0 && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) !== void 0;
5188
+ rebuilt.add(located.esi);
5189
+ const recovered = this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn);
5190
+ if (recovered === null && !this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName)) {
5191
+ if (wasShort && this.#activeBlocks.has(key) && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) === void 0) {
5192
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, this.#multicastWaitMs(config));
5193
+ }
5194
+ }
5195
+ return { taken: true, recovered };
5196
+ }
5197
+ /**
5198
+ * A block that holds every one of its `length` sources, received or
5199
+ * rebuilt by another instance, with at least one rebuilt, is recovered:
5200
+ * every packet of it was delivered, by its own arrival or by the instance
5201
+ * that rebuilt it, so nothing is routed. Returns whether it completed it.
5202
+ */
5203
+ #completeWhenSourcesPresent(key, sbn, length, packetId, catalogTrackName) {
5204
+ const rebuilt = this.#blockRebuiltEsis.get(key);
5205
+ if (rebuilt === void 0 || this.#completedBlocks.has(key)) return false;
5206
+ let present = rebuilt.size;
5207
+ for (const esi of this.#blockSourceEsis.get(key) ?? []) if (!rebuilt.has(esi)) present++;
5208
+ if (present < length) return false;
5209
+ this.#traceLifecycle("recovered", sbn, packetId, catalogTrackName);
5210
+ this.countRecovery(packetId, sbn, catalogTrackName);
5211
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
5212
+ if (catalogTrackName === void 0) {
5213
+ this.onBlockComplete?.(sbn, packetId);
5214
+ } else {
5215
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName);
5216
+ }
5217
+ return true;
5218
+ }
5005
5219
  /**
5006
5220
  * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
5007
5221
  * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
@@ -5204,8 +5418,75 @@ var FECManager = class _FECManager {
5204
5418
  this.#completeCleanBlock(blockKey, sbn, packetId, catalogTrackName);
5205
5419
  return null;
5206
5420
  }
5421
+ if (recovered === null) this.#shortenUnrecoverableWait(blockKey, sbn, packetId, catalogTrackName);
5207
5422
  return recovered;
5208
5423
  }
5424
+ /**
5425
+ * A first-arrival multicast source, held or placed. A datagram flow keeps
5426
+ * its sources in send order, so one that moves the stream's newest source
5427
+ * position past a block leaves the sources that block still misses
5428
+ * reordered behind it at best: it shortens the wait of every block it
5429
+ * passed that only a late source can complete. MoQ is left out: its streams
5430
+ * can overtake one another, so a MoQ source shows nothing about the sources
5431
+ * sent before it.
5432
+ */
5433
+ #noteMulticastSource(locator, ssId, packetId, catalogTrackName) {
5434
+ const previous = locator.newestSource;
5435
+ if (!locator.noteSource(ssId) || previous === void 0) return;
5436
+ for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
5437
+ if (block.span || !serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
5438
+ this.#shortenUnrecoverableWait(
5439
+ this.#blockKey(block.start, packetId, catalogTrackName),
5440
+ block.start,
5441
+ packetId,
5442
+ catalogTrackName
5443
+ );
5444
+ }
5445
+ }
5446
+ /**
5447
+ * The wait of a block that only a late source can complete (BLO-52085): a
5448
+ * repair stated it, its received sources plus every symbol its repair group
5449
+ * carries (RSB_length) are short of K' (the repair scheduler's
5450
+ * group-cannot-complete), and a later source of the stream has arrived, so
5451
+ * a source it misses is lost or reordered behind that one. The span, which
5452
+ * covers repair symbols paced after its sources, buys it nothing: it waits
5453
+ * the late-symbol allowance alone, the multicast wait less the span (the
5454
+ * catalog tolerance or the measured delivery gap). Undefined for any other
5455
+ * block.
5456
+ */
5457
+ #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
5458
+ const authoredLength = this.#blockAuthoredLengths.get(key);
5459
+ const rsbLength = this.#blockRsbLengths.get(key);
5460
+ if (authoredLength === void 0 || rsbLength === void 0) return void 0;
5461
+ let present = this.#blockSourceCounts.get(key) ?? 0;
5462
+ const received = this.#blockSourceEsis.get(key);
5463
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
5464
+ if (present + rsbLength >= authoredLength) return void 0;
5465
+ const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
5466
+ if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
5467
+ return void 0;
5468
+ }
5469
+ return this.#multicastWaitMs(config) - config.interleaveDepthMs;
5470
+ }
5471
+ /**
5472
+ * Bring an open block's wait in to its late-source wait, when it has one.
5473
+ * Never later than it is armed: only a source can complete such a block,
5474
+ * so a repair of its group (paced across the span) must not keep it open.
5475
+ */
5476
+ #shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName) {
5477
+ if (!this.#activeBlocks.has(key)) return;
5478
+ const config = this.#trackConfigs.get(packetId);
5479
+ if (config === void 0) return;
5480
+ const waitMs = this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config);
5481
+ if (waitMs === void 0) return;
5482
+ const armedAtMs = this.#blockWaitDeadlinesMs.get(key);
5483
+ this.#armBlockTimeout(
5484
+ sbn,
5485
+ packetId,
5486
+ catalogTrackName,
5487
+ armedAtMs === void 0 ? waitMs : Math.min(waitMs, armedAtMs - this.#receiptNow())
5488
+ );
5489
+ }
5209
5490
  /**
5210
5491
  * Record a block's authored SSB_length from a repair symbol. Returns false,
5211
5492
  * leaving the block unchanged, when the symbol contradicts the block: a
@@ -5303,12 +5584,13 @@ var FECManager = class _FECManager {
5303
5584
  * the inactivity deadline on each symbol, records the symbol's in-band
5304
5585
  * classification evidence, and marks the block clean when all of its
5305
5586
  * authored source symbols arrived: the SSB_length a repair symbol declared,
5306
- * otherwise K.
5587
+ * otherwise K. `held` marks a source held unplaced since it arrived and
5588
+ * placed only now (see #noteSbnSeen).
5307
5589
  *
5308
5590
  * Throws for a packetId that was never configured, so a classified block
5309
5591
  * never reads the manager-global K or timeout.
5310
5592
  */
5311
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
5593
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
5312
5594
  const trackConfig = this.#trackConfigs.get(packetId);
5313
5595
  if (trackConfig === void 0) {
5314
5596
  throw new Error(
@@ -5324,7 +5606,8 @@ var FECManager = class _FECManager {
5324
5606
  catalogTrackName,
5325
5607
  "source",
5326
5608
  evidence.packetSequenceNumber,
5327
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
5609
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
5610
+ held
5328
5611
  );
5329
5612
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
5330
5613
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -5360,6 +5643,15 @@ var FECManager = class _FECManager {
5360
5643
  this.#completeCleanBlock(key, sbn, packetId, catalogTrackName);
5361
5644
  return;
5362
5645
  }
5646
+ if (this.#blockRebuiltEsis.has(key) && this.#completeWhenSourcesPresent(
5647
+ key,
5648
+ sbn,
5649
+ this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? authoredLength,
5650
+ packetId,
5651
+ catalogTrackName
5652
+ )) {
5653
+ return;
5654
+ }
5363
5655
  this.noteBlockActivity(sbn, packetId, catalogTrackName, true);
5364
5656
  }
5365
5657
  #completeCleanBlock(key, sbn, packetId, catalogTrackName) {
@@ -5368,7 +5660,9 @@ var FECManager = class _FECManager {
5368
5660
  this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
5369
5661
  this.#blockSourceCounts.delete(key);
5370
5662
  this.#blockSourceEsis.delete(key);
5663
+ this.#blockRebuiltEsis.delete(key);
5371
5664
  this.#blockAuthoredLengths.delete(key);
5665
+ this.#isoSpanKeys.delete(key);
5372
5666
  this.#blockRepairRsIds.delete(key);
5373
5667
  this.#blockRsbLengths.delete(key);
5374
5668
  this.#markTerminal(key, sbn, packetId, true);
@@ -5399,6 +5693,19 @@ var FECManager = class _FECManager {
5399
5693
  #receiptNow() {
5400
5694
  return this.#receiptAtMs ?? performance.now();
5401
5695
  }
5696
+ /**
5697
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
5698
+ * scope: counted from the receipt time, as the timer of a symbol fed when
5699
+ * it was received was, less the whole ms since. So it fires on the tick
5700
+ * that timer would have, never later than a delay counted from now, and
5701
+ * its handler still re-arms a timer that fires before its deadline.
5702
+ * Counted from now, a deadline set from the receipt time is rounded up
5703
+ * from another fraction of a ms (BLO-52085).
5704
+ */
5705
+ #receiptTimerDelayMs(deadlineMs, minMs) {
5706
+ const receivedAtMs = this.#receiptAtMs;
5707
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
5708
+ }
5402
5709
  /**
5403
5710
  * A held packet admitted late arms from its (earlier) receipt time; that
5404
5711
  * never pulls in a deadline later activity already armed. Outside a
@@ -5434,10 +5741,20 @@ var FECManager = class _FECManager {
5434
5741
  this.#repairDeadlineMs(trackConfig)
5435
5742
  );
5436
5743
  }
5437
- this.#armBlockTimeout(sbn, packetId, catalogTrackName, timeoutMs);
5744
+ if (!sourceProgress && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) !== void 0) {
5745
+ this.#shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName);
5746
+ return;
5747
+ }
5748
+ this.#armBlockTimeout(
5749
+ sbn,
5750
+ packetId,
5751
+ catalogTrackName,
5752
+ this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) ?? timeoutMs
5753
+ );
5438
5754
  }
5439
5755
  #failBlock(sbn, packetId, catalogTrackName) {
5440
5756
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
5757
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
5441
5758
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
5442
5759
  this.#clearRepairDeadline(key);
5443
5760
  this.#clearBlockTimer(key);
@@ -5447,6 +5764,7 @@ var FECManager = class _FECManager {
5447
5764
  }
5448
5765
  this.#blockSourceCounts.delete(key);
5449
5766
  this.#blockSourceEsis.delete(key);
5767
+ this.#blockRebuiltEsis.delete(key);
5450
5768
  this.#blockAuthoredLengths.delete(key);
5451
5769
  this.#blockRepairRsIds.delete(key);
5452
5770
  this.#blockRsbLengths.delete(key);
@@ -5456,7 +5774,8 @@ var FECManager = class _FECManager {
5456
5774
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
5457
5775
  this.#fecStats.blocksFailed++;
5458
5776
  this.#statsForPacket(packetId).blocksFailed++;
5459
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5777
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5778
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
5460
5779
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
5461
5780
  }
5462
5781
  /**
@@ -5485,7 +5804,9 @@ var FECManager = class _FECManager {
5485
5804
  this.#retireBlockClass(key, block.sbn, block.packetId, block.catalogTrackName);
5486
5805
  this.#blockSourceCounts.delete(key);
5487
5806
  this.#blockSourceEsis.delete(key);
5807
+ this.#blockRebuiltEsis.delete(key);
5488
5808
  this.#blockAuthoredLengths.delete(key);
5809
+ this.#isoSpanKeys.delete(key);
5489
5810
  this.#blockRepairRsIds.delete(key);
5490
5811
  this.#blockRsbLengths.delete(key);
5491
5812
  this.#clearBlockTimer(key);
@@ -5576,7 +5897,9 @@ var FECManager = class _FECManager {
5576
5897
  this.#blockKeysBySbn.clear();
5577
5898
  this.#blockSourceCounts.clear();
5578
5899
  this.#blockSourceEsis.clear();
5900
+ this.#blockRebuiltEsis.clear();
5579
5901
  this.#blockAuthoredLengths.clear();
5902
+ this.#isoSpanKeys.clear();
5580
5903
  this.#blockRepairRsIds.clear();
5581
5904
  this.#blockRsbLengths.clear();
5582
5905
  this.#heldLayerStates.clear();
@@ -6955,9 +7278,9 @@ async function openSubscription(rx, openedPromise, options, packetIds) {
6955
7278
  } catch (error) {
6956
7279
  throw new MulticastError("subscription-failed", "MulticastReceiver did not open", error);
6957
7280
  }
6958
- if (rx.integrityScheme !== INTEGRITY_SCHEME) {
7281
+ if (opened.integrityScheme !== INTEGRITY_SCHEME) {
6959
7282
  await rx.close();
6960
- throw unsupported(`integrity scheme ${String(rx.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
7283
+ throw unsupported(`integrity scheme ${String(opened.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
6961
7284
  }
6962
7285
  const events = new EventTarget();
6963
7286
  let state = "connected";
@@ -13489,6 +13812,9 @@ function authoredGap(before, after) {
13489
13812
  function ssIdAfter(a, b) {
13490
13813
  return (a - b | 0) > 0;
13491
13814
  }
13815
+ function holdsRebuilt(stream) {
13816
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
13817
+ }
13492
13818
  var FecReleaseSequencer = class {
13493
13819
  #streams = /* @__PURE__ */ new Map();
13494
13820
  #gate;
@@ -13551,6 +13877,7 @@ var FecReleaseSequencer = class {
13551
13877
  stream.lastSbn = void 0;
13552
13878
  stream.discontinuity = false;
13553
13879
  stream.rapSsId = void 0;
13880
+ stream.sourced = false;
13554
13881
  }
13555
13882
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
13556
13883
  this.#recordStat("droppedStale");
@@ -13577,6 +13904,7 @@ var FecReleaseSequencer = class {
13577
13904
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
13578
13905
  else hi = mid;
13579
13906
  }
13907
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
13580
13908
  stream.buf.splice(lo, 0, frame);
13581
13909
  this.#drainUnlessDeferred(stream);
13582
13910
  }
@@ -13612,6 +13940,41 @@ var FecReleaseSequencer = class {
13612
13940
  }
13613
13941
  return false;
13614
13942
  }
13943
+ /**
13944
+ * These streams' sink is being replaced by one that has seen no source
13945
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
13946
+ * release to the sink being replaced the frames the unanchored path had
13947
+ * already released to it (#cursorPassed): there they waited in its queue,
13948
+ * which its replacement flushes. A stream that holds none is not drained:
13949
+ * it holds nothing the anchor kept back, and a drain would still force out
13950
+ * a frame held past the hold limit, which before the anchor waited for the
13951
+ * next push. Then treat the streams as unsourced until a source frame is
13952
+ * released.
13953
+ */
13954
+ unsource(packetId, catalogTrackName) {
13955
+ for (const stream of this.#streams.values()) {
13956
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
13957
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
13958
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
13959
+ else this.#drain(stream, true);
13960
+ }
13961
+ stream.sourced = false;
13962
+ }
13963
+ }
13964
+ }
13965
+ /**
13966
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
13967
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
13968
+ * packetId.
13969
+ */
13970
+ holdsRebuilt(packetId, catalogTrackName) {
13971
+ for (const stream of this.#streams.values()) {
13972
+ if (stream.packetId !== packetId) continue;
13973
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
13974
+ if (holdsRebuilt(stream)) return true;
13975
+ }
13976
+ return false;
13977
+ }
13615
13978
  /** Re-evaluate held gaps after FEC state changed. */
13616
13979
  poke(streamKey) {
13617
13980
  if (streamKey !== void 0) {
@@ -13703,16 +14066,32 @@ var FecReleaseSequencer = class {
13703
14066
  last: null,
13704
14067
  lastSbn: void 0,
13705
14068
  discontinuity: false,
13706
- rapSsId: void 0
14069
+ rapSsId: void 0,
14070
+ sourced: false,
14071
+ draining: 0
13707
14072
  };
13708
14073
  this.#streams.set(streamKey, stream);
13709
14074
  }
13710
14075
  return stream;
13711
14076
  }
13712
- #drain(stream) {
14077
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
14078
+ #drain(stream, asUnanchored = false) {
14079
+ stream.draining++;
14080
+ try {
14081
+ this.#drainLoop(stream, asUnanchored);
14082
+ } finally {
14083
+ stream.draining--;
14084
+ }
14085
+ }
14086
+ #drainLoop(stream, asUnanchored) {
13713
14087
  while (stream.buf.length > 0 && stream.last !== null) {
13714
14088
  const head = stream.buf[0];
13715
14089
  const last = stream.last;
14090
+ if (compareFrameOrder(head, last) <= 0) {
14091
+ stream.buf.shift();
14092
+ this.#release(stream, head, void 0);
14093
+ continue;
14094
+ }
13716
14095
  if (stream.discontinuity) {
13717
14096
  stream.discontinuity = false;
13718
14097
  stream.buf.shift();
@@ -13726,9 +14105,10 @@ var FecReleaseSequencer = class {
13726
14105
  }
13727
14106
  const headSbn = head.meta.fecSbn;
13728
14107
  const from = stream.lastSbn ?? headSbn;
13729
- const to = headSbn ?? stream.lastSbn;
14108
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
13730
14109
  let lost = [];
13731
14110
  const unanchored = from === void 0 && to === void 0;
14111
+ let unresolved = false;
13732
14112
  if (from !== void 0 && to !== void 0) {
13733
14113
  const resolved = this.#gate.resolvedLoss(
13734
14114
  stream.packetId,
@@ -13737,7 +14117,8 @@ var FecReleaseSequencer = class {
13737
14117
  Math.max(from, to),
13738
14118
  from
13739
14119
  );
13740
- if (resolved === null) {
14120
+ unresolved = resolved === null;
14121
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored)) {
13741
14122
  const heldMs = performance.now() - head.arrivedAtMs;
13742
14123
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
13743
14124
  this.#recordStat("forcedWindowFlushes");
@@ -13745,22 +14126,56 @@ var FecReleaseSequencer = class {
13745
14126
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
13746
14127
  continue;
13747
14128
  }
13748
- lost = resolved;
14129
+ lost = resolved ?? [];
13749
14130
  }
13750
14131
  stream.buf.shift();
13751
14132
  this.#release(
13752
14133
  stream,
13753
14134
  head,
13754
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
14135
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
13755
14136
  );
13756
14137
  }
13757
14138
  }
14139
+ /**
14140
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
14141
+ * source cursor holds it unanchored, and neither does a later frame behind
14142
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
14143
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
14144
+ * like each frame that arrived in front of it since (stale there). The head
14145
+ * then goes, decided as it would be unanchored, once a frame the base path
14146
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
14147
+ * marked one: the base path has passed that one, so a frame still missing
14148
+ * before it can only come from a repair. It also goes while no source frame
14149
+ * has been released, when the direct path shows a recovered frame at once.
14150
+ * And it goes at once while a staged switch decides on when frames arrive
14151
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
14152
+ * sink being replaced: unanchored, it had already reached the sink.
14153
+ * The scan also writes: the `passed` marks it sets stay on the frames,
14154
+ * and push marks a frame it inserts in front of a marked one from them.
14155
+ */
14156
+ #cursorPassed(stream, asUnanchored) {
14157
+ let at = -1;
14158
+ for (let i = 0; i < stream.buf.length; i++) {
14159
+ const frame = stream.buf[i];
14160
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
14161
+ frame.passed = true;
14162
+ if (at < 0) at = i;
14163
+ } else if (frame.passed !== true) break;
14164
+ }
14165
+ if (at < 0) return false;
14166
+ return asUnanchored || !stream.sourced || this.#gate.releaseUnanchored?.(stream.packetId, stream.catalogTrackName) === true || stream.buf.some(({ meta }, i) => i > at && meta.fecSbnFirst === void 0 && (meta.recovered !== true || meta.fecSbn !== void 0));
14167
+ }
13758
14168
  #release(stream, frame, decision) {
14169
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
14170
+ if (stale) this.#recordStat("droppedStale");
13759
14171
  if (decision) frame.meta.gapBefore = decision;
13760
14172
  stream.last = frame;
13761
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
14173
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
14174
+ stream.lastSbn = frame.meta.fecSbn;
14175
+ }
14176
+ if (frame.meta.recovered !== true) stream.sourced = true;
13762
14177
  this.#gate.onReleased?.(frame.data, frame.meta);
13763
- this.#emit(frame.data, frame.meta);
14178
+ if (!stale) this.#emit(frame.data, frame.meta);
13764
14179
  }
13765
14180
  };
13766
14181
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -13801,6 +14216,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
13801
14216
  this.#reclaimedTimingSamples = 0;
13802
14217
  this.#evictedTimingSamples = 0;
13803
14218
  this.#rejectedMovieFragments = 0;
14219
+ this.#recoveredHeadsAwaitingTiming = {
14220
+ held: 0,
14221
+ expired: 0,
14222
+ discarded: 0,
14223
+ superseded: 0
14224
+ };
13804
14225
  this.#sequencers = /* @__PURE__ */ new Map();
13805
14226
  this.#fecGate = null;
13806
14227
  this.#fecSequencer = null;
@@ -13909,6 +14330,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
13909
14330
  #reclaimedTimingSamples;
13910
14331
  #evictedTimingSamples;
13911
14332
  #rejectedMovieFragments;
14333
+ #recoveredHeadsAwaitingTiming;
13912
14334
  #sequencers;
13913
14335
  #fecGate;
13914
14336
  #fecSequencer;
@@ -14014,11 +14436,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
14014
14436
  /**
14015
14437
  * Typed view of the ISO-BMFF timing-sample budget.
14016
14438
  *
14017
- * This is the acceptance signal for the budget ratchet: `pending` walking
14018
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
14019
- * and it is observable here rather than only as media silently stopping.
14020
- * Per repo policy this is a producer-owned counter -- never infer budget
14021
- * state by parsing logs.
14439
+ * Each stream admits timing against its own window of `capacity` slots
14440
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
14441
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
14442
+ * timing a stream declared and never delivered shows up there. `pending`
14443
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
14444
+ * a producer-owned counter -- never infer budget state by parsing logs.
14022
14445
  */
14023
14446
  get timingBudgetStats() {
14024
14447
  return {
@@ -14029,6 +14452,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
14029
14452
  rejectedMovieFragments: this.#rejectedMovieFragments
14030
14453
  };
14031
14454
  }
14455
+ /** Recovered heads parked for FT=1 timing (BLO-53369). Survives dispose(). */
14456
+ get recoveredHeadsAwaitingTiming() {
14457
+ let pending = 0;
14458
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
14459
+ for (const head of awaitingTiming) if (head.options?.recovered) pending++;
14460
+ }
14461
+ return { ...this.#recoveredHeadsAwaitingTiming, pending };
14462
+ }
14032
14463
  get reorderStats() {
14033
14464
  let bufferedFrames = this.#fecSequencer?.buffered ?? 0;
14034
14465
  for (const { sequencer } of this.#sequencers.values()) bufferedFrames += sequencer.buffered;
@@ -14070,6 +14501,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
14070
14501
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
14071
14502
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
14072
14503
  }
14504
+ /** See FecReleaseSequencer.unsource. */
14505
+ unsourceFecRelease(packetId, catalogTrackName) {
14506
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
14507
+ }
14508
+ /** See FecReleaseSequencer.holdsRebuilt. */
14509
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
14510
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
14511
+ }
14073
14512
  /** Re-evaluate held gaps after FEC block state changed. */
14074
14513
  pokeFecRelease(packetId, catalogTrackName) {
14075
14514
  if (!this.#fecSequencer) return;
@@ -14202,7 +14641,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14202
14641
  const now = Date.now();
14203
14642
  for (const { awaitingTiming } of this.#timingStreams.values()) {
14204
14643
  while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
14205
- awaitingTiming.shift();
14644
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
14206
14645
  }
14207
14646
  }
14208
14647
  }
@@ -14323,7 +14762,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14323
14762
  if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
14324
14763
  const pendingBefore = resolver2.pendingSampleCount;
14325
14764
  const evictedBefore = resolver2.evictedSampleCount;
14326
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
14765
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
14327
14766
  const admitted = resolver2.addMovieFragment(
14328
14767
  mpu.mpuSequenceNumber,
14329
14768
  data,
@@ -14370,6 +14809,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14370
14809
  mpuSequenceNumber: mpu.mpuSequenceNumber,
14371
14810
  movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
14372
14811
  sampleNumber: mfuDuHeader.sampleNumber,
14812
+ sequenceNumber: info.sequenceNumber,
14373
14813
  arrivedAt: Date.now()
14374
14814
  });
14375
14815
  return this.#drop("mfu-sample-timing-missing");
@@ -14395,7 +14835,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14395
14835
  info,
14396
14836
  resolver,
14397
14837
  options?.recovered === true,
14398
- options?.fecSbn
14838
+ options?.fecSbn,
14839
+ options?.fecSbnFirst
14399
14840
  );
14400
14841
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
14401
14842
  }
@@ -14488,7 +14929,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14488
14929
  info,
14489
14930
  resolver,
14490
14931
  options?.recovered === true,
14491
- options?.fecSbn
14932
+ options?.fecSbn,
14933
+ options?.fecSbnFirst
14492
14934
  );
14493
14935
  if (outcome.record !== void 0) return outcome.record;
14494
14936
  return this.#drop(outcome.reason);
@@ -14508,7 +14950,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14508
14950
  * attribution exists to keep readable. Leaving the choice at the call site
14509
14951
  * is what keeps both true.
14510
14952
  */
14511
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
14953
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
14512
14954
  const timing = resolver.sampleTiming(
14513
14955
  combined.mpuSequenceNumber,
14514
14956
  combined.movieFragmentSequenceNumber,
@@ -14525,6 +14967,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14525
14967
  );
14526
14968
  if (!meta) return { reason: "combined-meta-build-failed" };
14527
14969
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
14970
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
14528
14971
  if (!resolver.consumeSample(
14529
14972
  combined.mpuSequenceNumber,
14530
14973
  combined.movieFragmentSequenceNumber,
@@ -14758,6 +15201,9 @@ var MmtpContainerParser = class _MmtpContainerParser {
14758
15201
  for (const { sequencer } of this.#sequencers.values()) sequencer.discard();
14759
15202
  this.#sequencers.clear();
14760
15203
  this.#fecSequencer?.discard();
15204
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
15205
+ for (const head of awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
15206
+ }
14761
15207
  this.#timingStreams.clear();
14762
15208
  this.#pendingTimingSamples = 0;
14763
15209
  this.#reliableMoqStartupGate.clear();
@@ -14776,10 +15222,23 @@ var MmtpContainerParser = class _MmtpContainerParser {
14776
15222
  return resolver;
14777
15223
  }
14778
15224
  #awaitTiming(streamKey, head) {
14779
- const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
14780
- if (!awaitingTiming) return;
15225
+ const state = this.#timingStreams.get(streamKey);
15226
+ if (!state) return;
15227
+ if (!head.options?.recovered) {
15228
+ const kept = state.awaitingTiming.filter((queued) => !queued.options?.recovered || queued.sequenceNumber !== head.sequenceNumber);
15229
+ this.#recoveredHeadsAwaitingTiming.superseded += state.awaitingTiming.length - kept.length;
15230
+ state.awaitingTiming = kept;
15231
+ }
15232
+ const awaitingTiming = state.awaitingTiming;
14781
15233
  awaitingTiming.push(head);
14782
- if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
15234
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming.held++;
15235
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) {
15236
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
15237
+ }
15238
+ }
15239
+ /** Count a recovered head leaving the queue other than by replay or its source copy. */
15240
+ #leaveAwaitingTiming(head, outcome) {
15241
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming[outcome]++;
14783
15242
  }
14784
15243
  /**
14785
15244
  * Feed again the heads whose timing the FT=1 just admitted declares. That
@@ -14807,6 +15266,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14807
15266
  const state = this.#timingStreams.get(streamKey);
14808
15267
  if (!state) return;
14809
15268
  this.#timingStreams.delete(streamKey);
15269
+ for (const head of state.awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
14810
15270
  this.#pendingTimingSamples -= state.resolver.pendingSampleCount;
14811
15271
  if (this.#pendingTimingSamples < 0) {
14812
15272
  throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");
@@ -18012,7 +18472,18 @@ function keyframeOverlaySsId(header) {
18012
18472
  if (ext?.type !== KEYFRAME_OVERLAY_EXTENSION_TYPE || ext.data.length !== 4) return void 0;
18013
18473
  return new DataView(ext.data.buffer, ext.data.byteOffset, 4).getUint32(0);
18014
18474
  }
18475
+ function overlayBaseSsId(anchor, overlaySsId, restoredPsn, headerPsn) {
18476
+ if (anchor.baseSsId === void 0 || headerPsn !== restoredPsn) return void 0;
18477
+ return serial32Add(anchor.baseSsId, overlaySsId - anchor.overlaySsId | 0);
18478
+ }
18479
+ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
18480
+ if (offset === void 0 || offset !== unstampedOffset) return void 0;
18481
+ return headerPsn + offset >>> 0;
18482
+ }
18483
+ var OVERLAY_ROUTED_LIMIT = 1024;
18484
+ var OVERLAY_PENDING_LIMIT = 256;
18015
18485
  var OVERLAY_OFFSET_MPUS = 16;
18486
+ var OVERLAY_REBUILT_LIMIT = 256;
18016
18487
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
18017
18488
  function assertStreamIdentity(role, stream) {
18018
18489
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -18123,6 +18594,7 @@ var MmtpRouter = class {
18123
18594
  #provenance = /* @__PURE__ */ new Map();
18124
18595
  #onFlowProtected = null;
18125
18596
  #unadmittedListedDrops = 0;
18597
+ #admittedSourceDatagrams = 0;
18126
18598
  #unlistedRepairSetAside = 0;
18127
18599
  #assistBlocks = /* @__PURE__ */ new Map();
18128
18600
  #assistFailures = /* @__PURE__ */ new Map();
@@ -18179,6 +18651,26 @@ var MmtpRouter = class {
18179
18651
  * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
18180
18652
  */
18181
18653
  #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18654
+ /**
18655
+ * Per stream, the SS_ID offset at which a base recovery last showed the
18656
+ * sender's own packet_sequence_number: a recovered packet's header psn
18657
+ * equal to its SS_ID minus that offset. While it equals the stream's
18658
+ * current offset, no hop re-stamps the stream, and a packet's protected psn
18659
+ * names its base SS_ID within unstampedBaseSsId's limits (joint decoding of
18660
+ * an MPU no member of which arrived).
18661
+ */
18662
+ #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18663
+ /**
18664
+ * The same, shown by the overlay alone, before any base recovery did: a
18665
+ * packet it rebuilt whose base copy carries its protected psn
18666
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
18667
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
18668
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
18669
+ * make the base drop a late base copy of a keyframe the overlay never
18670
+ * finished, and lift a block's late-source cut, which nothing before
18671
+ * this offset did.
18672
+ */
18673
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18182
18674
  /**
18183
18675
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
18184
18676
  * not parsed, typically because its overlap copy was parsed first
@@ -18248,7 +18740,9 @@ var MmtpRouter = class {
18248
18740
  recovered: 0,
18249
18741
  restarts: 0,
18250
18742
  unsequencedDropped: 0,
18251
- protectedDropped: 0
18743
+ protectedDropped: 0,
18744
+ baseFed: 0,
18745
+ baseUndetermined: 0
18252
18746
  };
18253
18747
  /** Callback fired when a delta-track FEC block completes or fails. */
18254
18748
  #onDeltaBlockCompleteCb = null;
@@ -18421,7 +18915,7 @@ var MmtpRouter = class {
18421
18915
  const cb = this.#getFrameCallback(packetId);
18422
18916
  if (isVideo && !assembler) {
18423
18917
  if (frameMeta.recovered) {
18424
- this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb);
18918
+ this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb, meta.fecSbn);
18425
18919
  } else {
18426
18920
  this.#routeDirectSourceVideo(packetId, data, frameMeta, cb);
18427
18921
  }
@@ -18454,13 +18948,18 @@ var MmtpRouter = class {
18454
18948
  this.#onDeltaBlockCompleteCb?.(packetId, false);
18455
18949
  }
18456
18950
  };
18457
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
18951
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
18458
18952
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
18459
18953
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
18460
18954
  this.#onDeltaBlockCompleteCb?.(packetId, true);
18461
18955
  }
18462
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18463
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18956
+ if (span === void 0) {
18957
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18958
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18959
+ } else {
18960
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
18961
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
18962
+ }
18464
18963
  };
18465
18964
  }
18466
18965
  }
@@ -18505,8 +19004,9 @@ var MmtpRouter = class {
18505
19004
  }
18506
19005
  /**
18507
19006
  * FEC-recovered source symbols whose reconstructed header named a
18508
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
18509
- * a hop re-stamped the sequence after the sender protected the packet.
19007
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
19008
+ * or, rebuilt by the overlay, than their base copy carries: a hop
19009
+ * re-stamped the sequence after the sender protected the packet.
18510
19010
  */
18511
19011
  get restampedRecoveredSequenceCount() {
18512
19012
  return this.#restampedRecoveredSeqs;
@@ -18685,6 +19185,7 @@ var MmtpRouter = class {
18685
19185
  enableMseAssembler(packetId, config, catalogTrackName) {
18686
19186
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
18687
19187
  const previous = this.#mseAssemblers.get(assemblerKey);
19188
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
18688
19189
  if (previous) {
18689
19190
  previous.flush();
18690
19191
  previous.dispose();
@@ -18811,6 +19312,10 @@ var MmtpRouter = class {
18811
19312
  get keyframeOverlayStats() {
18812
19313
  return { ...this.#overlayStats };
18813
19314
  }
19315
+ /** Recovered FT=2 heads held for their FT=1, and how each left the wait (BLO-53369). */
19316
+ get recoveredHeadsAwaitingTiming() {
19317
+ return this.#parser.recoveredHeadsAwaitingTiming;
19318
+ }
18814
19319
  #isOverlayRepair(repairPacketId, repairTrackName) {
18815
19320
  return this.#overlayLegs.has(repairPacketId) || repairTrackName !== void 0 && this.#overlayRepairNames.has(repairTrackName);
18816
19321
  }
@@ -18831,7 +19336,8 @@ var MmtpRouter = class {
18831
19336
  fec,
18832
19337
  k,
18833
19338
  offsets: /* @__PURE__ */ new Map(),
18834
- moqBlocks: /* @__PURE__ */ new Set()
19339
+ moqBlocks: /* @__PURE__ */ new Set(),
19340
+ rebuilt: /* @__PURE__ */ new Map()
18835
19341
  };
18836
19342
  this.#overlays.set(repairPacketId, inst);
18837
19343
  return () => {
@@ -18861,12 +19367,18 @@ var MmtpRouter = class {
18861
19367
  */
18862
19368
  resetKeyframeOverlays(sourcePacketId, catalogTrackName) {
18863
19369
  for (const inst of this.#overlaysForSource(sourcePacketId, catalogTrackName)) this.#resetOverlay(inst);
19370
+ for (const [name, stream] of this.#streams.get(sourcePacketId) ?? []) {
19371
+ if (catalogTrackName !== void 0 && name !== catalogTrackName) continue;
19372
+ stream.overlayToBase.routed.clear();
19373
+ stream.overlayToBase.pending.clear();
19374
+ }
18864
19375
  }
18865
19376
  #resetOverlay(inst) {
18866
19377
  inst.fec.resetTrack(inst.repairPacketId, inst.streamName);
18867
19378
  inst.last = void 0;
18868
19379
  inst.offsets.clear();
18869
19380
  inst.moqBlocks.clear();
19381
+ inst.rebuilt.clear();
18870
19382
  }
18871
19383
  #overlaysForSource(sourcePacketId, catalogTrackName) {
18872
19384
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -18917,18 +19429,33 @@ var MmtpRouter = class {
18917
19429
  * A source packet that carries a 0x8B01 overlay SS_ID is also a symbol of
18918
19430
  * every overlay installed for its source, at that SS_ID, with the bytes the
18919
19431
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
18920
- * included (7.1, 7.4.3).
18921
- */
18922
- #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source) {
19432
+ * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
19433
+ * FEC reads it.
19434
+ *
19435
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
19436
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
19437
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
19438
+ * the stream unstamped at the SS_ID offset it states, for the release gate
19439
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
19440
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
19441
+ */
19442
+ #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
18923
19443
  if (this.#overlays.size === 0) return;
18924
19444
  const ssId = keyframeOverlaySsId(header);
18925
19445
  if (ssId === void 0) return;
19446
+ let rebuiltPsn;
18926
19447
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
18927
19448
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
19449
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
19450
+ inst.rebuilt.delete(ssId);
18928
19451
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
18929
19452
  if (identity !== null) {
18930
19453
  inst.offsets.delete(identity.mpuSequenceNumber);
18931
- inst.offsets.set(identity.mpuSequenceNumber, ssId - sequenceNumber >>> 0);
19454
+ inst.offsets.set(identity.mpuSequenceNumber, {
19455
+ psnOffset: ssId - sequenceNumber >>> 0,
19456
+ overlaySsId: ssId,
19457
+ ...baseSsId === void 0 ? {} : { baseSsId }
19458
+ });
18932
19459
  if (inst.offsets.size > OVERLAY_OFFSET_MPUS) inst.offsets.delete(inst.offsets.keys().next().value);
18933
19460
  }
18934
19461
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -18950,6 +19477,14 @@ var MmtpRouter = class {
18950
19477
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
18951
19478
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
18952
19479
  }
19480
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
19481
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
19482
+ if (rebuiltPsn !== sequenceNumber) {
19483
+ this.#restampedRecoveredSeqs++;
19484
+ } else if (baseSsId !== void 0) {
19485
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19486
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
19487
+ }
18953
19488
  }
18954
19489
  #noteOverlayMoqBlock(inst, blockStart) {
18955
19490
  inst.moqBlocks.add(blockStart);
@@ -18983,11 +19518,16 @@ var MmtpRouter = class {
18983
19518
  }
18984
19519
  /**
18985
19520
  * Route an overlay-recovered block's packets as source media of the
18986
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
18987
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
18988
- * base re-stamp, no block advance. Each packet's wire sequence is restored
18989
- * from its keyframe's own offset; without one, a stream the base never
18990
- * re-stamped keeps the header's sequence and any other drops the packet.
19521
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
19522
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
19523
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
19524
+ * base FEC recovered does, so it waits behind base frames still in flight,
19525
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
19526
+ * longer than unanchored; one whose base SS_ID is undetermined has no
19527
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
19528
+ * advance. Each packet's wire sequence is restored from its keyframe's own
19529
+ * offset; without one, a stream the base never re-stamped keeps the
19530
+ * header's sequence and any other drops the packet.
18991
19531
  */
18992
19532
  #routeOverlayRecovered(inst, blockStart, recovered) {
18993
19533
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -19007,22 +19547,139 @@ var MmtpRouter = class {
19007
19547
  const streamKey = this.#mediaStreamKey(sourcePacketId, sourceName);
19008
19548
  const restamped = this.#restampedStreams.has(streamKey);
19009
19549
  const restored = /* @__PURE__ */ new Set();
19550
+ const baseSsIds = /* @__PURE__ */ new Map();
19551
+ const gateOnly = /* @__PURE__ */ new Set();
19010
19552
  const symbols = result.symbols.flatMap((sym) => {
19011
- const offset = inst.offsets.get(sym.fragment.mpuSequenceNumber);
19012
- if (offset !== void 0) {
19013
- const packetSequenceNumber = serial32Add(blockStart, sym.index) - offset >>> 0;
19553
+ const overlaySsId = serial32Add(blockStart, sym.index);
19554
+ const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
19555
+ if (anchor !== void 0) {
19556
+ const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
19014
19557
  restored.add(packetSequenceNumber);
19015
- return [{ ...sym, packetSequenceNumber }];
19558
+ const out = { ...sym, packetSequenceNumber };
19559
+ const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
19560
+ if (baseSsId !== void 0) {
19561
+ baseSsIds.set(sym.index, baseSsId);
19562
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19563
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
19564
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
19565
+ }
19566
+ }
19567
+ return [out];
19568
+ }
19569
+ if (!restamped) {
19570
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19571
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
19572
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
19573
+ if (baseSsId !== void 0) {
19574
+ baseSsIds.set(sym.index, baseSsId);
19575
+ if (fedSsId === void 0) gateOnly.add(sym.index);
19576
+ } else {
19577
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
19578
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
19579
+ }
19580
+ return [sym];
19016
19581
  }
19017
- if (!restamped) return [sym];
19018
19582
  this.#overlayStats.unsequencedDropped++;
19019
19583
  return [];
19020
19584
  });
19021
19585
  this.#overlayStats.recovered++;
19586
+ const mpuFirst = /* @__PURE__ */ new Map();
19587
+ for (const sym of symbols) {
19588
+ const ssId = baseSsIds.get(sym.index);
19589
+ const mpu = sym.fragment.mpuSequenceNumber;
19590
+ const first = mpuFirst.get(mpu);
19591
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
19592
+ }
19593
+ const firstSsIds = /* @__PURE__ */ new Map();
19594
+ for (const sym of symbols) {
19595
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
19596
+ }
19022
19597
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
19023
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
19598
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
19599
+ baseSsIds,
19600
+ firstSsIds
19024
19601
  });
19025
19602
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
19603
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
19604
+ }
19605
+ /**
19606
+ * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
19607
+ * its base block too, once its base SS_ID is determined (overlayBaseSsId,
19608
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
19609
+ * base recovery showed; `baseSsIds` holds no other),
19610
+ * so it is fed to the base decoder as a rebuilt source
19611
+ * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
19612
+ * fewer to solve, and its repair can recover the block's other packets.
19613
+ * A base block no repair has stated yet takes it when one does
19614
+ * (#feedPendingRebuilt).
19615
+ *
19616
+ * The overlay route already handled each packet fed (delivered it, or
19617
+ * held an untimed head for its FT=1), so a base recovery routes none of
19618
+ * them again (#routeVerifiedFecSymbols): a second recovered copy of a
19619
+ * held head would wait in the parser for timing its first copy consumed.
19620
+ * Only an overlay block decoded from multicast symbols alone is fed: with
19621
+ * a MoQ symbol in it, the base block's recovery would depend on bytes
19622
+ * that crossed no multicast socket, which the provenance counted from the
19623
+ * block's own arrivals cannot show.
19624
+ */
19625
+ #feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds) {
19626
+ const fec = this.#fecManager;
19627
+ const owner = inst.leg.sourcePacketId;
19628
+ const name = inst.leg.sourceCatalogTrackName;
19629
+ if (!fec?.feedRebuiltSourceSymbol || inst.moqBlocks.has(blockStart)) return;
19630
+ if (this.#classifyPacketId(owner) === null || fec.isTrackConfigured?.(owner) === false) return;
19631
+ const { duplicates, overlayToBase: { routed } } = this.#stream(owner, name);
19632
+ const feeds = [];
19633
+ for (const sym of symbols) {
19634
+ if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
19635
+ const ssId = baseSsIds.get(sym.index);
19636
+ if (ssId === void 0) {
19637
+ this.#overlayStats.baseUndetermined++;
19638
+ continue;
19639
+ }
19640
+ routed.delete(ssId);
19641
+ routed.add(ssId);
19642
+ if (routed.size > OVERLAY_ROUTED_LIMIT) routed.delete(routed.values().next().value);
19643
+ feeds.push([ssId, sym.rawSymbol]);
19644
+ }
19645
+ for (const [ssId, symbolData] of feeds) {
19646
+ if (this.#classifyPacketId(owner) === null) return;
19647
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
19648
+ }
19649
+ }
19650
+ /** Feed one rebuilt source to its base block, or keep it until a repair states that block. */
19651
+ #feedRebuiltToBase(owner, name, ssId, symbolData) {
19652
+ const fec = this.#fecManager;
19653
+ if (!fec?.feedRebuiltSourceSymbol) return;
19654
+ const coords = fec.locateIsoSource?.(owner, name, ssId);
19655
+ if (coords == null) {
19656
+ const pending = this.#stream(owner, name).overlayToBase.pending;
19657
+ pending.delete(ssId);
19658
+ pending.set(ssId, symbolData.slice());
19659
+ if (pending.size > OVERLAY_PENDING_LIMIT) pending.delete(pending.keys().next().value);
19660
+ return;
19661
+ }
19662
+ const fed = fec.feedRebuiltSourceSymbol(owner, ssId, symbolData, name);
19663
+ if (!fed.taken) return;
19664
+ this.#overlayStats.baseFed++;
19665
+ if (fed.recovered === null) return;
19666
+ const sbn = coords.sbn;
19667
+ this.#routeRecoveredBlock(sbn, fed.recovered, owner, name, () => {
19668
+ fec.cancelBlockTimeout(sbn, owner, name);
19669
+ fec.countRecovery(owner, sbn, name);
19670
+ fec.markBlockCompleted(sbn, owner, name);
19671
+ });
19672
+ }
19673
+ /** A repair stated `block`: the rebuilt sources that waited for it join it now. */
19674
+ #feedPendingRebuilt(owner, name, block) {
19675
+ const pending = this.#streams.get(owner)?.get(name)?.overlayToBase.pending;
19676
+ if (pending === void 0 || pending.size === 0) return;
19677
+ for (const [ssId, symbolData] of [...pending]) {
19678
+ if (this.#classifyPacketId(owner) === null) return;
19679
+ if (serial32Distance(block.start, ssId) >= block.length) continue;
19680
+ pending.delete(ssId);
19681
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
19682
+ }
19026
19683
  }
19027
19684
  /** fec-multicast-00 §6.6: report each base block whose RAP MFU fragments
19028
19685
  * the overlay restored, when the keyframe's FT=0 and FT=1 are held too. A
@@ -19162,6 +19819,10 @@ var MmtpRouter = class {
19162
19819
  get unadmittedListedDropCount() {
19163
19820
  return this.#unadmittedListedDrops;
19164
19821
  }
19822
+ /** Source datagrams (multicast or MoQ) a protected flow's bc-provenance v2 receiver released: admitted at once or held, then admitted by a record. Repair symbols and user-agent-admitted datagrams are not counted. Counted at release, before this router's own track checks: a released datagram those drop, which only a track change between hold and release can cause, still counts, so this is not a count of routed media. */
19823
+ get admittedSourceDatagramCount() {
19824
+ return this.#admittedSourceDatagrams;
19825
+ }
19165
19826
  /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
19166
19827
  get unlistedRepairSetAsideCount() {
19167
19828
  return this.#unlistedRepairSetAside;
@@ -19648,6 +20309,8 @@ var MmtpRouter = class {
19648
20309
  )) return;
19649
20310
  fec.noteBlockActivity?.(blockStart, ownerPacketId, catalogTrackName);
19650
20311
  fec.noteRepairGroupLength?.(blockStart, ownerPacketId, repair.rsbLength, catalogTrackName);
20312
+ this.#feedPendingRebuilt(ownerPacketId, catalogTrackName, placement.block);
20313
+ if (this.#classifyPacketId(ownerPacketId) === null) return;
19651
20314
  const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
19652
20315
  const recovered = fec.feedRepairSymbol(
19653
20316
  ownerPacketId,
@@ -19698,7 +20361,7 @@ var MmtpRouter = class {
19698
20361
  catalogTrackName
19699
20362
  )) continue;
19700
20363
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
19701
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
20364
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
19702
20365
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
19703
20366
  }
19704
20367
  if (payload.oversized) continue;
@@ -19785,6 +20448,8 @@ var MmtpRouter = class {
19785
20448
  this.#droppedPreSyncVideo.delete(streamKey);
19786
20449
  this.#latestVideoSeqByStream.delete(streamKey);
19787
20450
  this.#ssIdSeqOffsetByStream.delete(streamKey);
20451
+ this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
20452
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
19788
20453
  this.#multicastRapTwinByStream.delete(streamKey);
19789
20454
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
19790
20455
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -19911,6 +20576,12 @@ var MmtpRouter = class {
19911
20576
  * the outgoing stream stops. The hold is bounded by the incoming stream's
19912
20577
  * own RAP cadence, so no timer is involved.
19913
20578
  *
20579
+ * While the switch is staged, the FEC release gate lets a keyframe the
20580
+ * overlay rebuilt reach it, on either side, when the keyframe did before
20581
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
20582
+ * decides on what each side delivered, and the commit discards the gate's
20583
+ * frames of the outgoing stream.
20584
+ *
19914
20585
  * The commit is one synchronous transition inside the frame path: the
19915
20586
  * outgoing stream's already-admitted frames are released (its queued FEC
19916
20587
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -19961,6 +20632,9 @@ var MmtpRouter = class {
19961
20632
  droppedIncomingFrames: 0
19962
20633
  };
19963
20634
  this.#staged = state;
20635
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
20636
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
20637
+ }
19964
20638
  return {
19965
20639
  cancel: () => {
19966
20640
  if (this.#staged !== state) return false;
@@ -20043,7 +20717,17 @@ var MmtpRouter = class {
20043
20717
  */
20044
20718
  #routeParsedFrame(data, meta) {
20045
20719
  if (this.#classifyPacketId(meta.packetId) === null) return;
20046
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
20720
+ if (this.#staged !== null) {
20721
+ let consumed = false;
20722
+ this.#fecPokeDepth++;
20723
+ try {
20724
+ consumed = this.#interceptSwitchFrame(data, meta);
20725
+ } finally {
20726
+ this.#fecPokeDepth--;
20727
+ this.#flushPendingFecPokes();
20728
+ }
20729
+ if (consumed) return;
20730
+ }
20047
20731
  this.#deliverParsedFrame(data, meta);
20048
20732
  }
20049
20733
  #commitStreamSwitch(state, rap, reason) {
@@ -20195,12 +20879,16 @@ var MmtpRouter = class {
20195
20879
  this.#parser.deferFecRelease(work);
20196
20880
  } finally {
20197
20881
  this.#fecPokeDepth--;
20198
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
20199
- const pokes = [...this.#pendingFecPokes.values()];
20200
- this.#pendingFecPokes.clear();
20201
- for (const poke of pokes) {
20202
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20203
- }
20882
+ this.#flushPendingFecPokes();
20883
+ }
20884
+ }
20885
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
20886
+ #flushPendingFecPokes() {
20887
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
20888
+ const pokes = [...this.#pendingFecPokes.values()];
20889
+ this.#pendingFecPokes.clear();
20890
+ for (const poke of pokes) {
20891
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20204
20892
  }
20205
20893
  }
20206
20894
  }
@@ -20278,6 +20966,14 @@ var MmtpRouter = class {
20278
20966
  onRap: (packetId, catalogTrackName, ssId) => {
20279
20967
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
20280
20968
  },
20969
+ // A staged switch commits on when each side's frames reach it
20970
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
20971
+ // they did unanchored.
20972
+ releaseUnanchored: (packetId, catalogTrackName) => {
20973
+ const staged = this.#staged;
20974
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
20975
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
20976
+ },
20281
20977
  onReleased: (data, meta) => {
20282
20978
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
20283
20979
  const timing = meta.authoredTiming;
@@ -20419,6 +21115,7 @@ var MmtpRouter = class {
20419
21115
  const parsed = this.#parser.parsePacket(packet);
20420
21116
  if (!parsed) return;
20421
21117
  const info = parsed.info;
21118
+ if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
20422
21119
  if (source === "multicast" && !manifestAdmitted) {
20423
21120
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
20424
21121
  }
@@ -20700,7 +21397,8 @@ var MmtpRouter = class {
20700
21397
  parsed.header,
20701
21398
  info.sequenceNumber,
20702
21399
  info.rapFlag,
20703
- source
21400
+ source,
21401
+ fecPayloadId?.ssId
20704
21402
  );
20705
21403
  }
20706
21404
  }
@@ -20726,7 +21424,8 @@ var MmtpRouter = class {
20726
21424
  source: parserOptions?.source,
20727
21425
  deliveryProvenance: parserOptions?.deliveryProvenance,
20728
21426
  catalogTrackName: parserOptions?.catalogTrackName,
20729
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
21427
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
21428
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
20730
21429
  };
20731
21430
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
20732
21431
  else this.#parser.feed(packet, feedOptions);
@@ -20850,7 +21549,8 @@ var MmtpRouter = class {
20850
21549
  if (stream === void 0) {
20851
21550
  stream = {
20852
21551
  key: JSON.stringify([packetId, catalogTrackName ?? null]),
20853
- duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId))
21552
+ duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId)),
21553
+ overlayToBase: { routed: /* @__PURE__ */ new Set(), pending: /* @__PURE__ */ new Map() }
20854
21554
  };
20855
21555
  byName.set(catalogTrackName, stream);
20856
21556
  }
@@ -20965,8 +21665,16 @@ var MmtpRouter = class {
20965
21665
  this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
20966
21666
  this.#emitDirectVideo(packetId, data, meta, cb);
20967
21667
  }
20968
- #routeDirectRecoveredVideo(packetId, data, meta, cb) {
21668
+ #routeDirectRecoveredVideo(packetId, data, meta, cb, fecSbn) {
20969
21669
  const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);
21670
+ if (this.#isFecTrack(packetId)) {
21671
+ const high = this.#deliveredVideoHighWaterByStream.get(streamKey);
21672
+ if (fecSbn !== void 0 || high !== void 0 && authoredAdjacent(high, meta)) {
21673
+ this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
21674
+ this.#emitDirectVideo(packetId, data, meta, cb);
21675
+ return;
21676
+ }
21677
+ }
20970
21678
  this.#enqueueDirectRecoveredVideo(packetId, data, meta);
20971
21679
  const lastSourceTs = this.#lastDirectSourceVideoTsByStream.get(streamKey);
20972
21680
  this.#drainDirectRecoveredVideo(
@@ -21120,6 +21828,13 @@ var MmtpRouter = class {
21120
21828
  * frames by epoch only if pre-protection input ever matters.
21121
21829
  */
21122
21830
  #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete, assisted = false) {
21831
+ const overlayRouted = ownerPacketId == null ? void 0 : this.#streams.get(ownerPacketId)?.get(catalogTrackName)?.overlayToBase.routed;
21832
+ if (overlayRouted !== void 0 && overlayRouted.size > 0) {
21833
+ result = {
21834
+ ...result,
21835
+ symbols: result.symbols.filter((sym) => !overlayRouted.has(this.#fecAnchorForRecovered(blockId, sym.index)))
21836
+ };
21837
+ }
21123
21838
  const entry = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
21124
21839
  const receiver = entry === void 0 || entry === "ambiguous" ? entry : entry.receiver;
21125
21840
  const userAgent = !assisted && entry !== void 0 && entry !== "ambiguous" && entry.protected === true && entry.userAgent === true;
@@ -21176,7 +21891,12 @@ var MmtpRouter = class {
21176
21891
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
21177
21892
  if (ownerPacketId == null) return;
21178
21893
  if (this.#classifyPacketId(ownerPacketId) === null) return;
21179
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
21894
+ const fecSbnOf = (index) => {
21895
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
21896
+ const fecSbn = overlay.baseSsIds.get(index);
21897
+ const fecSbnFirst = overlay.firstSsIds.get(index);
21898
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
21899
+ };
21180
21900
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
21181
21901
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
21182
21902
  if (ssIdSeqOffset !== void 0) {
@@ -21184,7 +21904,10 @@ var MmtpRouter = class {
21184
21904
  ...result,
21185
21905
  symbols: result.symbols.map((sym) => {
21186
21906
  const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
21187
- if (wire === sym.packetSequenceNumber) return sym;
21907
+ if (wire === sym.packetSequenceNumber) {
21908
+ this.#unstampedSsIdSeqOffsetByStream.set(streamKey, ssIdSeqOffset);
21909
+ return sym;
21910
+ }
21188
21911
  this.#restampedRecoveredSeqs++;
21189
21912
  this.#restampedStreams.add(streamKey);
21190
21913
  return { ...sym, packetSequenceNumber: wire };
@@ -21220,16 +21943,29 @@ var MmtpRouter = class {
21220
21943
  }
21221
21944
  );
21222
21945
  }
21223
- result = {
21224
- ...result,
21225
- symbols: result.symbols.filter((sym) => sym.fragmentType !== 2 || sym.fragment.fragmentationIndicator !== 1 || sym.fragment.movieFragmentSequenceNumber === void 0 || sym.fragment.sampleNumber === void 0 || this.#parser.hasAuthoredTimingFor(
21226
- ownerPacketId,
21227
- sym.fragment.mpuSequenceNumber,
21228
- sym.fragment.movieFragmentSequenceNumber,
21229
- sym.fragment.sampleNumber,
21230
- catalogTrackName
21231
- ))
21232
- };
21946
+ const untimedHead = (sym) => sym.fragmentType === 2 && sym.fragment.fragmentationIndicator === 1 && sym.fragment.movieFragmentSequenceNumber !== void 0 && sym.fragment.sampleNumber !== void 0 && !this.#parser.hasAuthoredTimingFor(
21947
+ ownerPacketId,
21948
+ sym.fragment.mpuSequenceNumber,
21949
+ sym.fragment.movieFragmentSequenceNumber,
21950
+ sym.fragment.sampleNumber,
21951
+ catalogTrackName
21952
+ );
21953
+ for (const sym of result.symbols) {
21954
+ if (!untimedHead(sym) || this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) continue;
21955
+ this.#feedViaParser(
21956
+ sym.rawSymbol,
21957
+ { packetId: ownerPacketId, sequenceNumber: sym.packetSequenceNumber },
21958
+ void 0,
21959
+ {
21960
+ skipFecPayloadId: true,
21961
+ recovered: true,
21962
+ deliveryProvenance,
21963
+ ...fecSbnOf(sym.index),
21964
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
21965
+ }
21966
+ );
21967
+ }
21968
+ result = { ...result, symbols: result.symbols.filter((sym) => !untimedHead(sym)) };
21233
21969
  const gated = this.#isFecTrack(ownerPacketId);
21234
21970
  const assembler = this.#mseAssemblerFor(ownerPacketId, catalogTrackName);
21235
21971
  if (assembler) {
@@ -22706,6 +23442,12 @@ function isNonNegativeSafeInteger(value) {
22706
23442
  function isSymbolCounts(value) {
22707
23443
  return isRecord(value) && hasExactKeys(value, ["multicast", "moq"]) && isNonNegativeSafeInteger(value["multicast"]) && isNonNegativeSafeInteger(value["moq"]);
22708
23444
  }
23445
+ function isSpanFailure(value) {
23446
+ if (!isRecord(value) || !hasExactKeys(value, ["length", "sources"])) return false;
23447
+ const length = value["length"];
23448
+ const sources = value["sources"];
23449
+ return Number.isSafeInteger(length) && length > 0 && isNonNegativeSafeInteger(sources) && sources < length;
23450
+ }
22709
23451
  function isNullableNonNegative(value) {
22710
23452
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
22711
23453
  }
@@ -22725,7 +23467,10 @@ function isRepairLifecycleEvent(value) {
22725
23467
  case "recovered":
22726
23468
  return hasExactKeys(value, ["version", "type", "block", "blockClass", "via", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && (value["via"] === "inband" || value["via"] === "quic") && isSymbolCounts(value["symbols"]);
22727
23469
  case "failed":
22728
- return hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]);
23470
+ return hasExactKeys(
23471
+ value,
23472
+ "span" in value ? ["version", "type", "block", "blockClass", "symbols", "span"] : ["version", "type", "block", "blockClass", "symbols"]
23473
+ ) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]) && (!("span" in value) || isSpanFailure(value["span"]));
22729
23474
  case "repair-preempted":
22730
23475
  case "repair-deferred":
22731
23476
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
@@ -22934,6 +23679,8 @@ var MulticastManager = class {
22934
23679
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
22935
23680
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
22936
23681
  #repairReleases = /* @__PURE__ */ new Map();
23682
+ /** Protected repair flows owned by each live repair-endpoint release. */
23683
+ #repairProvenanceFlows = /* @__PURE__ */ new Map();
22937
23684
  /** Each source's catalog keyframe overlay, from its `ok` binding. */
22938
23685
  #overlayBindings = /* @__PURE__ */ new Map();
22939
23686
  /** Installed overlay decoders (`setKeyframeOverlayDecoder`), by source. */
@@ -22991,7 +23738,7 @@ var MulticastManager = class {
22991
23738
  onPublisherRestart: (packetId, catalogTrackName) => {
22992
23739
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
22993
23740
  },
22994
- onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
23741
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass, span) => {
22995
23742
  const pathCount = this.#fec.blockPathCount(
22996
23743
  sbn,
22997
23744
  packetId,
@@ -23009,7 +23756,8 @@ var MulticastManager = class {
23009
23756
  symbols: {
23010
23757
  multicast: pathCount?.multicastSymbols ?? 0,
23011
23758
  moq: pathCount?.moqSymbols ?? 0
23012
- }
23759
+ },
23760
+ ...span === void 0 ? {} : { span }
23013
23761
  });
23014
23762
  },
23015
23763
  onFrameGap: (decision) => {
@@ -23599,6 +24347,9 @@ var MulticastManager = class {
23599
24347
  this.#transport.onFailback((reason) => {
23600
24348
  const joined = this.#provenanceJoin;
23601
24349
  if (joined !== null) this.#router.unprotectProvenanceFlow(joined.flow);
24350
+ for (const flows of this.#repairProvenanceFlows.values()) {
24351
+ for (const flow of flows) this.#router.unprotectProvenanceFlow(flow);
24352
+ }
23602
24353
  this.#onFailback?.(reason);
23603
24354
  });
23604
24355
  }
@@ -23633,6 +24384,12 @@ var MulticastManager = class {
23633
24384
  "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
23634
24385
  );
23635
24386
  }
24387
+ if (provenanceFlow !== void 0) {
24388
+ const flow = multicastProvenanceFlowKey(provenanceFlow);
24389
+ if ([...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
24390
+ throw new TypeError(`[MulticastManager] join: provenance flow already registered by a repair endpoint: ${flow}`);
24391
+ }
24392
+ }
23636
24393
  const staged = this.#renditionSwitch;
23637
24394
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
23638
24395
  this.configureFec(config);
@@ -23640,8 +24397,8 @@ var MulticastManager = class {
23640
24397
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
23641
24398
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
23642
24399
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
23643
- this.#releaseProvenanceJoin();
23644
24400
  const provenance = config.provenance;
24401
+ this.#releaseProvenanceJoin();
23645
24402
  const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
23646
24403
  const ingress = protectedTracks === void 0 ? void 0 : {
23647
24404
  tracks: Object.freeze(
@@ -23694,8 +24451,13 @@ var MulticastManager = class {
23694
24451
  * feeds the flow's receiver; media datagrams are held until one admits them.
23695
24452
  */
23696
24453
  #joinProvenance(provenance, ingress) {
24454
+ this.#router.registerProvenanceFlow(ingress, this.#provenanceReceiver(provenance));
24455
+ this.#hookFailback();
24456
+ this.#provenanceJoin = { flow: ingress.flow };
24457
+ }
24458
+ #provenanceReceiver(provenance) {
23697
24459
  const { flow, auth } = provenance;
23698
- const receiver = new BcProvenanceV2Receiver({
24460
+ return new BcProvenanceV2Receiver({
23699
24461
  ...provenance.receiver,
23700
24462
  // The caller's ctx when it passes one, else the catalog's: an explicit
23701
24463
  // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
@@ -23712,9 +24474,6 @@ var MulticastManager = class {
23712
24474
  maxAuthDelayMs: flow.maxAuthDelayMs,
23713
24475
  manifestTimerMs: flow.manifestTimerMs
23714
24476
  });
23715
- this.#router.registerProvenanceFlow(ingress, receiver);
23716
- this.#hookFailback();
23717
- this.#provenanceJoin = { flow: ingress.flow };
23718
24477
  }
23719
24478
  /** Un-protect: drop the flow's hold queues (no expiry counted). */
23720
24479
  #releaseProvenanceJoin() {
@@ -23745,8 +24504,25 @@ var MulticastManager = class {
23745
24504
  * callback delivers must come from a subscription opened on
23746
24505
  * `options.gateway`. A callback that also merges another source (a MoQ or
23747
24506
  * WebSocket repair feed) must not name a native provider here.
24507
+ *
24508
+ * An endpoint's `provenance` makes its group a protected flow of its own
24509
+ * (multicast-02 7.2.7), registered here and released with the group; its
24510
+ * records ride in band on the group's port. On the user-agent path a
24511
+ * flow-less repair group of a protected track is set aside, never read, so
24512
+ * a player joining a protected catalog's repair groups passes it.
23748
24513
  */
23749
24514
  joinRepairEndpoints(endpoints, provider, options) {
24515
+ for (const { provenance, flow, source, group, port } of endpoints) {
24516
+ if (provenance === void 0) continue;
24517
+ if (flow !== void 0) {
24518
+ throw new TypeError("[MulticastManager] joinRepairEndpoints: an endpoint names provenance or flow, never both");
24519
+ }
24520
+ if (!sameIpAddress(source, provenance.flow.source) || !sameIpAddress(group, provenance.flow.groupAddress) || port !== provenance.flow.port) {
24521
+ throw new RangeError(
24522
+ "[MulticastManager] joinRepairEndpoints: provenance flow (S, G, port) must match the endpoint's source, group and port"
24523
+ );
24524
+ }
24525
+ }
23750
24526
  const releases = [];
23751
24527
  let released = false;
23752
24528
  const safely = (each) => {
@@ -23756,17 +24532,36 @@ var MulticastManager = class {
23756
24532
  console.warn("[MulticastManager] repair group release failed", error);
23757
24533
  }
23758
24534
  };
24535
+ const usedFlows = /* @__PURE__ */ new Set();
24536
+ const preparedProvenance = endpoints.map((endpoint) => {
24537
+ if (endpoint.provenance === void 0) return void 0;
24538
+ const flow = multicastProvenanceFlowKey(endpoint.provenance.flow);
24539
+ if (usedFlows.has(flow) || this.#provenanceJoin?.flow === flow || [...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
24540
+ throw new TypeError(`[MulticastManager] joinRepairEndpoints: provenance flow already registered: ${flow}`);
24541
+ }
24542
+ usedFlows.add(flow);
24543
+ return { flow, receiver: this.#provenanceReceiver(endpoint.provenance) };
24544
+ });
24545
+ const provenanceFlows = [];
23759
24546
  const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners.map((owner) => owner.instance !== "keyframe" ? owner : {
23760
24547
  ...owner,
23761
24548
  ownerTrackName: endpoint.tracks.find((t) => t.packetId === owner.ownerPacketId)?.name,
23762
24549
  repairTrackName: endpoint.tracks.find((t) => t.packetId === owner.packetId)?.name
23763
24550
  }));
23764
24551
  this.#applyRepairOwners(repairOwners);
23765
- for (const endpoint of endpoints) {
24552
+ for (const [index, endpoint] of endpoints.entries()) {
24553
+ const flow = endpoint.provenance === void 0 ? endpoint.flow : multicastProvenanceFlowKey(endpoint.provenance.flow);
23766
24554
  const ingress = {
23767
24555
  tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
23768
- ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
24556
+ ...flow === void 0 ? {} : { flow }
23769
24557
  };
24558
+ if (endpoint.provenance !== void 0) {
24559
+ const prepared = preparedProvenance[index];
24560
+ if (prepared === void 0) throw new Error("[MulticastManager] repair provenance preparation missing");
24561
+ this.#router.registerProvenanceFlow(ingress, prepared.receiver);
24562
+ provenanceFlows.push(prepared.flow);
24563
+ releases.push(() => this.#router.releaseProvenanceFlow(flow));
24564
+ }
23770
24565
  let sender;
23771
24566
  const feed = (packet, sourceAddress, ingressToFeed) => {
23772
24567
  if (released) return;
@@ -23796,7 +24591,7 @@ var MulticastManager = class {
23796
24591
  packetIds: endpoint.packetIds,
23797
24592
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
23798
24593
  // A protected repair group's records ride in band on its port (7.2.3).
23799
- ...endpoint.flow === void 0 ? {} : { protected: true }
24594
+ ...flow === void 0 ? {} : { protected: true }
23800
24595
  }, ingress).then((joined) => {
23801
24596
  if (!joined && !released) fail(transport.lastJoinOutcome);
23802
24597
  });
@@ -23805,9 +24600,12 @@ var MulticastManager = class {
23805
24600
  if (released) return;
23806
24601
  released = true;
23807
24602
  this.#repairReleases.delete(release);
24603
+ this.#repairProvenanceFlows.delete(release);
23808
24604
  for (const each of releases.splice(0)) safely(each);
23809
24605
  };
23810
24606
  this.#repairReleases.set(release, repairOwners);
24607
+ this.#repairProvenanceFlows.set(release, provenanceFlows);
24608
+ if (provenanceFlows.length) this.#hookFailback();
23811
24609
  return release;
23812
24610
  }
23813
24611
  #applyRepairOwners(owners) {
@@ -24389,10 +25187,12 @@ var MulticastManager = class {
24389
25187
  * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
24390
25188
  * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
24391
25189
  * pending hole and reported here, and `closeIsoHoles` must be called for it
24392
- * once its range FETCH ends (or none is sent).
25190
+ * once its range FETCH ends (or none is sent). `onExpired` is told of a
25191
+ * pending hole the stream runs past the locator's horizon: returning true,
25192
+ * the caller closes it (`closeIsoHoles`); otherwise it is discarded.
24393
25193
  */
24394
- onUndelimitedLoss(cb) {
24395
- this.#fec.setUndelimitedLossHandler(cb);
25194
+ onUndelimitedLoss(cb, onExpired) {
25195
+ this.#fec.setUndelimitedLossHandler(cb, onExpired ?? null);
24396
25196
  }
24397
25197
  /**
24398
25198
  * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
@@ -24628,7 +25428,8 @@ var MulticastManager = class {
24628
25428
  "stream" in event ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
24629
25429
  ...event,
24630
25430
  block: Object.freeze({ ...event.block }),
24631
- ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {}
25431
+ ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {},
25432
+ ..."span" in event && event.span !== void 0 ? { span: Object.freeze({ ...event.span }) } : {}
24632
25433
  }
24633
25434
  );
24634
25435
  if (this.#logRepairLifecycle) {