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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/browser-runtime.js +1447 -179
  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 +105 -14
  12. package/dist/fec-manager.d.ts.map +1 -1
  13. package/dist/fec-manager.js +502 -58
  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 +104 -12
  29. package/dist/mmtp-container-parser.d.ts.map +1 -1
  30. package/dist/mmtp-container-parser.js +308 -27
  31. package/dist/mmtp-container-parser.js.map +2 -2
  32. package/dist/mmtp-container-parser.no-modules.js +310 -30
  33. package/dist/mmtp-container-parser.no-modules.js.map +3 -3
  34. package/dist/mmtp-decode-pipeline.js +307 -27
  35. package/dist/mmtp-decode-pipeline.js.map +2 -2
  36. package/dist/mmtp-router.d.ts +36 -8
  37. package/dist/mmtp-router.d.ts.map +1 -1
  38. package/dist/mmtp-router.js +675 -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 +1267 -152
  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 +307 -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 +307 -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 +571 -32
  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 +341 -32
  64. package/src/mmtp-router.ts +600 -55
  65. package/src/multicast-manager.ts +136 -16
  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();
@@ -2369,7 +2454,10 @@ var FECManager = class _FECManager {
2369
2454
  // arrives via onBlockRecovered callback.
2370
2455
  this.onBlockStarted = null;
2371
2456
  this.onBlockComplete = null;
2372
- /** 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
+ */
2373
2461
  this.onBlockFailed = null;
2374
2462
  /**
2375
2463
  * Fired once per stream when its Worker decoder stops being routable.
@@ -2411,12 +2499,24 @@ var FECManager = class _FECManager {
2411
2499
  * for it, which it must be.
2412
2500
  */
2413
2501
  this.#onUndelimitedLoss = null;
2502
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
2503
+ this.#onIsoHoleExpired = null;
2414
2504
  /** A block every symbol of which vanished was created by SBN evidence. */
2415
2505
  this.onBlockVanished = null;
2416
2506
  /** A block reached a terminal state (completed, recovered, or failed). */
2417
2507
  this.onBlockResolved = null;
2418
2508
  /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
2419
2509
  this.onSourceDiscontinuity = null;
2510
+ /**
2511
+ * The span and tolerance the catalog states for a keyframe overlay
2512
+ * installed over a source track (draft-ramadan-moq-mmt-02 7.4.1: the
2513
+ * overlay instance's own interleaveDepthMs and reorderToleranceMs), or
2514
+ * undefined while none is installed. A stated block only a late source
2515
+ * can complete, and a frame whose gap may hide a RAP behind a span only a
2516
+ * late source can fill, also wait for that overlay's repair
2517
+ * (#overlayLateWaitMs).
2518
+ */
2519
+ this.keyframeOverlayTiming = null;
2420
2520
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
2421
2521
  /**
2422
2522
  * A recovered source symbol. Return false when admission refused the
@@ -2453,7 +2553,9 @@ var FECManager = class _FECManager {
2453
2553
  #pendingWorkerCleanupBounds;
2454
2554
  #blockSourceCounts;
2455
2555
  #blockSourceEsis;
2556
+ #blockRebuiltEsis;
2456
2557
  #blockAuthoredLengths;
2558
+ #isoSpanKeys;
2457
2559
  #ssbLengthConflictCount;
2458
2560
  #blockRepairRsIds;
2459
2561
  #blockRsbLengths;
@@ -2520,6 +2622,7 @@ var FECManager = class _FECManager {
2520
2622
  #decoderUnavailableEvents;
2521
2623
  #repairSymbolSizeMismatchCount;
2522
2624
  #onUndelimitedLoss;
2625
+ #onIsoHoleExpired;
2523
2626
  #encodeTrackName(catalogTrackName) {
2524
2627
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
2525
2628
  if (encoded === void 0) {
@@ -2991,7 +3094,10 @@ var FECManager = class _FECManager {
2991
3094
  timer.handle = null;
2992
3095
  this.#requestRepair(sbn, packetId, catalogTrackName);
2993
3096
  };
2994
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
3097
+ timer.handle = setTimeout(
3098
+ onFire,
3099
+ this.#receiptAtMs === void 0 ? Math.max(0, deadlineMs - performance.now()) : this.#receiptTimerDelayMs(deadlineMs, 0)
3100
+ );
2995
3101
  this.#repairDeadlines.set(key, timer);
2996
3102
  }
2997
3103
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -3135,8 +3241,14 @@ var FECManager = class _FECManager {
3135
3241
  * Vanished blocks are not enumerated here: their starts are unknown until a
3136
3242
  * repair states them. The SS_IDs between two stated blocks become one
3137
3243
  * repair-less span when the later block's repair arrives (placeIsoRepair).
3244
+ *
3245
+ * A `held` source arrived before its block was known and is fed only now
3246
+ * that a repair, a span or a closed hole placed it: how far its block start
3247
+ * then lies behind the frontier measures how long the receiver held it, not
3248
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
3249
+ * it (BLO-52085).
3138
3250
  */
3139
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
3251
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn, held = false) {
3140
3252
  const streamKey = this.#streamKey(packetId, catalogTrackName);
3141
3253
  const now = performance.now();
3142
3254
  const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
@@ -3175,7 +3287,7 @@ var FECManager = class _FECManager {
3175
3287
  return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
3176
3288
  };
3177
3289
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
3178
- if (symbol === "source" && window2 !== null && this.#blockPrecedes(sbn, previous.sbn) && (this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId) || psn !== void 0 && anchor !== void 0 && serial32Precedes(ssId, anchor.ssId) && psn !== anchor.psn && !sentInOrder({ ssId, psn }, anchor))) {
3290
+ if (symbol === "source" && window2 !== null && this.#blockPrecedes(sbn, previous.sbn) && (!held && this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId) || psn !== void 0 && anchor !== void 0 && serial32Precedes(ssId, anchor.ssId) && psn !== anchor.psn && !sentInOrder({ ssId, psn }, anchor))) {
3179
3291
  discontinuity();
3180
3292
  return;
3181
3293
  }
@@ -3437,17 +3549,21 @@ var FECManager = class _FECManager {
3437
3549
  this.#blockWaitDeadlinesMs.delete(key);
3438
3550
  this.#repairHoldUntilMs.delete(key);
3439
3551
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
3440
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName);
3552
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs);
3441
3553
  };
3442
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)));
3554
+ timer.handle = setTimeout(
3555
+ onFire,
3556
+ this.#receiptAtMs === void 0 ? Math.max(1, Math.ceil(deadlineMs - nowMs)) : this.#receiptTimerDelayMs(deadlineMs, 1)
3557
+ );
3443
3558
  this.#activeBlocks.set(key, timer);
3444
3559
  this.#indexBlockKey(key, sbn, packetId);
3445
3560
  }
3446
3561
  /**
3447
3562
  * Hand a block whose delivery is over to its decoder for finalization: the
3448
- * datagram deadline fired, or the ordered relay moved past it.
3563
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
3564
+ * is when it was due: its deadline, or now.
3449
3565
  */
3450
- #finalizeExpiredBlock(sbn, packetId, catalogTrackName) {
3566
+ #finalizeExpiredBlock(sbn, packetId, catalogTrackName, dueAtMs = performance.now()) {
3451
3567
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
3452
3568
  if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
