@blockcast/mmt-container 2.2.0-main.b4ce3986f2dd → 2.2.0-main.c1482ff09fa3

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 (67) hide show
  1. package/dist/browser-runtime.js +1300 -180
  2. package/dist/browser-runtime.js.map +3 -3
  3. package/dist/cmaf-block-assembler.js +92 -1
  4. package/dist/cmaf-block-assembler.js.map +2 -2
  5. package/dist/codec-utils.d.ts.map +1 -1
  6. package/dist/codec-utils.js +92 -1
  7. package/dist/codec-utils.js.map +2 -2
  8. package/dist/delivery-catalog.js +2 -1
  9. package/dist/delivery-catalog.js.map +2 -2
  10. package/dist/delta-fallback-config.js.map +1 -1
  11. package/dist/fec-manager.d.ts +74 -14
  12. package/dist/fec-manager.d.ts.map +1 -1
  13. package/dist/fec-manager.js +419 -61
  14. package/dist/fec-manager.js.map +2 -2
  15. package/dist/fec-worker-setup.js.map +1 -1
  16. package/dist/index.d.ts +2 -2
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js.map +2 -2
  19. package/dist/iso-block-locator.d.ts +48 -13
  20. package/dist/iso-block-locator.d.ts.map +1 -1
  21. package/dist/iso-block-locator.js +97 -25
  22. package/dist/iso-block-locator.js.map +2 -2
  23. package/dist/iso-bmff-timing.d.ts +10 -1
  24. package/dist/iso-bmff-timing.d.ts.map +1 -1
  25. package/dist/iso-bmff-timing.js +36 -2
  26. package/dist/iso-bmff-timing.js.map +2 -2
  27. package/dist/media-router.js.map +1 -1
  28. package/dist/mmtp-container-parser.d.ts +77 -10
  29. package/dist/mmtp-container-parser.d.ts.map +1 -1
  30. package/dist/mmtp-container-parser.js +295 -27
  31. package/dist/mmtp-container-parser.js.map +2 -2
  32. package/dist/mmtp-container-parser.no-modules.js +297 -30
  33. package/dist/mmtp-container-parser.no-modules.js.map +3 -3
  34. package/dist/mmtp-decode-pipeline.js +294 -27
  35. package/dist/mmtp-decode-pipeline.js.map +2 -2
  36. package/dist/mmtp-router.d.ts +34 -8
  37. package/dist/mmtp-router.d.ts.map +1 -1
  38. package/dist/mmtp-router.js +619 -75
  39. package/dist/mmtp-router.js.map +3 -3
  40. package/dist/multicast-manager.d.ts +26 -3
  41. package/dist/multicast-manager.d.ts.map +1 -1
  42. package/dist/multicast-manager.js +1120 -153
  43. package/dist/multicast-manager.js.map +3 -3
  44. package/dist/multicast-transport.js +4 -3
  45. package/dist/multicast-transport.js.map +2 -2
  46. package/dist/no-modules.js +294 -27
  47. package/dist/no-modules.js.map +3 -3
  48. package/dist/repair-fetch.d.ts +38 -8
  49. package/dist/repair-fetch.d.ts.map +1 -1
  50. package/dist/repair-fetch.js +286 -27
  51. package/dist/repair-fetch.js.map +3 -3
  52. package/dist/track-session.d.ts.map +1 -1
  53. package/dist/track-session.js +1 -0
  54. package/dist/track-session.js.map +2 -2
  55. package/dist/wasm-mmtp-container-parser.js +294 -27
  56. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  57. package/package.json +5 -5
  58. package/src/codec-utils.ts +121 -1
  59. package/src/fec-manager.ts +454 -35
  60. package/src/index.ts +3 -0
  61. package/src/iso-block-locator.ts +133 -31
  62. package/src/iso-bmff-timing.ts +40 -1
  63. package/src/mmtp-container-parser.ts +294 -29
  64. package/src/mmtp-router.ts +544 -55
  65. package/src/multicast-manager.ts +118 -14
  66. package/src/repair-fetch.ts +366 -50
  67. 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,10 +2253,14 @@ 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
2178
- // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
2262
+ // symbols its repair group carries; 0 for a repair-less span no repair can
2263
+ // state (#openIsoSpan). Same lifecycle as #blockRepairRsIds.
2179
2264
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
2180
2265
  /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
2181
2266
  this.#heldLayerStates = /* @__PURE__ */ new Map();
@@ -2292,6 +2377,10 @@ var FECManager = class _FECManager {
2292
2377
  // ── Keyframe-protected repair policy (block-policy.ts) ──
2293
2378
  // One classifier per physical stream, built from that stream's geometry.
2294
2379
  this.#classifiers = /* @__PURE__ */ new Map();
2380
+ // A stream without catalog timing has no classifier, so the last RAP it
2381
+ // released stands in for one: "an MPU boundary bounds its RAPs" holds until
2382
+ // a second RAP is released inside one MPU (BLO-52085).
2383
+ this.#noSpanRaps = /* @__PURE__ */ new Map();
2295
2384
  // Geometry a stream-scoped configuration gave one stream (streamKey). ABR
2296
2385
  // rungs can share a packetId with a different framerate or GOP, so the
2297
2386
  // packet-level geometry is only the geometry of a packet whose streams
@@ -2365,7 +2454,10 @@ var FECManager = class _FECManager {
2365
2454
  // arrives via onBlockRecovered callback.
2366
2455
  this.onBlockStarted = null;
2367
2456
  this.onBlockComplete = null;
2368
- /** A block reached its fail bound. `blockClass` is its class at failure. */
2457
+ /**
2458
+ * A block reached its fail bound. `blockClass` is its class at failure.
2459
+ * `span` is set when what failed is a repair-less span starting at `sbn`.
2460
+ */
2369
2461
  this.onBlockFailed = null;
2370
2462
  /**
2371
2463
  * Fired once per stream when its Worker decoder stops being routable.
@@ -2407,6 +2499,8 @@ var FECManager = class _FECManager {
2407
2499
  * for it, which it must be.
2408
2500
  */
2409
2501
  this.#onUndelimitedLoss = null;
2502
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
2503
+ this.#onIsoHoleExpired = null;
2410
2504
  /** A block every symbol of which vanished was created by SBN evidence. */
2411
2505
  this.onBlockVanished = null;
2412
2506
  /** A block reached a terminal state (completed, recovered, or failed). */
@@ -2449,7 +2543,9 @@ var FECManager = class _FECManager {
2449
2543
  #pendingWorkerCleanupBounds;
2450
2544
  #blockSourceCounts;
2451
2545
  #blockSourceEsis;
2546
+ #blockRebuiltEsis;
2452
2547
  #blockAuthoredLengths;
2548
+ #isoSpanKeys;
2453
2549
  #ssbLengthConflictCount;
2454
2550
  #blockRepairRsIds;
2455
2551
  #blockRsbLengths;
@@ -2491,6 +2587,7 @@ var FECManager = class _FECManager {
2491
2587
  #orderedFrontiers;
2492
2588
  #orderedPendingBlocks;
2493
2589
  #classifiers;
2590
+ #noSpanRaps;
2494
2591
  #streamGeometries;
2495
2592
  #failedBlocks;
2496
2593
  #resolvedBlockClasses;
@@ -2515,6 +2612,7 @@ var FECManager = class _FECManager {
2515
2612
  #decoderUnavailableEvents;
2516
2613
  #repairSymbolSizeMismatchCount;
2517
2614
  #onUndelimitedLoss;
2615
+ #onIsoHoleExpired;
2518
2616
  #encodeTrackName(catalogTrackName) {
2519
2617
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
2520
2618
  if (encoded === void 0) {
@@ -2986,7 +3084,10 @@ var FECManager = class _FECManager {
2986
3084
  timer.handle = null;
2987
3085
  this.#requestRepair(sbn, packetId, catalogTrackName);
2988
3086
  };
2989
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
3087
+ timer.handle = setTimeout(
3088
+ onFire,
3089
+ this.#receiptAtMs === void 0 ? Math.max(0, deadlineMs - performance.now()) : this.#receiptTimerDelayMs(deadlineMs, 0)
3090
+ );
2990
3091
  this.#repairDeadlines.set(key, timer);
2991
3092
  }
2992
3093
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -3130,8 +3231,14 @@ var FECManager = class _FECManager {
3130
3231
  * Vanished blocks are not enumerated here: their starts are unknown until a
3131
3232
  * repair states them. The SS_IDs between two stated blocks become one
3132
3233
  * repair-less span when the later block's repair arrives (placeIsoRepair).
3234
+ *
3235
+ * A `held` source arrived before its block was known and is fed only now
3236
+ * that a repair, a span or a closed hole placed it: how far its block start
3237
+ * then lies behind the frontier measures how long the receiver held it, not
3238
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
3239
+ * it (BLO-52085).
3133
3240
  */
3134
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
3241
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn, held = false) {
3135
3242
  const streamKey = this.#streamKey(packetId, catalogTrackName);
3136
3243
  const now = performance.now();
3137
3244
  const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
@@ -3152,6 +3259,7 @@ var FECManager = class _FECManager {
3152
3259
  };
3153
3260
  const discontinuity = () => {
3154
3261
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity();
3262
+ this.#noSpanRaps.delete(streamKey);
3155
3263
  this.#highestSbn.set(streamKey, { sbn, atMs: now });
3156
3264
  this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
3157
3265
  if (psn === void 0) this.#sourceAnchors.delete(streamKey);
@@ -3169,7 +3277,7 @@ var FECManager = class _FECManager {
3169
3277
  return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
3170
3278
  };
3171
3279
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
3172
- 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))) {
3280
+ 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))) {
3173
3281
  discontinuity();
3174
3282
  return;
3175
3283
  }
@@ -3431,17 +3539,21 @@ var FECManager = class _FECManager {
3431
3539
  this.#blockWaitDeadlinesMs.delete(key);
3432
3540
  this.#repairHoldUntilMs.delete(key);
3433
3541
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
3434
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName);
3542
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs);
3435
3543
  };
3436
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)));
3544
+ timer.handle = setTimeout(
3545
+ onFire,
3546
+ this.#receiptAtMs === void 0 ? Math.max(1, Math.ceil(deadlineMs - nowMs)) : this.#receiptTimerDelayMs(deadlineMs, 1)
3547
+ );
3437
3548
  this.#activeBlocks.set(key, timer);
3438
3549
  this.#indexBlockKey(key, sbn, packetId);
3439
3550
  }
3440
3551
  /**
3441
3552
  * Hand a block whose delivery is over to its decoder for finalization: the
3442
- * datagram deadline fired, or the ordered relay moved past it.
3553
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
3554
+ * is when it was due: its deadline, or now.
3443
3555
  */
3444
- #finalizeExpiredBlock(sbn, packetId, catalogTrackName) {
3556
+ #finalizeExpiredBlock(sbn, packetId, catalogTrackName, dueAtMs = performance.now()) {
3445
3557
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
3446
3558
  if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