3453
3569
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -3463,7 +3579,7 @@ var FECManager = class _FECManager {
3463
3579
  if (workerClient) {
3464
3580
  this.#pendingWorkerCleanups.add(key);
3465
3581
  this.#pendingWorkerCleanupClients.set(key, workerClient);
3466
- this.#boundOwedCleanup(key, packetId, workerClient);
3582
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs);
3467
3583
  workerClient.cleanup(sbn);
3468
3584
  } else {
3469
3585
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
@@ -3775,7 +3891,9 @@ var FECManager = class _FECManager {
3775
3891
  }
3776
3892
  resetMap(this.#blockSourceCounts);
3777
3893
  resetMap(this.#blockSourceEsis);
3894
+ resetMap(this.#blockRebuiltEsis);
3778
3895
  resetMap(this.#blockAuthoredLengths);
3896
+ resetSet(this.#isoSpanKeys);
3779
3897
  resetMap(this.#blockRepairRsIds);
3780
3898
  resetMap(this.#blockRsbLengths);
3781
3899
  resetMap(this.#heldLayerStates);
@@ -3899,7 +4017,9 @@ var FECManager = class _FECManager {
3899
4017
  dropMap(this.#pendingWorkerCleanupClients);
3900
4018
  dropMap(this.#blockSourceCounts);
3901
4019
  dropMap(this.#blockSourceEsis);
4020
+ dropMap(this.#blockRebuiltEsis);
3902
4021
  dropMap(this.#blockAuthoredLengths);
4022
+ dropSet(this.#isoSpanKeys);
3903
4023
  dropMap(this.#blockRepairRsIds);
3904
4024
  dropMap(this.#blockRsbLengths);
3905
4025
  dropMap(this.#blockPathCounts);
@@ -4061,6 +4181,9 @@ var FECManager = class _FECManager {
4061
4181
  this.#unindexBlockKey(key);
4062
4182
  }
4063
4183
  }
4184
+ if (isSourceSymbol && source === "multicast") {
4185
+ this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), sbn + esi >>> 0, packetId, catalogTrackName);
4186
+ }
4064
4187
  return true;
4065
4188
  }
4066
4189
  #observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName) {
@@ -4170,8 +4293,10 @@ var FECManager = class _FECManager {
4170
4293
  }
4171
4294
  /**
4172
4295
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
4173
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
4174
- * Undefined for a block that is not open.
4296
+ * (SSB_length) and RSB_length (each undefined until a repair stated it; a
4297
+ * repair-less span states its length, and RSB_length 0 when it is longer
4298
+ * than K, since no repair can reach it). Undefined for a block that is not
4299
+ * open.
4175
4300
  */
4176
4301
  blockSymbolCounts(sbn, packetId, catalogTrackName) {
4177
4302
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -4239,8 +4364,9 @@ var FECManager = class _FECManager {
4239
4364
  return true;
4240
4365
  }
4241
4366
  /**
4242
- * Drop a block's repair hold: its FETCH ended without delivering. The block
4243
- * falls back to its multicast wait, which may already have passed.
4367
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
4368
+ * back only a repair that cannot complete it. The block falls back to its
4369
+ * multicast wait, which may already have passed.
4244
4370
  */
4245
4371
  releaseRepairHold(sbn, packetId, catalogTrackName) {
4246
4372
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -4286,7 +4412,7 @@ var FECManager = class _FECManager {
4286
4412
  }
4287
4413
  const trackConfig = this.#trackConfigs.get(packetId);
4288
4414
  if (trackConfig === void 0) return void 0;
4289
- return Math.max(1, trackConfig.timeoutMs - this.#repairDeadlineMs(trackConfig));
4415
+ return Math.max(1, this.#repairGraceMs(trackConfig, this.#multicastWaitMs(trackConfig)));
4290
4416
  }
4291
4417
  /** True once configureTrack/setFecDecoder/setFecWorker configured this packetId. */
4292
4418
  // -----------------------------------------------------------------------
@@ -4378,6 +4504,8 @@ var FECManager = class _FECManager {
4378
4504
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
4379
4505
  const evictedBefore = locator.heldEvicted;
4380
4506
  const held = locator.hold(ssId, source);
4507
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
4508
+ if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
4381
4509
  const evicted = locator.heldEvicted - evictedBefore;
4382
4510
  if (evicted > 0) {
4383
4511
  const before = this.#isoHeldEvictedCount;
@@ -4398,17 +4526,20 @@ var FECManager = class _FECManager {
4398
4526
  * contradicts a known block is refused (counted) and must be dropped.
4399
4527
  */
4400
4528
  placeIsoRepair(packetId, catalogTrackName, ssStart, ssbLength) {
4401
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength);
4529
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
4530
+ const placement = locator.placeRepair(ssStart, ssbLength);
4531
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
4402
4532
  if (placement.status !== "placed") {
4403
4533
  this.#isoRepairRefusedCount++;
4404
4534
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
4405
4535
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`);
4406
4536
  }
4537
+ if (placement.ofSpan !== void 0) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName);
4407
4538
  return placement;
4408
4539
  }
4540
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName));
4409
4541
  if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
4410
4542
  if (placement.hole !== void 0) {
4411
- const locator = this.#isoLocatorFor(packetId, catalogTrackName);
4412
4543
  const hole = placement.hole.block;
4413
4544
  const previous = locator.blockEndingAt(hole.start);
4414
4545
  const loss = {
@@ -4429,17 +4560,29 @@ var FECManager = class _FECManager {
4429
4560
  * `handler`, instead of a repair-less span; null restores spans. Set by the
4430
4561
  * range repair scheduler; applies to every stream from its next gap. The
4431
4562
  * handler and the deferral are one setting, so no hole is ever created with
4432
- * nobody to close it.
4563
+ * nobody to close it. `onExpired` is told of each pending hole the stream
4564
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
4565
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
4566
+ * reported; otherwise the hole is discarded with its sources.
4433
4567
  */
4434
- setUndelimitedLossHandler(handler) {
4568
+ setUndelimitedLossHandler(handler, onExpired = null) {
4435
4569
  this.#onUndelimitedLoss = handler;
4570
+ this.#onIsoHoleExpired = handler === null ? null : onExpired;
4436
4571
  this.#deferIsoGaps = handler !== null;
4437
4572
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
4438
4573
  }
4574
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
4575
+ #settleExpiredIsoHoles(locator, packetId, catalogTrackName) {
4576
+ for (const hole of locator.takeExpiredHoles()) {
4577
+ const expired = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length };
4578
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length);
4579
+ }
4580
+ }
4439
4581
  /**
4440
- * The range repair for a hole ended: every hole still pending inside
4441
- * `[start, start + length)` becomes a repair-less span. Returns those spans
4442
- * with the held sources they placed, for the caller to feed (MmtpRouter).
4582
+ * The range repair for a hole ended: every hole inside `[start, start +
4583
+ * length)`, pending or expired, becomes a repair-less span. Returns those
4584
+ * spans with the held sources they placed, for the caller to feed
4585
+ * (MmtpRouter).
4443
4586
  */
4444
4587
  closeIsoHoles(packetId, catalogTrackName, start, length) {
4445
4588
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
@@ -4455,10 +4598,25 @@ var FECManager = class _FECManager {
4455
4598
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
4456
4599
  * SS_ID of which vanished resolves through its deadline like any vanished
4457
4600
  * block.
4601
+ *
4602
+ * A span longer than K holds more than one block (SSB_length <= K), and the
4603
+ * locator states no block inside a span, only one exactly its range
4604
+ * (IsoBlockLocator.placeRepair): no repair, multicast or FETCHed, can ever
4605
+ * reach it. Its repair group is empty, so the repair scheduler FETCHes no
4606
+ * Group of it (group-cannot-complete). Every span still keeps its whole
4607
+ * wait (#lateSourceWaitMs): failing it early released the frames behind it
4608
+ * past a keyframe the overlay was still rebuilding (BLO-52085). The release
4609
+ * gate lets those frames go once only a late source can fill the gap
4610
+ * before them, as long after they arrived as the gap's decision allows
4611
+ * (isoRepairlessWaitMs).
4458
4612
  */
4459
4613
  #openIsoSpan(span, packetId, catalogTrackName) {
4460
4614
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
4461
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
4615
+ if (!this.#blockAuthoredLengths.has(key)) {
4616
+ this.#blockAuthoredLengths.set(key, span.block.length);
4617
+ this.#isoSpanKeys.add(key);
4618
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0);
4619
+ }
4462
4620
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
4463
4621
  }
4464
4622
  /**
@@ -4496,6 +4654,62 @@ var FECManager = class _FECManager {
4496
4654
  }
4497
4655
  return lost;
4498
4656
  }
4657
+ /**
4658
+ * The release gate's wait, from a frame's arrival, for the SS_IDs strictly
4659
+ * between two released frames' SS_IDs once only a late source can still
4660
+ * fill them, else undefined. That is when every one missing (neither
4661
+ * arrived nor held) lies in a repair-less span longer than K, which no
4662
+ * repair can state a block of (#openIsoSpan), or in a stated block its
4663
+ * own repair group cannot complete every SS_ID of which it misses lies
4664
+ * between them (so the gap's decision covers all it lost), and a multicast
4665
+ * source at or past `toSsId` arrived, so each is lost or reordered behind
4666
+ * it (a MoQ source shows nothing: MoQ streams overtake one another). The
4667
+ * span or block itself keeps its own wait.
4668
+ *
4669
+ * The wait is the late-symbol allowance, unless `rapMayHide`: the gap may
4670
+ * hold a RAP packet an installed keyframe overlay can still rebuild (its
4671
+ * decision stalls, or it ends at a RAP that may lie past a whole MPU).
4672
+ * Then the frame waits as a stated block its group cannot complete does
4673
+ * (#overlayLateWaitMs): the allowance alone with no overlay installed, the
4674
+ * overlay's span plus the larger of the allowance and its tolerance, or,
4675
+ * for an overlay that states no span, the span's whole wait (undefined).
4676
+ * So does `rapNext` (the gap ends at the RAP that opens the next MPU) when
4677
+ * the gap holds a stated block's loss.
4678
+ */
4679
+ isoRepairlessWaitMs(packetId, catalogTrackName, fromSsId, toSsId, rapMayHide = false, rapNext = false) {
4680
+ const config = this.#trackConfigs.get(packetId);
4681
+ if (config === void 0 || !_FECManager.#hasCatalogTiming(config)) return void 0;
4682
+ const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
4683
+ if (locator === void 0 || !locator.coversBetween(fromSsId, toSsId)) return void 0;
4684
+ const newestSource = locator.newestSource;
4685
+ if (newestSource === void 0 || serial32Precedes(newestSource, toSsId)) return void 0;
4686
+ let repairless = false;
4687
+ let stated = false;
4688
+ for (const block of locator.blocksBetween(fromSsId, toSsId)) {
4689
+ const key = this.#blockKey(block.start, packetId, catalogTrackName);
4690
+ if (this.#completedBlocks.has(key)) continue;
4691
+ if (block.span && block.length > locator.kMax) {
4692
+ repairless = true;
4693
+ continue;
4694
+ }
4695
+ const received = this.#blockSourceEsis.get(key);
4696
+ const rebuilt = this.#blockRebuiltEsis.get(key);
4697
+ let missesInGap = false;
4698
+ let missesOutside = false;
4699
+ for (let esi = 0; esi < block.length; esi++) {
4700
+ const ssId = serial32Add(block.start, esi);
4701
+ if (received?.has(esi) || locator.isHeld(ssId)) continue;
4702
+ if (serial32Precedes(fromSsId, ssId) && serial32Precedes(ssId, toSsId)) missesInGap = true;
4703
+ else if (!rebuilt?.has(esi)) missesOutside = true;
4704
+ }
4705
+ if (!missesInGap) continue;
4706
+ if (missesOutside || block.span || !this.#groupCannotComplete(key)) return void 0;
4707
+ repairless = stated = true;
4708
+ }
4709
+ if (!repairless) return void 0;
4710
+ const waitMs = rapMayHide || stated && rapNext ? this.#overlayLateWaitMs(packetId, catalogTrackName, config) : this.#multicastWaitMs(config) - config.interleaveDepthMs;
4711
+ return waitMs === void 0 ? void 0 : Math.max(0, waitMs);
4712
+ }
4499
4713
  /**
4500
4714
  * iso-ssbg1-v1 block location: repair symbols it refused, oversize sources,
4501
4715
  * the sources held now for a block no repair has stated yet, and the held
@@ -4799,11 +5013,14 @@ var FECManager = class _FECManager {
4799
5013
  });
4800
5014
  client.onCleanupComplete((sbn) => {
4801
5015
  if (this.#releasedWorkerClients.has(client)) return;
4802
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
5016
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
5017
+ const cleanupKeys = owed.filter((key) => {
4803
5018
  const block = this.#parseBlockKey(key);
4804
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
5019
+ return block.packetId === packetId && block.sbn === sbn;
4805
5020
  });
4806
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
5021
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
5022
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
5023
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
4807
5024
  });
4808
5025
  client.onError((msg, code) => {
4809
5026
  const requestedKind = code ?? msg;
@@ -4873,9 +5090,11 @@ var FECManager = class _FECManager {
4873
5090
  * fail deadline already passed, so failing it is the decision that deadline
4874
5091
  * made. A late ack then finds nothing owed and is a no-op.
4875
5092
  */
4876
- #boundOwedCleanup(key, packetId, client) {
5093
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
4877
5094
  this.#clearOwedCleanupBound(key);
4878
5095
  const bound = {
5096
+ dueAtMs,
5097
+ askedAtMs: performance.now(),
4879
5098
  handle: setTimeout(() => {
4880
5099
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
4881
5100
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -4973,7 +5192,15 @@ var FECManager = class _FECManager {
4973
5192
  this.#isoSourceOversizeCount++;
4974
5193
  return null;
4975
5194
  }
4976
- const sbn = located.block.start;
5195
+ return this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, located.block.start);
5196
+ }
5197
+ /**
5198
+ * Hand one placed source symbol to the stream's decoder: its Worker, which
5199
+ * answers through onFrame (null here), or its synchronous decoder, whose
5200
+ * recovered block is returned. `sbn` is the SS_Start of the block a repair
5201
+ * stated for `ssId`.
5202
+ */
5203
+ #feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn) {
4977
5204
  const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
4978
5205
  const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey);
4979
5206
  const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
@@ -5002,6 +5229,74 @@ var FECManager = class _FECManager {
5002
5229
  }
5003
5230
  return recovered;
5004
5231
  }
5232
+ /**
5233
+ * Feed a source symbol of this stream that another FEC instance over the
5234
+ * same packets rebuilt: a keyframe overlay recovery whose base SS_ID the
5235
+ * caller determined (draft-ramadan-moq-mmt-02 7.1, 7.4.4; joint decoding,
5236
+ * BLO-52085). It joins its block's decoder as a received source would, so
5237
+ * it reduces the erasures the block still has to solve, but it is not a
5238
+ * network arrival: no transport accounting, no classification evidence,
5239
+ * no deadline refresh, and it never makes a block clean.
5240
+ *
5241
+ * Only a block a repair stated takes one (a repair-less span has no
5242
+ * decoder block). A block that is terminal, or already holds that source,
5243
+ * does not. The symbol is the exact protected packet, unpadded, as
5244
+ * feedSourceSymbol takes it.
5245
+ *
5246
+ * `recovered` is the block the synchronous decoder completed with it; the
5247
+ * caller routes it and completes the block, as for any recovery. When
5248
+ * every source of the block is then present, received or rebuilt, and no
5249
+ * decoder returned it (a Worker answers asynchronously, and reports such a
5250
+ * block as clean on its own side), the block is completed here as
5251
+ * recovered, with nothing left to route.
5252
+ */
5253
+ feedRebuiltSourceSymbol(packetId, ssId, symbolData, catalogTrackName) {
5254
+ if (!this.#hasBlockProfile(packetId)) return NOT_TAKEN;
5255
+ const located = this.#isoLocatorFor(packetId, catalogTrackName).locate(ssId);
5256
+ if (located === null || located.block.span) return NOT_TAKEN;
5257
+ if (!ssbg1FitsSymbol(symbolData.byteLength, this.#trackConfig(packetId).symbolSize)) return NOT_TAKEN;
5258
+ const sbn = located.block.start;
5259
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
5260
+ if (this.#completedBlocks.has(key) || this.#blockSourceEsis.get(key)?.has(located.esi)) return NOT_TAKEN;
5261
+ let rebuilt = this.#blockRebuiltEsis.get(key);
5262
+ if (rebuilt?.has(located.esi)) return NOT_TAKEN;
5263
+ if (rebuilt === void 0) {
5264
+ rebuilt = /* @__PURE__ */ new Set();
5265
+ this.#blockRebuiltEsis.set(key, rebuilt);
5266
+ }
5267
+ const config = this.#trackConfigs.get(packetId);
5268
+ const wasShort = config !== void 0 && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) !== void 0;
5269
+ rebuilt.add(located.esi);
5270
+ const recovered = this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn);
5271
+ if (recovered === null && !this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName)) {
5272
+ if (wasShort && this.#activeBlocks.has(key) && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) === void 0) {
5273
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, this.#multicastWaitMs(config));
5274
+ }
5275
+ }
5276
+ return { taken: true, recovered };
5277
+ }
5278
+ /**
5279
+ * A block that holds every one of its `length` sources, received or
5280
+ * rebuilt by another instance, with at least one rebuilt, is recovered:
5281
+ * every packet of it was delivered, by its own arrival or by the instance
5282
+ * that rebuilt it, so nothing is routed. Returns whether it completed it.
5283
+ */
5284
+ #completeWhenSourcesPresent(key, sbn, length, packetId, catalogTrackName) {
5285
+ const rebuilt = this.#blockRebuiltEsis.get(key);
5286
+ if (rebuilt === void 0 || this.#completedBlocks.has(key)) return false;
5287
+ let present = rebuilt.size;
5288
+ for (const esi of this.#blockSourceEsis.get(key) ?? []) if (!rebuilt.has(esi)) present++;
5289
+ if (present < length) return false;
5290
+ this.#traceLifecycle("recovered", sbn, packetId, catalogTrackName);
5291
+ this.countRecovery(packetId, sbn, catalogTrackName);
5292
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
5293
+ if (catalogTrackName === void 0) {
5294
+ this.onBlockComplete?.(sbn, packetId);
5295
+ } else {
5296
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName);
5297
+ }
5298
+ return true;
5299
+ }
5005
5300
  /**
5006
5301
  * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
5007
5302
  * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
@@ -5204,8 +5499,115 @@ var FECManager = class _FECManager {
5204
5499
  this.#completeCleanBlock(blockKey, sbn, packetId, catalogTrackName);
5205
5500
  return null;
5206
5501
  }
5502
+ if (recovered === null) this.#shortenUnrecoverableWait(blockKey, sbn, packetId, catalogTrackName);
5207
5503
  return recovered;
5208
5504
  }
5505
+ /**
5506
+ * A first-arrival multicast source, held or placed. A datagram flow keeps
5507
+ * its sources in send order, so one that moves the stream's newest source
5508
+ * position past a block leaves the sources that block still misses
5509
+ * reordered behind it at best: it shortens the wait of every block it
5510
+ * passed that only a late source can complete. MoQ is left out: its streams
5511
+ * can overtake one another, so a MoQ source shows nothing about the sources
5512
+ * sent before it.
5513
+ */
5514
+ #noteMulticastSource(locator, ssId, packetId, catalogTrackName) {
5515
+ const previous = locator.newestSource;
5516
+ if (!locator.noteSource(ssId) || previous === void 0) return;
5517
+ for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
5518
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
5519
+ this.#shortenUnrecoverableWait(
5520
+ this.#blockKey(block.start, packetId, catalogTrackName),
5521
+ block.start,
5522
+ packetId,
5523
+ catalogTrackName
5524
+ );
5525
+ }
5526
+ }
5527
+ /**
5528
+ * The wait of a block that only a late source can complete (BLO-52085): a
5529
+ * repair stated it, its received sources plus every symbol its repair group
5530
+ * carries (RSB_length) are short of K' (the repair scheduler's
5531
+ * group-cannot-complete), and a later source of the stream has arrived, so
5532
+ * a source it misses is lost or reordered behind that one. The span, which
5533
+ * covers repair symbols paced after its sources, buys it nothing: it waits
5534
+ * the late-symbol allowance alone, the multicast wait less the span (the
5535
+ * catalog tolerance or the measured delivery gap). Undefined for any other
5536
+ * block. While a keyframe overlay is installed, the block waits for its
5537
+ * repair too (#overlayLateWaitMs). A repair-less span keeps its whole
5538
+ * wait, even one longer than K whose group is empty (#openIsoSpan): its
5539
+ * resolution is what releases the frames behind it, and failing it early
5540
+ * released them past a keyframe the overlay was still rebuilding, which
5541
+ * then arrived stale. The release gate lets them go instead
5542
+ * (isoRepairlessWaitMs).
5543
+ */
5544
+ #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
5545
+ if (this.#isoSpanKeys.has(key) || !this.#groupCannotComplete(key)) return void 0;
5546
+ const authoredLength = this.#blockAuthoredLengths.get(key);
5547
+ const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
5548
+ if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
5549
+ return void 0;
5550
+ }
5551
+ return this.#overlayLateWaitMs(packetId, catalogTrackName, config);
5552
+ }
5553
+ /**
5554
+ * A repair stated the block, and its sources plus every symbol its repair
5555
+ * group carries (RSB_length) are short of its SSB_length.
5556
+ */
5557
+ #groupCannotComplete(key) {
5558
+ const authoredLength = this.#blockAuthoredLengths.get(key);
5559
+ const rsbLength = this.#blockRsbLengths.get(key);
5560
+ if (authoredLength === void 0 || rsbLength === void 0) return false;
5561
+ let present = this.#blockSourceCounts.get(key) ?? 0;
5562
+ const received = this.#blockSourceEsis.get(key);
5563
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
5564
+ return present + rsbLength < authoredLength;
5565
+ }
5566
+ /**
5567
+ * How long a loss only a late source or an installed keyframe overlay can
5568
+ * still fill waits once a later source passed it: the late-symbol
5569
+ * allowance alone (the multicast wait less the span) while no overlay is
5570
+ * installed. An installed one (keyframeOverlayTiming) may still rebuild a
5571
+ * RAP packet the loss took: a second FEC instance over the same packets
5572
+ * (draft-ramadan-moq-mmt-02 7.4), whose repair is paced across its own
5573
+ * span, unrelated to the base's. That packet can complete a stated block
5574
+ * (feedRebuiltSourceSymbol), or play behind a span; giving the loss up
5575
+ * first lets the release gate pass the keyframe, whose rebuild then lands
5576
+ * stale. The overlay repair of a packet the loss took goes out within the
5577
+ * overlay's span of that packet (fec-core-00 9.3), and the later source was
5578
+ * sent after it, so the loss waits that span plus the larger of the
5579
+ * allowance and the overlay's own tolerance. An overlay that states no
5580
+ * span (its block may then span keyframes), or one whose wait is not
5581
+ * shorter than the whole multicast wait, leaves the whole wait: undefined.
5582
+ */
5583
+ #overlayLateWaitMs(packetId, catalogTrackName, config) {
5584
+ const waitMs = this.#multicastWaitMs(config);
5585
+ const allowanceMs = waitMs - config.interleaveDepthMs;
5586
+ const overlay = this.keyframeOverlayTiming?.(packetId, catalogTrackName);
5587
+ if (overlay === void 0) return allowanceMs;
5588
+ const overlaySpanMs = overlay.interleaveDepthMs ?? 0;
5589
+ const overlayWaitMs = overlaySpanMs + Math.max(allowanceMs, overlay.reorderToleranceMs ?? 0);
5590
+ return overlaySpanMs > 0 && overlayWaitMs < waitMs ? overlayWaitMs : void 0;
5591
+ }
5592
+ /**
5593
+ * Bring an open block's wait in to its late-source wait, when it has one.
5594
+ * Never later than it is armed: only a source can complete such a block,
5595
+ * so a repair of its group (paced across the span) must not keep it open.
5596
+ */
5597
+ #shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName) {
5598
+ if (!this.#activeBlocks.has(key)) return;
5599
+ const config = this.#trackConfigs.get(packetId);
5600
+ if (config === void 0) return;
5601
+ const waitMs = this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config);
5602
+ if (waitMs === void 0) return;
5603
+ const armedAtMs = this.#blockWaitDeadlinesMs.get(key);
5604
+ this.#armBlockTimeout(
5605
+ sbn,
5606
+ packetId,
5607
+ catalogTrackName,
5608
+ armedAtMs === void 0 ? waitMs : Math.min(waitMs, armedAtMs - this.#receiptNow())
5609
+ );
5610
+ }
5209
5611
  /**
5210
5612
  * Record a block's authored SSB_length from a repair symbol. Returns false,
5211
5613
  * leaving the block unchanged, when the symbol contradicts the block: a
@@ -5303,12 +5705,13 @@ var FECManager = class _FECManager {
5303
5705
  * the inactivity deadline on each symbol, records the symbol's in-band
5304
5706
  * classification evidence, and marks the block clean when all of its
5305
5707
  * authored source symbols arrived: the SSB_length a repair symbol declared,
5306
- * otherwise K.
5708
+ * otherwise K. `held` marks a source held unplaced since it arrived and
5709
+ * placed only now (see #noteSbnSeen).
5307
5710
  *
5308
5711
  * Throws for a packetId that was never configured, so a classified block
5309
5712
  * never reads the manager-global K or timeout.
5310
5713
  */
5311
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
5714
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
5312
5715
  const trackConfig = this.#trackConfigs.get(packetId);
5313
5716
  if (trackConfig === void 0) {
5314
5717
  throw new Error(
@@ -5324,7 +5727,8 @@ var FECManager = class _FECManager {
5324
5727
  catalogTrackName,
5325
5728
  "source",
5326
5729
  evidence.packetSequenceNumber,
5327
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
5730
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
5731
+ held
5328
5732
  );
5329
5733
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
5330
5734
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -5360,6 +5764,15 @@ var FECManager = class _FECManager {
5360
5764
  this.#completeCleanBlock(key, sbn, packetId, catalogTrackName);
5361
5765
  return;
5362
5766
  }
5767
+ if (this.#blockRebuiltEsis.has(key) && this.#completeWhenSourcesPresent(
5768
+ key,
5769
+ sbn,
5770
+ this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? authoredLength,
5771
+ packetId,
5772
+ catalogTrackName
5773
+ )) {
5774
+ return;
5775
+ }
5363
5776
  this.noteBlockActivity(sbn, packetId, catalogTrackName, true);
5364
5777
  }
5365
5778
  #completeCleanBlock(key, sbn, packetId, catalogTrackName) {
@@ -5368,7 +5781,9 @@ var FECManager = class _FECManager {
5368
5781
  this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
5369
5782
  this.#blockSourceCounts.delete(key);
5370
5783
  this.#blockSourceEsis.delete(key);
5784
+ this.#blockRebuiltEsis.delete(key);
5371
5785
  this.#blockAuthoredLengths.delete(key);
5786
+ this.#isoSpanKeys.delete(key);
5372
5787
  this.#blockRepairRsIds.delete(key);
5373
5788
  this.#blockRsbLengths.delete(key);
5374
5789
  this.#markTerminal(key, sbn, packetId, true);
@@ -5399,6 +5814,19 @@ var FECManager = class _FECManager {
5399
5814
  #receiptNow() {
5400
5815
  return this.#receiptAtMs ?? performance.now();
5401
5816
  }
5817
+ /**
5818
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
5819
+ * scope: counted from the receipt time, as the timer of a symbol fed when
5820
+ * it was received was, less the whole ms since. So it fires on the tick
5821
+ * that timer would have, never later than a delay counted from now, and
5822
+ * its handler still re-arms a timer that fires before its deadline.
5823
+ * Counted from now, a deadline set from the receipt time is rounded up
5824
+ * from another fraction of a ms (BLO-52085).
5825
+ */
5826
+ #receiptTimerDelayMs(deadlineMs, minMs) {
5827
+ const receivedAtMs = this.#receiptAtMs;
5828
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
5829
+ }
5402
5830
  /**
5403
5831
  * A held packet admitted late arms from its (earlier) receipt time; that
5404
5832
  * never pulls in a deadline later activity already armed. Outside a
@@ -5434,10 +5862,20 @@ var FECManager = class _FECManager {
5434
5862
  this.#repairDeadlineMs(trackConfig)
5435
5863
  );
5436
5864
  }
5437
- this.#armBlockTimeout(sbn, packetId, catalogTrackName, timeoutMs);
5865
+ if (!sourceProgress && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) !== void 0) {
5866
+ this.#shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName);
5867
+ return;
5868
+ }
5869
+ this.#armBlockTimeout(
5870
+ sbn,
5871
+ packetId,
5872
+ catalogTrackName,
5873
+ this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) ?? timeoutMs
5874
+ );
5438
5875
  }
5439
5876
  #failBlock(sbn, packetId, catalogTrackName) {
5440
5877
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
5878
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
5441
5879
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
5442
5880
  this.#clearRepairDeadline(key);
5443
5881
  this.#clearBlockTimer(key);
@@ -5447,6 +5885,7 @@ var FECManager = class _FECManager {
5447
5885
  }
5448
5886
  this.#blockSourceCounts.delete(key);
5449
5887
  this.#blockSourceEsis.delete(key);
5888
+ this.#blockRebuiltEsis.delete(key);
5450
5889
  this.#blockAuthoredLengths.delete(key);
5451
5890
  this.#blockRepairRsIds.delete(key);
5452
5891
  this.#blockRsbLengths.delete(key);
@@ -5456,7 +5895,8 @@ var FECManager = class _FECManager {
5456
5895
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
5457
5896
  this.#fecStats.blocksFailed++;
5458
5897
  this.#statsForPacket(packetId).blocksFailed++;
5459
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5898
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5899
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
5460
5900
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
5461
5901
  }
5462
5902
  /**
@@ -5485,7 +5925,9 @@ var FECManager = class _FECManager {
5485
5925
  this.#retireBlockClass(key, block.sbn, block.packetId, block.catalogTrackName);
5486
5926
  this.#blockSourceCounts.delete(key);
5487
5927
  this.#blockSourceEsis.delete(key);
5928
+ this.#blockRebuiltEsis.delete(key);
5488
5929
  this.#blockAuthoredLengths.delete(key);
5930
+ this.#isoSpanKeys.delete(key);
5489
5931
  this.#blockRepairRsIds.delete(key);
5490
5932
  this.#blockRsbLengths.delete(key);
5491
5933
  this.#clearBlockTimer(key);
@@ -5576,7 +6018,9 @@ var FECManager = class _FECManager {
5576
6018
  this.#blockKeysBySbn.clear();
5577
6019
  this.#blockSourceCounts.clear();
5578
6020
  this.#blockSourceEsis.clear();
6021
+ this.#blockRebuiltEsis.clear();
5579
6022
  this.#blockAuthoredLengths.clear();
6023
+ this.#isoSpanKeys.clear();
5580
6024
  this.#blockRepairRsIds.clear();
5581
6025
  this.#blockRsbLengths.clear();
5582
6026
  this.#heldLayerStates.clear();
@@ -6955,9 +7399,9 @@ async function openSubscription(rx, openedPromise, options, packetIds) {
6955
7399
  } catch (error) {
6956
7400
  throw new MulticastError("subscription-failed", "MulticastReceiver did not open", error);
6957
7401
  }
6958
- if (rx.integrityScheme !== INTEGRITY_SCHEME) {
7402
+ if (opened.integrityScheme !== INTEGRITY_SCHEME) {
6959
7403
  await rx.close();
6960
- throw unsupported(`integrity scheme ${String(rx.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
7404
+ throw unsupported(`integrity scheme ${String(opened.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
6961
7405
  }
6962
7406
  const events = new EventTarget();
6963
7407
  let state = "connected";
@@ -7076,6 +7520,7 @@ var MOQT_PUBLISHER_PRIORITY = Object.freeze({
7076
7520
  });
7077
7521
 
7078
7522
  // node_modules/@blockcast/mmt-transport/dist/amt-gateway.js
7523
+ var MAX_PENDING_PACKETS = 256;
7079
7524
  var AMTGatewayManager = class {
7080
7525
  subscriptions = /* @__PURE__ */ new Map();
7081
7526
  messageHandler;
@@ -7199,7 +7644,7 @@ var AMTGatewayManager = class {
7199
7644
  if (!subscription.handshakeComplete) {
7200
7645
  const queue = this.pendingPackets.get(subscriptionId);
7201
7646
  const packetData2 = data;
7202
- if (queue) {
7647
+ if (queue && queue.length < MAX_PENDING_PACKETS) {
7203
7648
  queue.push({
7204
7649
  data: packetData2.data,
7205
7650
  remoteAddress: packetData2.remoteAddress,
@@ -10292,9 +10737,10 @@ function isH264IntraSlice(nal) {
10292
10737
  const sliceType = readH264SliceType(nal);
10293
10738
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
10294
10739
  }
10740
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
10295
10741
  function readH264SliceType(nal) {
10296
10742
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
10297
- const rbsp = removeEmulationPrevention(nal.subarray(1));
10743
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
10298
10744
  const state = { bitOffset: 0 };
10299
10745
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
10300
10746
  return readUnsignedExpGolomb(rbsp, state);
@@ -10441,6 +10887,96 @@ if (void 0) {
10441
10887
  ]))).toBe(false);
10442
10888
  });
10443
10889
  });
10890
+ describe("readH264SliceType", () => {
10891
+ const wholeNalSliceType = (nal) => {
10892
+ if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
10893
+ const rbsp = removeEmulationPrevention(nal.subarray(1));
10894
+ const state = { bitOffset: 0 };
10895
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null;
10896
+ return readUnsignedExpGolomb(rbsp, state);
10897
+ };
10898
+ const hex2 = (text2) => Uint8Array.from(text2.match(/../g), (byte) => parseInt(byte, 16));
10899
+ const ue = (value) => {
10900
+ const code = (value + 1).toString(2);
10901
+ return "0".repeat(code.length - 1) + code;
10902
+ };
10903
+ const sliceNal = (bits) => {
10904
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, "0").match(/.{8}/g);
10905
+ const nal = [1];
10906
+ let zeros = 0;
10907
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
10908
+ if (zeros >= 2 && byte <= 3) {
10909
+ nal.push(3);
10910
+ zeros = 0;
10911
+ }
10912
+ nal.push(byte);
10913
+ zeros = byte === 0 ? zeros + 1 : 0;
10914
+ }
10915
+ return Uint8Array.from(nal);
10916
+ };
10917
+ const x264Slices = [
10918
+ ["64x48 P", hex2("419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176"), 5, false],
10919
+ ["64x48 B", hex2("419e414212fffeeade283707cb70f7"), 6, false],
10920
+ ["64x48 non-IDR I", hex2(
10921
+ "4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39a527e23eb34c8167fd"
10922
+ ), 7, true],
10923
+ ["1280x720 B, escape at byte 10", hex2(
10924
+ "01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e19b75d92170917306190f262fd58268702db2eff86a9651e48"
10925
+ ), 6, false],
10926
+ ["1280x720 P, escape at byte 15", hex2(
10927
+ "41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f02c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e85302da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3"
10928
+ ), 5, false],
10929
+ ["1280x720 B, escape at byte 22", hex2("01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352"), 6, false],
10930
+ ["7680x4320 IDR, first_mb_in_slice 97440", hex2(
10931
+ "650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9"
10932
+ ), null, true],
10933
+ ["7680x4320 P, first_mb_in_slice 32640", hex2(
10934
+ "410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020"
10935
+ ), 5, false],
10936
+ ["7680x4320 P, first_mb_in_slice 97440", hex2(
10937
+ "410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806"
10938
+ ), 5, false]
10939
+ ];
10940
+ const syntheticSlices = [
10941
+ ["an escape inside first_mb_in_slice", sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
10942
+ ["an escape between the fields", sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
10943
+ ["an escape inside slice_type", sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
10944
+ ["the longest fields, five escapes", sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
10945
+ ["the largest values", sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
10946
+ ["31 leading zeros in first_mb_in_slice", sliceNal(`${"0".repeat(31)}1`), null],
10947
+ ["31 leading zeros in slice_type", sliceNal(`1${"0".repeat(31)}1`), null],
10948
+ ["escapes running past the slice header", sliceNal(ue(0) + ue(5) + "0".repeat(400)), 5]
10949
+ ];
10950
+ test("reads the slice_type of real and synthetic slices", () => {
10951
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
10952
+ expect(readH264SliceType(nal), name).toBe(sliceType);
10953
+ }
10954
+ });
10955
+ test("matches the whole-NAL unescape at every truncation", () => {
10956
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
10957
+ for (let end = 0; end <= nal.length; end++) {
10958
+ const cut = nal.subarray(0, end);
10959
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut));
10960
+ }
10961
+ }
10962
+ });
10963
+ test("matches the whole-NAL unescape on zero-heavy NAL units", () => {
10964
+ const bytes = [0, 0, 0, 3, 1, 2, 128, 255];
10965
+ let seed = 1;
10966
+ const next = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) >>> 16;
10967
+ for (let i = 0; i < 5e3; i++) {
10968
+ const nal = new Uint8Array(2 + next() % 63);
10969
+ nal[0] = 65;
10970
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length];
10971
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal));
10972
+ }
10973
+ });
10974
+ test("classifies the x264 slices as keyframes or not", () => {
10975
+ for (const [name, nal, , keyframe] of x264Slices) {
10976
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe);
10977
+ }
10978
+ });
10979
+ });
10444
10980
  describe("avccToAnnexB", () => {
10445
10981
  test("converts with SPS/PPS on keyframe", () => {
10446
10982
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -13142,9 +13678,21 @@ var IsoBmffTimingResolver = class {
13142
13678
  }
13143
13679
  #track = null;
13144
13680
  #fragments = /* @__PURE__ */ new Map();
13681
+ /** First sample of each pending fragment, kept in `#delivered` with its sample count. */
13682
+ #firstSamples = /* @__PURE__ */ new Map();
13683
+ /**
13684
+ * First sample and sample count of the newest fragments whose every slot was
13685
+ * cleared. Abandonment counts: `releaseSample` clears a slot too, which
13686
+ * matches the combiner, since it retires an abandoned sample as well.
13687
+ */
13688
+ #delivered = /* @__PURE__ */ new Map();
13145
13689
  #pendingSamples = 0;
13146
13690
  #evictedSamples = 0;
13147
13691
  #lastMovieFragmentRejection = null;
13692
+ /** True once an FT=0 has bound the track that FT=1 timing is read against. */
13693
+ get initialized() {
13694
+ return this.#track !== null;
13695
+ }
13148
13696
  get pendingSampleCount() {
13149
13697
  return this.#pendingSamples;
13150
13698
  }
@@ -13168,7 +13716,14 @@ var IsoBmffTimingResolver = class {
13168
13716
  this.#track = timing;
13169
13717
  return true;
13170
13718
  }
13171
- addMovieFragment(mpuSequenceNumber, data, additionalSampleLimit = this.maxPendingSamples) {
13719
+ /**
13720
+ * `recovered` marks an FEC-recovered copy. A recovered block hands back
13721
+ * every FT=1 it holds, the received ones included, so a recovered copy of a
13722
+ * fragment whose samples are all done is a duplicate: admitting it again
13723
+ * would charge stale timing and could displace the live MPU's. A source
13724
+ * copy is still admitted again (a rendition switch re-arms timing that way).
13725
+ */
13726
+ addMovieFragment(mpuSequenceNumber, data, additionalSampleLimit = this.maxPendingSamples, recovered = false) {
13172
13727
  this.#lastMovieFragmentRejection = null;
13173
13728
  if (!Number.isInteger(additionalSampleLimit) || additionalSampleLimit < 0) {
13174
13729
  this.#lastMovieFragmentRejection = "invalid";
@@ -13194,6 +13749,8 @@ var IsoBmffTimingResolver = class {
13194
13749
  (sample, index) => sample !== null && sameSample(sample, parsed.samples[index])
13195
13750
  );
13196
13751
  }
13752
+ const delivered = recovered ? this.#delivered.get(key) : void 0;
13753
+ if (delivered && delivered.sampleCount === parsed.samples.length && sameSample(delivered.first, parsed.samples[0])) return true;
13197
13754
  let freed = 0;
13198
13755
  while (this.#fragments.size > 0 && (this.#pendingSamples + parsed.samples.length > this.maxPendingSamples || parsed.samples.length - freed > additionalSampleLimit)) {
13199
13756
  freed += this.#evictOldestFragment();
@@ -13207,6 +13764,7 @@ var IsoBmffTimingResolver = class {
13207
13764
  return false;
13208
13765
  }
13209
13766
  this.#fragments.set(key, [...parsed.samples]);
13767
+ this.#firstSamples.set(key, parsed.samples[0]);
13210
13768
  this.#pendingSamples += parsed.samples.length;
13211
13769
  return true;
13212
13770
  }
@@ -13264,6 +13822,7 @@ var IsoBmffTimingResolver = class {
13264
13822
  let live = 0;
13265
13823
  for (const sample of samples) if (sample !== null) live++;
13266
13824
  this.#fragments.delete(oldest);
13825
+ this.#firstSamples.delete(oldest);
13267
13826
  this.#pendingSamples -= live;
13268
13827
  this.#evictedSamples += live;
13269
13828
  return live;
@@ -13279,12 +13838,23 @@ var IsoBmffTimingResolver = class {
13279
13838
  if (!samples || !samples[index]) return false;
13280
13839
  samples[index] = null;
13281
13840
  this.#pendingSamples--;
13282
- if (samples.every((value) => value === null)) this.#fragments.delete(key);
13841
+ if (samples.every((value) => value === null)) {
13842
+ this.#fragments.delete(key);
13843
+ const first = this.#firstSamples.get(key);
13844
+ this.#firstSamples.delete(key);
13845
+ this.#delivered.delete(key);
13846
+ this.#delivered.set(key, { first, sampleCount: samples.length });
13847
+ if (this.#delivered.size > this.maxPendingSamples) {
13848
+ this.#delivered.delete(this.#delivered.keys().next().value);
13849
+ }
13850
+ }
13283
13851
  return true;
13284
13852
  }
13285
13853
  reset() {
13286
13854
  this.#track = null;
13287
13855
  this.#fragments.clear();
13856
+ this.#firstSamples.clear();
13857
+ this.#delivered.clear();
13288
13858
  this.#pendingSamples = 0;
13289
13859
  }
13290
13860
  };
@@ -13454,6 +14024,9 @@ function authoredGap(before, after) {
13454
14024
  function ssIdAfter(a, b) {
13455
14025
  return (a - b | 0) > 0;
13456
14026
  }
14027
+ function holdsRebuilt(stream) {
14028
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
14029
+ }
13457
14030
  var FecReleaseSequencer = class {
13458
14031
  #streams = /* @__PURE__ */ new Map();
13459
14032
  #gate;
@@ -13516,6 +14089,7 @@ var FecReleaseSequencer = class {
13516
14089
  stream.lastSbn = void 0;
13517
14090
  stream.discontinuity = false;
13518
14091
  stream.rapSsId = void 0;
14092
+ stream.sourced = false;
13519
14093
  }
13520
14094
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
13521
14095
  this.#recordStat("droppedStale");
@@ -13542,6 +14116,7 @@ var FecReleaseSequencer = class {
13542
14116
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
13543
14117
  else hi = mid;
13544
14118
  }
14119
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
13545
14120
  stream.buf.splice(lo, 0, frame);
13546
14121
  this.#drainUnlessDeferred(stream);
13547
14122
  }
@@ -13577,6 +14152,41 @@ var FecReleaseSequencer = class {
13577
14152
  }
13578
14153
  return false;
13579
14154
  }
14155
+ /**
14156
+ * These streams' sink is being replaced by one that has seen no source
14157
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
14158
+ * release to the sink being replaced the frames the unanchored path had
14159
+ * already released to it (#cursorPassed): there they waited in its queue,
14160
+ * which its replacement flushes. A stream that holds none is not drained:
14161
+ * it holds nothing the anchor kept back, and a drain would still force out
14162
+ * a frame held past the hold limit, which before the anchor waited for the
14163
+ * next push. Then treat the streams as unsourced until a source frame is
14164
+ * released.
14165
+ */
14166
+ unsource(packetId, catalogTrackName) {
14167
+ for (const stream of this.#streams.values()) {
14168
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
14169
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
14170
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
14171
+ else this.#drain(stream, true);
14172
+ }
14173
+ stream.sourced = false;
14174
+ }
14175
+ }
14176
+ }
14177
+ /**
14178
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
14179
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
14180
+ * packetId.
14181
+ */
14182
+ holdsRebuilt(packetId, catalogTrackName) {
14183
+ for (const stream of this.#streams.values()) {
14184
+ if (stream.packetId !== packetId) continue;
14185
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
14186
+ if (holdsRebuilt(stream)) return true;
14187
+ }
14188
+ return false;
14189
+ }
13580
14190
  /** Re-evaluate held gaps after FEC state changed. */
13581
14191
  poke(streamKey) {
13582
14192
  if (streamKey !== void 0) {
@@ -13668,16 +14278,32 @@ var FecReleaseSequencer = class {
13668
14278
  last: null,
13669
14279
  lastSbn: void 0,
13670
14280
  discontinuity: false,
13671
- rapSsId: void 0
14281
+ rapSsId: void 0,
14282
+ sourced: false,
14283
+ draining: 0
13672
14284
  };
13673
14285
  this.#streams.set(streamKey, stream);
13674
14286
  }
13675
14287
  return stream;
13676
14288
  }
13677
- #drain(stream) {
14289
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
14290
+ #drain(stream, asUnanchored = false) {
14291
+ stream.draining++;
14292
+ try {
14293
+ this.#drainLoop(stream, asUnanchored);
14294
+ } finally {
14295
+ stream.draining--;
14296
+ }
14297
+ }
14298
+ #drainLoop(stream, asUnanchored) {
13678
14299
  while (stream.buf.length > 0 && stream.last !== null) {
13679
14300
  const head = stream.buf[0];
13680
14301
  const last = stream.last;
14302
+ if (compareFrameOrder(head, last) <= 0) {
14303
+ stream.buf.shift();
14304
+ this.#release(stream, head, void 0);
14305
+ continue;
14306
+ }
13681
14307
  if (stream.discontinuity) {
13682
14308
  stream.discontinuity = false;
13683
14309
  stream.buf.shift();
@@ -13691,9 +14317,10 @@ var FecReleaseSequencer = class {
13691
14317
  }
13692
14318
  const headSbn = head.meta.fecSbn;
13693
14319
  const from = stream.lastSbn ?? headSbn;
13694
- const to = headSbn ?? stream.lastSbn;
14320
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
13695
14321
  let lost = [];
13696
14322
  const unanchored = from === void 0 && to === void 0;
14323
+ let unresolved = false;
13697
14324
  if (from !== void 0 && to !== void 0) {
13698
14325
  const resolved = this.#gate.resolvedLoss(
13699
14326
  stream.packetId,
@@ -13702,7 +14329,8 @@ var FecReleaseSequencer = class {
13702
14329
  Math.max(from, to),
13703
14330
  from
13704
14331
  );
13705
- if (resolved === null) {
14332
+ unresolved = resolved === null;
14333
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored) && !this.#unrepairableWaitOver(stream, last, head, from, to)) {
13706
14334
  const heldMs = performance.now() - head.arrivedAtMs;
13707
14335
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
13708
14336
  this.#recordStat("forcedWindowFlushes");
@@ -13710,22 +14338,69 @@ var FecReleaseSequencer = class {
13710
14338
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
13711
14339
  continue;
13712
14340
  }
13713
- lost = resolved;
14341
+ lost = resolved ?? [];
13714
14342
  }
13715
14343
  stream.buf.shift();
13716
14344
  this.#release(
13717
14345
  stream,
13718
14346
  head,
13719
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
14347
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
13720
14348
  );
13721
14349
  }
13722
14350
  }
14351
+ /**
14352
+ * The head has waited out a gap only a late source can still fill
14353
+ * (FecReleaseGate.unrepairableWaitMs). Not yet: the gate is asked to poke
14354
+ * the stream when it has (`wakeAt`), since no packet may come by then.
14355
+ */
14356
+ #unrepairableWaitOver(stream, last, head, from, to) {
14357
+ const waitMs = this.#gate.unrepairableWaitMs?.(last, head, from, to);
14358
+ if (waitMs === void 0) return false;
14359
+ const atMs = head.arrivedAtMs + waitMs;
14360
+ if (performance.now() >= atMs) return true;
14361
+ this.#gate.wakeAt?.(stream.packetId, stream.catalogTrackName, atMs);
14362
+ return false;
14363
+ }
14364
+ /**
14365
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
14366
+ * source cursor holds it unanchored, and neither does a later frame behind
14367
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
14368
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
14369
+ * like each frame that arrived in front of it since (stale there). The head
14370
+ * then goes, decided as it would be unanchored, once a frame the base path
14371
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
14372
+ * marked one: the base path has passed that one, so a frame still missing
14373
+ * before it can only come from a repair. It also goes while no source frame
14374
+ * has been released, when the direct path shows a recovered frame at once.
14375
+ * And it goes at once while a staged switch decides on when frames arrive
14376
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
14377
+ * sink being replaced: unanchored, it had already reached the sink.
14378
+ * The scan also writes: the `passed` marks it sets stay on the frames,
14379
+ * and push marks a frame it inserts in front of a marked one from them.
14380
+ */
14381
+ #cursorPassed(stream, asUnanchored) {
14382
+ let at = -1;
14383
+ for (let i = 0; i < stream.buf.length; i++) {
14384
+ const frame = stream.buf[i];
14385
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
14386
+ frame.passed = true;
14387
+ if (at < 0) at = i;
14388
+ } else if (frame.passed !== true) break;
14389
+ }
14390
+ if (at < 0) return false;
14391
+ return asUnanchored || !stream.sourced || this.#gate.releaseUnanchored?.(stream.packetId, stream.catalogTrackName) === true || stream.buf.some(({ meta }, i) => i > at && meta.fecSbnFirst === void 0 && (meta.recovered !== true || meta.fecSbn !== void 0));
14392
+ }
13723
14393
  #release(stream, frame, decision) {
14394
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
14395
+ if (stale) this.#recordStat("droppedStale");
13724
14396
  if (decision) frame.meta.gapBefore = decision;
13725
14397
  stream.last = frame;
13726
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
14398
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
14399
+ stream.lastSbn = frame.meta.fecSbn;
14400
+ }
14401
+ if (frame.meta.recovered !== true) stream.sourced = true;
13727
14402
  this.#gate.onReleased?.(frame.data, frame.meta);
13728
- this.#emit(frame.data, frame.meta);
14403
+ if (!stale) this.#emit(frame.data, frame.meta);
13729
14404
  }
13730
14405
  };
13731
14406
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -13766,6 +14441,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
13766
14441
  this.#reclaimedTimingSamples = 0;
13767
14442
  this.#evictedTimingSamples = 0;
13768
14443
  this.#rejectedMovieFragments = 0;
14444
+ this.#recoveredHeadsAwaitingTiming = {
14445
+ held: 0,
14446
+ expired: 0,
14447
+ discarded: 0,
14448
+ superseded: 0
14449
+ };
13769
14450
  this.#sequencers = /* @__PURE__ */ new Map();
13770
14451
  this.#fecGate = null;
13771
14452
  this.#fecSequencer = null;
@@ -13874,6 +14555,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
13874
14555
  #reclaimedTimingSamples;
13875
14556
  #evictedTimingSamples;
13876
14557
  #rejectedMovieFragments;
14558
+ #recoveredHeadsAwaitingTiming;
13877
14559
  #sequencers;
13878
14560
  #fecGate;
13879
14561
  #fecSequencer;
@@ -13979,11 +14661,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
13979
14661
  /**
13980
14662
  * Typed view of the ISO-BMFF timing-sample budget.
13981
14663
  *
13982
- * This is the acceptance signal for the budget ratchet: `pending` walking
13983
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
13984
- * and it is observable here rather than only as media silently stopping.
13985
- * Per repo policy this is a producer-owned counter -- never infer budget
13986
- * state by parsing logs.
14664
+ * Each stream admits timing against its own window of `capacity` slots
14665
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
14666
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
14667
+ * timing a stream declared and never delivered shows up there. `pending`
14668
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
14669
+ * a producer-owned counter -- never infer budget state by parsing logs.
13987
14670
  */
13988
14671
  get timingBudgetStats() {
13989
14672
  return {
@@ -13994,6 +14677,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
13994
14677
  rejectedMovieFragments: this.#rejectedMovieFragments
13995
14678
  };
13996
14679
  }
14680
+ /** Recovered heads parked for FT=1 timing (BLO-53369). Survives dispose(). */
14681
+ get recoveredHeadsAwaitingTiming() {
14682
+ let pending = 0;
14683
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
14684
+ for (const head of awaitingTiming) if (head.options?.recovered) pending++;
14685
+ }
14686
+ return { ...this.#recoveredHeadsAwaitingTiming, pending };
14687
+ }
13997
14688
  get reorderStats() {
13998
14689
  let bufferedFrames = this.#fecSequencer?.buffered ?? 0;
13999
14690
  for (const { sequencer } of this.#sequencers.values()) bufferedFrames += sequencer.buffered;
@@ -14035,6 +14726,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
14035
14726
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
14036
14727
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
14037
14728
  }
14729
+ /** See FecReleaseSequencer.unsource. */
14730
+ unsourceFecRelease(packetId, catalogTrackName) {
14731
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
14732
+ }
14733
+ /** See FecReleaseSequencer.holdsRebuilt. */
14734
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
14735
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
14736
+ }
14038
14737
  /** Re-evaluate held gaps after FEC block state changed. */
14039
14738
  pokeFecRelease(packetId, catalogTrackName) {
14040
14739
  if (!this.#fecSequencer) return;
@@ -14167,7 +14866,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14167
14866
  const now = Date.now();
14168
14867
  for (const { awaitingTiming } of this.#timingStreams.values()) {
14169
14868
  while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
14170
- awaitingTiming.shift();
14869
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
14171
14870
  }
14172
14871
  }
14173
14872
  }
@@ -14285,11 +14984,16 @@ var MmtpContainerParser = class _MmtpContainerParser {
14285
14984
  if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
14286
14985
  return this.#drop("fragment-unexpected-fragmentation");
14287
14986
  const resolver2 = this.#timingResolver(streamKey, info.packetId, false);
14288
- if (!resolver2) return this.#drop("fragment-no-resolver");
14987
+ if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
14289
14988
  const pendingBefore = resolver2.pendingSampleCount;
14290
14989
  const evictedBefore = resolver2.evictedSampleCount;
14291
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
14292
- const admitted = resolver2.addMovieFragment(mpu.mpuSequenceNumber, data, remaining);
14990
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
14991
+ const admitted = resolver2.addMovieFragment(
14992
+ mpu.mpuSequenceNumber,
14993
+ data,
14994
+ remaining,
14995
+ options?.recovered === true
14996
+ );
14293
14997
  this.#pendingTimingSamples += resolver2.pendingSampleCount - pendingBefore;
14294
14998
  this.#evictedTimingSamples += resolver2.evictedSampleCount - evictedBefore;
14295
14999
  if (!admitted) {
@@ -14309,7 +15013,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14309
15013
  };
14310
15014
  }
14311
15015
  if (fragmentType !== 2) return this.#drop("unknown-fragment-type");
14312
- const resolver = this.#timingResolver(streamKey, info.packetId, false);
15016
+ const resolver = this.#timingResolver(streamKey, info.packetId, true);
14313
15017
  if (!resolver) return this.#drop("mfu-no-resolver");
14314
15018
  if (!Number.isSafeInteger(data.byteLength) || data.byteLength <= 0)
14315
15019
  return this.#drop("mfu-empty-payload");
@@ -14330,6 +15034,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14330
15034
  mpuSequenceNumber: mpu.mpuSequenceNumber,
14331
15035
  movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
14332
15036
  sampleNumber: mfuDuHeader.sampleNumber,
15037
+ sequenceNumber: info.sequenceNumber,
14333
15038
  arrivedAt: Date.now()
14334
15039
  });
14335
15040
  return this.#drop("mfu-sample-timing-missing");
@@ -14355,7 +15060,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14355
15060
  info,
14356
15061
  resolver,
14357
15062
  options?.recovered === true,
14358
- options?.fecSbn
15063
+ options?.fecSbn,
15064
+ options?.fecSbnFirst
14359
15065
  );
14360
15066
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
14361
15067
  }
@@ -14448,7 +15154,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14448
15154
  info,
14449
15155
  resolver,
14450
15156
  options?.recovered === true,
14451
- options?.fecSbn
15157
+ options?.fecSbn,
15158
+ options?.fecSbnFirst
14452
15159
  );
14453
15160
  if (outcome.record !== void 0) return outcome.record;
14454
15161
  return this.#drop(outcome.reason);
@@ -14468,7 +15175,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14468
15175
  * attribution exists to keep readable. Leaving the choice at the call site
14469
15176
  * is what keeps both true.
14470
15177
  */
14471
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
15178
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
14472
15179
  const timing = resolver.sampleTiming(
14473
15180
  combined.mpuSequenceNumber,
14474
15181
  combined.movieFragmentSequenceNumber,
@@ -14485,6 +15192,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14485
15192
  );
14486
15193
  if (!meta) return { reason: "combined-meta-build-failed" };
14487
15194
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
15195
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
14488
15196
  if (!resolver.consumeSample(
14489
15197
  combined.mpuSequenceNumber,
14490
15198
  combined.movieFragmentSequenceNumber,
@@ -14718,6 +15426,9 @@ var MmtpContainerParser = class _MmtpContainerParser {
14718
15426
  for (const { sequencer } of this.#sequencers.values()) sequencer.discard();
14719
15427
  this.#sequencers.clear();
14720
15428
  this.#fecSequencer?.discard();
15429
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
15430
+ for (const head of awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
15431
+ }
14721
15432
  this.#timingStreams.clear();
14722
15433
  this.#pendingTimingSamples = 0;
14723
15434
  this.#reliableMoqStartupGate.clear();
@@ -14736,10 +15447,23 @@ var MmtpContainerParser = class _MmtpContainerParser {
14736
15447
  return resolver;
14737
15448
  }
14738
15449
  #awaitTiming(streamKey, head) {
14739
- const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
14740
- if (!awaitingTiming) return;
15450
+ const state = this.#timingStreams.get(streamKey);
15451
+ if (!state) return;
15452
+ if (!head.options?.recovered) {
15453
+ const kept = state.awaitingTiming.filter((queued) => !queued.options?.recovered || queued.sequenceNumber !== head.sequenceNumber);
15454
+ this.#recoveredHeadsAwaitingTiming.superseded += state.awaitingTiming.length - kept.length;
15455
+ state.awaitingTiming = kept;
15456
+ }
15457
+ const awaitingTiming = state.awaitingTiming;
14741
15458
  awaitingTiming.push(head);
14742
- if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
15459
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming.held++;
15460
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) {
15461
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
15462
+ }
15463
+ }
15464
+ /** Count a recovered head leaving the queue other than by replay or its source copy. */
15465
+ #leaveAwaitingTiming(head, outcome) {
15466
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming[outcome]++;
14743
15467
  }
14744
15468
  /**
14745
15469
  * Feed again the heads whose timing the FT=1 just admitted declares. That
@@ -14767,6 +15491,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14767
15491
  const state = this.#timingStreams.get(streamKey);
14768
15492
  if (!state) return;
14769
15493
  this.#timingStreams.delete(streamKey);
15494
+ for (const head of state.awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
14770
15495
  this.#pendingTimingSamples -= state.resolver.pendingSampleCount;
14771
15496
  if (this.#pendingTimingSamples < 0) {
14772
15497
  throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");
@@ -17972,7 +18697,18 @@ function keyframeOverlaySsId(header) {
17972
18697
  if (ext?.type !== KEYFRAME_OVERLAY_EXTENSION_TYPE || ext.data.length !== 4) return void 0;
17973
18698
  return new DataView(ext.data.buffer, ext.data.byteOffset, 4).getUint32(0);
17974
18699
  }
18700
+ function overlayBaseSsId(anchor, overlaySsId, restoredPsn, headerPsn) {
18701
+ if (anchor.baseSsId === void 0 || headerPsn !== restoredPsn) return void 0;
18702
+ return serial32Add(anchor.baseSsId, overlaySsId - anchor.overlaySsId | 0);
18703
+ }
18704
+ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
18705
+ if (offset === void 0 || offset !== unstampedOffset) return void 0;
18706
+ return headerPsn + offset >>> 0;
18707
+ }
18708
+ var OVERLAY_ROUTED_LIMIT = 1024;
18709
+ var OVERLAY_PENDING_LIMIT = 256;
17975
18710
  var OVERLAY_OFFSET_MPUS = 16;
18711
+ var OVERLAY_REBUILT_LIMIT = 256;
17976
18712
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
17977
18713
  function assertStreamIdentity(role, stream) {
17978
18714
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -18083,6 +18819,7 @@ var MmtpRouter = class {
18083
18819
  #provenance = /* @__PURE__ */ new Map();
18084
18820
  #onFlowProtected = null;
18085
18821
  #unadmittedListedDrops = 0;
18822
+ #admittedSourceDatagrams = 0;
18086
18823
  #unlistedRepairSetAside = 0;
18087
18824
  #assistBlocks = /* @__PURE__ */ new Map();
18088
18825
  #assistFailures = /* @__PURE__ */ new Map();
@@ -18139,6 +18876,26 @@ var MmtpRouter = class {
18139
18876
  * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
18140
18877
  */
18141
18878
  #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18879
+ /**
18880
+ * Per stream, the SS_ID offset at which a base recovery last showed the
18881
+ * sender's own packet_sequence_number: a recovered packet's header psn
18882
+ * equal to its SS_ID minus that offset. While it equals the stream's
18883
+ * current offset, no hop re-stamps the stream, and a packet's protected psn
18884
+ * names its base SS_ID within unstampedBaseSsId's limits (joint decoding of
18885
+ * an MPU no member of which arrived).
18886
+ */
18887
+ #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18888
+ /**
18889
+ * The same, shown by the overlay alone, before any base recovery did: a
18890
+ * packet it rebuilt whose base copy carries its protected psn
18891
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
18892
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
18893
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
18894
+ * make the base drop a late base copy of a keyframe the overlay never
18895
+ * finished, and lift a block's late-source cut, which nothing before
18896
+ * this offset did.
18897
+ */
18898
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18142
18899
  /**
18143
18900
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
18144
18901
  * not parsed, typically because its overlap copy was parsed first
@@ -18184,6 +18941,8 @@ var MmtpRouter = class {
18184
18941
  // end: a synchronous recovery completes its block BEFORE routing the
18185
18942
  // recovered frames, and releasing a held gap in between would strand them.
18186
18943
  #fecPokeDepth = 0;
18944
+ /** FecReleaseGate.wakeAt timers, by media stream key. */
18945
+ #fecWakes = /* @__PURE__ */ new Map();
18187
18946
  #pendingFecPokes = /* @__PURE__ */ new Map();
18188
18947
  // ── Phase 14: per-role packetId dispatch (D-26, D-27, D-28) ───────
18189
18948
  /** Maps packetId → TrackRole. Default: 'single' when absent (legacy path). */
@@ -18208,7 +18967,9 @@ var MmtpRouter = class {
18208
18967
  recovered: 0,
18209
18968
  restarts: 0,
18210
18969
  unsequencedDropped: 0,
18211
- protectedDropped: 0
18970
+ protectedDropped: 0,
18971
+ baseFed: 0,
18972
+ baseUndetermined: 0
18212
18973
  };
18213
18974
  /** Callback fired when a delta-track FEC block completes or fails. */
18214
18975
  #onDeltaBlockCompleteCb = null;
@@ -18381,7 +19142,7 @@ var MmtpRouter = class {
18381
19142
  const cb = this.#getFrameCallback(packetId);
18382
19143
  if (isVideo && !assembler) {
18383
19144
  if (frameMeta.recovered) {
18384
- this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb);
19145
+ this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb, meta.fecSbn);
18385
19146
  } else {
18386
19147
  this.#routeDirectSourceVideo(packetId, data, frameMeta, cb);
18387
19148
  }
@@ -18414,13 +19175,18 @@ var MmtpRouter = class {
18414
19175
  this.#onDeltaBlockCompleteCb?.(packetId, false);
18415
19176
  }
18416
19177
  };
18417
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
19178
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
18418
19179
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
18419
19180
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
18420
19181
  this.#onDeltaBlockCompleteCb?.(packetId, true);
18421
19182
  }
18422
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18423
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19183
+ if (span === void 0) {
19184
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19185
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19186
+ } else {
19187
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
19188
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
19189
+ }
18424
19190
  };
18425
19191
  }
18426
19192
  }
@@ -18465,8 +19231,9 @@ var MmtpRouter = class {
18465
19231
  }
18466
19232
  /**
18467
19233
  * FEC-recovered source symbols whose reconstructed header named a
18468
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
18469
- * a hop re-stamped the sequence after the sender protected the packet.
19234
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
19235
+ * or, rebuilt by the overlay, than their base copy carries: a hop
19236
+ * re-stamped the sequence after the sender protected the packet.
18470
19237
  */
18471
19238
  get restampedRecoveredSequenceCount() {
18472
19239
  return this.#restampedRecoveredSeqs;
@@ -18645,6 +19412,7 @@ var MmtpRouter = class {
18645
19412
  enableMseAssembler(packetId, config, catalogTrackName) {
18646
19413
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
18647
19414
  const previous = this.#mseAssemblers.get(assemblerKey);
19415
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
18648
19416
  if (previous) {
18649
19417
  previous.flush();
18650
19418
  previous.dispose();
@@ -18771,6 +19539,10 @@ var MmtpRouter = class {
18771
19539
  get keyframeOverlayStats() {
18772
19540
  return { ...this.#overlayStats };
18773
19541
  }
19542
+ /** Recovered FT=2 heads held for their FT=1, and how each left the wait (BLO-53369). */
19543
+ get recoveredHeadsAwaitingTiming() {
19544
+ return this.#parser.recoveredHeadsAwaitingTiming;
19545
+ }
18774
19546
  #isOverlayRepair(repairPacketId, repairTrackName) {
18775
19547
  return this.#overlayLegs.has(repairPacketId) || repairTrackName !== void 0 && this.#overlayRepairNames.has(repairTrackName);
18776
19548
  }
@@ -18791,7 +19563,8 @@ var MmtpRouter = class {
18791
19563
  fec,
18792
19564
  k,
18793
19565
  offsets: /* @__PURE__ */ new Map(),
18794
- moqBlocks: /* @__PURE__ */ new Set()
19566
+ moqBlocks: /* @__PURE__ */ new Set(),
19567
+ rebuilt: /* @__PURE__ */ new Map()
18795
19568
  };
18796
19569
  this.#overlays.set(repairPacketId, inst);
18797
19570
  return () => {
@@ -18821,12 +19594,18 @@ var MmtpRouter = class {
18821
19594
  */
18822
19595
  resetKeyframeOverlays(sourcePacketId, catalogTrackName) {
18823
19596
  for (const inst of this.#overlaysForSource(sourcePacketId, catalogTrackName)) this.#resetOverlay(inst);
19597
+ for (const [name, stream] of this.#streams.get(sourcePacketId) ?? []) {
19598
+ if (catalogTrackName !== void 0 && name !== catalogTrackName) continue;
19599
+ stream.overlayToBase.routed.clear();
19600
+ stream.overlayToBase.pending.clear();
19601
+ }
18824
19602
  }
18825
19603
  #resetOverlay(inst) {
18826
19604
  inst.fec.resetTrack(inst.repairPacketId, inst.streamName);
18827
19605
  inst.last = void 0;
18828
19606
  inst.offsets.clear();
18829
19607
  inst.moqBlocks.clear();
19608
+ inst.rebuilt.clear();
18830
19609
  }
18831
19610
  #overlaysForSource(sourcePacketId, catalogTrackName) {
18832
19611
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -18877,18 +19656,33 @@ var MmtpRouter = class {
18877
19656
  * A source packet that carries a 0x8B01 overlay SS_ID is also a symbol of
18878
19657
  * every overlay installed for its source, at that SS_ID, with the bytes the
18879
19658
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
18880
- * included (7.1, 7.4.3).
18881
- */
18882
- #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source) {
19659
+ * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
19660
+ * FEC reads it.
19661
+ *
19662
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
19663
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
19664
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
19665
+ * the stream unstamped at the SS_ID offset it states, for the release gate
19666
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
19667
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
19668
+ */
19669
+ #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
18883
19670
  if (this.#overlays.size === 0) return;
18884
19671
  const ssId = keyframeOverlaySsId(header);
18885
19672
  if (ssId === void 0) return;
19673
+ let rebuiltPsn;
18886
19674
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
18887
19675
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
19676
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
19677
+ inst.rebuilt.delete(ssId);
18888
19678
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
18889
19679
  if (identity !== null) {
18890
19680
  inst.offsets.delete(identity.mpuSequenceNumber);
18891
- inst.offsets.set(identity.mpuSequenceNumber, ssId - sequenceNumber >>> 0);
19681
+ inst.offsets.set(identity.mpuSequenceNumber, {
19682
+ psnOffset: ssId - sequenceNumber >>> 0,
19683
+ overlaySsId: ssId,
19684
+ ...baseSsId === void 0 ? {} : { baseSsId }
19685
+ });
18892
19686
  if (inst.offsets.size > OVERLAY_OFFSET_MPUS) inst.offsets.delete(inst.offsets.keys().next().value);
18893
19687
  }
18894
19688
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -18910,6 +19704,14 @@ var MmtpRouter = class {
18910
19704
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
18911
19705
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
18912
19706
  }
19707
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
19708
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
19709
+ if (rebuiltPsn !== sequenceNumber) {
19710
+ this.#restampedRecoveredSeqs++;
19711
+ } else if (baseSsId !== void 0) {
19712
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19713
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
19714
+ }
18913
19715
  }
18914
19716
  #noteOverlayMoqBlock(inst, blockStart) {
18915
19717
  inst.moqBlocks.add(blockStart);
@@ -18943,11 +19745,16 @@ var MmtpRouter = class {
18943
19745
  }
18944
19746
  /**
18945
19747
  * Route an overlay-recovered block's packets as source media of the
18946
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
18947
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
18948
- * base re-stamp, no block advance. Each packet's wire sequence is restored
18949
- * from its keyframe's own offset; without one, a stream the base never
18950
- * re-stamped keeps the header's sequence and any other drops the packet.
19748
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
19749
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
19750
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
19751
+ * base FEC recovered does, so it waits behind base frames still in flight,
19752
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
19753
+ * longer than unanchored; one whose base SS_ID is undetermined has no
19754
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
19755
+ * advance. Each packet's wire sequence is restored from its keyframe's own
19756
+ * offset; without one, a stream the base never re-stamped keeps the
19757
+ * header's sequence and any other drops the packet.
18951
19758
  */
18952
19759
  #routeOverlayRecovered(inst, blockStart, recovered) {
18953
19760
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -18967,22 +19774,139 @@ var MmtpRouter = class {
18967
19774
  const streamKey = this.#mediaStreamKey(sourcePacketId, sourceName);
18968
19775
  const restamped = this.#restampedStreams.has(streamKey);
18969
19776
  const restored = /* @__PURE__ */ new Set();
19777
+ const baseSsIds = /* @__PURE__ */ new Map();
19778
+ const gateOnly = /* @__PURE__ */ new Set();
18970
19779
  const symbols = result.symbols.flatMap((sym) => {
18971
- const offset = inst.offsets.get(sym.fragment.mpuSequenceNumber);
18972
- if (offset !== void 0) {
18973
- const packetSequenceNumber = serial32Add(blockStart, sym.index) - offset >>> 0;
19780
+ const overlaySsId = serial32Add(blockStart, sym.index);
19781
+ const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
19782
+ if (anchor !== void 0) {
19783
+ const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
18974
19784
  restored.add(packetSequenceNumber);
18975
- return [{ ...sym, packetSequenceNumber }];
19785
+ const out = { ...sym, packetSequenceNumber };
19786
+ const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
19787
+ if (baseSsId !== void 0) {
19788
+ baseSsIds.set(sym.index, baseSsId);
19789
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19790
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
19791
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
19792
+ }
19793
+ }
19794
+ return [out];
19795
+ }
19796
+ if (!restamped) {
19797
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19798
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
19799
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
19800
+ if (baseSsId !== void 0) {
19801
+ baseSsIds.set(sym.index, baseSsId);
19802
+ if (fedSsId === void 0) gateOnly.add(sym.index);
19803
+ } else {
19804
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
19805
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
19806
+ }
19807
+ return [sym];
18976
19808
  }
18977
- if (!restamped) return [sym];
18978
19809
  this.#overlayStats.unsequencedDropped++;
18979
19810
  return [];
18980
19811
  });
18981
19812
  this.#overlayStats.recovered++;
19813
+ const mpuFirst = /* @__PURE__ */ new Map();
19814
+ for (const sym of symbols) {
19815
+ const ssId = baseSsIds.get(sym.index);
19816
+ const mpu = sym.fragment.mpuSequenceNumber;
19817
+ const first = mpuFirst.get(mpu);
19818
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
19819
+ }
19820
+ const firstSsIds = /* @__PURE__ */ new Map();
19821
+ for (const sym of symbols) {
19822
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
19823
+ }
18982
19824
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
18983
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
19825
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
19826
+ baseSsIds,
19827
+ firstSsIds
18984
19828
  });
18985
19829
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
19830
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
19831
+ }
19832
+ /**
19833
+ * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
19834
+ * its base block too, once its base SS_ID is determined (overlayBaseSsId,
19835
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
19836
+ * base recovery showed; `baseSsIds` holds no other),
19837
+ * so it is fed to the base decoder as a rebuilt source
19838
+ * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
19839
+ * fewer to solve, and its repair can recover the block's other packets.
19840
+ * A base block no repair has stated yet takes it when one does
19841
+ * (#feedPendingRebuilt).
19842
+ *
19843
+ * The overlay route already handled each packet fed (delivered it, or
19844
+ * held an untimed head for its FT=1), so a base recovery routes none of
19845
+ * them again (#routeVerifiedFecSymbols): a second recovered copy of a
19846
+ * held head would wait in the parser for timing its first copy consumed.
19847
+ * Only an overlay block decoded from multicast symbols alone is fed: with
19848
+ * a MoQ symbol in it, the base block's recovery would depend on bytes
19849
+ * that crossed no multicast socket, which the provenance counted from the
19850
+ * block's own arrivals cannot show.
19851
+ */
19852
+ #feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds) {
19853
+ const fec = this.#fecManager;
19854
+ const owner = inst.leg.sourcePacketId;
19855
+ const name = inst.leg.sourceCatalogTrackName;
19856
+ if (!fec?.feedRebuiltSourceSymbol || inst.moqBlocks.has(blockStart)) return;
19857
+ if (this.#classifyPacketId(owner) === null || fec.isTrackConfigured?.(owner) === false) return;
19858
+ const { duplicates, overlayToBase: { routed } } = this.#stream(owner, name);
19859
+ const feeds = [];
19860
+ for (const sym of symbols) {
19861
+ if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
19862
+ const ssId = baseSsIds.get(sym.index);
19863
+ if (ssId === void 0) {
19864
+ this.#overlayStats.baseUndetermined++;
19865
+ continue;
19866
+ }
19867
+ routed.delete(ssId);
19868
+ routed.add(ssId);
19869
+ if (routed.size > OVERLAY_ROUTED_LIMIT) routed.delete(routed.values().next().value);
19870
+ feeds.push([ssId, sym.rawSymbol]);
19871
+ }
19872
+ for (const [ssId, symbolData] of feeds) {
19873
+ if (this.#classifyPacketId(owner) === null) return;
19874
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
19875
+ }
19876
+ }
19877
+ /** Feed one rebuilt source to its base block, or keep it until a repair states that block. */
19878
+ #feedRebuiltToBase(owner, name, ssId, symbolData) {
19879
+ const fec = this.#fecManager;
19880
+ if (!fec?.feedRebuiltSourceSymbol) return;
19881
+ const coords = fec.locateIsoSource?.(owner, name, ssId);
19882
+ if (coords == null) {
19883
+ const pending = this.#stream(owner, name).overlayToBase.pending;
19884
+ pending.delete(ssId);
19885
+ pending.set(ssId, symbolData.slice());
19886
+ if (pending.size > OVERLAY_PENDING_LIMIT) pending.delete(pending.keys().next().value);
19887
+ return;
19888
+ }
19889
+ const fed = fec.feedRebuiltSourceSymbol(owner, ssId, symbolData, name);
19890
+ if (!fed.taken) return;
19891
+ this.#overlayStats.baseFed++;
19892
+ if (fed.recovered === null) return;
19893
+ const sbn = coords.sbn;
19894
+ this.#routeRecoveredBlock(sbn, fed.recovered, owner, name, () => {
19895
+ fec.cancelBlockTimeout(sbn, owner, name);
19896
+ fec.countRecovery(owner, sbn, name);
19897
+ fec.markBlockCompleted(sbn, owner, name);
19898
+ });
19899
+ }
19900
+ /** A repair stated `block`: the rebuilt sources that waited for it join it now. */
19901
+ #feedPendingRebuilt(owner, name, block) {
19902
+ const pending = this.#streams.get(owner)?.get(name)?.overlayToBase.pending;
19903
+ if (pending === void 0 || pending.size === 0) return;
19904
+ for (const [ssId, symbolData] of [...pending]) {
19905
+ if (this.#classifyPacketId(owner) === null) return;
19906
+ if (serial32Distance(block.start, ssId) >= block.length) continue;
19907
+ pending.delete(ssId);
19908
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
19909
+ }
18986
19910
  }
18987
19911
  /** fec-multicast-00 §6.6: report each base block whose RAP MFU fragments
18988
19912
  * the overlay restored, when the keyframe's FT=0 and FT=1 are held too. A
@@ -19122,6 +20046,10 @@ var MmtpRouter = class {
19122
20046
  get unadmittedListedDropCount() {
19123
20047
  return this.#unadmittedListedDrops;
19124
20048
  }
20049
+ /** 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. */
20050
+ get admittedSourceDatagramCount() {
20051
+ return this.#admittedSourceDatagrams;
20052
+ }
19125
20053
  /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
19126
20054
  get unlistedRepairSetAsideCount() {
19127
20055
  return this.#unlistedRepairSetAside;
@@ -19608,6 +20536,8 @@ var MmtpRouter = class {
19608
20536
  )) return;
19609
20537
  fec.noteBlockActivity?.(blockStart, ownerPacketId, catalogTrackName);
19610
20538
  fec.noteRepairGroupLength?.(blockStart, ownerPacketId, repair.rsbLength, catalogTrackName);
20539
+ this.#feedPendingRebuilt(ownerPacketId, catalogTrackName, placement.block);
20540
+ if (this.#classifyPacketId(ownerPacketId) === null) return;
19611
20541
  const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
19612
20542
  const recovered = fec.feedRepairSymbol(
19613
20543
  ownerPacketId,
@@ -19658,7 +20588,7 @@ var MmtpRouter = class {
19658
20588
  catalogTrackName
19659
20589
  )) continue;
19660
20590
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
19661
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
20591
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
19662
20592
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
19663
20593
  }
19664
20594
  if (payload.oversized) continue;
@@ -19745,6 +20675,8 @@ var MmtpRouter = class {
19745
20675
  this.#droppedPreSyncVideo.delete(streamKey);
19746
20676
  this.#latestVideoSeqByStream.delete(streamKey);
19747
20677
  this.#ssIdSeqOffsetByStream.delete(streamKey);
20678
+ this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
20679
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
19748
20680
  this.#multicastRapTwinByStream.delete(streamKey);
19749
20681
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
19750
20682
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -19871,6 +20803,12 @@ var MmtpRouter = class {
19871
20803
  * the outgoing stream stops. The hold is bounded by the incoming stream's
19872
20804
  * own RAP cadence, so no timer is involved.
19873
20805
  *
20806
+ * While the switch is staged, the FEC release gate lets a keyframe the
20807
+ * overlay rebuilt reach it, on either side, when the keyframe did before
20808
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
20809
+ * decides on what each side delivered, and the commit discards the gate's
20810
+ * frames of the outgoing stream.
20811
+ *
19874
20812
  * The commit is one synchronous transition inside the frame path: the
19875
20813
  * outgoing stream's already-admitted frames are released (its queued FEC
19876
20814
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -19921,6 +20859,9 @@ var MmtpRouter = class {
19921
20859
  droppedIncomingFrames: 0
19922
20860
  };
19923
20861
  this.#staged = state;
20862
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
20863
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
20864
+ }
19924
20865
  return {
19925
20866
  cancel: () => {
19926
20867
  if (this.#staged !== state) return false;
@@ -20003,7 +20944,17 @@ var MmtpRouter = class {
20003
20944
  */
20004
20945
  #routeParsedFrame(data, meta) {
20005
20946
  if (this.#classifyPacketId(meta.packetId) === null) return;
20006
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
20947
+ if (this.#staged !== null) {
20948
+ let consumed = false;
20949
+ this.#fecPokeDepth++;
20950
+ try {
20951
+ consumed = this.#interceptSwitchFrame(data, meta);
20952
+ } finally {
20953
+ this.#fecPokeDepth--;
20954
+ this.#flushPendingFecPokes();
20955
+ }
20956
+ if (consumed) return;
20957
+ }
20007
20958
  this.#deliverParsedFrame(data, meta);
20008
20959
  }
20009
20960
  #commitStreamSwitch(state, rap, reason) {
@@ -20052,6 +21003,8 @@ var MmtpRouter = class {
20052
21003
  this.#disposed = true;
20053
21004
  this.#staged = null;
20054
21005
  this.cancelKeyframeLostTimer();
21006
+ for (const { timer } of this.#fecWakes.values()) clearTimeout(timer);
21007
+ this.#fecWakes.clear();
20055
21008
  this.#parser.dispose();
20056
21009
  this.#streams.clear();
20057
21010
  this.#trackPacketCallbacks.clear();
@@ -20155,12 +21108,16 @@ var MmtpRouter = class {
20155
21108
  this.#parser.deferFecRelease(work);
20156
21109
  } finally {
20157
21110
  this.#fecPokeDepth--;
20158
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
20159
- const pokes = [...this.#pendingFecPokes.values()];
20160
- this.#pendingFecPokes.clear();
20161
- for (const poke of pokes) {
20162
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20163
- }
21111
+ this.#flushPendingFecPokes();
21112
+ }
21113
+ }
21114
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
21115
+ #flushPendingFecPokes() {
21116
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
21117
+ const pokes = [...this.#pendingFecPokes.values()];
21118
+ this.#pendingFecPokes.clear();
21119
+ for (const poke of pokes) {
21120
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20164
21121
  }
20165
21122
  }
20166
21123
  }
@@ -20229,6 +21186,31 @@ var MmtpRouter = class {
20229
21186
  if (!fec?.terminalRetentionMsForPacket) return Infinity;
20230
21187
  return fec.terminalRetentionMsForPacket(packetId) ?? 0;
20231
21188
  },
21189
+ // Once no repair can fill a gap (FECManager.isoRepairlessWaitMs: only a
21190
+ // late source can), its frame waits the late-symbol allowance when the
21191
+ // gap holds no RAP an installed keyframe overlay could still rebuild:
21192
+ // lost deltas of one MPU (delta-lost), the tail of the MPU before a RAP
21193
+ // that opens the next one while MPU boundaries bound RAPs (rap-next,
21194
+ // unless the gap holds a stated block's loss: the overlay may rebuild
21195
+ // that MPU's FT=0, and the block's group then complete it), or
21196
+ // an audio gap. A gap that may hold one (rap-lost, rap-unknown, or any
21197
+ // other rap-next, whose gap may hold a whole MPU and the keyframe the
21198
+ // overlay protects) waits for that overlay's repair too (BLO-52085
21199
+ // D4). The FEC check comes first: most held gaps are not behind such a
21200
+ // span, and deciding one scans both frames' bitstreams.
21201
+ unrepairableWaitMs: (before, after, fromSbn, toSbn) => {
21202
+ const fec = this.#fecManager;
21203
+ const { packetId, catalogTrackName } = after.meta;
21204
+ const allowanceMs = fec?.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn);
21205
+ if (!fec || allowanceMs === void 0) return void 0;
21206
+ const decision = this.#decideGap(before, after, [], false);
21207
+ const mpu = before.meta.mpuSequenceNumber;
21208
+ const intoNextMpu = decision.reason === "rap-next" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu + 1 >>> 0 && fec.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
21209
+ if (decision.action === "stall" || decision.reason === "rap-next" && !intoNextMpu) {
21210
+ return fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, true);
21211
+ }
21212
+ return decision.reason === "rap-next" ? fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, true) : allowanceMs;
21213
+ },
20232
21214
  decide: (before, after, lostBlocks, discontinuity) => {
20233
21215
  const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
20234
21216
  this.#onFrameGap?.(decision);
@@ -20238,6 +21220,28 @@ var MmtpRouter = class {
20238
21220
  onRap: (packetId, catalogTrackName, ssId) => {
20239
21221
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
20240
21222
  },
21223
+ // One timer per stream, at the earliest wake asked: its drain re-arms
21224
+ // for the next frame still waiting.
21225
+ wakeAt: (packetId, catalogTrackName, atMs) => {
21226
+ if (this.#disposed) return;
21227
+ const key = this.#mediaStreamKey(packetId, catalogTrackName);
21228
+ const armed = this.#fecWakes.get(key);
21229
+ if (armed !== void 0 && armed.atMs <= atMs) return;
21230
+ if (armed !== void 0) clearTimeout(armed.timer);
21231
+ const timer = setTimeout(() => {
21232
+ this.#fecWakes.delete(key);
21233
+ this.#requestFecPoke(packetId, catalogTrackName);
21234
+ }, Math.max(0, Math.ceil(atMs - performance.now())));
21235
+ this.#fecWakes.set(key, { atMs, timer });
21236
+ },
21237
+ // A staged switch commits on when each side's frames reach it
21238
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
21239
+ // they did unanchored.
21240
+ releaseUnanchored: (packetId, catalogTrackName) => {
21241
+ const staged = this.#staged;
21242
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
21243
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
21244
+ },
20241
21245
  onReleased: (data, meta) => {
20242
21246
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
20243
21247
  const timing = meta.authoredTiming;
@@ -20379,6 +21383,7 @@ var MmtpRouter = class {
20379
21383
  const parsed = this.#parser.parsePacket(packet);
20380
21384
  if (!parsed) return;
20381
21385
  const info = parsed.info;
21386
+ if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
20382
21387
  if (source === "multicast" && !manifestAdmitted) {
20383
21388
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
20384
21389
  }
@@ -20660,7 +21665,8 @@ var MmtpRouter = class {
20660
21665
  parsed.header,
20661
21666
  info.sequenceNumber,
20662
21667
  info.rapFlag,
20663
- source
21668
+ source,
21669
+ fecPayloadId?.ssId
20664
21670
  );
20665
21671
  }
20666
21672
  }
@@ -20686,7 +21692,8 @@ var MmtpRouter = class {
20686
21692
  source: parserOptions?.source,
20687
21693
  deliveryProvenance: parserOptions?.deliveryProvenance,
20688
21694
  catalogTrackName: parserOptions?.catalogTrackName,
20689
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
21695
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
21696
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
20690
21697
  };
20691
21698
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
20692
21699
  else this.#parser.feed(packet, feedOptions);
@@ -20810,7 +21817,8 @@ var MmtpRouter = class {
20810
21817
  if (stream === void 0) {
20811
21818
  stream = {
20812
21819
  key: JSON.stringify([packetId, catalogTrackName ?? null]),
20813
- duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId))
21820
+ duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId)),
21821
+ overlayToBase: { routed: /* @__PURE__ */ new Set(), pending: /* @__PURE__ */ new Map() }
20814
21822
  };
20815
21823
  byName.set(catalogTrackName, stream);
20816
21824
  }
@@ -20925,8 +21933,16 @@ var MmtpRouter = class {
20925
21933
  this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
20926
21934
  this.#emitDirectVideo(packetId, data, meta, cb);
20927
21935
  }
20928
- #routeDirectRecoveredVideo(packetId, data, meta, cb) {
21936
+ #routeDirectRecoveredVideo(packetId, data, meta, cb, fecSbn) {
20929
21937
  const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);
21938
+ if (this.#isFecTrack(packetId)) {
21939
+ const high = this.#deliveredVideoHighWaterByStream.get(streamKey);
21940
+ if (fecSbn !== void 0 || high !== void 0 && authoredAdjacent(high, meta)) {
21941
+ this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
21942
+ this.#emitDirectVideo(packetId, data, meta, cb);
21943
+ return;
21944
+ }
21945
+ }
20930
21946
  this.#enqueueDirectRecoveredVideo(packetId, data, meta);
20931
21947
  const lastSourceTs = this.#lastDirectSourceVideoTsByStream.get(streamKey);
20932
21948
  this.#drainDirectRecoveredVideo(
@@ -21080,6 +22096,13 @@ var MmtpRouter = class {
21080
22096
  * frames by epoch only if pre-protection input ever matters.
21081
22097
  */
21082
22098
  #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete, assisted = false) {
22099
+ const overlayRouted = ownerPacketId == null ? void 0 : this.#streams.get(ownerPacketId)?.get(catalogTrackName)?.overlayToBase.routed;
22100
+ if (overlayRouted !== void 0 && overlayRouted.size > 0) {
22101
+ result = {
22102
+ ...result,
22103
+ symbols: result.symbols.filter((sym) => !overlayRouted.has(this.#fecAnchorForRecovered(blockId, sym.index)))
22104
+ };
22105
+ }
21083
22106
  const entry = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
21084
22107
  const receiver = entry === void 0 || entry === "ambiguous" ? entry : entry.receiver;
21085
22108
  const userAgent = !assisted && entry !== void 0 && entry !== "ambiguous" && entry.protected === true && entry.userAgent === true;
@@ -21136,7 +22159,12 @@ var MmtpRouter = class {
21136
22159
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
21137
22160
  if (ownerPacketId == null) return;
21138
22161
  if (this.#classifyPacketId(ownerPacketId) === null) return;
21139
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
22162
+ const fecSbnOf = (index) => {
22163
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
22164
+ const fecSbn = overlay.baseSsIds.get(index);
22165
+ const fecSbnFirst = overlay.firstSsIds.get(index);
22166
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
22167
+ };
21140
22168
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
21141
22169
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
21142
22170
  if (ssIdSeqOffset !== void 0) {
@@ -21144,7 +22172,10 @@ var MmtpRouter = class {
21144
22172
  ...result,
21145
22173
  symbols: result.symbols.map((sym) => {
21146
22174
  const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
21147
- if (wire === sym.packetSequenceNumber) return sym;
22175
+ if (wire === sym.packetSequenceNumber) {
22176
+ this.#unstampedSsIdSeqOffsetByStream.set(streamKey, ssIdSeqOffset);
22177
+ return sym;
22178
+ }
21148
22179
  this.#restampedRecoveredSeqs++;
21149
22180
  this.#restampedStreams.add(streamKey);
21150
22181
  return { ...sym, packetSequenceNumber: wire };
@@ -21180,16 +22211,29 @@ var MmtpRouter = class {
21180
22211
  }
21181
22212
  );
21182
22213
  }
21183
- result = {
21184
- ...result,
21185
- 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(
21186
- ownerPacketId,
21187
- sym.fragment.mpuSequenceNumber,
21188
- sym.fragment.movieFragmentSequenceNumber,
21189
- sym.fragment.sampleNumber,
21190
- catalogTrackName
21191
- ))
21192
- };
22214
+ const untimedHead = (sym) => sym.fragmentType === 2 && sym.fragment.fragmentationIndicator === 1 && sym.fragment.movieFragmentSequenceNumber !== void 0 && sym.fragment.sampleNumber !== void 0 && !this.#parser.hasAuthoredTimingFor(
22215
+ ownerPacketId,
22216
+ sym.fragment.mpuSequenceNumber,
22217
+ sym.fragment.movieFragmentSequenceNumber,
22218
+ sym.fragment.sampleNumber,
22219
+ catalogTrackName
22220
+ );
22221
+ for (const sym of result.symbols) {
22222
+ if (!untimedHead(sym) || this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) continue;
22223
+ this.#feedViaParser(
22224
+ sym.rawSymbol,
22225
+ { packetId: ownerPacketId, sequenceNumber: sym.packetSequenceNumber },
22226
+ void 0,
22227
+ {
22228
+ skipFecPayloadId: true,
22229
+ recovered: true,
22230
+ deliveryProvenance,
22231
+ ...fecSbnOf(sym.index),
22232
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
22233
+ }
22234
+ );
22235
+ }
22236
+ result = { ...result, symbols: result.symbols.filter((sym) => !untimedHead(sym)) };
21193
22237
  const gated = this.#isFecTrack(ownerPacketId);
21194
22238
  const assembler = this.#mseAssemblerFor(ownerPacketId, catalogTrackName);
21195
22239
  if (assembler) {
@@ -22666,6 +23710,12 @@ function isNonNegativeSafeInteger(value) {
22666
23710
  function isSymbolCounts(value) {
22667
23711
  return isRecord(value) && hasExactKeys(value, ["multicast", "moq"]) && isNonNegativeSafeInteger(value["multicast"]) && isNonNegativeSafeInteger(value["moq"]);
22668
23712
  }
23713
+ function isSpanFailure(value) {
23714
+ if (!isRecord(value) || !hasExactKeys(value, ["length", "sources"])) return false;
23715
+ const length = value["length"];
23716
+ const sources = value["sources"];
23717
+ return Number.isSafeInteger(length) && length > 0 && isNonNegativeSafeInteger(sources) && sources < length;
23718
+ }
22669
23719
  function isNullableNonNegative(value) {
22670
23720
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
22671
23721
  }
@@ -22685,7 +23735,10 @@ function isRepairLifecycleEvent(value) {
22685
23735
  case "recovered":
22686
23736
  return hasExactKeys(value, ["version", "type", "block", "blockClass", "via", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && (value["via"] === "inband" || value["via"] === "quic") && isSymbolCounts(value["symbols"]);
22687
23737
  case "failed":
22688
- return hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]);
23738
+ return hasExactKeys(
23739
+ value,
23740
+ "span" in value ? ["version", "type", "block", "blockClass", "symbols", "span"] : ["version", "type", "block", "blockClass", "symbols"]
23741
+ ) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]) && (!("span" in value) || isSpanFailure(value["span"]));
22689
23742
  case "repair-preempted":
22690
23743
  case "repair-deferred":
22691
23744
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
@@ -22894,6 +23947,8 @@ var MulticastManager = class {
22894
23947
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
22895
23948
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
22896
23949
  #repairReleases = /* @__PURE__ */ new Map();
23950
+ /** Protected repair flows owned by each live repair-endpoint release. */
23951
+ #repairProvenanceFlows = /* @__PURE__ */ new Map();
22897
23952
  /** Each source's catalog keyframe overlay, from its `ok` binding. */
22898
23953
  #overlayBindings = /* @__PURE__ */ new Map();
22899
23954
  /** Installed overlay decoders (`setKeyframeOverlayDecoder`), by source. */
@@ -22951,7 +24006,7 @@ var MulticastManager = class {
22951
24006
  onPublisherRestart: (packetId, catalogTrackName) => {
22952
24007
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
22953
24008
  },
22954
- onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
24009
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass, span) => {
22955
24010
  const pathCount = this.#fec.blockPathCount(
22956
24011
  sbn,
22957
24012
  packetId,
@@ -22969,7 +24024,8 @@ var MulticastManager = class {
22969
24024
  symbols: {
22970
24025
  multicast: pathCount?.multicastSymbols ?? 0,
22971
24026
  moq: pathCount?.moqSymbols ?? 0
22972
- }
24027
+ },
24028
+ ...span === void 0 ? {} : { span }
22973
24029
  });
22974
24030
  },
22975
24031
  onFrameGap: (decision) => {
@@ -23057,6 +24113,11 @@ var MulticastManager = class {
23057
24113
  this.#fec.onBlockVanished = (_sbn, packetId, catalogTrackName) => {
23058
24114
  this.#statsFor(packetId, catalogTrackName).vanishedBlocks++;
23059
24115
  };
24116
+ this.#fec.keyframeOverlayTiming = (packetId, catalogTrackName) => {
24117
+ const binding = this.#overlayInstalls.has(packetId) ? this.#overlayBindings.get(packetId) : void 0;
24118
+ if (binding === void 0) return void 0;
24119
+ return catalogTrackName === void 0 || catalogTrackName === binding.sourceCatalogTrackName ? binding.geometry : void 0;
24120
+ };
23060
24121
  this.#fec.onDecoderUnavailable = (event) => {
23061
24122
  this.#emitRepairLifecycle({
23062
24123
  version: 2,
@@ -23559,6 +24620,9 @@ var MulticastManager = class {
23559
24620
  this.#transport.onFailback((reason) => {
23560
24621
  const joined = this.#provenanceJoin;
23561
24622
  if (joined !== null) this.#router.unprotectProvenanceFlow(joined.flow);
24623
+ for (const flows of this.#repairProvenanceFlows.values()) {
24624
+ for (const flow of flows) this.#router.unprotectProvenanceFlow(flow);
24625
+ }
23562
24626
  this.#onFailback?.(reason);
23563
24627
  });
23564
24628
  }
@@ -23593,6 +24657,12 @@ var MulticastManager = class {
23593
24657
  "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
23594
24658
  );
23595
24659
  }
24660
+ if (provenanceFlow !== void 0) {
24661
+ const flow = multicastProvenanceFlowKey(provenanceFlow);
24662
+ if ([...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
24663
+ throw new TypeError(`[MulticastManager] join: provenance flow already registered by a repair endpoint: ${flow}`);
24664
+ }
24665
+ }
23596
24666
  const staged = this.#renditionSwitch;
23597
24667
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
23598
24668
  this.configureFec(config);
@@ -23600,8 +24670,8 @@ var MulticastManager = class {
23600
24670
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
23601
24671
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
23602
24672
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
23603
- this.#releaseProvenanceJoin();
23604
24673
  const provenance = config.provenance;
24674
+ this.#releaseProvenanceJoin();
23605
24675
  const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
23606
24676
  const ingress = protectedTracks === void 0 ? void 0 : {
23607
24677
  tracks: Object.freeze(
@@ -23654,8 +24724,13 @@ var MulticastManager = class {
23654
24724
  * feeds the flow's receiver; media datagrams are held until one admits them.
23655
24725
  */
23656
24726
  #joinProvenance(provenance, ingress) {
24727
+ this.#router.registerProvenanceFlow(ingress, this.#provenanceReceiver(provenance));
24728
+ this.#hookFailback();
24729
+ this.#provenanceJoin = { flow: ingress.flow };
24730
+ }
24731
+ #provenanceReceiver(provenance) {
23657
24732
  const { flow, auth } = provenance;
23658
- const receiver = new BcProvenanceV2Receiver({
24733
+ return new BcProvenanceV2Receiver({
23659
24734
  ...provenance.receiver,
23660
24735
  // The caller's ctx when it passes one, else the catalog's: an explicit
23661
24736
  // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
@@ -23672,9 +24747,6 @@ var MulticastManager = class {
23672
24747
  maxAuthDelayMs: flow.maxAuthDelayMs,
23673
24748
  manifestTimerMs: flow.manifestTimerMs
23674
24749
  });
23675
- this.#router.registerProvenanceFlow(ingress, receiver);
23676
- this.#hookFailback();
23677
- this.#provenanceJoin = { flow: ingress.flow };
23678
24750
  }
23679
24751
  /** Un-protect: drop the flow's hold queues (no expiry counted). */
23680
24752
  #releaseProvenanceJoin() {
@@ -23705,8 +24777,25 @@ var MulticastManager = class {
23705
24777
  * callback delivers must come from a subscription opened on
23706
24778
  * `options.gateway`. A callback that also merges another source (a MoQ or
23707
24779
  * WebSocket repair feed) must not name a native provider here.
24780
+ *
24781
+ * An endpoint's `provenance` makes its group a protected flow of its own
24782
+ * (multicast-02 7.2.7), registered here and released with the group; its
24783
+ * records ride in band on the group's port. On the user-agent path a
24784
+ * flow-less repair group of a protected track is set aside, never read, so
24785
+ * a player joining a protected catalog's repair groups passes it.
23708
24786
  */
23709
24787
  joinRepairEndpoints(endpoints, provider, options) {
24788
+ for (const { provenance, flow, source, group, port } of endpoints) {
24789
+ if (provenance === void 0) continue;
24790
+ if (flow !== void 0) {
24791
+ throw new TypeError("[MulticastManager] joinRepairEndpoints: an endpoint names provenance or flow, never both");
24792
+ }
24793
+ if (!sameIpAddress(source, provenance.flow.source) || !sameIpAddress(group, provenance.flow.groupAddress) || port !== provenance.flow.port) {
24794
+ throw new RangeError(
24795
+ "[MulticastManager] joinRepairEndpoints: provenance flow (S, G, port) must match the endpoint's source, group and port"
24796
+ );
24797
+ }
24798
+ }
23710
24799
  const releases = [];
23711
24800
  let released = false;
23712
24801
  const safely = (each) => {
@@ -23716,17 +24805,36 @@ var MulticastManager = class {
23716
24805
  console.warn("[MulticastManager] repair group release failed", error);
23717
24806
  }
23718
24807
  };
24808
+ const usedFlows = new Set(endpoints.flatMap(({ flow }) => flow === void 0 ? [] : [flow]));
24809
+ const preparedProvenance = endpoints.map((endpoint) => {
24810
+ if (endpoint.provenance === void 0) return void 0;
24811
+ const flow = multicastProvenanceFlowKey(endpoint.provenance.flow);
24812
+ if (usedFlows.has(flow) || this.#provenanceJoin?.flow === flow || [...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
24813
+ throw new TypeError(`[MulticastManager] joinRepairEndpoints: provenance flow already registered: ${flow}`);
24814
+ }
24815
+ usedFlows.add(flow);
24816
+ return { flow, receiver: this.#provenanceReceiver(endpoint.provenance) };
24817
+ });
24818
+ const provenanceFlows = [];
23719
24819
  const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners.map((owner) => owner.instance !== "keyframe" ? owner : {
23720
24820
  ...owner,
23721
24821
  ownerTrackName: endpoint.tracks.find((t) => t.packetId === owner.ownerPacketId)?.name,
23722
24822
  repairTrackName: endpoint.tracks.find((t) => t.packetId === owner.packetId)?.name
23723
24823
  }));
23724
24824
  this.#applyRepairOwners(repairOwners);
23725
- for (const endpoint of endpoints) {
24825
+ for (const [index, endpoint] of endpoints.entries()) {
24826
+ const flow = endpoint.provenance === void 0 ? endpoint.flow : multicastProvenanceFlowKey(endpoint.provenance.flow);
23726
24827
  const ingress = {
23727
24828
  tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
23728
- ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
24829
+ ...flow === void 0 ? {} : { flow }
23729
24830
  };
24831
+ if (endpoint.provenance !== void 0) {
24832
+ const prepared = preparedProvenance[index];
24833
+ if (prepared === void 0) throw new Error("[MulticastManager] repair provenance preparation missing");
24834
+ this.#router.registerProvenanceFlow(ingress, prepared.receiver);
24835
+ provenanceFlows.push(prepared.flow);
24836
+ releases.push(() => this.#router.releaseProvenanceFlow(flow));
24837
+ }
23730
24838
  let sender;
23731
24839
  const feed = (packet, sourceAddress, ingressToFeed) => {
23732
24840
  if (released) return;
@@ -23756,7 +24864,7 @@ var MulticastManager = class {
23756
24864
  packetIds: endpoint.packetIds,
23757
24865
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
23758
24866
  // A protected repair group's records ride in band on its port (7.2.3).
23759
- ...endpoint.flow === void 0 ? {} : { protected: true }
24867
+ ...flow === void 0 ? {} : { protected: true }
23760
24868
  }, ingress).then((joined) => {
23761
24869
  if (!joined && !released) fail(transport.lastJoinOutcome);
23762
24870
  });
@@ -23765,9 +24873,12 @@ var MulticastManager = class {
23765
24873
  if (released) return;
23766
24874
  released = true;
23767
24875
  this.#repairReleases.delete(release);
24876
+ this.#repairProvenanceFlows.delete(release);
23768
24877
  for (const each of releases.splice(0)) safely(each);
23769
24878
  };
23770
24879
  this.#repairReleases.set(release, repairOwners);
24880
+ this.#repairProvenanceFlows.set(release, provenanceFlows);
24881
+ if (provenanceFlows.length) this.#hookFailback();
23771
24882
  return release;
23772
24883
  }
23773
24884
  #applyRepairOwners(owners) {
@@ -24253,7 +25364,8 @@ var MulticastManager = class {
24253
25364
  blockProfile: parseFecBlockProfile(
24254
25365
  geometry2.blockProfile,
24255
25366
  `tracks[${JSON.stringify(track.name)}].fec keyframe overlay blockProfile`
24256
- )
25367
+ ),
25368
+ geometry: geometry2
24257
25369
  });
24258
25370
  }
24259
25371
  }
@@ -24292,7 +25404,7 @@ var MulticastManager = class {
24292
25404
  for (const [sourcePacketId, install] of [...this.#overlayInstalls]) {
24293
25405
  const before = this.#overlayBindings.get(sourcePacketId);
24294
25406
  const after = overlayBindings.get(sourcePacketId);
24295
- const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => after[key] === before[key]);
25407
+ const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => key === "geometry" || after[key] === before[key]);
24296
25408
  if (!same) install.dispose();
24297
25409
  else if (this.#router.hasKeyframeOverlay(after.repairPacketId)) this.#router.resetKeyframeOverlays(sourcePacketId);
24298
25410
  else install.reattach();
@@ -24349,10 +25461,12 @@ var MulticastManager = class {
24349
25461
  * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
24350
25462
  * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
24351
25463
  * pending hole and reported here, and `closeIsoHoles` must be called for it
24352
- * once its range FETCH ends (or none is sent).
25464
+ * once its range FETCH ends (or none is sent). `onExpired` is told of a
25465
+ * pending hole the stream runs past the locator's horizon: returning true,
25466
+ * the caller closes it (`closeIsoHoles`); otherwise it is discarded.
24353
25467
  */
24354
- onUndelimitedLoss(cb) {
24355
- this.#fec.setUndelimitedLossHandler(cb);
25468
+ onUndelimitedLoss(cb, onExpired) {
25469
+ this.#fec.setUndelimitedLossHandler(cb, onExpired ?? null);
24356
25470
  }
24357
25471
  /**
24358
25472
  * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
@@ -24588,7 +25702,8 @@ var MulticastManager = class {
24588
25702
  "stream" in event ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
24589
25703
  ...event,
24590
25704
  block: Object.freeze({ ...event.block }),
24591
- ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {}
25705
+ ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {},
25706
+ ..."span" in event && event.span !== void 0 ? { span: Object.freeze({ ...event.span }) } : {}
24592
25707
  }
24593
25708
  );
24594
25709
  if (this.#logRepairLifecycle) {