3447
3559
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -3457,7 +3569,7 @@ var FECManager = class _FECManager {
3457
3569
  if (workerClient) {
3458
3570
  this.#pendingWorkerCleanups.add(key);
3459
3571
  this.#pendingWorkerCleanupClients.set(key, workerClient);
3460
- this.#boundOwedCleanup(key, packetId, workerClient);
3572
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs);
3461
3573
  workerClient.cleanup(sbn);
3462
3574
  } else {
3463
3575
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
@@ -3564,6 +3676,9 @@ var FECManager = class _FECManager {
3564
3676
  }
3565
3677
  if (policyChanged) {
3566
3678
  this.#bumpEpoch(packetId);
3679
+ for (const key of [...this.#noSpanRaps.keys()]) {
3680
+ if (this.#belongsToPacket(key, packetId)) this.#noSpanRaps.delete(key);
3681
+ }
3567
3682
  for (const [key, classifier] of [...this.#classifiers]) {
3568
3683
  if (!this.#belongsToPacket(key, packetId)) continue;
3569
3684
  const stream = this.#parseStreamKey(key);
@@ -3766,7 +3881,9 @@ var FECManager = class _FECManager {
3766
3881
  }
3767
3882
  resetMap(this.#blockSourceCounts);
3768
3883
  resetMap(this.#blockSourceEsis);
3884
+ resetMap(this.#blockRebuiltEsis);
3769
3885
  resetMap(this.#blockAuthoredLengths);
3886
+ resetSet(this.#isoSpanKeys);
3770
3887
  resetMap(this.#blockRepairRsIds);
3771
3888
  resetMap(this.#blockRsbLengths);
3772
3889
  resetMap(this.#heldLayerStates);
@@ -3799,6 +3916,7 @@ var FECManager = class _FECManager {
3799
3916
  resetMap(this.#isoLocators);
3800
3917
  resetMap(this.#sourceAnchors);
3801
3918
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName));
3919
+ this.#noSpanRaps.delete(this.#streamKey(packetId, catalogTrackName));
3802
3920
  this.#bumpEpoch(packetId);
3803
3921
  for (const [sbn, keys] of this.#blockKeysBySbn) {
3804
3922
  for (const key of keys.keys()) {
@@ -3889,7 +4007,9 @@ var FECManager = class _FECManager {
3889
4007
  dropMap(this.#pendingWorkerCleanupClients);
3890
4008
  dropMap(this.#blockSourceCounts);
3891
4009
  dropMap(this.#blockSourceEsis);
4010
+ dropMap(this.#blockRebuiltEsis);
3892
4011
  dropMap(this.#blockAuthoredLengths);
4012
+ dropSet(this.#isoSpanKeys);
3893
4013
  dropMap(this.#blockRepairRsIds);
3894
4014
  dropMap(this.#blockRsbLengths);
3895
4015
  dropMap(this.#blockPathCounts);
@@ -3905,6 +4025,7 @@ var FECManager = class _FECManager {
3905
4025
  dropMap(this.#isoLocators);
3906
4026
  dropMap(this.#sourceAnchors);
3907
4027
  dropMap(this.#classifiers);
4028
+ dropMap(this.#noSpanRaps);
3908
4029
  dropMap(this.#streamGeometries);
3909
4030
  dropSet(this.#pendingWorkerCleanups);
3910
4031
  dropSet(this.#completedBlocks);
@@ -4050,6 +4171,9 @@ var FECManager = class _FECManager {
4050
4171
  this.#unindexBlockKey(key);
4051
4172
  }
4052
4173
  }
4174
+ if (isSourceSymbol && source === "multicast") {
4175
+ this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), sbn + esi >>> 0, packetId, catalogTrackName);
4176
+ }
4053
4177
  return true;
4054
4178
  }
4055
4179
  #observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName) {
@@ -4159,8 +4283,10 @@ var FECManager = class _FECManager {
4159
4283
  }
4160
4284
  /**
4161
4285
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
4162
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
4163
- * Undefined for a block that is not open.
4286
+ * (SSB_length) and RSB_length (each undefined until a repair stated it; a
4287
+ * repair-less span states its length, and RSB_length 0 when it is longer
4288
+ * than K, since no repair can reach it). Undefined for a block that is not
4289
+ * open.
4164
4290
  */
4165
4291
  blockSymbolCounts(sbn, packetId, catalogTrackName) {
4166
4292
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -4228,8 +4354,9 @@ var FECManager = class _FECManager {
4228
4354
  return true;
4229
4355
  }
4230
4356
  /**
4231
- * Drop a block's repair hold: its FETCH ended without delivering. The block
4232
- * falls back to its multicast wait, which may already have passed.
4357
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
4358
+ * back only a repair that cannot complete it. The block falls back to its
4359
+ * multicast wait, which may already have passed.
4233
4360
  */
4234
4361
  releaseRepairHold(sbn, packetId, catalogTrackName) {
4235
4362
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -4367,6 +4494,8 @@ var FECManager = class _FECManager {
4367
4494
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
4368
4495
  const evictedBefore = locator.heldEvicted;
4369
4496
  const held = locator.hold(ssId, source);
4497
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
4498
+ if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
4370
4499
  const evicted = locator.heldEvicted - evictedBefore;
4371
4500
  if (evicted > 0) {
4372
4501
  const before = this.#isoHeldEvictedCount;
@@ -4387,17 +4516,20 @@ var FECManager = class _FECManager {
4387
4516
  * contradicts a known block is refused (counted) and must be dropped.
4388
4517
  */
4389
4518
  placeIsoRepair(packetId, catalogTrackName, ssStart, ssbLength) {
4390
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength);
4519
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
4520
+ const placement = locator.placeRepair(ssStart, ssbLength);
4521
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
4391
4522
  if (placement.status !== "placed") {
4392
4523
  this.#isoRepairRefusedCount++;
4393
4524
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
4394
4525
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`);
4395
4526
  }
4527
+ if (placement.ofSpan !== void 0) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName);
4396
4528
  return placement;
4397
4529
  }
4530
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName));
4398
4531
  if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
4399
4532
  if (placement.hole !== void 0) {
4400
- const locator = this.#isoLocatorFor(packetId, catalogTrackName);
4401
4533
  const hole = placement.hole.block;
4402
4534
  const previous = locator.blockEndingAt(hole.start);
4403
4535
  const loss = {
@@ -4418,17 +4550,29 @@ var FECManager = class _FECManager {
4418
4550
  * `handler`, instead of a repair-less span; null restores spans. Set by the
4419
4551
  * range repair scheduler; applies to every stream from its next gap. The
4420
4552
  * handler and the deferral are one setting, so no hole is ever created with
4421
- * nobody to close it.
4553
+ * nobody to close it. `onExpired` is told of each pending hole the stream
4554
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
4555
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
4556
+ * reported; otherwise the hole is discarded with its sources.
4422
4557
  */
4423
- setUndelimitedLossHandler(handler) {
4558
+ setUndelimitedLossHandler(handler, onExpired = null) {
4424
4559
  this.#onUndelimitedLoss = handler;
4560
+ this.#onIsoHoleExpired = handler === null ? null : onExpired;
4425
4561
  this.#deferIsoGaps = handler !== null;
4426
4562
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
4427
4563
  }
4564
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
4565
+ #settleExpiredIsoHoles(locator, packetId, catalogTrackName) {
4566
+ for (const hole of locator.takeExpiredHoles()) {
4567
+ const expired = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length };
4568
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length);
4569
+ }
4570
+ }
4428
4571
  /**
4429
- * The range repair for a hole ended: every hole still pending inside
4430
- * `[start, start + length)` becomes a repair-less span. Returns those spans
4431
- * with the held sources they placed, for the caller to feed (MmtpRouter).
4572
+ * The range repair for a hole ended: every hole inside `[start, start +
4573
+ * length)`, pending or expired, becomes a repair-less span. Returns those
4574
+ * spans with the held sources they placed, for the caller to feed
4575
+ * (MmtpRouter).
4432
4576
  */
4433
4577
  closeIsoHoles(packetId, catalogTrackName, start, length) {
4434
4578
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
@@ -4444,10 +4588,22 @@ var FECManager = class _FECManager {
4444
4588
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
4445
4589
  * SS_ID of which vanished resolves through its deadline like any vanished
4446
4590
  * block.
4591
+ *
4592
+ * A span longer than K holds more than one block (SSB_length <= K), and the
4593
+ * locator states no block inside a span, only one exactly its range
4594
+ * (IsoBlockLocator.placeRepair): no repair, multicast or FETCHed, can ever
4595
+ * reach it. Its repair group is empty, so only its own late sources can
4596
+ * complete it, and it waits as a stated block its group cannot complete
4597
+ * does (#lateSourceWaitMs; BLO-52085 D4). A span of K or less may be one
4598
+ * block whose repair is still to come, and keeps the whole wait.
4447
4599
  */
4448
4600
  #openIsoSpan(span, packetId, catalogTrackName) {
4449
4601
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
4450
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
4602
+ if (!this.#blockAuthoredLengths.has(key)) {
4603
+ this.#blockAuthoredLengths.set(key, span.block.length);
4604
+ this.#isoSpanKeys.add(key);
4605
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0);
4606
+ }
4451
4607
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
4452
4608
  }
4453
4609
  /**
@@ -4535,11 +4691,14 @@ var FECManager = class _FECManager {
4535
4691
  /**
4536
4692
  * Whether an MPU boundary still bounds this stream's RAPs (see
4537
4693
  * `BlockClassifier.mpuBoundsRaps`). Gap decisions drop MPU evidence once
4538
- * it does not. A stream with no classifier yet has shown nothing against it.
4694
+ * it does not. A stream with no classifier yet has shown nothing against it,
4695
+ * and neither has a stream without catalog timing until it releases two
4696
+ * RAPs inside one MPU.
4539
4697
  */
4540
4698
  mpuBoundsRapsFor(packetId, catalogTrackName) {
4541
- if (!this.#hasCatalogTimingForPacket(packetId)) return false;
4542
- return this.#classifiers.get(this.#streamKey(packetId, catalogTrackName))?.mpuBoundsRaps ?? true;
4699
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
4700
+ if (!this.#hasCatalogTimingForPacket(packetId)) return this.#noSpanRaps.get(streamKey)?.inside !== true;
4701
+ return this.#classifiers.get(streamKey)?.mpuBoundsRaps ?? true;
4543
4702
  }
4544
4703
  /** A block's class now, or frozen at its resolution. */
4545
4704
  blockClassFor(sbn, packetId, catalogTrackName) {
@@ -4565,7 +4724,14 @@ var FECManager = class _FECManager {
4565
4724
  * invariant (consecutive MPUs exactly one keyframe interval apart).
4566
4725
  */
4567
4726
  noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale) {
4568
- if (!this.#trackConfigs.has(packetId) || !this.#hasCatalogTimingForPacket(packetId)) return;
4727
+ if (!this.#trackConfigs.has(packetId)) return;
4728
+ if (!this.#hasCatalogTimingForPacket(packetId)) {
4729
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
4730
+ const last = this.#noSpanRaps.get(streamKey);
4731
+ const inside = last?.inside === true || last?.mpu === mpu && last.presentationTime !== presentationTime;
4732
+ this.#noSpanRaps.set(streamKey, { mpu, presentationTime, inside });
4733
+ return;
4734
+ }
4569
4735
  this.#applyClassifierChanges(
4570
4736
  packetId,
4571
4737
  catalogTrackName,
@@ -4778,11 +4944,14 @@ var FECManager = class _FECManager {
4778
4944
  });
4779
4945
  client.onCleanupComplete((sbn) => {
4780
4946
  if (this.#releasedWorkerClients.has(client)) return;
4781
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
4947
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
4948
+ const cleanupKeys = owed.filter((key) => {
4782
4949
  const block = this.#parseBlockKey(key);
4783
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
4950
+ return block.packetId === packetId && block.sbn === sbn;
4784
4951
  });
4785
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
4952
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
4953
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
4954
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
4786
4955
  });
4787
4956
  client.onError((msg, code) => {
4788
4957
  const requestedKind = code ?? msg;
@@ -4852,9 +5021,11 @@ var FECManager = class _FECManager {
4852
5021
  * fail deadline already passed, so failing it is the decision that deadline
4853
5022
  * made. A late ack then finds nothing owed and is a no-op.
4854
5023
  */
4855
- #boundOwedCleanup(key, packetId, client) {
5024
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
4856
5025
  this.#clearOwedCleanupBound(key);
4857
5026
  const bound = {
5027
+ dueAtMs,
5028
+ askedAtMs: performance.now(),
4858
5029
  handle: setTimeout(() => {
4859
5030
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
4860
5031
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -4952,7 +5123,15 @@ var FECManager = class _FECManager {
4952
5123
  this.#isoSourceOversizeCount++;
4953
5124
  return null;
4954
5125
  }
4955
- const sbn = located.block.start;
5126
+ return this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, located.block.start);
5127
+ }
5128
+ /**
5129
+ * Hand one placed source symbol to the stream's decoder: its Worker, which
5130
+ * answers through onFrame (null here), or its synchronous decoder, whose
5131
+ * recovered block is returned. `sbn` is the SS_Start of the block a repair
5132
+ * stated for `ssId`.
5133
+ */
5134
+ #feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn) {
4956
5135
  const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
4957
5136
  const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey);
4958
5137
  const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
@@ -4981,6 +5160,74 @@ var FECManager = class _FECManager {
4981
5160
  }
4982
5161
  return recovered;
4983
5162
  }
5163
+ /**
5164
+ * Feed a source symbol of this stream that another FEC instance over the
5165
+ * same packets rebuilt: a keyframe overlay recovery whose base SS_ID the
5166
+ * caller determined (draft-ramadan-moq-mmt-02 7.1, 7.4.4; joint decoding,
5167
+ * BLO-52085). It joins its block's decoder as a received source would, so
5168
+ * it reduces the erasures the block still has to solve, but it is not a
5169
+ * network arrival: no transport accounting, no classification evidence,
5170
+ * no deadline refresh, and it never makes a block clean.
5171
+ *
5172
+ * Only a block a repair stated takes one (a repair-less span has no
5173
+ * decoder block). A block that is terminal, or already holds that source,
5174
+ * does not. The symbol is the exact protected packet, unpadded, as
5175
+ * feedSourceSymbol takes it.
5176
+ *
5177
+ * `recovered` is the block the synchronous decoder completed with it; the
5178
+ * caller routes it and completes the block, as for any recovery. When
5179
+ * every source of the block is then present, received or rebuilt, and no
5180
+ * decoder returned it (a Worker answers asynchronously, and reports such a
5181
+ * block as clean on its own side), the block is completed here as
5182
+ * recovered, with nothing left to route.
5183
+ */
5184
+ feedRebuiltSourceSymbol(packetId, ssId, symbolData, catalogTrackName) {
5185
+ if (!this.#hasBlockProfile(packetId)) return NOT_TAKEN;
5186
+ const located = this.#isoLocatorFor(packetId, catalogTrackName).locate(ssId);
5187
+ if (located === null || located.block.span) return NOT_TAKEN;
5188
+ if (!ssbg1FitsSymbol(symbolData.byteLength, this.#trackConfig(packetId).symbolSize)) return NOT_TAKEN;
5189
+ const sbn = located.block.start;
5190
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
5191
+ if (this.#completedBlocks.has(key) || this.#blockSourceEsis.get(key)?.has(located.esi)) return NOT_TAKEN;
5192
+ let rebuilt = this.#blockRebuiltEsis.get(key);
5193
+ if (rebuilt?.has(located.esi)) return NOT_TAKEN;
5194
+ if (rebuilt === void 0) {
5195
+ rebuilt = /* @__PURE__ */ new Set();
5196
+ this.#blockRebuiltEsis.set(key, rebuilt);
5197
+ }
5198
+ const config = this.#trackConfigs.get(packetId);
5199
+ const wasShort = config !== void 0 && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) !== void 0;
5200
+ rebuilt.add(located.esi);
5201
+ const recovered = this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn);
5202
+ if (recovered === null && !this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName)) {
5203
+ if (wasShort && this.#activeBlocks.has(key) && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) === void 0) {
5204
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, this.#multicastWaitMs(config));
5205
+ }
5206
+ }
5207
+ return { taken: true, recovered };
5208
+ }
5209
+ /**
5210
+ * A block that holds every one of its `length` sources, received or
5211
+ * rebuilt by another instance, with at least one rebuilt, is recovered:
5212
+ * every packet of it was delivered, by its own arrival or by the instance
5213
+ * that rebuilt it, so nothing is routed. Returns whether it completed it.
5214
+ */
5215
+ #completeWhenSourcesPresent(key, sbn, length, packetId, catalogTrackName) {
5216
+ const rebuilt = this.#blockRebuiltEsis.get(key);
5217
+ if (rebuilt === void 0 || this.#completedBlocks.has(key)) return false;
5218
+ let present = rebuilt.size;
5219
+ for (const esi of this.#blockSourceEsis.get(key) ?? []) if (!rebuilt.has(esi)) present++;
5220
+ if (present < length) return false;
5221
+ this.#traceLifecycle("recovered", sbn, packetId, catalogTrackName);
5222
+ this.countRecovery(packetId, sbn, catalogTrackName);
5223
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
5224
+ if (catalogTrackName === void 0) {
5225
+ this.onBlockComplete?.(sbn, packetId);
5226
+ } else {
5227
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName);
5228
+ }
5229
+ return true;
5230
+ }
4984
5231
  /**
4985
5232
  * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
4986
5233
  * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
@@ -5183,8 +5430,76 @@ var FECManager = class _FECManager {
5183
5430
  this.#completeCleanBlock(blockKey, sbn, packetId, catalogTrackName);
5184
5431
  return null;
5185
5432
  }
5433
+ if (recovered === null) this.#shortenUnrecoverableWait(blockKey, sbn, packetId, catalogTrackName);
5186
5434
  return recovered;
5187
5435
  }
5436
+ /**
5437
+ * A first-arrival multicast source, held or placed. A datagram flow keeps
5438
+ * its sources in send order, so one that moves the stream's newest source
5439
+ * position past a block leaves the sources that block still misses
5440
+ * reordered behind it at best: it shortens the wait of every block it
5441
+ * passed that only a late source can complete. MoQ is left out: its streams
5442
+ * can overtake one another, so a MoQ source shows nothing about the sources
5443
+ * sent before it.
5444
+ */
5445
+ #noteMulticastSource(locator, ssId, packetId, catalogTrackName) {
5446
+ const previous = locator.newestSource;
5447
+ if (!locator.noteSource(ssId) || previous === void 0) return;
5448
+ for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
5449
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
5450
+ this.#shortenUnrecoverableWait(
5451
+ this.#blockKey(block.start, packetId, catalogTrackName),
5452
+ block.start,
5453
+ packetId,
5454
+ catalogTrackName
5455
+ );
5456
+ }
5457
+ }
5458
+ /**
5459
+ * The wait of a block that only a late source can complete (BLO-52085): a
5460
+ * repair stated it, or it is a repair-less span longer than K (whose group
5461
+ * is empty, #openIsoSpan), its received sources plus every symbol its
5462
+ * repair group carries (RSB_length) are short of K' (the repair scheduler's
5463
+ * group-cannot-complete), and a later source of the stream has arrived, so
5464
+ * a source it misses is lost or reordered behind that one. The span, which
5465
+ * covers repair symbols paced after its sources, buys it nothing: it waits
5466
+ * the late-symbol allowance alone, the multicast wait less the span (the
5467
+ * catalog tolerance or the measured delivery gap). Undefined for any other
5468
+ * block.
5469
+ */
5470
+ #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
5471
+ const authoredLength = this.#blockAuthoredLengths.get(key);
5472
+ const rsbLength = this.#blockRsbLengths.get(key);
5473
+ if (authoredLength === void 0 || rsbLength === void 0) return void 0;
5474
+ let present = this.#blockSourceCounts.get(key) ?? 0;
5475
+ const received = this.#blockSourceEsis.get(key);
5476
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
5477
+ if (present + rsbLength >= authoredLength) return void 0;
5478
+ const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
5479
+ if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
5480
+ return void 0;
5481
+ }
5482
+ return this.#multicastWaitMs(config) - config.interleaveDepthMs;
5483
+ }
5484
+ /**
5485
+ * Bring an open block's wait in to its late-source wait, when it has one.
5486
+ * Never later than it is armed: only a source can complete such a block,
5487
+ * so a repair of its group (paced across the span) must not keep it open.
5488
+ */
5489
+ #shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName) {
5490
+ if (!this.#activeBlocks.has(key)) return;
5491
+ const config = this.#trackConfigs.get(packetId);
5492
+ if (config === void 0) return;
5493
+ const waitMs = this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config);
5494
+ if (waitMs === void 0) return;
5495
+ const armedAtMs = this.#blockWaitDeadlinesMs.get(key);
5496
+ this.#armBlockTimeout(
5497
+ sbn,
5498
+ packetId,
5499
+ catalogTrackName,
5500
+ armedAtMs === void 0 ? waitMs : Math.min(waitMs, armedAtMs - this.#receiptNow())
5501
+ );
5502
+ }
5188
5503
  /**
5189
5504
  * Record a block's authored SSB_length from a repair symbol. Returns false,
5190
5505
  * leaving the block unchanged, when the symbol contradicts the block: a
@@ -5282,12 +5597,13 @@ var FECManager = class _FECManager {
5282
5597
  * the inactivity deadline on each symbol, records the symbol's in-band
5283
5598
  * classification evidence, and marks the block clean when all of its
5284
5599
  * authored source symbols arrived: the SSB_length a repair symbol declared,
5285
- * otherwise K.
5600
+ * otherwise K. `held` marks a source held unplaced since it arrived and
5601
+ * placed only now (see #noteSbnSeen).
5286
5602
  *
5287
5603
  * Throws for a packetId that was never configured, so a classified block
5288
5604
  * never reads the manager-global K or timeout.
5289
5605
  */
5290
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
5606
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
5291
5607
  const trackConfig = this.#trackConfigs.get(packetId);
5292
5608
  if (trackConfig === void 0) {
5293
5609
  throw new Error(
@@ -5303,7 +5619,8 @@ var FECManager = class _FECManager {
5303
5619
  catalogTrackName,
5304
5620
  "source",
5305
5621
  evidence.packetSequenceNumber,
5306
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
5622
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
5623
+ held
5307
5624
  );
5308
5625
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
5309
5626
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -5339,6 +5656,15 @@ var FECManager = class _FECManager {
5339
5656
  this.#completeCleanBlock(key, sbn, packetId, catalogTrackName);
5340
5657
  return;
5341
5658
  }
5659
+ if (this.#blockRebuiltEsis.has(key) && this.#completeWhenSourcesPresent(
5660
+ key,
5661
+ sbn,
5662
+ this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? authoredLength,
5663
+ packetId,
5664
+ catalogTrackName
5665
+ )) {
5666
+ return;
5667
+ }
5342
5668
  this.noteBlockActivity(sbn, packetId, catalogTrackName, true);
5343
5669
  }
5344
5670
  #completeCleanBlock(key, sbn, packetId, catalogTrackName) {
@@ -5347,7 +5673,9 @@ var FECManager = class _FECManager {
5347
5673
  this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
5348
5674
  this.#blockSourceCounts.delete(key);
5349
5675
  this.#blockSourceEsis.delete(key);
5676
+ this.#blockRebuiltEsis.delete(key);
5350
5677
  this.#blockAuthoredLengths.delete(key);
5678
+ this.#isoSpanKeys.delete(key);
5351
5679
  this.#blockRepairRsIds.delete(key);
5352
5680
  this.#blockRsbLengths.delete(key);
5353
5681
  this.#markTerminal(key, sbn, packetId, true);
@@ -5378,6 +5706,19 @@ var FECManager = class _FECManager {
5378
5706
  #receiptNow() {
5379
5707
  return this.#receiptAtMs ?? performance.now();
5380
5708
  }
5709
+ /**
5710
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
5711
+ * scope: counted from the receipt time, as the timer of a symbol fed when
5712
+ * it was received was, less the whole ms since. So it fires on the tick
5713
+ * that timer would have, never later than a delay counted from now, and
5714
+ * its handler still re-arms a timer that fires before its deadline.
5715
+ * Counted from now, a deadline set from the receipt time is rounded up
5716
+ * from another fraction of a ms (BLO-52085).
5717
+ */
5718
+ #receiptTimerDelayMs(deadlineMs, minMs) {
5719
+ const receivedAtMs = this.#receiptAtMs;
5720
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
5721
+ }
5381
5722
  /**
5382
5723
  * A held packet admitted late arms from its (earlier) receipt time; that
5383
5724
  * never pulls in a deadline later activity already armed. Outside a
@@ -5413,10 +5754,20 @@ var FECManager = class _FECManager {
5413
5754
  this.#repairDeadlineMs(trackConfig)
5414
5755
  );
5415
5756
  }
5416
- this.#armBlockTimeout(sbn, packetId, catalogTrackName, timeoutMs);
5757
+ if (!sourceProgress && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) !== void 0) {
5758
+ this.#shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName);
5759
+ return;
5760
+ }
5761
+ this.#armBlockTimeout(
5762
+ sbn,
5763
+ packetId,
5764
+ catalogTrackName,
5765
+ this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) ?? timeoutMs
5766
+ );
5417
5767
  }
5418
5768
  #failBlock(sbn, packetId, catalogTrackName) {
5419
5769
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
5770
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
5420
5771
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
5421
5772
  this.#clearRepairDeadline(key);
5422
5773
  this.#clearBlockTimer(key);
@@ -5426,6 +5777,7 @@ var FECManager = class _FECManager {
5426
5777
  }
5427
5778
  this.#blockSourceCounts.delete(key);
5428
5779
  this.#blockSourceEsis.delete(key);
5780
+ this.#blockRebuiltEsis.delete(key);
5429
5781
  this.#blockAuthoredLengths.delete(key);
5430
5782
  this.#blockRepairRsIds.delete(key);
5431
5783
  this.#blockRsbLengths.delete(key);
@@ -5435,7 +5787,8 @@ var FECManager = class _FECManager {
5435
5787
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
5436
5788
  this.#fecStats.blocksFailed++;
5437
5789
  this.#statsForPacket(packetId).blocksFailed++;
5438
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5790
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5791
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
5439
5792
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
5440
5793
  }
5441
5794
  /**
@@ -5464,7 +5817,9 @@ var FECManager = class _FECManager {
5464
5817
  this.#retireBlockClass(key, block.sbn, block.packetId, block.catalogTrackName);
5465
5818
  this.#blockSourceCounts.delete(key);
5466
5819
  this.#blockSourceEsis.delete(key);
5820
+ this.#blockRebuiltEsis.delete(key);
5467
5821
  this.#blockAuthoredLengths.delete(key);
5822
+ this.#isoSpanKeys.delete(key);
5468
5823
  this.#blockRepairRsIds.delete(key);
5469
5824
  this.#blockRsbLengths.delete(key);
5470
5825
  this.#clearBlockTimer(key);
@@ -5555,7 +5910,9 @@ var FECManager = class _FECManager {
5555
5910
  this.#blockKeysBySbn.clear();
5556
5911
  this.#blockSourceCounts.clear();
5557
5912
  this.#blockSourceEsis.clear();
5913
+ this.#blockRebuiltEsis.clear();
5558
5914
  this.#blockAuthoredLengths.clear();
5915
+ this.#isoSpanKeys.clear();
5559
5916
  this.#blockRepairRsIds.clear();
5560
5917
  this.#blockRsbLengths.clear();
5561
5918
  this.#heldLayerStates.clear();
@@ -5580,6 +5937,7 @@ var FECManager = class _FECManager {
5580
5937
  this.#blockAnchorsMs.clear();
5581
5938
  this.#blockCatalogTrackNames.clear();
5582
5939
  this.#classifiers.clear();
5940
+ this.#noSpanRaps.clear();
5583
5941
  this.#streamGeometries.clear();
5584
5942
  this.#failedBlocks.clear();
5585
5943
  this.#resolvedBlockClasses.clear();
@@ -6933,9 +7291,9 @@ async function openSubscription(rx, openedPromise, options, packetIds) {
6933
7291
  } catch (error) {
6934
7292
  throw new MulticastError("subscription-failed", "MulticastReceiver did not open", error);
6935
7293
  }
6936
- if (rx.integrityScheme !== INTEGRITY_SCHEME) {
7294
+ if (opened.integrityScheme !== INTEGRITY_SCHEME) {
6937
7295
  await rx.close();
6938
- throw unsupported(`integrity scheme ${String(rx.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
7296
+ throw unsupported(`integrity scheme ${String(opened.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
6939
7297
  }
6940
7298
  const events = new EventTarget();
6941
7299
  let state = "connected";
@@ -7054,6 +7412,7 @@ var MOQT_PUBLISHER_PRIORITY = Object.freeze({
7054
7412
  });
7055
7413
 
7056
7414
  // node_modules/@blockcast/mmt-transport/dist/amt-gateway.js
7415
+ var MAX_PENDING_PACKETS = 256;
7057
7416
  var AMTGatewayManager = class {
7058
7417
  subscriptions = /* @__PURE__ */ new Map();
7059
7418
  messageHandler;
@@ -7177,7 +7536,7 @@ var AMTGatewayManager = class {
7177
7536
  if (!subscription.handshakeComplete) {
7178
7537
  const queue = this.pendingPackets.get(subscriptionId);
7179
7538
  const packetData2 = data;
7180
- if (queue) {
7539
+ if (queue && queue.length < MAX_PENDING_PACKETS) {
7181
7540
  queue.push({
7182
7541
  data: packetData2.data,
7183
7542
  remoteAddress: packetData2.remoteAddress,
@@ -10270,9 +10629,10 @@ function isH264IntraSlice(nal) {
10270
10629
  const sliceType = readH264SliceType(nal);
10271
10630
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
10272
10631
  }
10632
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
10273
10633
  function readH264SliceType(nal) {
10274
10634
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
10275
- const rbsp = removeEmulationPrevention(nal.subarray(1));
10635
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
10276
10636
  const state = { bitOffset: 0 };
10277
10637
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
10278
10638
  return readUnsignedExpGolomb(rbsp, state);
@@ -10419,6 +10779,96 @@ if (void 0) {
10419
10779
  ]))).toBe(false);
10420
10780
  });
10421
10781
  });
10782
+ describe("readH264SliceType", () => {
10783
+ const wholeNalSliceType = (nal) => {
10784
+ if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
10785
+ const rbsp = removeEmulationPrevention(nal.subarray(1));
10786
+ const state = { bitOffset: 0 };
10787
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null;
10788
+ return readUnsignedExpGolomb(rbsp, state);
10789
+ };
10790
+ const hex2 = (text2) => Uint8Array.from(text2.match(/../g), (byte) => parseInt(byte, 16));
10791
+ const ue = (value) => {
10792
+ const code = (value + 1).toString(2);
10793
+ return "0".repeat(code.length - 1) + code;
10794
+ };
10795
+ const sliceNal = (bits) => {
10796
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, "0").match(/.{8}/g);
10797
+ const nal = [1];
10798
+ let zeros = 0;
10799
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
10800
+ if (zeros >= 2 && byte <= 3) {
10801
+ nal.push(3);
10802
+ zeros = 0;
10803
+ }
10804
+ nal.push(byte);
10805
+ zeros = byte === 0 ? zeros + 1 : 0;
10806
+ }
10807
+ return Uint8Array.from(nal);
10808
+ };
10809
+ const x264Slices = [
10810
+ ["64x48 P", hex2("419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176"), 5, false],
10811
+ ["64x48 B", hex2("419e414212fffeeade283707cb70f7"), 6, false],
10812
+ ["64x48 non-IDR I", hex2(
10813
+ "4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39a527e23eb34c8167fd"
10814
+ ), 7, true],
10815
+ ["1280x720 B, escape at byte 10", hex2(
10816
+ "01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e19b75d92170917306190f262fd58268702db2eff86a9651e48"
10817
+ ), 6, false],
10818
+ ["1280x720 P, escape at byte 15", hex2(
10819
+ "41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f02c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e85302da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3"
10820
+ ), 5, false],
10821
+ ["1280x720 B, escape at byte 22", hex2("01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352"), 6, false],
10822
+ ["7680x4320 IDR, first_mb_in_slice 97440", hex2(
10823
+ "650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9"
10824
+ ), null, true],
10825
+ ["7680x4320 P, first_mb_in_slice 32640", hex2(
10826
+ "410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020"
10827
+ ), 5, false],
10828
+ ["7680x4320 P, first_mb_in_slice 97440", hex2(
10829
+ "410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806"
10830
+ ), 5, false]
10831
+ ];
10832
+ const syntheticSlices = [
10833
+ ["an escape inside first_mb_in_slice", sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
10834
+ ["an escape between the fields", sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
10835
+ ["an escape inside slice_type", sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
10836
+ ["the longest fields, five escapes", sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
10837
+ ["the largest values", sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
10838
+ ["31 leading zeros in first_mb_in_slice", sliceNal(`${"0".repeat(31)}1`), null],
10839
+ ["31 leading zeros in slice_type", sliceNal(`1${"0".repeat(31)}1`), null],
10840
+ ["escapes running past the slice header", sliceNal(ue(0) + ue(5) + "0".repeat(400)), 5]
10841
+ ];
10842
+ test("reads the slice_type of real and synthetic slices", () => {
10843
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
10844
+ expect(readH264SliceType(nal), name).toBe(sliceType);
10845
+ }
10846
+ });
10847
+ test("matches the whole-NAL unescape at every truncation", () => {
10848
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
10849
+ for (let end = 0; end <= nal.length; end++) {
10850
+ const cut = nal.subarray(0, end);
10851
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut));
10852
+ }
10853
+ }
10854
+ });
10855
+ test("matches the whole-NAL unescape on zero-heavy NAL units", () => {
10856
+ const bytes = [0, 0, 0, 3, 1, 2, 128, 255];
10857
+ let seed = 1;
10858
+ const next = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) >>> 16;
10859
+ for (let i = 0; i < 5e3; i++) {
10860
+ const nal = new Uint8Array(2 + next() % 63);
10861
+ nal[0] = 65;
10862
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length];
10863
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal));
10864
+ }
10865
+ });
10866
+ test("classifies the x264 slices as keyframes or not", () => {
10867
+ for (const [name, nal, , keyframe] of x264Slices) {
10868
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe);
10869
+ }
10870
+ });
10871
+ });
10422
10872
  describe("avccToAnnexB", () => {
10423
10873
  test("converts with SPS/PPS on keyframe", () => {
10424
10874
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -13120,9 +13570,21 @@ var IsoBmffTimingResolver = class {
13120
13570
  }
13121
13571
  #track = null;
13122
13572
  #fragments = /* @__PURE__ */ new Map();
13573
+ /** First sample of each pending fragment, kept in `#delivered` with its sample count. */
13574
+ #firstSamples = /* @__PURE__ */ new Map();
13575
+ /**
13576
+ * First sample and sample count of the newest fragments whose every slot was
13577
+ * cleared. Abandonment counts: `releaseSample` clears a slot too, which
13578
+ * matches the combiner, since it retires an abandoned sample as well.
13579
+ */
13580
+ #delivered = /* @__PURE__ */ new Map();
13123
13581
  #pendingSamples = 0;
13124
13582
  #evictedSamples = 0;
13125
13583
  #lastMovieFragmentRejection = null;
13584
+ /** True once an FT=0 has bound the track that FT=1 timing is read against. */
13585
+ get initialized() {
13586
+ return this.#track !== null;
13587
+ }
13126
13588
  get pendingSampleCount() {
13127
13589
  return this.#pendingSamples;
13128
13590
  }
@@ -13146,7 +13608,14 @@ var IsoBmffTimingResolver = class {
13146
13608
  this.#track = timing;
13147
13609
  return true;
13148
13610
  }
13149
- addMovieFragment(mpuSequenceNumber, data, additionalSampleLimit = this.maxPendingSamples) {
13611
+ /**
13612
+ * `recovered` marks an FEC-recovered copy. A recovered block hands back
13613
+ * every FT=1 it holds, the received ones included, so a recovered copy of a
13614
+ * fragment whose samples are all done is a duplicate: admitting it again
13615
+ * would charge stale timing and could displace the live MPU's. A source
13616
+ * copy is still admitted again (a rendition switch re-arms timing that way).
13617
+ */
13618
+ addMovieFragment(mpuSequenceNumber, data, additionalSampleLimit = this.maxPendingSamples, recovered = false) {
13150
13619
  this.#lastMovieFragmentRejection = null;
13151
13620
  if (!Number.isInteger(additionalSampleLimit) || additionalSampleLimit < 0) {
13152
13621
  this.#lastMovieFragmentRejection = "invalid";
@@ -13172,6 +13641,8 @@ var IsoBmffTimingResolver = class {
13172
13641
  (sample, index) => sample !== null && sameSample(sample, parsed.samples[index])
13173
13642
  );
13174
13643
  }
13644
+ const delivered = recovered ? this.#delivered.get(key) : void 0;
13645
+ if (delivered && delivered.sampleCount === parsed.samples.length && sameSample(delivered.first, parsed.samples[0])) return true;
13175
13646
  let freed = 0;
13176
13647
  while (this.#fragments.size > 0 && (this.#pendingSamples + parsed.samples.length > this.maxPendingSamples || parsed.samples.length - freed > additionalSampleLimit)) {
13177
13648
  freed += this.#evictOldestFragment();
@@ -13185,6 +13656,7 @@ var IsoBmffTimingResolver = class {
13185
13656
  return false;
13186
13657
  }
13187
13658
  this.#fragments.set(key, [...parsed.samples]);
13659
+ this.#firstSamples.set(key, parsed.samples[0]);
13188
13660
  this.#pendingSamples += parsed.samples.length;
13189
13661
  return true;
13190
13662
  }
@@ -13242,6 +13714,7 @@ var IsoBmffTimingResolver = class {
13242
13714
  let live = 0;
13243
13715
  for (const sample of samples) if (sample !== null) live++;
13244
13716
  this.#fragments.delete(oldest);
13717
+ this.#firstSamples.delete(oldest);
13245
13718
  this.#pendingSamples -= live;
13246
13719
  this.#evictedSamples += live;
13247
13720
  return live;
@@ -13257,12 +13730,23 @@ var IsoBmffTimingResolver = class {
13257
13730
  if (!samples || !samples[index]) return false;
13258
13731
  samples[index] = null;
13259
13732
  this.#pendingSamples--;
13260
- if (samples.every((value) => value === null)) this.#fragments.delete(key);
13733
+ if (samples.every((value) => value === null)) {
13734
+ this.#fragments.delete(key);
13735
+ const first = this.#firstSamples.get(key);
13736
+ this.#firstSamples.delete(key);
13737
+ this.#delivered.delete(key);
13738
+ this.#delivered.set(key, { first, sampleCount: samples.length });
13739
+ if (this.#delivered.size > this.maxPendingSamples) {
13740
+ this.#delivered.delete(this.#delivered.keys().next().value);
13741
+ }
13742
+ }
13261
13743
  return true;
13262
13744
  }
13263
13745
  reset() {
13264
13746
  this.#track = null;
13265
13747
  this.#fragments.clear();
13748
+ this.#firstSamples.clear();
13749
+ this.#delivered.clear();
13266
13750
  this.#pendingSamples = 0;
13267
13751
  }
13268
13752
  };
@@ -13432,6 +13916,9 @@ function authoredGap(before, after) {
13432
13916
  function ssIdAfter(a, b) {
13433
13917
  return (a - b | 0) > 0;
13434
13918
  }
13919
+ function holdsRebuilt(stream) {
13920
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
13921
+ }
13435
13922
  var FecReleaseSequencer = class {
13436
13923
  #streams = /* @__PURE__ */ new Map();
13437
13924
  #gate;
@@ -13494,6 +13981,7 @@ var FecReleaseSequencer = class {
13494
13981
  stream.lastSbn = void 0;
13495
13982
  stream.discontinuity = false;
13496
13983
  stream.rapSsId = void 0;
13984
+ stream.sourced = false;
13497
13985
  }
13498
13986
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
13499
13987
  this.#recordStat("droppedStale");
@@ -13520,6 +14008,7 @@ var FecReleaseSequencer = class {
13520
14008
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
13521
14009
  else hi = mid;
13522
14010
  }
14011
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
13523
14012
  stream.buf.splice(lo, 0, frame);
13524
14013
  this.#drainUnlessDeferred(stream);
13525
14014
  }
@@ -13555,6 +14044,41 @@ var FecReleaseSequencer = class {
13555
14044
  }
13556
14045
  return false;
13557
14046
  }
14047
+ /**
14048
+ * These streams' sink is being replaced by one that has seen no source
14049
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
14050
+ * release to the sink being replaced the frames the unanchored path had
14051
+ * already released to it (#cursorPassed): there they waited in its queue,
14052
+ * which its replacement flushes. A stream that holds none is not drained:
14053
+ * it holds nothing the anchor kept back, and a drain would still force out
14054
+ * a frame held past the hold limit, which before the anchor waited for the
14055
+ * next push. Then treat the streams as unsourced until a source frame is
14056
+ * released.
14057
+ */
14058
+ unsource(packetId, catalogTrackName) {
14059
+ for (const stream of this.#streams.values()) {
14060
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
14061
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
14062
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
14063
+ else this.#drain(stream, true);
14064
+ }
14065
+ stream.sourced = false;
14066
+ }
14067
+ }
14068
+ }
14069
+ /**
14070
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
14071
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
14072
+ * packetId.
14073
+ */
14074
+ holdsRebuilt(packetId, catalogTrackName) {
14075
+ for (const stream of this.#streams.values()) {
14076
+ if (stream.packetId !== packetId) continue;
14077
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
14078
+ if (holdsRebuilt(stream)) return true;
14079
+ }
14080
+ return false;
14081
+ }
13558
14082
  /** Re-evaluate held gaps after FEC state changed. */
13559
14083
  poke(streamKey) {
13560
14084
  if (streamKey !== void 0) {
@@ -13646,16 +14170,32 @@ var FecReleaseSequencer = class {
13646
14170
  last: null,
13647
14171
  lastSbn: void 0,
13648
14172
  discontinuity: false,
13649
- rapSsId: void 0
14173
+ rapSsId: void 0,
14174
+ sourced: false,
14175
+ draining: 0
13650
14176
  };
13651
14177
  this.#streams.set(streamKey, stream);
13652
14178
  }
13653
14179
  return stream;
13654
14180
  }
13655
- #drain(stream) {
14181
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
14182
+ #drain(stream, asUnanchored = false) {
14183
+ stream.draining++;
14184
+ try {
14185
+ this.#drainLoop(stream, asUnanchored);
14186
+ } finally {
14187
+ stream.draining--;
14188
+ }
14189
+ }
14190
+ #drainLoop(stream, asUnanchored) {
13656
14191
  while (stream.buf.length > 0 && stream.last !== null) {
13657
14192
  const head = stream.buf[0];
13658
14193
  const last = stream.last;
14194
+ if (compareFrameOrder(head, last) <= 0) {
14195
+ stream.buf.shift();
14196
+ this.#release(stream, head, void 0);
14197
+ continue;
14198
+ }
13659
14199
  if (stream.discontinuity) {
13660
14200
  stream.discontinuity = false;
13661
14201
  stream.buf.shift();
@@ -13669,9 +14209,10 @@ var FecReleaseSequencer = class {
13669
14209
  }
13670
14210
  const headSbn = head.meta.fecSbn;
13671
14211
  const from = stream.lastSbn ?? headSbn;
13672
- const to = headSbn ?? stream.lastSbn;
14212
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
13673
14213
  let lost = [];
13674
14214
  const unanchored = from === void 0 && to === void 0;
14215
+ let unresolved = false;
13675
14216
  if (from !== void 0 && to !== void 0) {
13676
14217
  const resolved = this.#gate.resolvedLoss(
13677
14218
  stream.packetId,
@@ -13680,7 +14221,8 @@ var FecReleaseSequencer = class {
13680
14221
  Math.max(from, to),
13681
14222
  from
13682
14223
  );
13683
- if (resolved === null) {
14224
+ unresolved = resolved === null;
14225
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored)) {
13684
14226
  const heldMs = performance.now() - head.arrivedAtMs;
13685
14227
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
13686
14228
  this.#recordStat("forcedWindowFlushes");
@@ -13688,22 +14230,56 @@ var FecReleaseSequencer = class {
13688
14230
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
13689
14231
  continue;
13690
14232
  }
13691
- lost = resolved;
14233
+ lost = resolved ?? [];
13692
14234
  }
13693
14235
  stream.buf.shift();
13694
14236
  this.#release(
13695
14237
  stream,
13696
14238
  head,
13697
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
14239
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
13698
14240
  );
13699
14241
  }
13700
14242
  }
14243
+ /**
14244
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
14245
+ * source cursor holds it unanchored, and neither does a later frame behind
14246
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
14247
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
14248
+ * like each frame that arrived in front of it since (stale there). The head
14249
+ * then goes, decided as it would be unanchored, once a frame the base path
14250
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
14251
+ * marked one: the base path has passed that one, so a frame still missing
14252
+ * before it can only come from a repair. It also goes while no source frame
14253
+ * has been released, when the direct path shows a recovered frame at once.
14254
+ * And it goes at once while a staged switch decides on when frames arrive
14255
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
14256
+ * sink being replaced: unanchored, it had already reached the sink.
14257
+ * The scan also writes: the `passed` marks it sets stay on the frames,
14258
+ * and push marks a frame it inserts in front of a marked one from them.
14259
+ */
14260
+ #cursorPassed(stream, asUnanchored) {
14261
+ let at = -1;
14262
+ for (let i = 0; i < stream.buf.length; i++) {
14263
+ const frame = stream.buf[i];
14264
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
14265
+ frame.passed = true;
14266
+ if (at < 0) at = i;
14267
+ } else if (frame.passed !== true) break;
14268
+ }
14269
+ if (at < 0) return false;
14270
+ 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));
14271
+ }
13701
14272
  #release(stream, frame, decision) {
14273
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
14274
+ if (stale) this.#recordStat("droppedStale");
13702
14275
  if (decision) frame.meta.gapBefore = decision;
13703
14276
  stream.last = frame;
13704
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
14277
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
14278
+ stream.lastSbn = frame.meta.fecSbn;
14279
+ }
14280
+ if (frame.meta.recovered !== true) stream.sourced = true;
13705
14281
  this.#gate.onReleased?.(frame.data, frame.meta);
13706
- this.#emit(frame.data, frame.meta);
14282
+ if (!stale) this.#emit(frame.data, frame.meta);
13707
14283
  }
13708
14284
  };
13709
14285
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -13744,6 +14320,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
13744
14320
  this.#reclaimedTimingSamples = 0;
13745
14321
  this.#evictedTimingSamples = 0;
13746
14322
  this.#rejectedMovieFragments = 0;
14323
+ this.#recoveredHeadsAwaitingTiming = {
14324
+ held: 0,
14325
+ expired: 0,
14326
+ discarded: 0,
14327
+ superseded: 0
14328
+ };
13747
14329
  this.#sequencers = /* @__PURE__ */ new Map();
13748
14330
  this.#fecGate = null;
13749
14331
  this.#fecSequencer = null;
@@ -13852,6 +14434,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
13852
14434
  #reclaimedTimingSamples;
13853
14435
  #evictedTimingSamples;
13854
14436
  #rejectedMovieFragments;
14437
+ #recoveredHeadsAwaitingTiming;
13855
14438
  #sequencers;
13856
14439
  #fecGate;
13857
14440
  #fecSequencer;
@@ -13957,11 +14540,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
13957
14540
  /**
13958
14541
  * Typed view of the ISO-BMFF timing-sample budget.
13959
14542
  *
13960
- * This is the acceptance signal for the budget ratchet: `pending` walking
13961
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
13962
- * and it is observable here rather than only as media silently stopping.
13963
- * Per repo policy this is a producer-owned counter -- never infer budget
13964
- * state by parsing logs.
14543
+ * Each stream admits timing against its own window of `capacity` slots
14544
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
14545
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
14546
+ * timing a stream declared and never delivered shows up there. `pending`
14547
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
14548
+ * a producer-owned counter -- never infer budget state by parsing logs.
13965
14549
  */
13966
14550
  get timingBudgetStats() {
13967
14551
  return {
@@ -13972,6 +14556,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
13972
14556
  rejectedMovieFragments: this.#rejectedMovieFragments
13973
14557
  };
13974
14558
  }
14559
+ /** Recovered heads parked for FT=1 timing (BLO-53369). Survives dispose(). */
14560
+ get recoveredHeadsAwaitingTiming() {
14561
+ let pending = 0;
14562
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
14563
+ for (const head of awaitingTiming) if (head.options?.recovered) pending++;
14564
+ }
14565
+ return { ...this.#recoveredHeadsAwaitingTiming, pending };
14566
+ }
13975
14567
  get reorderStats() {
13976
14568
  let bufferedFrames = this.#fecSequencer?.buffered ?? 0;
13977
14569
  for (const { sequencer } of this.#sequencers.values()) bufferedFrames += sequencer.buffered;
@@ -14013,6 +14605,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
14013
14605
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
14014
14606
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
14015
14607
  }
14608
+ /** See FecReleaseSequencer.unsource. */
14609
+ unsourceFecRelease(packetId, catalogTrackName) {
14610
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
14611
+ }
14612
+ /** See FecReleaseSequencer.holdsRebuilt. */
14613
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
14614
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
14615
+ }
14016
14616
  /** Re-evaluate held gaps after FEC block state changed. */
14017
14617
  pokeFecRelease(packetId, catalogTrackName) {
14018
14618
  if (!this.#fecSequencer) return;
@@ -14145,7 +14745,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14145
14745
  const now = Date.now();
14146
14746
  for (const { awaitingTiming } of this.#timingStreams.values()) {
14147
14747
  while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
14148
- awaitingTiming.shift();
14748
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
14149
14749
  }
14150
14750
  }
14151
14751
  }
@@ -14263,11 +14863,16 @@ var MmtpContainerParser = class _MmtpContainerParser {
14263
14863
  if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
14264
14864
  return this.#drop("fragment-unexpected-fragmentation");
14265
14865
  const resolver2 = this.#timingResolver(streamKey, info.packetId, false);
14266
- if (!resolver2) return this.#drop("fragment-no-resolver");
14866
+ if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
14267
14867
  const pendingBefore = resolver2.pendingSampleCount;
14268
14868
  const evictedBefore = resolver2.evictedSampleCount;
14269
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
14270
- const admitted = resolver2.addMovieFragment(mpu.mpuSequenceNumber, data, remaining);
14869
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
14870
+ const admitted = resolver2.addMovieFragment(
14871
+ mpu.mpuSequenceNumber,
14872
+ data,
14873
+ remaining,
14874
+ options?.recovered === true
14875
+ );
14271
14876
  this.#pendingTimingSamples += resolver2.pendingSampleCount - pendingBefore;
14272
14877
  this.#evictedTimingSamples += resolver2.evictedSampleCount - evictedBefore;
14273
14878
  if (!admitted) {
@@ -14287,7 +14892,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14287
14892
  };
14288
14893
  }
14289
14894
  if (fragmentType !== 2) return this.#drop("unknown-fragment-type");
14290
- const resolver = this.#timingResolver(streamKey, info.packetId, false);
14895
+ const resolver = this.#timingResolver(streamKey, info.packetId, true);
14291
14896
  if (!resolver) return this.#drop("mfu-no-resolver");
14292
14897
  if (!Number.isSafeInteger(data.byteLength) || data.byteLength <= 0)
14293
14898
  return this.#drop("mfu-empty-payload");
@@ -14308,6 +14913,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14308
14913
  mpuSequenceNumber: mpu.mpuSequenceNumber,
14309
14914
  movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
14310
14915
  sampleNumber: mfuDuHeader.sampleNumber,
14916
+ sequenceNumber: info.sequenceNumber,
14311
14917
  arrivedAt: Date.now()
14312
14918
  });
14313
14919
  return this.#drop("mfu-sample-timing-missing");
@@ -14333,7 +14939,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14333
14939
  info,
14334
14940
  resolver,
14335
14941
  options?.recovered === true,
14336
- options?.fecSbn
14942
+ options?.fecSbn,
14943
+ options?.fecSbnFirst
14337
14944
  );
14338
14945
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
14339
14946
  }
@@ -14426,7 +15033,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14426
15033
  info,
14427
15034
  resolver,
14428
15035
  options?.recovered === true,
14429
- options?.fecSbn
15036
+ options?.fecSbn,
15037
+ options?.fecSbnFirst
14430
15038
  );
14431
15039
  if (outcome.record !== void 0) return outcome.record;
14432
15040
  return this.#drop(outcome.reason);
@@ -14446,7 +15054,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14446
15054
  * attribution exists to keep readable. Leaving the choice at the call site
14447
15055
  * is what keeps both true.
14448
15056
  */
14449
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
15057
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
14450
15058
  const timing = resolver.sampleTiming(
14451
15059
  combined.mpuSequenceNumber,
14452
15060
  combined.movieFragmentSequenceNumber,
@@ -14463,6 +15071,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14463
15071
  );
14464
15072
  if (!meta) return { reason: "combined-meta-build-failed" };
14465
15073
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
15074
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
14466
15075
  if (!resolver.consumeSample(
14467
15076
  combined.mpuSequenceNumber,
14468
15077
  combined.movieFragmentSequenceNumber,
@@ -14696,6 +15305,9 @@ var MmtpContainerParser = class _MmtpContainerParser {
14696
15305
  for (const { sequencer } of this.#sequencers.values()) sequencer.discard();
14697
15306
  this.#sequencers.clear();
14698
15307
  this.#fecSequencer?.discard();
15308
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
15309
+ for (const head of awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
15310
+ }
14699
15311
  this.#timingStreams.clear();
14700
15312
  this.#pendingTimingSamples = 0;
14701
15313
  this.#reliableMoqStartupGate.clear();
@@ -14714,10 +15326,23 @@ var MmtpContainerParser = class _MmtpContainerParser {
14714
15326
  return resolver;
14715
15327
  }
14716
15328
  #awaitTiming(streamKey, head) {
14717
- const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
14718
- if (!awaitingTiming) return;
15329
+ const state = this.#timingStreams.get(streamKey);
15330
+ if (!state) return;
15331
+ if (!head.options?.recovered) {
15332
+ const kept = state.awaitingTiming.filter((queued) => !queued.options?.recovered || queued.sequenceNumber !== head.sequenceNumber);
15333
+ this.#recoveredHeadsAwaitingTiming.superseded += state.awaitingTiming.length - kept.length;
15334
+ state.awaitingTiming = kept;
15335
+ }
15336
+ const awaitingTiming = state.awaitingTiming;
14719
15337
  awaitingTiming.push(head);
14720
- if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
15338
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming.held++;
15339
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) {
15340
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
15341
+ }
15342
+ }
15343
+ /** Count a recovered head leaving the queue other than by replay or its source copy. */
15344
+ #leaveAwaitingTiming(head, outcome) {
15345
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming[outcome]++;
14721
15346
  }
14722
15347
  /**
14723
15348
  * Feed again the heads whose timing the FT=1 just admitted declares. That
@@ -14745,6 +15370,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14745
15370
  const state = this.#timingStreams.get(streamKey);
14746
15371
  if (!state) return;
14747
15372
  this.#timingStreams.delete(streamKey);
15373
+ for (const head of state.awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
14748
15374
  this.#pendingTimingSamples -= state.resolver.pendingSampleCount;
14749
15375
  if (this.#pendingTimingSamples < 0) {
14750
15376
  throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");
@@ -17950,7 +18576,18 @@ function keyframeOverlaySsId(header) {
17950
18576
  if (ext?.type !== KEYFRAME_OVERLAY_EXTENSION_TYPE || ext.data.length !== 4) return void 0;
17951
18577
  return new DataView(ext.data.buffer, ext.data.byteOffset, 4).getUint32(0);
17952
18578
  }
18579
+ function overlayBaseSsId(anchor, overlaySsId, restoredPsn, headerPsn) {
18580
+ if (anchor.baseSsId === void 0 || headerPsn !== restoredPsn) return void 0;
18581
+ return serial32Add(anchor.baseSsId, overlaySsId - anchor.overlaySsId | 0);
18582
+ }
18583
+ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
18584
+ if (offset === void 0 || offset !== unstampedOffset) return void 0;
18585
+ return headerPsn + offset >>> 0;
18586
+ }
18587
+ var OVERLAY_ROUTED_LIMIT = 1024;
18588
+ var OVERLAY_PENDING_LIMIT = 256;
17953
18589
  var OVERLAY_OFFSET_MPUS = 16;
18590
+ var OVERLAY_REBUILT_LIMIT = 256;
17954
18591
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
17955
18592
  function assertStreamIdentity(role, stream) {
17956
18593
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -18061,6 +18698,7 @@ var MmtpRouter = class {
18061
18698
  #provenance = /* @__PURE__ */ new Map();
18062
18699
  #onFlowProtected = null;
18063
18700
  #unadmittedListedDrops = 0;
18701
+ #admittedSourceDatagrams = 0;
18064
18702
  #unlistedRepairSetAside = 0;
18065
18703
  #assistBlocks = /* @__PURE__ */ new Map();
18066
18704
  #assistFailures = /* @__PURE__ */ new Map();
@@ -18117,6 +18755,26 @@ var MmtpRouter = class {
18117
18755
  * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
18118
18756
  */
18119
18757
  #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18758
+ /**
18759
+ * Per stream, the SS_ID offset at which a base recovery last showed the
18760
+ * sender's own packet_sequence_number: a recovered packet's header psn
18761
+ * equal to its SS_ID minus that offset. While it equals the stream's
18762
+ * current offset, no hop re-stamps the stream, and a packet's protected psn
18763
+ * names its base SS_ID within unstampedBaseSsId's limits (joint decoding of
18764
+ * an MPU no member of which arrived).
18765
+ */
18766
+ #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18767
+ /**
18768
+ * The same, shown by the overlay alone, before any base recovery did: a
18769
+ * packet it rebuilt whose base copy carries its protected psn
18770
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
18771
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
18772
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
18773
+ * make the base drop a late base copy of a keyframe the overlay never
18774
+ * finished, and lift a block's late-source cut, which nothing before
18775
+ * this offset did.
18776
+ */
18777
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18120
18778
  /**
18121
18779
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
18122
18780
  * not parsed, typically because its overlap copy was parsed first
@@ -18186,7 +18844,9 @@ var MmtpRouter = class {
18186
18844
  recovered: 0,
18187
18845
  restarts: 0,
18188
18846
  unsequencedDropped: 0,
18189
- protectedDropped: 0
18847
+ protectedDropped: 0,
18848
+ baseFed: 0,
18849
+ baseUndetermined: 0
18190
18850
  };
18191
18851
  /** Callback fired when a delta-track FEC block completes or fails. */
18192
18852
  #onDeltaBlockCompleteCb = null;
@@ -18359,7 +19019,7 @@ var MmtpRouter = class {
18359
19019
  const cb = this.#getFrameCallback(packetId);
18360
19020
  if (isVideo && !assembler) {
18361
19021
  if (frameMeta.recovered) {
18362
- this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb);
19022
+ this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb, meta.fecSbn);
18363
19023
  } else {
18364
19024
  this.#routeDirectSourceVideo(packetId, data, frameMeta, cb);
18365
19025
  }
@@ -18392,13 +19052,18 @@ var MmtpRouter = class {
18392
19052
  this.#onDeltaBlockCompleteCb?.(packetId, false);
18393
19053
  }
18394
19054
  };
18395
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
19055
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
18396
19056
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
18397
19057
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
18398
19058
  this.#onDeltaBlockCompleteCb?.(packetId, true);
18399
19059
  }
18400
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18401
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19060
+ if (span === void 0) {
19061
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19062
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19063
+ } else {
19064
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
19065
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
19066
+ }
18402
19067
  };
18403
19068
  }
18404
19069
  }
@@ -18443,8 +19108,9 @@ var MmtpRouter = class {
18443
19108
  }
18444
19109
  /**
18445
19110
  * FEC-recovered source symbols whose reconstructed header named a
18446
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
18447
- * a hop re-stamped the sequence after the sender protected the packet.
19111
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
19112
+ * or, rebuilt by the overlay, than their base copy carries: a hop
19113
+ * re-stamped the sequence after the sender protected the packet.
18448
19114
  */
18449
19115
  get restampedRecoveredSequenceCount() {
18450
19116
  return this.#restampedRecoveredSeqs;
@@ -18623,6 +19289,7 @@ var MmtpRouter = class {
18623
19289
  enableMseAssembler(packetId, config, catalogTrackName) {
18624
19290
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
18625
19291
  const previous = this.#mseAssemblers.get(assemblerKey);
19292
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
18626
19293
  if (previous) {
18627
19294
  previous.flush();
18628
19295
  previous.dispose();
@@ -18749,6 +19416,10 @@ var MmtpRouter = class {
18749
19416
  get keyframeOverlayStats() {
18750
19417
  return { ...this.#overlayStats };
18751
19418
  }
19419
+ /** Recovered FT=2 heads held for their FT=1, and how each left the wait (BLO-53369). */
19420
+ get recoveredHeadsAwaitingTiming() {
19421
+ return this.#parser.recoveredHeadsAwaitingTiming;
19422
+ }
18752
19423
  #isOverlayRepair(repairPacketId, repairTrackName) {
18753
19424
  return this.#overlayLegs.has(repairPacketId) || repairTrackName !== void 0 && this.#overlayRepairNames.has(repairTrackName);
18754
19425
  }
@@ -18769,7 +19440,8 @@ var MmtpRouter = class {
18769
19440
  fec,
18770
19441
  k,
18771
19442
  offsets: /* @__PURE__ */ new Map(),
18772
- moqBlocks: /* @__PURE__ */ new Set()
19443
+ moqBlocks: /* @__PURE__ */ new Set(),
19444
+ rebuilt: /* @__PURE__ */ new Map()
18773
19445
  };
18774
19446
  this.#overlays.set(repairPacketId, inst);
18775
19447
  return () => {
@@ -18799,12 +19471,18 @@ var MmtpRouter = class {
18799
19471
  */
18800
19472
  resetKeyframeOverlays(sourcePacketId, catalogTrackName) {
18801
19473
  for (const inst of this.#overlaysForSource(sourcePacketId, catalogTrackName)) this.#resetOverlay(inst);
19474
+ for (const [name, stream] of this.#streams.get(sourcePacketId) ?? []) {
19475
+ if (catalogTrackName !== void 0 && name !== catalogTrackName) continue;
19476
+ stream.overlayToBase.routed.clear();
19477
+ stream.overlayToBase.pending.clear();
19478
+ }
18802
19479
  }
18803
19480
  #resetOverlay(inst) {
18804
19481
  inst.fec.resetTrack(inst.repairPacketId, inst.streamName);
18805
19482
  inst.last = void 0;
18806
19483
  inst.offsets.clear();
18807
19484
  inst.moqBlocks.clear();
19485
+ inst.rebuilt.clear();
18808
19486
  }
18809
19487
  #overlaysForSource(sourcePacketId, catalogTrackName) {
18810
19488
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -18855,18 +19533,33 @@ var MmtpRouter = class {
18855
19533
  * A source packet that carries a 0x8B01 overlay SS_ID is also a symbol of
18856
19534
  * every overlay installed for its source, at that SS_ID, with the bytes the
18857
19535
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
18858
- * included (7.1, 7.4.3).
18859
- */
18860
- #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source) {
19536
+ * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
19537
+ * FEC reads it.
19538
+ *
19539
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
19540
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
19541
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
19542
+ * the stream unstamped at the SS_ID offset it states, for the release gate
19543
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
19544
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
19545
+ */
19546
+ #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
18861
19547
  if (this.#overlays.size === 0) return;
18862
19548
  const ssId = keyframeOverlaySsId(header);
18863
19549
  if (ssId === void 0) return;
19550
+ let rebuiltPsn;
18864
19551
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
18865
19552
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
19553
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
19554
+ inst.rebuilt.delete(ssId);
18866
19555
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
18867
19556
  if (identity !== null) {
18868
19557
  inst.offsets.delete(identity.mpuSequenceNumber);
18869
- inst.offsets.set(identity.mpuSequenceNumber, ssId - sequenceNumber >>> 0);
19558
+ inst.offsets.set(identity.mpuSequenceNumber, {
19559
+ psnOffset: ssId - sequenceNumber >>> 0,
19560
+ overlaySsId: ssId,
19561
+ ...baseSsId === void 0 ? {} : { baseSsId }
19562
+ });
18870
19563
  if (inst.offsets.size > OVERLAY_OFFSET_MPUS) inst.offsets.delete(inst.offsets.keys().next().value);
18871
19564
  }
18872
19565
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -18888,6 +19581,14 @@ var MmtpRouter = class {
18888
19581
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
18889
19582
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
18890
19583
  }
19584
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
19585
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
19586
+ if (rebuiltPsn !== sequenceNumber) {
19587
+ this.#restampedRecoveredSeqs++;
19588
+ } else if (baseSsId !== void 0) {
19589
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19590
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
19591
+ }
18891
19592
  }
18892
19593
  #noteOverlayMoqBlock(inst, blockStart) {
18893
19594
  inst.moqBlocks.add(blockStart);
@@ -18921,11 +19622,16 @@ var MmtpRouter = class {
18921
19622
  }
18922
19623
  /**
18923
19624
  * Route an overlay-recovered block's packets as source media of the
18924
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
18925
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
18926
- * base re-stamp, no block advance. Each packet's wire sequence is restored
18927
- * from its keyframe's own offset; without one, a stream the base never
18928
- * re-stamped keeps the header's sequence and any other drops the packet.
19625
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
19626
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
19627
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
19628
+ * base FEC recovered does, so it waits behind base frames still in flight,
19629
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
19630
+ * longer than unanchored; one whose base SS_ID is undetermined has no
19631
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
19632
+ * advance. Each packet's wire sequence is restored from its keyframe's own
19633
+ * offset; without one, a stream the base never re-stamped keeps the
19634
+ * header's sequence and any other drops the packet.
18929
19635
  */
18930
19636
  #routeOverlayRecovered(inst, blockStart, recovered) {
18931
19637
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -18945,22 +19651,139 @@ var MmtpRouter = class {
18945
19651
  const streamKey = this.#mediaStreamKey(sourcePacketId, sourceName);
18946
19652
  const restamped = this.#restampedStreams.has(streamKey);
18947
19653
  const restored = /* @__PURE__ */ new Set();
19654
+ const baseSsIds = /* @__PURE__ */ new Map();
19655
+ const gateOnly = /* @__PURE__ */ new Set();
18948
19656
  const symbols = result.symbols.flatMap((sym) => {
18949
- const offset = inst.offsets.get(sym.fragment.mpuSequenceNumber);
18950
- if (offset !== void 0) {
18951
- const packetSequenceNumber = serial32Add(blockStart, sym.index) - offset >>> 0;
19657
+ const overlaySsId = serial32Add(blockStart, sym.index);
19658
+ const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
19659
+ if (anchor !== void 0) {
19660
+ const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
18952
19661
  restored.add(packetSequenceNumber);
18953
- return [{ ...sym, packetSequenceNumber }];
19662
+ const out = { ...sym, packetSequenceNumber };
19663
+ const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
19664
+ if (baseSsId !== void 0) {
19665
+ baseSsIds.set(sym.index, baseSsId);
19666
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19667
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
19668
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
19669
+ }
19670
+ }
19671
+ return [out];
19672
+ }
19673
+ if (!restamped) {
19674
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19675
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
19676
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
19677
+ if (baseSsId !== void 0) {
19678
+ baseSsIds.set(sym.index, baseSsId);
19679
+ if (fedSsId === void 0) gateOnly.add(sym.index);
19680
+ } else {
19681
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
19682
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
19683
+ }
19684
+ return [sym];
18954
19685
  }
18955
- if (!restamped) return [sym];
18956
19686
  this.#overlayStats.unsequencedDropped++;
18957
19687
  return [];
18958
19688
  });
18959
19689
  this.#overlayStats.recovered++;
19690
+ const mpuFirst = /* @__PURE__ */ new Map();
19691
+ for (const sym of symbols) {
19692
+ const ssId = baseSsIds.get(sym.index);
19693
+ const mpu = sym.fragment.mpuSequenceNumber;
19694
+ const first = mpuFirst.get(mpu);
19695
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
19696
+ }
19697
+ const firstSsIds = /* @__PURE__ */ new Map();
19698
+ for (const sym of symbols) {
19699
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
19700
+ }
18960
19701
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
18961
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
19702
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
19703
+ baseSsIds,
19704
+ firstSsIds
18962
19705
  });
18963
19706
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
19707
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
19708
+ }
19709
+ /**
19710
+ * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
19711
+ * its base block too, once its base SS_ID is determined (overlayBaseSsId,
19712
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
19713
+ * base recovery showed; `baseSsIds` holds no other),
19714
+ * so it is fed to the base decoder as a rebuilt source
19715
+ * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
19716
+ * fewer to solve, and its repair can recover the block's other packets.
19717
+ * A base block no repair has stated yet takes it when one does
19718
+ * (#feedPendingRebuilt).
19719
+ *
19720
+ * The overlay route already handled each packet fed (delivered it, or
19721
+ * held an untimed head for its FT=1), so a base recovery routes none of
19722
+ * them again (#routeVerifiedFecSymbols): a second recovered copy of a
19723
+ * held head would wait in the parser for timing its first copy consumed.
19724
+ * Only an overlay block decoded from multicast symbols alone is fed: with
19725
+ * a MoQ symbol in it, the base block's recovery would depend on bytes
19726
+ * that crossed no multicast socket, which the provenance counted from the
19727
+ * block's own arrivals cannot show.
19728
+ */
19729
+ #feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds) {
19730
+ const fec = this.#fecManager;
19731
+ const owner = inst.leg.sourcePacketId;
19732
+ const name = inst.leg.sourceCatalogTrackName;
19733
+ if (!fec?.feedRebuiltSourceSymbol || inst.moqBlocks.has(blockStart)) return;
19734
+ if (this.#classifyPacketId(owner) === null || fec.isTrackConfigured?.(owner) === false) return;
19735
+ const { duplicates, overlayToBase: { routed } } = this.#stream(owner, name);
19736
+ const feeds = [];
19737
+ for (const sym of symbols) {
19738
+ if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
19739
+ const ssId = baseSsIds.get(sym.index);
19740
+ if (ssId === void 0) {
19741
+ this.#overlayStats.baseUndetermined++;
19742
+ continue;
19743
+ }
19744
+ routed.delete(ssId);
19745
+ routed.add(ssId);
19746
+ if (routed.size > OVERLAY_ROUTED_LIMIT) routed.delete(routed.values().next().value);
19747
+ feeds.push([ssId, sym.rawSymbol]);
19748
+ }
19749
+ for (const [ssId, symbolData] of feeds) {
19750
+ if (this.#classifyPacketId(owner) === null) return;
19751
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
19752
+ }
19753
+ }
19754
+ /** Feed one rebuilt source to its base block, or keep it until a repair states that block. */
19755
+ #feedRebuiltToBase(owner, name, ssId, symbolData) {
19756
+ const fec = this.#fecManager;
19757
+ if (!fec?.feedRebuiltSourceSymbol) return;
19758
+ const coords = fec.locateIsoSource?.(owner, name, ssId);
19759
+ if (coords == null) {
19760
+ const pending = this.#stream(owner, name).overlayToBase.pending;
19761
+ pending.delete(ssId);
19762
+ pending.set(ssId, symbolData.slice());
19763
+ if (pending.size > OVERLAY_PENDING_LIMIT) pending.delete(pending.keys().next().value);
19764
+ return;
19765
+ }
19766
+ const fed = fec.feedRebuiltSourceSymbol(owner, ssId, symbolData, name);
19767
+ if (!fed.taken) return;
19768
+ this.#overlayStats.baseFed++;
19769
+ if (fed.recovered === null) return;
19770
+ const sbn = coords.sbn;
19771
+ this.#routeRecoveredBlock(sbn, fed.recovered, owner, name, () => {
19772
+ fec.cancelBlockTimeout(sbn, owner, name);
19773
+ fec.countRecovery(owner, sbn, name);
19774
+ fec.markBlockCompleted(sbn, owner, name);
19775
+ });
19776
+ }
19777
+ /** A repair stated `block`: the rebuilt sources that waited for it join it now. */
19778
+ #feedPendingRebuilt(owner, name, block) {
19779
+ const pending = this.#streams.get(owner)?.get(name)?.overlayToBase.pending;
19780
+ if (pending === void 0 || pending.size === 0) return;
19781
+ for (const [ssId, symbolData] of [...pending]) {
19782
+ if (this.#classifyPacketId(owner) === null) return;
19783
+ if (serial32Distance(block.start, ssId) >= block.length) continue;
19784
+ pending.delete(ssId);
19785
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
19786
+ }
18964
19787
  }
18965
19788
  /** fec-multicast-00 §6.6: report each base block whose RAP MFU fragments
18966
19789
  * the overlay restored, when the keyframe's FT=0 and FT=1 are held too. A
@@ -19100,6 +19923,10 @@ var MmtpRouter = class {
19100
19923
  get unadmittedListedDropCount() {
19101
19924
  return this.#unadmittedListedDrops;
19102
19925
  }
19926
+ /** 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. */
19927
+ get admittedSourceDatagramCount() {
19928
+ return this.#admittedSourceDatagrams;
19929
+ }
19103
19930
  /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
19104
19931
  get unlistedRepairSetAsideCount() {
19105
19932
  return this.#unlistedRepairSetAside;
@@ -19586,6 +20413,8 @@ var MmtpRouter = class {
19586
20413
  )) return;
19587
20414
  fec.noteBlockActivity?.(blockStart, ownerPacketId, catalogTrackName);
19588
20415
  fec.noteRepairGroupLength?.(blockStart, ownerPacketId, repair.rsbLength, catalogTrackName);
20416
+ this.#feedPendingRebuilt(ownerPacketId, catalogTrackName, placement.block);
20417
+ if (this.#classifyPacketId(ownerPacketId) === null) return;
19589
20418
  const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
19590
20419
  const recovered = fec.feedRepairSymbol(
19591
20420
  ownerPacketId,
@@ -19636,7 +20465,7 @@ var MmtpRouter = class {
19636
20465
  catalogTrackName
19637
20466
  )) continue;
19638
20467
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
19639
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
20468
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
19640
20469
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
19641
20470
  }
19642
20471
  if (payload.oversized) continue;
@@ -19723,6 +20552,8 @@ var MmtpRouter = class {
19723
20552
  this.#droppedPreSyncVideo.delete(streamKey);
19724
20553
  this.#latestVideoSeqByStream.delete(streamKey);
19725
20554
  this.#ssIdSeqOffsetByStream.delete(streamKey);
20555
+ this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
20556
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
19726
20557
  this.#multicastRapTwinByStream.delete(streamKey);
19727
20558
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
19728
20559
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -19849,6 +20680,12 @@ var MmtpRouter = class {
19849
20680
  * the outgoing stream stops. The hold is bounded by the incoming stream's
19850
20681
  * own RAP cadence, so no timer is involved.
19851
20682
  *
20683
+ * While the switch is staged, the FEC release gate lets a keyframe the
20684
+ * overlay rebuilt reach it, on either side, when the keyframe did before
20685
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
20686
+ * decides on what each side delivered, and the commit discards the gate's
20687
+ * frames of the outgoing stream.
20688
+ *
19852
20689
  * The commit is one synchronous transition inside the frame path: the
19853
20690
  * outgoing stream's already-admitted frames are released (its queued FEC
19854
20691
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -19899,6 +20736,9 @@ var MmtpRouter = class {
19899
20736
  droppedIncomingFrames: 0
19900
20737
  };
19901
20738
  this.#staged = state;
20739
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
20740
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
20741
+ }
19902
20742
  return {
19903
20743
  cancel: () => {
19904
20744
  if (this.#staged !== state) return false;
@@ -19981,7 +20821,17 @@ var MmtpRouter = class {
19981
20821
  */
19982
20822
  #routeParsedFrame(data, meta) {
19983
20823
  if (this.#classifyPacketId(meta.packetId) === null) return;
19984
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
20824
+ if (this.#staged !== null) {
20825
+ let consumed = false;
20826
+ this.#fecPokeDepth++;
20827
+ try {
20828
+ consumed = this.#interceptSwitchFrame(data, meta);
20829
+ } finally {
20830
+ this.#fecPokeDepth--;
20831
+ this.#flushPendingFecPokes();
20832
+ }
20833
+ if (consumed) return;
20834
+ }
19985
20835
  this.#deliverParsedFrame(data, meta);
19986
20836
  }
19987
20837
  #commitStreamSwitch(state, rap, reason) {
@@ -20133,12 +20983,16 @@ var MmtpRouter = class {
20133
20983
  this.#parser.deferFecRelease(work);
20134
20984
  } finally {
20135
20985
  this.#fecPokeDepth--;
20136
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
20137
- const pokes = [...this.#pendingFecPokes.values()];
20138
- this.#pendingFecPokes.clear();
20139
- for (const poke of pokes) {
20140
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20141
- }
20986
+ this.#flushPendingFecPokes();
20987
+ }
20988
+ }
20989
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
20990
+ #flushPendingFecPokes() {
20991
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
20992
+ const pokes = [...this.#pendingFecPokes.values()];
20993
+ this.#pendingFecPokes.clear();
20994
+ for (const poke of pokes) {
20995
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20142
20996
  }
20143
20997
  }
20144
20998
  }
@@ -20216,6 +21070,14 @@ var MmtpRouter = class {
20216
21070
  onRap: (packetId, catalogTrackName, ssId) => {
20217
21071
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
20218
21072
  },
21073
+ // A staged switch commits on when each side's frames reach it
21074
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
21075
+ // they did unanchored.
21076
+ releaseUnanchored: (packetId, catalogTrackName) => {
21077
+ const staged = this.#staged;
21078
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
21079
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
21080
+ },
20219
21081
  onReleased: (data, meta) => {
20220
21082
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
20221
21083
  const timing = meta.authoredTiming;
@@ -20357,6 +21219,7 @@ var MmtpRouter = class {
20357
21219
  const parsed = this.#parser.parsePacket(packet);
20358
21220
  if (!parsed) return;
20359
21221
  const info = parsed.info;
21222
+ if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
20360
21223
  if (source === "multicast" && !manifestAdmitted) {
20361
21224
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
20362
21225
  }
@@ -20638,7 +21501,8 @@ var MmtpRouter = class {
20638
21501
  parsed.header,
20639
21502
  info.sequenceNumber,
20640
21503
  info.rapFlag,
20641
- source
21504
+ source,
21505
+ fecPayloadId?.ssId
20642
21506
  );
20643
21507
  }
20644
21508
  }
@@ -20664,7 +21528,8 @@ var MmtpRouter = class {
20664
21528
  source: parserOptions?.source,
20665
21529
  deliveryProvenance: parserOptions?.deliveryProvenance,
20666
21530
  catalogTrackName: parserOptions?.catalogTrackName,
20667
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
21531
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
21532
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
20668
21533
  };
20669
21534
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
20670
21535
  else this.#parser.feed(packet, feedOptions);
@@ -20788,7 +21653,8 @@ var MmtpRouter = class {
20788
21653
  if (stream === void 0) {
20789
21654
  stream = {
20790
21655
  key: JSON.stringify([packetId, catalogTrackName ?? null]),
20791
- duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId))
21656
+ duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId)),
21657
+ overlayToBase: { routed: /* @__PURE__ */ new Set(), pending: /* @__PURE__ */ new Map() }
20792
21658
  };
20793
21659
  byName.set(catalogTrackName, stream);
20794
21660
  }
@@ -20903,8 +21769,16 @@ var MmtpRouter = class {
20903
21769
  this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
20904
21770
  this.#emitDirectVideo(packetId, data, meta, cb);
20905
21771
  }
20906
- #routeDirectRecoveredVideo(packetId, data, meta, cb) {
21772
+ #routeDirectRecoveredVideo(packetId, data, meta, cb, fecSbn) {
20907
21773
  const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);
21774
+ if (this.#isFecTrack(packetId)) {
21775
+ const high = this.#deliveredVideoHighWaterByStream.get(streamKey);
21776
+ if (fecSbn !== void 0 || high !== void 0 && authoredAdjacent(high, meta)) {
21777
+ this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
21778
+ this.#emitDirectVideo(packetId, data, meta, cb);
21779
+ return;
21780
+ }
21781
+ }
20908
21782
  this.#enqueueDirectRecoveredVideo(packetId, data, meta);
20909
21783
  const lastSourceTs = this.#lastDirectSourceVideoTsByStream.get(streamKey);
20910
21784
  this.#drainDirectRecoveredVideo(
@@ -21058,6 +21932,13 @@ var MmtpRouter = class {
21058
21932
  * frames by epoch only if pre-protection input ever matters.
21059
21933
  */
21060
21934
  #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete, assisted = false) {
21935
+ const overlayRouted = ownerPacketId == null ? void 0 : this.#streams.get(ownerPacketId)?.get(catalogTrackName)?.overlayToBase.routed;
21936
+ if (overlayRouted !== void 0 && overlayRouted.size > 0) {
21937
+ result = {
21938
+ ...result,
21939
+ symbols: result.symbols.filter((sym) => !overlayRouted.has(this.#fecAnchorForRecovered(blockId, sym.index)))
21940
+ };
21941
+ }
21061
21942
  const entry = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
21062
21943
  const receiver = entry === void 0 || entry === "ambiguous" ? entry : entry.receiver;
21063
21944
  const userAgent = !assisted && entry !== void 0 && entry !== "ambiguous" && entry.protected === true && entry.userAgent === true;
@@ -21114,7 +21995,12 @@ var MmtpRouter = class {
21114
21995
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
21115
21996
  if (ownerPacketId == null) return;
21116
21997
  if (this.#classifyPacketId(ownerPacketId) === null) return;
21117
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
21998
+ const fecSbnOf = (index) => {
21999
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
22000
+ const fecSbn = overlay.baseSsIds.get(index);
22001
+ const fecSbnFirst = overlay.firstSsIds.get(index);
22002
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
22003
+ };
21118
22004
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
21119
22005
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
21120
22006
  if (ssIdSeqOffset !== void 0) {
@@ -21122,7 +22008,10 @@ var MmtpRouter = class {
21122
22008
  ...result,
21123
22009
  symbols: result.symbols.map((sym) => {
21124
22010
  const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
21125
- if (wire === sym.packetSequenceNumber) return sym;
22011
+ if (wire === sym.packetSequenceNumber) {
22012
+ this.#unstampedSsIdSeqOffsetByStream.set(streamKey, ssIdSeqOffset);
22013
+ return sym;
22014
+ }
21126
22015
  this.#restampedRecoveredSeqs++;
21127
22016
  this.#restampedStreams.add(streamKey);
21128
22017
  return { ...sym, packetSequenceNumber: wire };
@@ -21158,16 +22047,29 @@ var MmtpRouter = class {
21158
22047
  }
21159
22048
  );
21160
22049
  }
21161
- result = {
21162
- ...result,
21163
- 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(
21164
- ownerPacketId,
21165
- sym.fragment.mpuSequenceNumber,
21166
- sym.fragment.movieFragmentSequenceNumber,
21167
- sym.fragment.sampleNumber,
21168
- catalogTrackName
21169
- ))
21170
- };
22050
+ const untimedHead = (sym) => sym.fragmentType === 2 && sym.fragment.fragmentationIndicator === 1 && sym.fragment.movieFragmentSequenceNumber !== void 0 && sym.fragment.sampleNumber !== void 0 && !this.#parser.hasAuthoredTimingFor(
22051
+ ownerPacketId,
22052
+ sym.fragment.mpuSequenceNumber,
22053
+ sym.fragment.movieFragmentSequenceNumber,
22054
+ sym.fragment.sampleNumber,
22055
+ catalogTrackName
22056
+ );
22057
+ for (const sym of result.symbols) {
22058
+ if (!untimedHead(sym) || this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) continue;
22059
+ this.#feedViaParser(
22060
+ sym.rawSymbol,
22061
+ { packetId: ownerPacketId, sequenceNumber: sym.packetSequenceNumber },
22062
+ void 0,
22063
+ {
22064
+ skipFecPayloadId: true,
22065
+ recovered: true,
22066
+ deliveryProvenance,
22067
+ ...fecSbnOf(sym.index),
22068
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
22069
+ }
22070
+ );
22071
+ }
22072
+ result = { ...result, symbols: result.symbols.filter((sym) => !untimedHead(sym)) };
21171
22073
  const gated = this.#isFecTrack(ownerPacketId);
21172
22074
  const assembler = this.#mseAssemblerFor(ownerPacketId, catalogTrackName);
21173
22075
  if (assembler) {
@@ -22644,6 +23546,12 @@ function isNonNegativeSafeInteger(value) {
22644
23546
  function isSymbolCounts(value) {
22645
23547
  return isRecord(value) && hasExactKeys(value, ["multicast", "moq"]) && isNonNegativeSafeInteger(value["multicast"]) && isNonNegativeSafeInteger(value["moq"]);
22646
23548
  }
23549
+ function isSpanFailure(value) {
23550
+ if (!isRecord(value) || !hasExactKeys(value, ["length", "sources"])) return false;
23551
+ const length = value["length"];
23552
+ const sources = value["sources"];
23553
+ return Number.isSafeInteger(length) && length > 0 && isNonNegativeSafeInteger(sources) && sources < length;
23554
+ }
22647
23555
  function isNullableNonNegative(value) {
22648
23556
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
22649
23557
  }
@@ -22663,7 +23571,10 @@ function isRepairLifecycleEvent(value) {
22663
23571
  case "recovered":
22664
23572
  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"]);
22665
23573
  case "failed":
22666
- return hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]);
23574
+ return hasExactKeys(
23575
+ value,
23576
+ "span" in value ? ["version", "type", "block", "blockClass", "symbols", "span"] : ["version", "type", "block", "blockClass", "symbols"]
23577
+ ) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]) && (!("span" in value) || isSpanFailure(value["span"]));
22667
23578
  case "repair-preempted":
22668
23579
  case "repair-deferred":
22669
23580
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
@@ -22872,6 +23783,8 @@ var MulticastManager = class {
22872
23783
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
22873
23784
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
22874
23785
  #repairReleases = /* @__PURE__ */ new Map();
23786
+ /** Protected repair flows owned by each live repair-endpoint release. */
23787
+ #repairProvenanceFlows = /* @__PURE__ */ new Map();
22875
23788
  /** Each source's catalog keyframe overlay, from its `ok` binding. */
22876
23789
  #overlayBindings = /* @__PURE__ */ new Map();
22877
23790
  /** Installed overlay decoders (`setKeyframeOverlayDecoder`), by source. */
@@ -22929,7 +23842,7 @@ var MulticastManager = class {
22929
23842
  onPublisherRestart: (packetId, catalogTrackName) => {
22930
23843
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
22931
23844
  },
22932
- onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
23845
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass, span) => {
22933
23846
  const pathCount = this.#fec.blockPathCount(
22934
23847
  sbn,
22935
23848
  packetId,
@@ -22947,7 +23860,8 @@ var MulticastManager = class {
22947
23860
  symbols: {
22948
23861
  multicast: pathCount?.multicastSymbols ?? 0,
22949
23862
  moq: pathCount?.moqSymbols ?? 0
22950
- }
23863
+ },
23864
+ ...span === void 0 ? {} : { span }
22951
23865
  });
22952
23866
  },
22953
23867
  onFrameGap: (decision) => {
@@ -23537,6 +24451,9 @@ var MulticastManager = class {
23537
24451
  this.#transport.onFailback((reason) => {
23538
24452
  const joined = this.#provenanceJoin;
23539
24453
  if (joined !== null) this.#router.unprotectProvenanceFlow(joined.flow);
24454
+ for (const flows of this.#repairProvenanceFlows.values()) {
24455
+ for (const flow of flows) this.#router.unprotectProvenanceFlow(flow);
24456
+ }
23540
24457
  this.#onFailback?.(reason);
23541
24458
  });
23542
24459
  }
@@ -23571,6 +24488,12 @@ var MulticastManager = class {
23571
24488
  "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
23572
24489
  );
23573
24490
  }
24491
+ if (provenanceFlow !== void 0) {
24492
+ const flow = multicastProvenanceFlowKey(provenanceFlow);
24493
+ if ([...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
24494
+ throw new TypeError(`[MulticastManager] join: provenance flow already registered by a repair endpoint: ${flow}`);
24495
+ }
24496
+ }
23574
24497
  const staged = this.#renditionSwitch;
23575
24498
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
23576
24499
  this.configureFec(config);
@@ -23578,8 +24501,8 @@ var MulticastManager = class {
23578
24501
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
23579
24502
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
23580
24503
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
23581
- this.#releaseProvenanceJoin();
23582
24504
  const provenance = config.provenance;
24505
+ this.#releaseProvenanceJoin();
23583
24506
  const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
23584
24507
  const ingress = protectedTracks === void 0 ? void 0 : {
23585
24508
  tracks: Object.freeze(
@@ -23632,8 +24555,13 @@ var MulticastManager = class {
23632
24555
  * feeds the flow's receiver; media datagrams are held until one admits them.
23633
24556
  */
23634
24557
  #joinProvenance(provenance, ingress) {
24558
+ this.#router.registerProvenanceFlow(ingress, this.#provenanceReceiver(provenance));
24559
+ this.#hookFailback();
24560
+ this.#provenanceJoin = { flow: ingress.flow };
24561
+ }
24562
+ #provenanceReceiver(provenance) {
23635
24563
  const { flow, auth } = provenance;
23636
- const receiver = new BcProvenanceV2Receiver({
24564
+ return new BcProvenanceV2Receiver({
23637
24565
  ...provenance.receiver,
23638
24566
  // The caller's ctx when it passes one, else the catalog's: an explicit
23639
24567
  // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
@@ -23650,9 +24578,6 @@ var MulticastManager = class {
23650
24578
  maxAuthDelayMs: flow.maxAuthDelayMs,
23651
24579
  manifestTimerMs: flow.manifestTimerMs
23652
24580
  });
23653
- this.#router.registerProvenanceFlow(ingress, receiver);
23654
- this.#hookFailback();
23655
- this.#provenanceJoin = { flow: ingress.flow };
23656
24581
  }
23657
24582
  /** Un-protect: drop the flow's hold queues (no expiry counted). */
23658
24583
  #releaseProvenanceJoin() {
@@ -23683,8 +24608,25 @@ var MulticastManager = class {
23683
24608
  * callback delivers must come from a subscription opened on
23684
24609
  * `options.gateway`. A callback that also merges another source (a MoQ or
23685
24610
  * WebSocket repair feed) must not name a native provider here.
24611
+ *
24612
+ * An endpoint's `provenance` makes its group a protected flow of its own
24613
+ * (multicast-02 7.2.7), registered here and released with the group; its
24614
+ * records ride in band on the group's port. On the user-agent path a
24615
+ * flow-less repair group of a protected track is set aside, never read, so
24616
+ * a player joining a protected catalog's repair groups passes it.
23686
24617
  */
23687
24618
  joinRepairEndpoints(endpoints, provider, options) {
24619
+ for (const { provenance, flow, source, group, port } of endpoints) {
24620
+ if (provenance === void 0) continue;
24621
+ if (flow !== void 0) {
24622
+ throw new TypeError("[MulticastManager] joinRepairEndpoints: an endpoint names provenance or flow, never both");
24623
+ }
24624
+ if (!sameIpAddress(source, provenance.flow.source) || !sameIpAddress(group, provenance.flow.groupAddress) || port !== provenance.flow.port) {
24625
+ throw new RangeError(
24626
+ "[MulticastManager] joinRepairEndpoints: provenance flow (S, G, port) must match the endpoint's source, group and port"
24627
+ );
24628
+ }
24629
+ }
23688
24630
  const releases = [];
23689
24631
  let released = false;
23690
24632
  const safely = (each) => {
@@ -23694,17 +24636,36 @@ var MulticastManager = class {
23694
24636
  console.warn("[MulticastManager] repair group release failed", error);
23695
24637
  }
23696
24638
  };
24639
+ const usedFlows = /* @__PURE__ */ new Set();
24640
+ const preparedProvenance = endpoints.map((endpoint) => {
24641
+ if (endpoint.provenance === void 0) return void 0;
24642
+ const flow = multicastProvenanceFlowKey(endpoint.provenance.flow);
24643
+ if (usedFlows.has(flow) || this.#provenanceJoin?.flow === flow || [...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
24644
+ throw new TypeError(`[MulticastManager] joinRepairEndpoints: provenance flow already registered: ${flow}`);
24645
+ }
24646
+ usedFlows.add(flow);
24647
+ return { flow, receiver: this.#provenanceReceiver(endpoint.provenance) };
24648
+ });
24649
+ const provenanceFlows = [];
23697
24650
  const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners.map((owner) => owner.instance !== "keyframe" ? owner : {
23698
24651
  ...owner,
23699
24652
  ownerTrackName: endpoint.tracks.find((t) => t.packetId === owner.ownerPacketId)?.name,
23700
24653
  repairTrackName: endpoint.tracks.find((t) => t.packetId === owner.packetId)?.name
23701
24654
  }));
23702
24655
  this.#applyRepairOwners(repairOwners);
23703
- for (const endpoint of endpoints) {
24656
+ for (const [index, endpoint] of endpoints.entries()) {
24657
+ const flow = endpoint.provenance === void 0 ? endpoint.flow : multicastProvenanceFlowKey(endpoint.provenance.flow);
23704
24658
  const ingress = {
23705
24659
  tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
23706
- ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
24660
+ ...flow === void 0 ? {} : { flow }
23707
24661
  };
24662
+ if (endpoint.provenance !== void 0) {
24663
+ const prepared = preparedProvenance[index];
24664
+ if (prepared === void 0) throw new Error("[MulticastManager] repair provenance preparation missing");
24665
+ this.#router.registerProvenanceFlow(ingress, prepared.receiver);
24666
+ provenanceFlows.push(prepared.flow);
24667
+ releases.push(() => this.#router.releaseProvenanceFlow(flow));
24668
+ }
23708
24669
  let sender;
23709
24670
  const feed = (packet, sourceAddress, ingressToFeed) => {
23710
24671
  if (released) return;
@@ -23734,7 +24695,7 @@ var MulticastManager = class {
23734
24695
  packetIds: endpoint.packetIds,
23735
24696
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
23736
24697
  // A protected repair group's records ride in band on its port (7.2.3).
23737
- ...endpoint.flow === void 0 ? {} : { protected: true }
24698
+ ...flow === void 0 ? {} : { protected: true }
23738
24699
  }, ingress).then((joined) => {
23739
24700
  if (!joined && !released) fail(transport.lastJoinOutcome);
23740
24701
  });
@@ -23743,9 +24704,12 @@ var MulticastManager = class {
23743
24704
  if (released) return;
23744
24705
  released = true;
23745
24706
  this.#repairReleases.delete(release);
24707
+ this.#repairProvenanceFlows.delete(release);
23746
24708
  for (const each of releases.splice(0)) safely(each);
23747
24709
  };
23748
24710
  this.#repairReleases.set(release, repairOwners);
24711
+ this.#repairProvenanceFlows.set(release, provenanceFlows);
24712
+ if (provenanceFlows.length) this.#hookFailback();
23749
24713
  return release;
23750
24714
  }
23751
24715
  #applyRepairOwners(owners) {
@@ -24327,10 +25291,12 @@ var MulticastManager = class {
24327
25291
  * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
24328
25292
  * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
24329
25293
  * pending hole and reported here, and `closeIsoHoles` must be called for it
24330
- * once its range FETCH ends (or none is sent).
25294
+ * once its range FETCH ends (or none is sent). `onExpired` is told of a
25295
+ * pending hole the stream runs past the locator's horizon: returning true,
25296
+ * the caller closes it (`closeIsoHoles`); otherwise it is discarded.
24331
25297
  */
24332
- onUndelimitedLoss(cb) {
24333
- this.#fec.setUndelimitedLossHandler(cb);
25298
+ onUndelimitedLoss(cb, onExpired) {
25299
+ this.#fec.setUndelimitedLossHandler(cb, onExpired ?? null);
24334
25300
  }
24335
25301
  /**
24336
25302
  * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
@@ -24566,7 +25532,8 @@ var MulticastManager = class {
24566
25532
  "stream" in event ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
24567
25533
  ...event,
24568
25534
  block: Object.freeze({ ...event.block }),
24569
- ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {}
25535
+ ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {},
25536
+ ..."span" in event && event.span !== void 0 ? { span: Object.freeze({ ...event.span }) } : {}
24570
25537
  }
24571
25538
  );
24572
25539
  if (this.#logRepairLifecycle) {