@blockcast/mmt-container 2.2.0-main.c4fa878f4ff4 → 2.2.0-main.cb533d6dfc95

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 (89) hide show
  1. package/README.md +29 -17
  2. package/dist/browser-runtime.js +1540 -317
  3. package/dist/browser-runtime.js.map +3 -3
  4. package/dist/catalog-fec-params.d.ts +17 -1
  5. package/dist/catalog-fec-params.d.ts.map +1 -1
  6. package/dist/catalog-fec-params.js +15 -0
  7. package/dist/catalog-fec-params.js.map +2 -2
  8. package/dist/cmaf-block-assembler.js +92 -1
  9. package/dist/cmaf-block-assembler.js.map +2 -2
  10. package/dist/cmcd-producer.d.ts +60 -47
  11. package/dist/cmcd-producer.d.ts.map +1 -1
  12. package/dist/cmcd-producer.js +138 -109
  13. package/dist/cmcd-producer.js.map +2 -2
  14. package/dist/codec-utils.d.ts.map +1 -1
  15. package/dist/codec-utils.js +92 -1
  16. package/dist/codec-utils.js.map +2 -2
  17. package/dist/delivery-catalog.js +26 -16
  18. package/dist/delivery-catalog.js.map +2 -2
  19. package/dist/delta-fallback-config.js.map +1 -1
  20. package/dist/fec-manager.d.ts +83 -15
  21. package/dist/fec-manager.d.ts.map +1 -1
  22. package/dist/fec-manager.js +446 -61
  23. package/dist/fec-manager.js.map +2 -2
  24. package/dist/fec-worker-setup.d.ts +1 -1
  25. package/dist/fec-worker-setup.js +1 -1
  26. package/dist/fec-worker-setup.js.map +1 -1
  27. package/dist/index.d.ts +4 -4
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +5 -1
  30. package/dist/index.js.map +2 -2
  31. package/dist/iso-block-locator.d.ts +48 -13
  32. package/dist/iso-block-locator.d.ts.map +1 -1
  33. package/dist/iso-block-locator.js +97 -25
  34. package/dist/iso-block-locator.js.map +2 -2
  35. package/dist/iso-bmff-timing.d.ts +10 -1
  36. package/dist/iso-bmff-timing.d.ts.map +1 -1
  37. package/dist/iso-bmff-timing.js +36 -2
  38. package/dist/iso-bmff-timing.js.map +2 -2
  39. package/dist/media-router.js.map +1 -1
  40. package/dist/mmtp-container-parser.d.ts +79 -10
  41. package/dist/mmtp-container-parser.d.ts.map +1 -1
  42. package/dist/mmtp-container-parser.js +299 -27
  43. package/dist/mmtp-container-parser.js.map +2 -2
  44. package/dist/mmtp-container-parser.no-modules.js +301 -30
  45. package/dist/mmtp-container-parser.no-modules.js.map +3 -3
  46. package/dist/mmtp-decode-pipeline.js +298 -27
  47. package/dist/mmtp-decode-pipeline.js.map +2 -2
  48. package/dist/mmtp-router.d.ts +34 -8
  49. package/dist/mmtp-router.d.ts.map +1 -1
  50. package/dist/mmtp-router.js +647 -80
  51. package/dist/mmtp-router.js.map +3 -3
  52. package/dist/multicast-manager.d.ts +26 -3
  53. package/dist/multicast-manager.d.ts.map +1 -1
  54. package/dist/multicast-manager.js +1183 -160
  55. package/dist/multicast-manager.js.map +3 -3
  56. package/dist/multicast-transport.js +28 -18
  57. package/dist/multicast-transport.js.map +2 -2
  58. package/dist/no-modules.js +298 -27
  59. package/dist/no-modules.js.map +3 -3
  60. package/dist/repair-fetch.d.ts +38 -8
  61. package/dist/repair-fetch.d.ts.map +1 -1
  62. package/dist/repair-fetch.js +286 -27
  63. package/dist/repair-fetch.js.map +3 -3
  64. package/dist/repair-layer-subscriptions.d.ts +6 -2
  65. package/dist/repair-layer-subscriptions.d.ts.map +1 -1
  66. package/dist/repair-layer-subscriptions.js +6 -3
  67. package/dist/repair-layer-subscriptions.js.map +2 -2
  68. package/dist/track-session.d.ts +1 -1
  69. package/dist/track-session.d.ts.map +1 -1
  70. package/dist/track-session.js +1 -0
  71. package/dist/track-session.js.map +2 -2
  72. package/dist/wasm-mmtp-container-parser.js +298 -27
  73. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  74. package/package.json +8 -5
  75. package/schemas/catalog.schema.json +4 -0
  76. package/src/catalog-fec-params.ts +36 -1
  77. package/src/cmcd-producer.ts +189 -179
  78. package/src/codec-utils.ts +121 -1
  79. package/src/fec-manager.ts +487 -35
  80. package/src/fec-worker-setup.ts +2 -2
  81. package/src/index.ts +9 -2
  82. package/src/iso-block-locator.ts +133 -31
  83. package/src/iso-bmff-timing.ts +40 -1
  84. package/src/mmtp-container-parser.ts +306 -29
  85. package/src/mmtp-router.ts +548 -38
  86. package/src/multicast-manager.ts +134 -16
  87. package/src/repair-fetch.ts +366 -50
  88. package/src/repair-layer-subscriptions.ts +13 -5
  89. package/src/track-session.ts +4 -1
@@ -1189,6 +1189,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
1189
1189
  this.#heldEvicted = 0;
1190
1190
  /** Pending holes (see `deferIncompleteGaps`): unstated, sources still held. */
1191
1191
  this.#holes = [];
1192
+ /** Holes the horizon passed while pending: sources held until closed. */
1193
+ this.#expired = [];
1194
+ /** Of `#expired`, those `takeExpiredHoles` has not handed out yet. */
1195
+ this.#newlyExpired = [];
1196
+ /**
1197
+ * Spans closed from expired holes: behind the horizon, so kept only for
1198
+ * `locate` while their sources are fed, until the next retirement.
1199
+ */
1200
+ this.#closedBehind = [];
1192
1201
  /**
1193
1202
  * Keep a gap that is missing a source as a pending hole rather than a span,
1194
1203
  * so a repair FETCHed for it (draft-ramadan-moq-fec §7.5) can still state
@@ -1210,7 +1219,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
1210
1219
  #retentionBlocks;
1211
1220
  #heldEvicted;
1212
1221
  #newest;
1222
+ #newestSource;
1213
1223
  #holes;
1224
+ #expired;
1225
+ #newlyExpired;
1226
+ #closedBehind;
1214
1227
  static #checkedRetention(retentionBlocks) {
1215
1228
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
1216
1229
  throw new Error(
@@ -1247,6 +1260,21 @@ var IsoBlockLocator = class _IsoBlockLocator {
1247
1260
  observe(position) {
1248
1261
  if (this.#newest === void 0 || serial32Precedes(this.#newest, position)) this.#newest = position;
1249
1262
  }
1263
+ /**
1264
+ * The newest source SS_ID noted with `noteSource` (RFC 1982 order). Unlike
1265
+ * `newest`, a repair never moves it: a repair can run ahead of its sources,
1266
+ * a source cannot run ahead of the sources sent before it except by
1267
+ * reordering.
1268
+ */
1269
+ get newestSource() {
1270
+ return this.#newestSource;
1271
+ }
1272
+ /** Note a received source's SS_ID; true when it is the newest one yet. */
1273
+ noteSource(ssId) {
1274
+ if (this.#newestSource !== void 0 && !serial32Precedes(this.#newestSource, ssId)) return false;
1275
+ this.#newestSource = ssId;
1276
+ return true;
1277
+ }
1250
1278
  /** Held sources evicted by `heldCapacity` (never by the horizon itself). */
1251
1279
  get heldEvicted() {
1252
1280
  return this.#heldEvicted;
@@ -1265,17 +1293,29 @@ var IsoBlockLocator = class _IsoBlockLocator {
1265
1293
  }
1266
1294
  /** The known block or span containing `ssId`, with its ESI. */
1267
1295
  locate(ssId) {
1268
- for (let i = this.#blocks.length - 1; i >= 0; i--) {
1269
- const block = this.#blocks[i];
1270
- if (isoBlockContains(block.start, block.length, ssId)) {
1271
- return { block, esi: serial32Distance(block.start, ssId) };
1296
+ for (const blocks of [this.#blocks, this.#closedBehind]) {
1297
+ for (let i = blocks.length - 1; i >= 0; i--) {
1298
+ const block = blocks[i];
1299
+ if (isoBlockContains(block.start, block.length, ssId)) {
1300
+ return { block, esi: serial32Distance(block.start, ssId) };
1301
+ }
1272
1302
  }
1273
1303
  }
1274
1304
  return null;
1275
1305
  }
1276
- /** Number of pending holes. */
1306
+ /** Number of holes not closed yet, pending or past the horizon. */
1277
1307
  get holeCount() {
1278
- return this.#holes.length;
1308
+ return this.#holes.length + this.#expired.length;
1309
+ }
1310
+ /**
1311
+ * The pending holes the horizon has passed since the last call, in the
1312
+ * order it passed them. Each is no longer pending: no repair states a block
1313
+ * in it (that repair is `stale`, as for a span the horizon retired) and the
1314
+ * release gate does not wait for it. Its owner must close it
1315
+ * (`closeHolesWithin`), which turns it into a span that is not kept here.
1316
+ */
1317
+ takeExpiredHoles() {
1318
+ return this.#newlyExpired.splice(0);
1279
1319
  }
1280
1320
  /** The stated block (never a span) ending exactly at `end`. */
1281
1321
  blockEndingAt(end) {
@@ -1331,9 +1371,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
1331
1371
  /**
1332
1372
  * Apply one repair symbol's `(SS_Start, SSB_length)`. The first repair of a
1333
1373
  * block states its range and places every held source in it; later repair
1334
- * symbols of the same block change nothing. A range that contradicts a
1335
- * known block (a different length, or an overlap with another block or a
1336
- * span) fails closed: the repair symbol is dropped and no block changes.
1374
+ * symbols of the same block change nothing. A repair whose range is exactly
1375
+ * a repair-less span states that span's one block. A range that contradicts
1376
+ * a known block (a different length, or an overlap with another block or
1377
+ * with part of a span) fails closed: the repair symbol is dropped and no
1378
+ * block changes.
1337
1379
  * A newly stated block retires behind its SS_Start (see the class note).
1338
1380
  * A block so far past `newest` that stating it would retire the position
1339
1381
  * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
@@ -1352,7 +1394,16 @@ var IsoBlockLocator = class _IsoBlockLocator {
1352
1394
  const known = this.blockAt(start);
1353
1395
  if (known !== void 0) {
1354
1396
  if (known.span) {
1355
- return { status: "overlap", reason: `repair block ${start}+${length} falls inside a repair-less span` };
1397
+ if (known.length === length) {
1398
+ const block2 = { start, length, span: false };
1399
+ this.#blocks[this.#blocks.indexOf(known)] = block2;
1400
+ return { status: "placed", block: block2, placed: [] };
1401
+ }
1402
+ return length < known.length ? {
1403
+ status: "overlap",
1404
+ reason: `repair block ${start}+${length} is only the first block of repair-less span ${known.start}+${known.length}`,
1405
+ ofSpan: known
1406
+ } : { status: "overlap", reason: `repair block ${start}+${length} runs past repair-less span ${known.start}+${known.length}` };
1356
1407
  }
1357
1408
  if (known.length !== length) {
1358
1409
  return {
@@ -1420,18 +1471,28 @@ var IsoBlockLocator = class _IsoBlockLocator {
1420
1471
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
1421
1472
  }
1422
1473
  /**
1423
- * Turn every pending hole inside `[start, start + length)` into a
1424
- * repair-less span, claiming its held sources: its range FETCH ended, so
1425
- * nothing more will state its blocks. Returns the spans, in SS_ID order.
1474
+ * Turn every hole inside `[start, start + length)` into a repair-less span,
1475
+ * claiming its held sources: its range FETCH ended, so nothing more will
1476
+ * state its blocks. A hole the horizon passed (`takeExpiredHoles`) leaves a
1477
+ * span that is not kept among the blocks, as the horizon would retire it at
1478
+ * once; only `locate` finds it, until the next retirement, so its sources
1479
+ * can be fed. Returns the spans, in SS_ID order.
1426
1480
  */
1427
1481
  closeHolesWithin(start, length) {
1428
1482
  const closed = [];
1429
- for (const hole of [...this.#holes]) {
1430
- if (!isoBlockContains(start, length, hole.start)) continue;
1431
- this.#holes.splice(this.#holes.indexOf(hole), 1);
1432
- const spanBlock = { start: hole.start, length: hole.length, span: true };
1433
- closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
1434
- this.#blocks.push(spanBlock);
1483
+ for (const holes of [this.#holes, this.#expired]) {
1484
+ for (const hole of [...holes]) {
1485
+ if (!isoBlockContains(start, length, hole.start)) continue;
1486
+ holes.splice(holes.indexOf(hole), 1);
1487
+ const spanBlock = { start: hole.start, length: hole.length, span: true };
1488
+ closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
1489
+ if (holes === this.#holes) {
1490
+ this.#blocks.push(spanBlock);
1491
+ } else {
1492
+ this.#closedBehind.push(spanBlock);
1493
+ if (this.#newlyExpired.includes(hole)) this.#newlyExpired.splice(this.#newlyExpired.indexOf(hole), 1);
1494
+ }
1495
+ }
1435
1496
  }
1436
1497
  return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
1437
1498
  }
@@ -1445,15 +1506,17 @@ var IsoBlockLocator = class _IsoBlockLocator {
1445
1506
  return void 0;
1446
1507
  }
1447
1508
  /**
1448
- * Retire every block and span whose last SS_ID, and every held source,
1449
- * lies more than `retentionBlocks` blocks behind `position`, with the shared
1450
- * lower-bound metric (`isoBlocksBehindLowerBound`) every ISO interleave
1451
- * horizon uses. Returns the retired block starts.
1509
+ * Retire every block and span whose last SS_ID, and every held source
1510
+ * outside a hole, lies more than `retentionBlocks` blocks behind
1511
+ * `position`, with the shared lower-bound metric (`isoBlocksBehindLowerBound`)
1512
+ * every ISO interleave horizon uses; a pending hole so far behind expires
1513
+ * (`takeExpiredHoles`). Returns the retired block starts.
1452
1514
  */
1453
1515
  retireBehind(position) {
1454
1516
  this.observe(position);
1455
1517
  const horizon = this.#retentionBlocks;
1456
1518
  const retired = [];
1519
+ this.#closedBehind.length = 0;
1457
1520
  for (let i = this.#blocks.length - 1; i >= 0; i--) {
1458
1521
  const block = this.#blocks[i];
1459
1522
  const last = serial32Add(block.start, block.length - 1);
@@ -1465,10 +1528,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
1465
1528
  for (let i = this.#holes.length - 1; i >= 0; i--) {
1466
1529
  const hole = this.#holes[i];
1467
1530
  const last = serial32Add(hole.start, hole.length - 1);
1468
- if (isoBlocksBehindLowerBound(last, position, this.#kMax) > horizon) this.#holes.splice(i, 1);
1531
+ if (isoBlocksBehindLowerBound(last, position, this.#kMax) <= horizon) continue;
1532
+ this.#holes.splice(i, 1);
1533
+ this.#expired.push(hole);
1534
+ this.#newlyExpired.push(hole);
1469
1535
  }
1470
1536
  for (const ssId of [...this.#held.keys()]) {
1471
- if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon) this.#held.delete(ssId);
1537
+ if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon && !this.#holes.some((hole) => isoBlockContains(hole.start, hole.length, ssId)) && !this.#expired.some((hole) => isoBlockContains(hole.start, hole.length, ssId))) {
1538
+ this.#held.delete(ssId);
1539
+ }
1472
1540
  }
1473
1541
  return retired;
1474
1542
  }
@@ -1476,9 +1544,13 @@ var IsoBlockLocator = class _IsoBlockLocator {
1476
1544
  reset() {
1477
1545
  this.#blocks.length = 0;
1478
1546
  this.#holes.length = 0;
1547
+ this.#expired.length = 0;
1548
+ this.#newlyExpired.length = 0;
1549
+ this.#closedBehind.length = 0;
1479
1550
  this.#held.clear();
1480
1551
  this.#coverageEnd = void 0;
1481
1552
  this.#newest = void 0;
1553
+ this.#newestSource = void 0;
1482
1554
  }
1483
1555
  #claim(block) {
1484
1556
  const placed = [];
@@ -2067,6 +2139,7 @@ var WORKER_ERROR_LOG_CAP = 5;
2067
2139
  var WORKER_ERROR_KIND_CAP = 32;
2068
2140
  var WORKER_ERROR_OVERFLOW_KIND = "other";
2069
2141
  var STARTUP_REPAIR_WAIT_SOURCE_BOUNDARIES = 2;
2142
+ var NOT_TAKEN = Object.freeze({ taken: false, recovered: null });
2070
2143
  function isMulticastSymbolDelivery(value) {
2071
2144
  return value === "datagram" || value === "ordered-relay";
2072
2145
  }
@@ -2160,10 +2233,18 @@ var FECManager = class _FECManager {
2160
2233
  // 'pending' forever, which would park every later frame of its stream in
2161
2234
  // the in-order release gate. Each entry owns its handle; the callback
2162
2235
  // checks it still owns the key, so a settled or reset key is never touched.
2236
+ /**
2237
+ * Per owed Worker cleanup: the bound on its acknowledgement, when its block
2238
+ * was due, and when its cleanup was asked for (see `onCleanupComplete`).
2239
+ */
2163
2240
  this.#pendingWorkerCleanupBounds = /* @__PURE__ */ new Map();
2164
2241
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
2165
2242
  this.#blockSourceCounts = /* @__PURE__ */ new Map();
2166
2243
  this.#blockSourceEsis = /* @__PURE__ */ new Map();
2244
+ // Source ESIs per block that another FEC instance rebuilt and fed in
2245
+ // (feedRebuiltSourceSymbol). Kept apart from #blockSourceEsis: they are
2246
+ // not network arrivals and never make a block clean.
2247
+ this.#blockRebuiltEsis = /* @__PURE__ */ new Map();
2167
2248
  // Authored SSB_length per block (ISO/IEC 23008-1 §C.5.3), learned from the
2168
2249
  // first repair symbol. The FFmpeg moq_mmt publisher closes a block every D
2169
2250
  // media units, usually before it holds K symbols; under iso-ssbg1-v1
@@ -2172,10 +2253,14 @@ var FECManager = class _FECManager {
2172
2253
  // SSB_length source arrivals and recoverable from SSB_length received
2173
2254
  // symbols; waiting for K fails every one of them.
2174
2255
  this.#blockAuthoredLengths = /* @__PURE__ */ new Map();
2256
+ // Keys whose authored length is a repair-less span's (#openIsoSpan), until
2257
+ // a repair states the block there or the span resolves.
2258
+ this.#isoSpanKeys = /* @__PURE__ */ new Set();
2175
2259
  this.#ssbLengthConflictCount = 0;
2176
2260
  this.#blockRepairRsIds = /* @__PURE__ */ new Map();
2177
2261
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
2178
- // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
2262
+ // symbols its repair group carries; 0 for a repair-less span no repair can
2263
+ // state (#openIsoSpan). Same lifecycle as #blockRepairRsIds.
2179
2264
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
2180
2265
  /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
2181
2266
  this.#heldLayerStates = /* @__PURE__ */ new Map();
@@ -2292,6 +2377,10 @@ var FECManager = class _FECManager {
2292
2377
  // ── Keyframe-protected repair policy (block-policy.ts) ──
2293
2378
  // One classifier per physical stream, built from that stream's geometry.
2294
2379
  this.#classifiers = /* @__PURE__ */ new Map();
2380
+ // A stream without catalog timing has no classifier, so the last RAP it
2381
+ // released stands in for one: "an MPU boundary bounds its RAPs" holds until
2382
+ // a second RAP is released inside one MPU (BLO-52085).
2383
+ this.#noSpanRaps = /* @__PURE__ */ new Map();
2295
2384
  // Geometry a stream-scoped configuration gave one stream (streamKey). ABR
2296
2385
  // rungs can share a packetId with a different framerate or GOP, so the
2297
2386
  // packet-level geometry is only the geometry of a packet whose streams
@@ -2365,7 +2454,10 @@ var FECManager = class _FECManager {
2365
2454
  // arrives via onBlockRecovered callback.
2366
2455
  this.onBlockStarted = null;
2367
2456
  this.onBlockComplete = null;
2368
- /** A block reached its fail bound. `blockClass` is its class at failure. */
2457
+ /**
2458
+ * A block reached its fail bound. `blockClass` is its class at failure.
2459
+ * `span` is set when what failed is a repair-less span starting at `sbn`.
2460
+ */
2369
2461
  this.onBlockFailed = null;
2370
2462
  /**
2371
2463
  * Fired once per stream when its Worker decoder stops being routable.
@@ -2407,12 +2499,22 @@ var FECManager = class _FECManager {
2407
2499
  * for it, which it must be.
2408
2500
  */
2409
2501
  this.#onUndelimitedLoss = null;
2502
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
2503
+ this.#onIsoHoleExpired = null;
2410
2504
  /** A block every symbol of which vanished was created by SBN evidence. */
2411
2505
  this.onBlockVanished = null;
2412
2506
  /** A block reached a terminal state (completed, recovered, or failed). */
2413
2507
  this.onBlockResolved = null;
2414
2508
  /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
2415
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 block only a late source can
2515
+ * complete also waits for that overlay's repair (#lateSourceWaitMs).
2516
+ */
2517
+ this.keyframeOverlayTiming = null;
2416
2518
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
2417
2519
  /**
2418
2520
  * A recovered source symbol. Return false when admission refused the
@@ -2449,7 +2551,9 @@ var FECManager = class _FECManager {
2449
2551
  #pendingWorkerCleanupBounds;
2450
2552
  #blockSourceCounts;
2451
2553
  #blockSourceEsis;
2554
+ #blockRebuiltEsis;
2452
2555
  #blockAuthoredLengths;
2556
+ #isoSpanKeys;
2453
2557
  #ssbLengthConflictCount;
2454
2558
  #blockRepairRsIds;
2455
2559
  #blockRsbLengths;
@@ -2491,6 +2595,7 @@ var FECManager = class _FECManager {
2491
2595
  #orderedFrontiers;
2492
2596
  #orderedPendingBlocks;
2493
2597
  #classifiers;
2598
+ #noSpanRaps;
2494
2599
  #streamGeometries;
2495
2600
  #failedBlocks;
2496
2601
  #resolvedBlockClasses;
@@ -2515,6 +2620,7 @@ var FECManager = class _FECManager {
2515
2620
  #decoderUnavailableEvents;
2516
2621
  #repairSymbolSizeMismatchCount;
2517
2622
  #onUndelimitedLoss;
2623
+ #onIsoHoleExpired;
2518
2624
  #encodeTrackName(catalogTrackName) {
2519
2625
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
2520
2626
  if (encoded === void 0) {
@@ -2986,7 +3092,10 @@ var FECManager = class _FECManager {
2986
3092
  timer.handle = null;
2987
3093
  this.#requestRepair(sbn, packetId, catalogTrackName);
2988
3094
  };
2989
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
3095
+ timer.handle = setTimeout(
3096
+ onFire,
3097
+ this.#receiptAtMs === void 0 ? Math.max(0, deadlineMs - performance.now()) : this.#receiptTimerDelayMs(deadlineMs, 0)
3098
+ );
2990
3099
  this.#repairDeadlines.set(key, timer);
2991
3100
  }
2992
3101
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -3130,8 +3239,14 @@ var FECManager = class _FECManager {
3130
3239
  * Vanished blocks are not enumerated here: their starts are unknown until a
3131
3240
  * repair states them. The SS_IDs between two stated blocks become one
3132
3241
  * repair-less span when the later block's repair arrives (placeIsoRepair).
3242
+ *
3243
+ * A `held` source arrived before its block was known and is fed only now
3244
+ * that a repair, a span or a closed hole placed it: how far its block start
3245
+ * then lies behind the frontier measures how long the receiver held it, not
3246
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
3247
+ * it (BLO-52085).
3133
3248
  */
3134
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
3249
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn, held = false) {
3135
3250
  const streamKey = this.#streamKey(packetId, catalogTrackName);
3136
3251
  const now = performance.now();
3137
3252
  const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
@@ -3152,6 +3267,7 @@ var FECManager = class _FECManager {
3152
3267
  };
3153
3268
  const discontinuity = () => {
3154
3269
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity();
3270
+ this.#noSpanRaps.delete(streamKey);
3155
3271
  this.#highestSbn.set(streamKey, { sbn, atMs: now });
3156
3272
  this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
3157
3273
  if (psn === void 0) this.#sourceAnchors.delete(streamKey);
@@ -3169,7 +3285,7 @@ var FECManager = class _FECManager {
3169
3285
  return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
3170
3286
  };
3171
3287
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
3172
- if (symbol === "source" && window2 !== null && this.#blockPrecedes(sbn, previous.sbn) && (this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId) || psn !== void 0 && anchor !== void 0 && serial32Precedes(ssId, anchor.ssId) && psn !== anchor.psn && !sentInOrder({ ssId, psn }, anchor))) {
3288
+ if (symbol === "source" && window2 !== null && this.#blockPrecedes(sbn, previous.sbn) && (!held && this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId) || psn !== void 0 && anchor !== void 0 && serial32Precedes(ssId, anchor.ssId) && psn !== anchor.psn && !sentInOrder({ ssId, psn }, anchor))) {
3173
3289
  discontinuity();
3174
3290
  return;
3175
3291
  }
@@ -3431,17 +3547,21 @@ var FECManager = class _FECManager {
3431
3547
  this.#blockWaitDeadlinesMs.delete(key);
3432
3548
  this.#repairHoldUntilMs.delete(key);
3433
3549
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
3434
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName);
3550
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs);
3435
3551
  };
3436
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)));
3552
+ timer.handle = setTimeout(
3553
+ onFire,
3554
+ this.#receiptAtMs === void 0 ? Math.max(1, Math.ceil(deadlineMs - nowMs)) : this.#receiptTimerDelayMs(deadlineMs, 1)
3555
+ );
3437
3556
  this.#activeBlocks.set(key, timer);
3438
3557
  this.#indexBlockKey(key, sbn, packetId);
3439
3558
  }
3440
3559
  /**
3441
3560
  * Hand a block whose delivery is over to its decoder for finalization: the
3442
- * datagram deadline fired, or the ordered relay moved past it.
3561
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
3562
+ * is when it was due: its deadline, or now.
3443
3563
  */
3444
- #finalizeExpiredBlock(sbn, packetId, catalogTrackName) {
3564
+ #finalizeExpiredBlock(sbn, packetId, catalogTrackName, dueAtMs = performance.now()) {
3445
3565
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
3446
3566
  if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
3447
3567
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -3457,7 +3577,7 @@ var FECManager = class _FECManager {
3457
3577
  if (workerClient) {
3458
3578
  this.#pendingWorkerCleanups.add(key);
3459
3579
  this.#pendingWorkerCleanupClients.set(key, workerClient);
3460
- this.#boundOwedCleanup(key, packetId, workerClient);
3580
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs);
3461
3581
  workerClient.cleanup(sbn);
3462
3582
  } else {
3463
3583
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
@@ -3564,6 +3684,9 @@ var FECManager = class _FECManager {
3564
3684
  }
3565
3685
  if (policyChanged) {
3566
3686
  this.#bumpEpoch(packetId);
3687
+ for (const key of [...this.#noSpanRaps.keys()]) {
3688
+ if (this.#belongsToPacket(key, packetId)) this.#noSpanRaps.delete(key);
3689
+ }
3567
3690
  for (const [key, classifier] of [...this.#classifiers]) {
3568
3691
  if (!this.#belongsToPacket(key, packetId)) continue;
3569
3692
  const stream = this.#parseStreamKey(key);
@@ -3766,7 +3889,9 @@ var FECManager = class _FECManager {
3766
3889
  }
3767
3890
  resetMap(this.#blockSourceCounts);
3768
3891
  resetMap(this.#blockSourceEsis);
3892
+ resetMap(this.#blockRebuiltEsis);
3769
3893
  resetMap(this.#blockAuthoredLengths);
3894
+ resetSet(this.#isoSpanKeys);
3770
3895
  resetMap(this.#blockRepairRsIds);
3771
3896
  resetMap(this.#blockRsbLengths);
3772
3897
  resetMap(this.#heldLayerStates);
@@ -3799,6 +3924,7 @@ var FECManager = class _FECManager {
3799
3924
  resetMap(this.#isoLocators);
3800
3925
  resetMap(this.#sourceAnchors);
3801
3926
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName));
3927
+ this.#noSpanRaps.delete(this.#streamKey(packetId, catalogTrackName));
3802
3928
  this.#bumpEpoch(packetId);
3803
3929
  for (const [sbn, keys] of this.#blockKeysBySbn) {
3804
3930
  for (const key of keys.keys()) {
@@ -3889,7 +4015,9 @@ var FECManager = class _FECManager {
3889
4015
  dropMap(this.#pendingWorkerCleanupClients);
3890
4016
  dropMap(this.#blockSourceCounts);
3891
4017
  dropMap(this.#blockSourceEsis);
4018
+ dropMap(this.#blockRebuiltEsis);
3892
4019
  dropMap(this.#blockAuthoredLengths);
4020
+ dropSet(this.#isoSpanKeys);
3893
4021
  dropMap(this.#blockRepairRsIds);
3894
4022
  dropMap(this.#blockRsbLengths);
3895
4023
  dropMap(this.#blockPathCounts);
@@ -3905,6 +4033,7 @@ var FECManager = class _FECManager {
3905
4033
  dropMap(this.#isoLocators);
3906
4034
  dropMap(this.#sourceAnchors);
3907
4035
  dropMap(this.#classifiers);
4036
+ dropMap(this.#noSpanRaps);
3908
4037
  dropMap(this.#streamGeometries);
3909
4038
  dropSet(this.#pendingWorkerCleanups);
3910
4039
  dropSet(this.#completedBlocks);
@@ -4050,6 +4179,9 @@ var FECManager = class _FECManager {
4050
4179
  this.#unindexBlockKey(key);
4051
4180
  }
4052
4181
  }
4182
+ if (isSourceSymbol && source === "multicast") {
4183
+ this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), sbn + esi >>> 0, packetId, catalogTrackName);
4184
+ }
4053
4185
  return true;
4054
4186
  }
4055
4187
  #observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName) {
@@ -4159,8 +4291,10 @@ var FECManager = class _FECManager {
4159
4291
  }
4160
4292
  /**
4161
4293
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
4162
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
4163
- * Undefined for a block that is not open.
4294
+ * (SSB_length) and RSB_length (each undefined until a repair stated it; a
4295
+ * repair-less span states its length, and RSB_length 0 when it is longer
4296
+ * than K, since no repair can reach it). Undefined for a block that is not
4297
+ * open.
4164
4298
  */
4165
4299
  blockSymbolCounts(sbn, packetId, catalogTrackName) {
4166
4300
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -4228,8 +4362,9 @@ var FECManager = class _FECManager {
4228
4362
  return true;
4229
4363
  }
4230
4364
  /**
4231
- * Drop a block's repair hold: its FETCH ended without delivering. The block
4232
- * falls back to its multicast wait, which may already have passed.
4365
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
4366
+ * back only a repair that cannot complete it. The block falls back to its
4367
+ * multicast wait, which may already have passed.
4233
4368
  */
4234
4369
  releaseRepairHold(sbn, packetId, catalogTrackName) {
4235
4370
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -4367,6 +4502,8 @@ var FECManager = class _FECManager {
4367
4502
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
4368
4503
  const evictedBefore = locator.heldEvicted;
4369
4504
  const held = locator.hold(ssId, source);
4505
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
4506
+ if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
4370
4507
  const evicted = locator.heldEvicted - evictedBefore;
4371
4508
  if (evicted > 0) {
4372
4509
  const before = this.#isoHeldEvictedCount;
@@ -4387,17 +4524,20 @@ var FECManager = class _FECManager {
4387
4524
  * contradicts a known block is refused (counted) and must be dropped.
4388
4525
  */
4389
4526
  placeIsoRepair(packetId, catalogTrackName, ssStart, ssbLength) {
4390
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength);
4527
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
4528
+ const placement = locator.placeRepair(ssStart, ssbLength);
4529
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
4391
4530
  if (placement.status !== "placed") {
4392
4531
  this.#isoRepairRefusedCount++;
4393
4532
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
4394
4533
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`);
4395
4534
  }
4535
+ if (placement.ofSpan !== void 0) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName);
4396
4536
  return placement;
4397
4537
  }
4538
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName));
4398
4539
  if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
4399
4540
  if (placement.hole !== void 0) {
4400
- const locator = this.#isoLocatorFor(packetId, catalogTrackName);
4401
4541
  const hole = placement.hole.block;
4402
4542
  const previous = locator.blockEndingAt(hole.start);
4403
4543
  const loss = {
@@ -4418,17 +4558,29 @@ var FECManager = class _FECManager {
4418
4558
  * `handler`, instead of a repair-less span; null restores spans. Set by the
4419
4559
  * range repair scheduler; applies to every stream from its next gap. The
4420
4560
  * handler and the deferral are one setting, so no hole is ever created with
4421
- * nobody to close it.
4561
+ * nobody to close it. `onExpired` is told of each pending hole the stream
4562
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
4563
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
4564
+ * reported; otherwise the hole is discarded with its sources.
4422
4565
  */
4423
- setUndelimitedLossHandler(handler) {
4566
+ setUndelimitedLossHandler(handler, onExpired = null) {
4424
4567
  this.#onUndelimitedLoss = handler;
4568
+ this.#onIsoHoleExpired = handler === null ? null : onExpired;
4425
4569
  this.#deferIsoGaps = handler !== null;
4426
4570
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
4427
4571
  }
4572
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
4573
+ #settleExpiredIsoHoles(locator, packetId, catalogTrackName) {
4574
+ for (const hole of locator.takeExpiredHoles()) {
4575
+ const expired = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length };
4576
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length);
4577
+ }
4578
+ }
4428
4579
  /**
4429
- * The range repair for a hole ended: every hole still pending inside
4430
- * `[start, start + length)` becomes a repair-less span. Returns those spans
4431
- * with the held sources they placed, for the caller to feed (MmtpRouter).
4580
+ * The range repair for a hole ended: every hole inside `[start, start +
4581
+ * length)`, pending or expired, becomes a repair-less span. Returns those
4582
+ * spans with the held sources they placed, for the caller to feed
4583
+ * (MmtpRouter).
4432
4584
  */
4433
4585
  closeIsoHoles(packetId, catalogTrackName, start, length) {
4434
4586
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
@@ -4444,10 +4596,22 @@ var FECManager = class _FECManager {
4444
4596
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
4445
4597
  * SS_ID of which vanished resolves through its deadline like any vanished
4446
4598
  * block.
4599
+ *
4600
+ * A span longer than K holds more than one block (SSB_length <= K), and the
4601
+ * locator states no block inside a span, only one exactly its range
4602
+ * (IsoBlockLocator.placeRepair): no repair, multicast or FETCHed, can ever
4603
+ * reach it. Its repair group is empty, so only its own late sources can
4604
+ * complete it, and it waits as a stated block its group cannot complete
4605
+ * does (#lateSourceWaitMs; BLO-52085 D4). A span of K or less may be one
4606
+ * block whose repair is still to come, and keeps the whole wait.
4447
4607
  */
4448
4608
  #openIsoSpan(span, packetId, catalogTrackName) {
4449
4609
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
4450
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
4610
+ if (!this.#blockAuthoredLengths.has(key)) {
4611
+ this.#blockAuthoredLengths.set(key, span.block.length);
4612
+ this.#isoSpanKeys.add(key);
4613
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0);
4614
+ }
4451
4615
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
4452
4616
  }
4453
4617
  /**
@@ -4535,11 +4699,14 @@ var FECManager = class _FECManager {
4535
4699
  /**
4536
4700
  * Whether an MPU boundary still bounds this stream's RAPs (see
4537
4701
  * `BlockClassifier.mpuBoundsRaps`). Gap decisions drop MPU evidence once
4538
- * it does not. A stream with no classifier yet has shown nothing against it.
4702
+ * it does not. A stream with no classifier yet has shown nothing against it,
4703
+ * and neither has a stream without catalog timing until it releases two
4704
+ * RAPs inside one MPU.
4539
4705
  */
4540
4706
  mpuBoundsRapsFor(packetId, catalogTrackName) {
4541
- if (!this.#hasCatalogTimingForPacket(packetId)) return false;
4542
- return this.#classifiers.get(this.#streamKey(packetId, catalogTrackName))?.mpuBoundsRaps ?? true;
4707
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
4708
+ if (!this.#hasCatalogTimingForPacket(packetId)) return this.#noSpanRaps.get(streamKey)?.inside !== true;
4709
+ return this.#classifiers.get(streamKey)?.mpuBoundsRaps ?? true;
4543
4710
  }
4544
4711
  /** A block's class now, or frozen at its resolution. */
4545
4712
  blockClassFor(sbn, packetId, catalogTrackName) {
@@ -4565,7 +4732,14 @@ var FECManager = class _FECManager {
4565
4732
  * invariant (consecutive MPUs exactly one keyframe interval apart).
4566
4733
  */
4567
4734
  noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale) {
4568
- if (!this.#trackConfigs.has(packetId) || !this.#hasCatalogTimingForPacket(packetId)) return;
4735
+ if (!this.#trackConfigs.has(packetId)) return;
4736
+ if (!this.#hasCatalogTimingForPacket(packetId)) {
4737
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
4738
+ const last = this.#noSpanRaps.get(streamKey);
4739
+ const inside = last?.inside === true || last?.mpu === mpu && last.presentationTime !== presentationTime;
4740
+ this.#noSpanRaps.set(streamKey, { mpu, presentationTime, inside });
4741
+ return;
4742
+ }
4569
4743
  this.#applyClassifierChanges(
4570
4744
  packetId,
4571
4745
  catalogTrackName,
@@ -4778,11 +4952,14 @@ var FECManager = class _FECManager {
4778
4952
  });
4779
4953
  client.onCleanupComplete((sbn) => {
4780
4954
  if (this.#releasedWorkerClients.has(client)) return;
4781
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
4955
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
4956
+ const cleanupKeys = owed.filter((key) => {
4782
4957
  const block = this.#parseBlockKey(key);
4783
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
4958
+ return block.packetId === packetId && block.sbn === sbn;
4784
4959
  });
4785
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
4960
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
4961
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
4962
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
4786
4963
  });
4787
4964
  client.onError((msg, code) => {
4788
4965
  const requestedKind = code ?? msg;
@@ -4852,9 +5029,11 @@ var FECManager = class _FECManager {
4852
5029
  * fail deadline already passed, so failing it is the decision that deadline
4853
5030
  * made. A late ack then finds nothing owed and is a no-op.
4854
5031
  */
4855
- #boundOwedCleanup(key, packetId, client) {
5032
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
4856
5033
  this.#clearOwedCleanupBound(key);
4857
5034
  const bound = {
5035
+ dueAtMs,
5036
+ askedAtMs: performance.now(),
4858
5037
  handle: setTimeout(() => {
4859
5038
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
4860
5039
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -4952,7 +5131,15 @@ var FECManager = class _FECManager {
4952
5131
  this.#isoSourceOversizeCount++;
4953
5132
  return null;
4954
5133
  }
4955
- const sbn = located.block.start;
5134
+ return this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, located.block.start);
5135
+ }
5136
+ /**
5137
+ * Hand one placed source symbol to the stream's decoder: its Worker, which
5138
+ * answers through onFrame (null here), or its synchronous decoder, whose
5139
+ * recovered block is returned. `sbn` is the SS_Start of the block a repair
5140
+ * stated for `ssId`.
5141
+ */
5142
+ #feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn) {
4956
5143
  const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
4957
5144
  const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey);
4958
5145
  const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
@@ -4981,6 +5168,74 @@ var FECManager = class _FECManager {
4981
5168
  }
4982
5169
  return recovered;
4983
5170
  }
5171
+ /**
5172
+ * Feed a source symbol of this stream that another FEC instance over the
5173
+ * same packets rebuilt: a keyframe overlay recovery whose base SS_ID the
5174
+ * caller determined (draft-ramadan-moq-mmt-02 7.1, 7.4.4; joint decoding,
5175
+ * BLO-52085). It joins its block's decoder as a received source would, so
5176
+ * it reduces the erasures the block still has to solve, but it is not a
5177
+ * network arrival: no transport accounting, no classification evidence,
5178
+ * no deadline refresh, and it never makes a block clean.
5179
+ *
5180
+ * Only a block a repair stated takes one (a repair-less span has no
5181
+ * decoder block). A block that is terminal, or already holds that source,
5182
+ * does not. The symbol is the exact protected packet, unpadded, as
5183
+ * feedSourceSymbol takes it.
5184
+ *
5185
+ * `recovered` is the block the synchronous decoder completed with it; the
5186
+ * caller routes it and completes the block, as for any recovery. When
5187
+ * every source of the block is then present, received or rebuilt, and no
5188
+ * decoder returned it (a Worker answers asynchronously, and reports such a
5189
+ * block as clean on its own side), the block is completed here as
5190
+ * recovered, with nothing left to route.
5191
+ */
5192
+ feedRebuiltSourceSymbol(packetId, ssId, symbolData, catalogTrackName) {
5193
+ if (!this.#hasBlockProfile(packetId)) return NOT_TAKEN;
5194
+ const located = this.#isoLocatorFor(packetId, catalogTrackName).locate(ssId);
5195
+ if (located === null || located.block.span) return NOT_TAKEN;
5196
+ if (!ssbg1FitsSymbol(symbolData.byteLength, this.#trackConfig(packetId).symbolSize)) return NOT_TAKEN;
5197
+ const sbn = located.block.start;
5198
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
5199
+ if (this.#completedBlocks.has(key) || this.#blockSourceEsis.get(key)?.has(located.esi)) return NOT_TAKEN;
5200
+ let rebuilt = this.#blockRebuiltEsis.get(key);
5201
+ if (rebuilt?.has(located.esi)) return NOT_TAKEN;
5202
+ if (rebuilt === void 0) {
5203
+ rebuilt = /* @__PURE__ */ new Set();
5204
+ this.#blockRebuiltEsis.set(key, rebuilt);
5205
+ }
5206
+ const config = this.#trackConfigs.get(packetId);
5207
+ const wasShort = config !== void 0 && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) !== void 0;
5208
+ rebuilt.add(located.esi);
5209
+ const recovered = this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn);
5210
+ if (recovered === null && !this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName)) {
5211
+ if (wasShort && this.#activeBlocks.has(key) && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) === void 0) {
5212
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, this.#multicastWaitMs(config));
5213
+ }
5214
+ }
5215
+ return { taken: true, recovered };
5216
+ }
5217
+ /**
5218
+ * A block that holds every one of its `length` sources, received or
5219
+ * rebuilt by another instance, with at least one rebuilt, is recovered:
5220
+ * every packet of it was delivered, by its own arrival or by the instance
5221
+ * that rebuilt it, so nothing is routed. Returns whether it completed it.
5222
+ */
5223
+ #completeWhenSourcesPresent(key, sbn, length, packetId, catalogTrackName) {
5224
+ const rebuilt = this.#blockRebuiltEsis.get(key);
5225
+ if (rebuilt === void 0 || this.#completedBlocks.has(key)) return false;
5226
+ let present = rebuilt.size;
5227
+ for (const esi of this.#blockSourceEsis.get(key) ?? []) if (!rebuilt.has(esi)) present++;
5228
+ if (present < length) return false;
5229
+ this.#traceLifecycle("recovered", sbn, packetId, catalogTrackName);
5230
+ this.countRecovery(packetId, sbn, catalogTrackName);
5231
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
5232
+ if (catalogTrackName === void 0) {
5233
+ this.onBlockComplete?.(sbn, packetId);
5234
+ } else {
5235
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName);
5236
+ }
5237
+ return true;
5238
+ }
4984
5239
  /**
4985
5240
  * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
4986
5241
  * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
@@ -5183,8 +5438,95 @@ var FECManager = class _FECManager {
5183
5438
  this.#completeCleanBlock(blockKey, sbn, packetId, catalogTrackName);
5184
5439
  return null;
5185
5440
  }
5441
+ if (recovered === null) this.#shortenUnrecoverableWait(blockKey, sbn, packetId, catalogTrackName);
5186
5442
  return recovered;
5187
5443
  }
5444
+ /**
5445
+ * A first-arrival multicast source, held or placed. A datagram flow keeps
5446
+ * its sources in send order, so one that moves the stream's newest source
5447
+ * position past a block leaves the sources that block still misses
5448
+ * reordered behind it at best: it shortens the wait of every block it
5449
+ * passed that only a late source can complete. MoQ is left out: its streams
5450
+ * can overtake one another, so a MoQ source shows nothing about the sources
5451
+ * sent before it.
5452
+ */
5453
+ #noteMulticastSource(locator, ssId, packetId, catalogTrackName) {
5454
+ const previous = locator.newestSource;
5455
+ if (!locator.noteSource(ssId) || previous === void 0) return;
5456
+ for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
5457
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
5458
+ this.#shortenUnrecoverableWait(
5459
+ this.#blockKey(block.start, packetId, catalogTrackName),
5460
+ block.start,
5461
+ packetId,
5462
+ catalogTrackName
5463
+ );
5464
+ }
5465
+ }
5466
+ /**
5467
+ * The wait of a block that only a late source can complete (BLO-52085): a
5468
+ * repair stated it, or it is a repair-less span longer than K (whose group
5469
+ * is empty, #openIsoSpan), its received sources plus every symbol its
5470
+ * repair group carries (RSB_length) are short of K' (the repair scheduler's
5471
+ * group-cannot-complete), and a later source of the stream has arrived, so
5472
+ * a source it misses is lost or reordered behind that one. The span, which
5473
+ * covers repair symbols paced after its sources, buys it nothing: it waits
5474
+ * the late-symbol allowance alone, the multicast wait less the span (the
5475
+ * catalog tolerance or the measured delivery gap). Undefined for any other
5476
+ * block.
5477
+ *
5478
+ * An installed keyframe overlay (keyframeOverlayTiming) may still rebuild
5479
+ * a RAP packet the block lost: a second FEC instance over the same packets
5480
+ * (draft-ramadan-moq-mmt-02 7.4), whose repair is paced across its own
5481
+ * span, unrelated to the base's. That packet can complete a stated block
5482
+ * (feedRebuiltSourceSymbol), and failing the block first would let the
5483
+ * release gate pass the keyframe, whose rebuild then lands stale. The
5484
+ * overlay repair of a packet the block lost goes out within the overlay's
5485
+ * span of that packet (fec-core-00 9.3), and the later source was sent
5486
+ * after it, so the block waits that span plus the larger of the allowance
5487
+ * and the overlay's own tolerance. An overlay that states no span (its
5488
+ * block may then span keyframes), or one whose wait is not shorter than
5489
+ * the whole multicast wait, leaves the block its whole wait: undefined.
5490
+ */
5491
+ #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
5492
+ const authoredLength = this.#blockAuthoredLengths.get(key);
5493
+ const rsbLength = this.#blockRsbLengths.get(key);
5494
+ if (authoredLength === void 0 || rsbLength === void 0) return void 0;
5495
+ let present = this.#blockSourceCounts.get(key) ?? 0;
5496
+ const received = this.#blockSourceEsis.get(key);
5497
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
5498
+ if (present + rsbLength >= authoredLength) return void 0;
5499
+ const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
5500
+ if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
5501
+ return void 0;
5502
+ }
5503
+ const waitMs = this.#multicastWaitMs(config);
5504
+ const allowanceMs = waitMs - config.interleaveDepthMs;
5505
+ const overlay = this.keyframeOverlayTiming?.(packetId, catalogTrackName);
5506
+ if (overlay === void 0) return allowanceMs;
5507
+ const overlaySpanMs = overlay.interleaveDepthMs ?? 0;
5508
+ const overlayWaitMs = overlaySpanMs + Math.max(allowanceMs, overlay.reorderToleranceMs ?? 0);
5509
+ return overlaySpanMs > 0 && overlayWaitMs < waitMs ? overlayWaitMs : void 0;
5510
+ }
5511
+ /**
5512
+ * Bring an open block's wait in to its late-source wait, when it has one.
5513
+ * Never later than it is armed: only a source can complete such a block,
5514
+ * so a repair of its group (paced across the span) must not keep it open.
5515
+ */
5516
+ #shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName) {
5517
+ if (!this.#activeBlocks.has(key)) return;
5518
+ const config = this.#trackConfigs.get(packetId);
5519
+ if (config === void 0) return;
5520
+ const waitMs = this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config);
5521
+ if (waitMs === void 0) return;
5522
+ const armedAtMs = this.#blockWaitDeadlinesMs.get(key);
5523
+ this.#armBlockTimeout(
5524
+ sbn,
5525
+ packetId,
5526
+ catalogTrackName,
5527
+ armedAtMs === void 0 ? waitMs : Math.min(waitMs, armedAtMs - this.#receiptNow())
5528
+ );
5529
+ }
5188
5530
  /**
5189
5531
  * Record a block's authored SSB_length from a repair symbol. Returns false,
5190
5532
  * leaving the block unchanged, when the symbol contradicts the block: a
@@ -5282,12 +5624,13 @@ var FECManager = class _FECManager {
5282
5624
  * the inactivity deadline on each symbol, records the symbol's in-band
5283
5625
  * classification evidence, and marks the block clean when all of its
5284
5626
  * authored source symbols arrived: the SSB_length a repair symbol declared,
5285
- * otherwise K.
5627
+ * otherwise K. `held` marks a source held unplaced since it arrived and
5628
+ * placed only now (see #noteSbnSeen).
5286
5629
  *
5287
5630
  * Throws for a packetId that was never configured, so a classified block
5288
5631
  * never reads the manager-global K or timeout.
5289
5632
  */
5290
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
5633
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
5291
5634
  const trackConfig = this.#trackConfigs.get(packetId);
5292
5635
  if (trackConfig === void 0) {
5293
5636
  throw new Error(
@@ -5303,7 +5646,8 @@ var FECManager = class _FECManager {
5303
5646
  catalogTrackName,
5304
5647
  "source",
5305
5648
  evidence.packetSequenceNumber,
5306
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
5649
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
5650
+ held
5307
5651
  );
5308
5652
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
5309
5653
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -5339,6 +5683,15 @@ var FECManager = class _FECManager {
5339
5683
  this.#completeCleanBlock(key, sbn, packetId, catalogTrackName);
5340
5684
  return;
5341
5685
  }
5686
+ if (this.#blockRebuiltEsis.has(key) && this.#completeWhenSourcesPresent(
5687
+ key,
5688
+ sbn,
5689
+ this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? authoredLength,
5690
+ packetId,
5691
+ catalogTrackName
5692
+ )) {
5693
+ return;
5694
+ }
5342
5695
  this.noteBlockActivity(sbn, packetId, catalogTrackName, true);
5343
5696
  }
5344
5697
  #completeCleanBlock(key, sbn, packetId, catalogTrackName) {
@@ -5347,7 +5700,9 @@ var FECManager = class _FECManager {
5347
5700
  this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
5348
5701
  this.#blockSourceCounts.delete(key);
5349
5702
  this.#blockSourceEsis.delete(key);
5703
+ this.#blockRebuiltEsis.delete(key);
5350
5704
  this.#blockAuthoredLengths.delete(key);
5705
+ this.#isoSpanKeys.delete(key);
5351
5706
  this.#blockRepairRsIds.delete(key);
5352
5707
  this.#blockRsbLengths.delete(key);
5353
5708
  this.#markTerminal(key, sbn, packetId, true);
@@ -5378,6 +5733,19 @@ var FECManager = class _FECManager {
5378
5733
  #receiptNow() {
5379
5734
  return this.#receiptAtMs ?? performance.now();
5380
5735
  }
5736
+ /**
5737
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
5738
+ * scope: counted from the receipt time, as the timer of a symbol fed when
5739
+ * it was received was, less the whole ms since. So it fires on the tick
5740
+ * that timer would have, never later than a delay counted from now, and
5741
+ * its handler still re-arms a timer that fires before its deadline.
5742
+ * Counted from now, a deadline set from the receipt time is rounded up
5743
+ * from another fraction of a ms (BLO-52085).
5744
+ */
5745
+ #receiptTimerDelayMs(deadlineMs, minMs) {
5746
+ const receivedAtMs = this.#receiptAtMs;
5747
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
5748
+ }
5381
5749
  /**
5382
5750
  * A held packet admitted late arms from its (earlier) receipt time; that
5383
5751
  * never pulls in a deadline later activity already armed. Outside a
@@ -5413,10 +5781,20 @@ var FECManager = class _FECManager {
5413
5781
  this.#repairDeadlineMs(trackConfig)
5414
5782
  );
5415
5783
  }
5416
- this.#armBlockTimeout(sbn, packetId, catalogTrackName, timeoutMs);
5784
+ if (!sourceProgress && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) !== void 0) {
5785
+ this.#shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName);
5786
+ return;
5787
+ }
5788
+ this.#armBlockTimeout(
5789
+ sbn,
5790
+ packetId,
5791
+ catalogTrackName,
5792
+ this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) ?? timeoutMs
5793
+ );
5417
5794
  }
5418
5795
  #failBlock(sbn, packetId, catalogTrackName) {
5419
5796
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
5797
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
5420
5798
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
5421
5799
  this.#clearRepairDeadline(key);
5422
5800
  this.#clearBlockTimer(key);
@@ -5426,6 +5804,7 @@ var FECManager = class _FECManager {
5426
5804
  }
5427
5805
  this.#blockSourceCounts.delete(key);
5428
5806
  this.#blockSourceEsis.delete(key);
5807
+ this.#blockRebuiltEsis.delete(key);
5429
5808
  this.#blockAuthoredLengths.delete(key);
5430
5809
  this.#blockRepairRsIds.delete(key);
5431
5810
  this.#blockRsbLengths.delete(key);
@@ -5435,7 +5814,8 @@ var FECManager = class _FECManager {
5435
5814
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
5436
5815
  this.#fecStats.blocksFailed++;
5437
5816
  this.#statsForPacket(packetId).blocksFailed++;
5438
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5817
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5818
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
5439
5819
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
5440
5820
  }
5441
5821
  /**
@@ -5464,7 +5844,9 @@ var FECManager = class _FECManager {
5464
5844
  this.#retireBlockClass(key, block.sbn, block.packetId, block.catalogTrackName);
5465
5845
  this.#blockSourceCounts.delete(key);
5466
5846
  this.#blockSourceEsis.delete(key);
5847
+ this.#blockRebuiltEsis.delete(key);
5467
5848
  this.#blockAuthoredLengths.delete(key);
5849
+ this.#isoSpanKeys.delete(key);
5468
5850
  this.#blockRepairRsIds.delete(key);
5469
5851
  this.#blockRsbLengths.delete(key);
5470
5852
  this.#clearBlockTimer(key);
@@ -5555,7 +5937,9 @@ var FECManager = class _FECManager {
5555
5937
  this.#blockKeysBySbn.clear();
5556
5938
  this.#blockSourceCounts.clear();
5557
5939
  this.#blockSourceEsis.clear();
5940
+ this.#blockRebuiltEsis.clear();
5558
5941
  this.#blockAuthoredLengths.clear();
5942
+ this.#isoSpanKeys.clear();
5559
5943
  this.#blockRepairRsIds.clear();
5560
5944
  this.#blockRsbLengths.clear();
5561
5945
  this.#heldLayerStates.clear();
@@ -5580,6 +5964,7 @@ var FECManager = class _FECManager {
5580
5964
  this.#blockAnchorsMs.clear();
5581
5965
  this.#blockCatalogTrackNames.clear();
5582
5966
  this.#classifiers.clear();
5967
+ this.#noSpanRaps.clear();
5583
5968
  this.#streamGeometries.clear();
5584
5969
  this.#failedBlocks.clear();
5585
5970
  this.#resolvedBlockClasses.clear();
@@ -6933,9 +7318,9 @@ async function openSubscription(rx, openedPromise, options, packetIds) {
6933
7318
  } catch (error) {
6934
7319
  throw new MulticastError("subscription-failed", "MulticastReceiver did not open", error);
6935
7320
  }
6936
- if (rx.integrityScheme !== INTEGRITY_SCHEME) {
7321
+ if (opened.integrityScheme !== INTEGRITY_SCHEME) {
6937
7322
  await rx.close();
6938
- throw unsupported(`integrity scheme ${String(rx.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
7323
+ throw unsupported(`integrity scheme ${String(opened.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
6939
7324
  }
6940
7325
  const events = new EventTarget();
6941
7326
  let state = "connected";
@@ -7054,14 +7439,15 @@ var MOQT_PUBLISHER_PRIORITY = Object.freeze({
7054
7439
  });
7055
7440
 
7056
7441
  // node_modules/@blockcast/mmt-transport/dist/amt-gateway.js
7442
+ var MAX_PENDING_PACKETS = 256;
7057
7443
  var AMTGatewayManager = class {
7058
7444
  subscriptions = /* @__PURE__ */ new Map();
7059
7445
  messageHandler;
7446
+ messageListenerRegistered = false;
7060
7447
  pendingPackets = /* @__PURE__ */ new Map();
7061
7448
  constructor() {
7062
7449
  this.messageHandler = (event) => {
7063
7450
  const data = event.data;
7064
- console.log(`[AMT] SW message received:`, data.type);
7065
7451
  if (data.type === "UDP_PACKET") {
7066
7452
  this.handlePacket(data);
7067
7453
  } else if (data.type === "SOCKET_ERROR") {
@@ -7070,12 +7456,22 @@ var AMTGatewayManager = class {
7070
7456
  console.log(`[AMT SW Debug] ${data.message}`);
7071
7457
  }
7072
7458
  };
7073
- if (typeof navigator !== "undefined" && navigator.serviceWorker) {
7074
- navigator.serviceWorker.addEventListener("message", this.messageHandler);
7075
- console.log("[AMT] Registered service worker message handler");
7076
- } else {
7077
- console.warn("[AMT] Service worker not available");
7459
+ }
7460
+ ensureMessageListener() {
7461
+ if (this.messageListenerRegistered || typeof navigator === "undefined" || !navigator.serviceWorker || !this.messageHandler) {
7462
+ return;
7463
+ }
7464
+ navigator.serviceWorker.addEventListener("message", this.messageHandler);
7465
+ this.messageListenerRegistered = true;
7466
+ console.log("[AMT] Registered service worker message handler");
7467
+ }
7468
+ removeMessageListener() {
7469
+ if (!this.messageListenerRegistered)
7470
+ return;
7471
+ if (this.messageHandler && typeof navigator !== "undefined" && navigator.serviceWorker) {
7472
+ navigator.serviceWorker.removeEventListener("message", this.messageHandler);
7078
7473
  }
7474
+ this.messageListenerRegistered = false;
7079
7475
  }
7080
7476
  /**
7081
7477
  * Subscribe via AMT tunnel
@@ -7085,6 +7481,7 @@ var AMTGatewayManager = class {
7085
7481
  if (config.protected) {
7086
7482
  throw new Error("AMTGatewayManager refuses a protected join: it reports no per-datagram sender (multicast-02 7.2.7)");
7087
7483
  }
7484
+ this.ensureMessageListener();
7088
7485
  const keyStr = this.getKeyString(key);
7089
7486
  if (this.subscriptions.has(keyStr)) {
7090
7487
  console.log(`[AMT] Reusing existing subscription to ${keyStr}`);
@@ -7120,6 +7517,8 @@ var AMTGatewayManager = class {
7120
7517
  this.subscriptions.delete(keyStr);
7121
7518
  this.pendingPackets.delete(subscription.subscriptionId);
7122
7519
  }
7520
+ if (this.subscriptions.size === 0)
7521
+ this.removeMessageListener();
7123
7522
  throw new Error(`Failed to subscribe via AMT: ${error instanceof Error ? error.message : String(error)}`);
7124
7523
  }
7125
7524
  }
@@ -7141,6 +7540,8 @@ var AMTGatewayManager = class {
7141
7540
  } finally {
7142
7541
  this.subscriptions.delete(handle);
7143
7542
  this.pendingPackets.delete(subscription.subscriptionId);
7543
+ if (this.subscriptions.size === 0)
7544
+ this.removeMessageListener();
7144
7545
  }
7145
7546
  }
7146
7547
  /**
@@ -7157,14 +7558,12 @@ var AMTGatewayManager = class {
7157
7558
  if (!subscriptionId)
7158
7559
  return;
7159
7560
  const subscription = this.subscriptions.get(subscriptionId);
7160
- if (!subscription) {
7161
- console.warn(`[AMT] Received packet for unknown subscription: ${subscriptionId}`);
7561
+ if (!subscription)
7162
7562
  return;
7163
- }
7164
7563
  if (!subscription.handshakeComplete) {
7165
7564
  const queue = this.pendingPackets.get(subscriptionId);
7166
7565
  const packetData2 = data;
7167
- if (queue) {
7566
+ if (queue && queue.length < MAX_PENDING_PACKETS) {
7168
7567
  queue.push({
7169
7568
  data: packetData2.data,
7170
7569
  remoteAddress: packetData2.remoteAddress,
@@ -7190,19 +7589,15 @@ var AMTGatewayManager = class {
7190
7589
  if (!subscriptionId)
7191
7590
  return;
7192
7591
  const subscription = this.subscriptions.get(subscriptionId);
7193
- if (!subscription) {
7194
- console.warn(`[AMT] Received error for unknown subscription: ${subscriptionId}`);
7592
+ if (!subscription)
7195
7593
  return;
7196
- }
7197
7594
  subscription.config.onError(new Error(error || "Unknown error"));
7198
7595
  }
7199
7596
  /**
7200
7597
  * Cleanup on destroy
7201
7598
  */
7202
7599
  destroy() {
7203
- if (this.messageHandler && typeof navigator !== "undefined" && navigator.serviceWorker) {
7204
- navigator.serviceWorker.removeEventListener("message", this.messageHandler);
7205
- }
7600
+ this.removeMessageListener();
7206
7601
  const handles = Array.from(this.subscriptions.keys());
7207
7602
  for (const handle of handles) {
7208
7603
  this.unsubscribe(handle).catch((err) => {
@@ -10261,9 +10656,10 @@ function isH264IntraSlice(nal) {
10261
10656
  const sliceType = readH264SliceType(nal);
10262
10657
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
10263
10658
  }
10659
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
10264
10660
  function readH264SliceType(nal) {
10265
10661
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
10266
- const rbsp = removeEmulationPrevention(nal.subarray(1));
10662
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
10267
10663
  const state = { bitOffset: 0 };
10268
10664
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
10269
10665
  return readUnsignedExpGolomb(rbsp, state);
@@ -10410,6 +10806,96 @@ if (void 0) {
10410
10806
  ]))).toBe(false);
10411
10807
  });
10412
10808
  });
10809
+ describe("readH264SliceType", () => {
10810
+ const wholeNalSliceType = (nal) => {
10811
+ if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
10812
+ const rbsp = removeEmulationPrevention(nal.subarray(1));
10813
+ const state = { bitOffset: 0 };
10814
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null;
10815
+ return readUnsignedExpGolomb(rbsp, state);
10816
+ };
10817
+ const hex2 = (text2) => Uint8Array.from(text2.match(/../g), (byte) => parseInt(byte, 16));
10818
+ const ue = (value) => {
10819
+ const code = (value + 1).toString(2);
10820
+ return "0".repeat(code.length - 1) + code;
10821
+ };
10822
+ const sliceNal = (bits) => {
10823
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, "0").match(/.{8}/g);
10824
+ const nal = [1];
10825
+ let zeros = 0;
10826
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
10827
+ if (zeros >= 2 && byte <= 3) {
10828
+ nal.push(3);
10829
+ zeros = 0;
10830
+ }
10831
+ nal.push(byte);
10832
+ zeros = byte === 0 ? zeros + 1 : 0;
10833
+ }
10834
+ return Uint8Array.from(nal);
10835
+ };
10836
+ const x264Slices = [
10837
+ ["64x48 P", hex2("419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176"), 5, false],
10838
+ ["64x48 B", hex2("419e414212fffeeade283707cb70f7"), 6, false],
10839
+ ["64x48 non-IDR I", hex2(
10840
+ "4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39a527e23eb34c8167fd"
10841
+ ), 7, true],
10842
+ ["1280x720 B, escape at byte 10", hex2(
10843
+ "01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e19b75d92170917306190f262fd58268702db2eff86a9651e48"
10844
+ ), 6, false],
10845
+ ["1280x720 P, escape at byte 15", hex2(
10846
+ "41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f02c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e85302da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3"
10847
+ ), 5, false],
10848
+ ["1280x720 B, escape at byte 22", hex2("01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352"), 6, false],
10849
+ ["7680x4320 IDR, first_mb_in_slice 97440", hex2(
10850
+ "650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9"
10851
+ ), null, true],
10852
+ ["7680x4320 P, first_mb_in_slice 32640", hex2(
10853
+ "410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020"
10854
+ ), 5, false],
10855
+ ["7680x4320 P, first_mb_in_slice 97440", hex2(
10856
+ "410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806"
10857
+ ), 5, false]
10858
+ ];
10859
+ const syntheticSlices = [
10860
+ ["an escape inside first_mb_in_slice", sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
10861
+ ["an escape between the fields", sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
10862
+ ["an escape inside slice_type", sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
10863
+ ["the longest fields, five escapes", sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
10864
+ ["the largest values", sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
10865
+ ["31 leading zeros in first_mb_in_slice", sliceNal(`${"0".repeat(31)}1`), null],
10866
+ ["31 leading zeros in slice_type", sliceNal(`1${"0".repeat(31)}1`), null],
10867
+ ["escapes running past the slice header", sliceNal(ue(0) + ue(5) + "0".repeat(400)), 5]
10868
+ ];
10869
+ test("reads the slice_type of real and synthetic slices", () => {
10870
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
10871
+ expect(readH264SliceType(nal), name).toBe(sliceType);
10872
+ }
10873
+ });
10874
+ test("matches the whole-NAL unescape at every truncation", () => {
10875
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
10876
+ for (let end = 0; end <= nal.length; end++) {
10877
+ const cut = nal.subarray(0, end);
10878
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut));
10879
+ }
10880
+ }
10881
+ });
10882
+ test("matches the whole-NAL unescape on zero-heavy NAL units", () => {
10883
+ const bytes = [0, 0, 0, 3, 1, 2, 128, 255];
10884
+ let seed = 1;
10885
+ const next = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) >>> 16;
10886
+ for (let i = 0; i < 5e3; i++) {
10887
+ const nal = new Uint8Array(2 + next() % 63);
10888
+ nal[0] = 65;
10889
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length];
10890
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal));
10891
+ }
10892
+ });
10893
+ test("classifies the x264 slices as keyframes or not", () => {
10894
+ for (const [name, nal, , keyframe] of x264Slices) {
10895
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe);
10896
+ }
10897
+ });
10898
+ });
10413
10899
  describe("avccToAnnexB", () => {
10414
10900
  test("converts with SPS/PPS on keyframe", () => {
10415
10901
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -13111,9 +13597,21 @@ var IsoBmffTimingResolver = class {
13111
13597
  }
13112
13598
  #track = null;
13113
13599
  #fragments = /* @__PURE__ */ new Map();
13600
+ /** First sample of each pending fragment, kept in `#delivered` with its sample count. */
13601
+ #firstSamples = /* @__PURE__ */ new Map();
13602
+ /**
13603
+ * First sample and sample count of the newest fragments whose every slot was
13604
+ * cleared. Abandonment counts: `releaseSample` clears a slot too, which
13605
+ * matches the combiner, since it retires an abandoned sample as well.
13606
+ */
13607
+ #delivered = /* @__PURE__ */ new Map();
13114
13608
  #pendingSamples = 0;
13115
13609
  #evictedSamples = 0;
13116
13610
  #lastMovieFragmentRejection = null;
13611
+ /** True once an FT=0 has bound the track that FT=1 timing is read against. */
13612
+ get initialized() {
13613
+ return this.#track !== null;
13614
+ }
13117
13615
  get pendingSampleCount() {
13118
13616
  return this.#pendingSamples;
13119
13617
  }
@@ -13137,7 +13635,14 @@ var IsoBmffTimingResolver = class {
13137
13635
  this.#track = timing;
13138
13636
  return true;
13139
13637
  }
13140
- addMovieFragment(mpuSequenceNumber, data, additionalSampleLimit = this.maxPendingSamples) {
13638
+ /**
13639
+ * `recovered` marks an FEC-recovered copy. A recovered block hands back
13640
+ * every FT=1 it holds, the received ones included, so a recovered copy of a
13641
+ * fragment whose samples are all done is a duplicate: admitting it again
13642
+ * would charge stale timing and could displace the live MPU's. A source
13643
+ * copy is still admitted again (a rendition switch re-arms timing that way).
13644
+ */
13645
+ addMovieFragment(mpuSequenceNumber, data, additionalSampleLimit = this.maxPendingSamples, recovered = false) {
13141
13646
  this.#lastMovieFragmentRejection = null;
13142
13647
  if (!Number.isInteger(additionalSampleLimit) || additionalSampleLimit < 0) {
13143
13648
  this.#lastMovieFragmentRejection = "invalid";
@@ -13163,6 +13668,8 @@ var IsoBmffTimingResolver = class {
13163
13668
  (sample, index) => sample !== null && sameSample(sample, parsed.samples[index])
13164
13669
  );
13165
13670
  }
13671
+ const delivered = recovered ? this.#delivered.get(key) : void 0;
13672
+ if (delivered && delivered.sampleCount === parsed.samples.length && sameSample(delivered.first, parsed.samples[0])) return true;
13166
13673
  let freed = 0;
13167
13674
  while (this.#fragments.size > 0 && (this.#pendingSamples + parsed.samples.length > this.maxPendingSamples || parsed.samples.length - freed > additionalSampleLimit)) {
13168
13675
  freed += this.#evictOldestFragment();
@@ -13176,6 +13683,7 @@ var IsoBmffTimingResolver = class {
13176
13683
  return false;
13177
13684
  }
13178
13685
  this.#fragments.set(key, [...parsed.samples]);
13686
+ this.#firstSamples.set(key, parsed.samples[0]);
13179
13687
  this.#pendingSamples += parsed.samples.length;
13180
13688
  return true;
13181
13689
  }
@@ -13233,6 +13741,7 @@ var IsoBmffTimingResolver = class {
13233
13741
  let live = 0;
13234
13742
  for (const sample of samples) if (sample !== null) live++;
13235
13743
  this.#fragments.delete(oldest);
13744
+ this.#firstSamples.delete(oldest);
13236
13745
  this.#pendingSamples -= live;
13237
13746
  this.#evictedSamples += live;
13238
13747
  return live;
@@ -13248,12 +13757,23 @@ var IsoBmffTimingResolver = class {
13248
13757
  if (!samples || !samples[index]) return false;
13249
13758
  samples[index] = null;
13250
13759
  this.#pendingSamples--;
13251
- if (samples.every((value) => value === null)) this.#fragments.delete(key);
13760
+ if (samples.every((value) => value === null)) {
13761
+ this.#fragments.delete(key);
13762
+ const first = this.#firstSamples.get(key);
13763
+ this.#firstSamples.delete(key);
13764
+ this.#delivered.delete(key);
13765
+ this.#delivered.set(key, { first, sampleCount: samples.length });
13766
+ if (this.#delivered.size > this.maxPendingSamples) {
13767
+ this.#delivered.delete(this.#delivered.keys().next().value);
13768
+ }
13769
+ }
13252
13770
  return true;
13253
13771
  }
13254
13772
  reset() {
13255
13773
  this.#track = null;
13256
13774
  this.#fragments.clear();
13775
+ this.#firstSamples.clear();
13776
+ this.#delivered.clear();
13257
13777
  this.#pendingSamples = 0;
13258
13778
  }
13259
13779
  };
@@ -13423,6 +13943,9 @@ function authoredGap(before, after) {
13423
13943
  function ssIdAfter(a, b) {
13424
13944
  return (a - b | 0) > 0;
13425
13945
  }
13946
+ function holdsRebuilt(stream) {
13947
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
13948
+ }
13426
13949
  var FecReleaseSequencer = class {
13427
13950
  #streams = /* @__PURE__ */ new Map();
13428
13951
  #gate;
@@ -13485,6 +14008,7 @@ var FecReleaseSequencer = class {
13485
14008
  stream.lastSbn = void 0;
13486
14009
  stream.discontinuity = false;
13487
14010
  stream.rapSsId = void 0;
14011
+ stream.sourced = false;
13488
14012
  }
13489
14013
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
13490
14014
  this.#recordStat("droppedStale");
@@ -13511,6 +14035,7 @@ var FecReleaseSequencer = class {
13511
14035
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
13512
14036
  else hi = mid;
13513
14037
  }
14038
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
13514
14039
  stream.buf.splice(lo, 0, frame);
13515
14040
  this.#drainUnlessDeferred(stream);
13516
14041
  }
@@ -13546,6 +14071,41 @@ var FecReleaseSequencer = class {
13546
14071
  }
13547
14072
  return false;
13548
14073
  }
14074
+ /**
14075
+ * These streams' sink is being replaced by one that has seen no source
14076
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
14077
+ * release to the sink being replaced the frames the unanchored path had
14078
+ * already released to it (#cursorPassed): there they waited in its queue,
14079
+ * which its replacement flushes. A stream that holds none is not drained:
14080
+ * it holds nothing the anchor kept back, and a drain would still force out
14081
+ * a frame held past the hold limit, which before the anchor waited for the
14082
+ * next push. Then treat the streams as unsourced until a source frame is
14083
+ * released.
14084
+ */
14085
+ unsource(packetId, catalogTrackName) {
14086
+ for (const stream of this.#streams.values()) {
14087
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
14088
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
14089
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
14090
+ else this.#drain(stream, true);
14091
+ }
14092
+ stream.sourced = false;
14093
+ }
14094
+ }
14095
+ }
14096
+ /**
14097
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
14098
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
14099
+ * packetId.
14100
+ */
14101
+ holdsRebuilt(packetId, catalogTrackName) {
14102
+ for (const stream of this.#streams.values()) {
14103
+ if (stream.packetId !== packetId) continue;
14104
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
14105
+ if (holdsRebuilt(stream)) return true;
14106
+ }
14107
+ return false;
14108
+ }
13549
14109
  /** Re-evaluate held gaps after FEC state changed. */
13550
14110
  poke(streamKey) {
13551
14111
  if (streamKey !== void 0) {
@@ -13637,16 +14197,32 @@ var FecReleaseSequencer = class {
13637
14197
  last: null,
13638
14198
  lastSbn: void 0,
13639
14199
  discontinuity: false,
13640
- rapSsId: void 0
14200
+ rapSsId: void 0,
14201
+ sourced: false,
14202
+ draining: 0
13641
14203
  };
13642
14204
  this.#streams.set(streamKey, stream);
13643
14205
  }
13644
14206
  return stream;
13645
14207
  }
13646
- #drain(stream) {
14208
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
14209
+ #drain(stream, asUnanchored = false) {
14210
+ stream.draining++;
14211
+ try {
14212
+ this.#drainLoop(stream, asUnanchored);
14213
+ } finally {
14214
+ stream.draining--;
14215
+ }
14216
+ }
14217
+ #drainLoop(stream, asUnanchored) {
13647
14218
  while (stream.buf.length > 0 && stream.last !== null) {
13648
14219
  const head = stream.buf[0];
13649
14220
  const last = stream.last;
14221
+ if (compareFrameOrder(head, last) <= 0) {
14222
+ stream.buf.shift();
14223
+ this.#release(stream, head, void 0);
14224
+ continue;
14225
+ }
13650
14226
  if (stream.discontinuity) {
13651
14227
  stream.discontinuity = false;
13652
14228
  stream.buf.shift();
@@ -13660,9 +14236,10 @@ var FecReleaseSequencer = class {
13660
14236
  }
13661
14237
  const headSbn = head.meta.fecSbn;
13662
14238
  const from = stream.lastSbn ?? headSbn;
13663
- const to = headSbn ?? stream.lastSbn;
14239
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
13664
14240
  let lost = [];
13665
14241
  const unanchored = from === void 0 && to === void 0;
14242
+ let unresolved = false;
13666
14243
  if (from !== void 0 && to !== void 0) {
13667
14244
  const resolved = this.#gate.resolvedLoss(
13668
14245
  stream.packetId,
@@ -13671,7 +14248,8 @@ var FecReleaseSequencer = class {
13671
14248
  Math.max(from, to),
13672
14249
  from
13673
14250
  );
13674
- if (resolved === null) {
14251
+ unresolved = resolved === null;
14252
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored)) {
13675
14253
  const heldMs = performance.now() - head.arrivedAtMs;
13676
14254
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
13677
14255
  this.#recordStat("forcedWindowFlushes");
@@ -13679,22 +14257,56 @@ var FecReleaseSequencer = class {
13679
14257
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
13680
14258
  continue;
13681
14259
  }
13682
- lost = resolved;
14260
+ lost = resolved ?? [];
13683
14261
  }
13684
14262
  stream.buf.shift();
13685
14263
  this.#release(
13686
14264
  stream,
13687
14265
  head,
13688
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
14266
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
13689
14267
  );
13690
14268
  }
13691
14269
  }
14270
+ /**
14271
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
14272
+ * source cursor holds it unanchored, and neither does a later frame behind
14273
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
14274
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
14275
+ * like each frame that arrived in front of it since (stale there). The head
14276
+ * then goes, decided as it would be unanchored, once a frame the base path
14277
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
14278
+ * marked one: the base path has passed that one, so a frame still missing
14279
+ * before it can only come from a repair. It also goes while no source frame
14280
+ * has been released, when the direct path shows a recovered frame at once.
14281
+ * And it goes at once while a staged switch decides on when frames arrive
14282
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
14283
+ * sink being replaced: unanchored, it had already reached the sink.
14284
+ * The scan also writes: the `passed` marks it sets stay on the frames,
14285
+ * and push marks a frame it inserts in front of a marked one from them.
14286
+ */
14287
+ #cursorPassed(stream, asUnanchored) {
14288
+ let at = -1;
14289
+ for (let i = 0; i < stream.buf.length; i++) {
14290
+ const frame = stream.buf[i];
14291
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
14292
+ frame.passed = true;
14293
+ if (at < 0) at = i;
14294
+ } else if (frame.passed !== true) break;
14295
+ }
14296
+ if (at < 0) return false;
14297
+ 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));
14298
+ }
13692
14299
  #release(stream, frame, decision) {
14300
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
14301
+ if (stale) this.#recordStat("droppedStale");
13693
14302
  if (decision) frame.meta.gapBefore = decision;
13694
14303
  stream.last = frame;
13695
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
14304
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
14305
+ stream.lastSbn = frame.meta.fecSbn;
14306
+ }
14307
+ if (frame.meta.recovered !== true) stream.sourced = true;
13696
14308
  this.#gate.onReleased?.(frame.data, frame.meta);
13697
- this.#emit(frame.data, frame.meta);
14309
+ if (!stale) this.#emit(frame.data, frame.meta);
13698
14310
  }
13699
14311
  };
13700
14312
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -13735,6 +14347,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
13735
14347
  this.#reclaimedTimingSamples = 0;
13736
14348
  this.#evictedTimingSamples = 0;
13737
14349
  this.#rejectedMovieFragments = 0;
14350
+ this.#recoveredHeadsAwaitingTiming = {
14351
+ held: 0,
14352
+ expired: 0,
14353
+ discarded: 0,
14354
+ superseded: 0
14355
+ };
13738
14356
  this.#sequencers = /* @__PURE__ */ new Map();
13739
14357
  this.#fecGate = null;
13740
14358
  this.#fecSequencer = null;
@@ -13843,6 +14461,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
13843
14461
  #reclaimedTimingSamples;
13844
14462
  #evictedTimingSamples;
13845
14463
  #rejectedMovieFragments;
14464
+ #recoveredHeadsAwaitingTiming;
13846
14465
  #sequencers;
13847
14466
  #fecGate;
13848
14467
  #fecSequencer;
@@ -13948,11 +14567,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
13948
14567
  /**
13949
14568
  * Typed view of the ISO-BMFF timing-sample budget.
13950
14569
  *
13951
- * This is the acceptance signal for the budget ratchet: `pending` walking
13952
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
13953
- * and it is observable here rather than only as media silently stopping.
13954
- * Per repo policy this is a producer-owned counter -- never infer budget
13955
- * state by parsing logs.
14570
+ * Each stream admits timing against its own window of `capacity` slots
14571
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
14572
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
14573
+ * timing a stream declared and never delivered shows up there. `pending`
14574
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
14575
+ * a producer-owned counter -- never infer budget state by parsing logs.
13956
14576
  */
13957
14577
  get timingBudgetStats() {
13958
14578
  return {
@@ -13963,6 +14583,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
13963
14583
  rejectedMovieFragments: this.#rejectedMovieFragments
13964
14584
  };
13965
14585
  }
14586
+ /** Recovered heads parked for FT=1 timing (BLO-53369). Survives dispose(). */
14587
+ get recoveredHeadsAwaitingTiming() {
14588
+ let pending = 0;
14589
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
14590
+ for (const head of awaitingTiming) if (head.options?.recovered) pending++;
14591
+ }
14592
+ return { ...this.#recoveredHeadsAwaitingTiming, pending };
14593
+ }
13966
14594
  get reorderStats() {
13967
14595
  let bufferedFrames = this.#fecSequencer?.buffered ?? 0;
13968
14596
  for (const { sequencer } of this.#sequencers.values()) bufferedFrames += sequencer.buffered;
@@ -14004,6 +14632,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
14004
14632
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
14005
14633
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
14006
14634
  }
14635
+ /** See FecReleaseSequencer.unsource. */
14636
+ unsourceFecRelease(packetId, catalogTrackName) {
14637
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
14638
+ }
14639
+ /** See FecReleaseSequencer.holdsRebuilt. */
14640
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
14641
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
14642
+ }
14007
14643
  /** Re-evaluate held gaps after FEC block state changed. */
14008
14644
  pokeFecRelease(packetId, catalogTrackName) {
14009
14645
  if (!this.#fecSequencer) return;
@@ -14136,7 +14772,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14136
14772
  const now = Date.now();
14137
14773
  for (const { awaitingTiming } of this.#timingStreams.values()) {
14138
14774
  while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
14139
- awaitingTiming.shift();
14775
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
14140
14776
  }
14141
14777
  }
14142
14778
  }
@@ -14254,11 +14890,16 @@ var MmtpContainerParser = class _MmtpContainerParser {
14254
14890
  if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
14255
14891
  return this.#drop("fragment-unexpected-fragmentation");
14256
14892
  const resolver2 = this.#timingResolver(streamKey, info.packetId, false);
14257
- if (!resolver2) return this.#drop("fragment-no-resolver");
14893
+ if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
14258
14894
  const pendingBefore = resolver2.pendingSampleCount;
14259
14895
  const evictedBefore = resolver2.evictedSampleCount;
14260
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
14261
- const admitted = resolver2.addMovieFragment(mpu.mpuSequenceNumber, data, remaining);
14896
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
14897
+ const admitted = resolver2.addMovieFragment(
14898
+ mpu.mpuSequenceNumber,
14899
+ data,
14900
+ remaining,
14901
+ options?.recovered === true
14902
+ );
14262
14903
  this.#pendingTimingSamples += resolver2.pendingSampleCount - pendingBefore;
14263
14904
  this.#evictedTimingSamples += resolver2.evictedSampleCount - evictedBefore;
14264
14905
  if (!admitted) {
@@ -14278,7 +14919,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14278
14919
  };
14279
14920
  }
14280
14921
  if (fragmentType !== 2) return this.#drop("unknown-fragment-type");
14281
- const resolver = this.#timingResolver(streamKey, info.packetId, false);
14922
+ const resolver = this.#timingResolver(streamKey, info.packetId, true);
14282
14923
  if (!resolver) return this.#drop("mfu-no-resolver");
14283
14924
  if (!Number.isSafeInteger(data.byteLength) || data.byteLength <= 0)
14284
14925
  return this.#drop("mfu-empty-payload");
@@ -14299,6 +14940,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14299
14940
  mpuSequenceNumber: mpu.mpuSequenceNumber,
14300
14941
  movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
14301
14942
  sampleNumber: mfuDuHeader.sampleNumber,
14943
+ sequenceNumber: info.sequenceNumber,
14302
14944
  arrivedAt: Date.now()
14303
14945
  });
14304
14946
  return this.#drop("mfu-sample-timing-missing");
@@ -14324,7 +14966,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14324
14966
  info,
14325
14967
  resolver,
14326
14968
  options?.recovered === true,
14327
- options?.fecSbn
14969
+ options?.fecSbn,
14970
+ options?.fecSbnFirst
14328
14971
  );
14329
14972
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
14330
14973
  }
@@ -14417,7 +15060,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14417
15060
  info,
14418
15061
  resolver,
14419
15062
  options?.recovered === true,
14420
- options?.fecSbn
15063
+ options?.fecSbn,
15064
+ options?.fecSbnFirst
14421
15065
  );
14422
15066
  if (outcome.record !== void 0) return outcome.record;
14423
15067
  return this.#drop(outcome.reason);
@@ -14437,7 +15081,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14437
15081
  * attribution exists to keep readable. Leaving the choice at the call site
14438
15082
  * is what keeps both true.
14439
15083
  */
14440
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
15084
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
14441
15085
  const timing = resolver.sampleTiming(
14442
15086
  combined.mpuSequenceNumber,
14443
15087
  combined.movieFragmentSequenceNumber,
@@ -14454,6 +15098,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14454
15098
  );
14455
15099
  if (!meta) return { reason: "combined-meta-build-failed" };
14456
15100
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
15101
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
14457
15102
  if (!resolver.consumeSample(
14458
15103
  combined.mpuSequenceNumber,
14459
15104
  combined.movieFragmentSequenceNumber,
@@ -14622,6 +15267,10 @@ var MmtpContainerParser = class _MmtpContainerParser {
14622
15267
  }
14623
15268
  this.#emitFrame(data, meta);
14624
15269
  }
15270
+ /** Whether FT=1 metadata already names this sample, without claiming it. */
15271
+ hasAuthoredTimingFor(packetId, mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber, catalogTrackName) {
15272
+ return this.#timingResolver(this.#streamKey(packetId, catalogTrackName), packetId, false)?.sampleTiming(mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber) != null;
15273
+ }
14625
15274
  /**
14626
15275
  * Claim and return the authored timing for a recovered sample. Recovery does
14627
15276
  * not pass through the ordinary `feed()` completion path, so it must retire
@@ -14683,6 +15332,9 @@ var MmtpContainerParser = class _MmtpContainerParser {
14683
15332
  for (const { sequencer } of this.#sequencers.values()) sequencer.discard();
14684
15333
  this.#sequencers.clear();
14685
15334
  this.#fecSequencer?.discard();
15335
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
15336
+ for (const head of awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
15337
+ }
14686
15338
  this.#timingStreams.clear();
14687
15339
  this.#pendingTimingSamples = 0;
14688
15340
  this.#reliableMoqStartupGate.clear();
@@ -14701,10 +15353,23 @@ var MmtpContainerParser = class _MmtpContainerParser {
14701
15353
  return resolver;
14702
15354
  }
14703
15355
  #awaitTiming(streamKey, head) {
14704
- const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
14705
- if (!awaitingTiming) return;
15356
+ const state = this.#timingStreams.get(streamKey);
15357
+ if (!state) return;
15358
+ if (!head.options?.recovered) {
15359
+ const kept = state.awaitingTiming.filter((queued) => !queued.options?.recovered || queued.sequenceNumber !== head.sequenceNumber);
15360
+ this.#recoveredHeadsAwaitingTiming.superseded += state.awaitingTiming.length - kept.length;
15361
+ state.awaitingTiming = kept;
15362
+ }
15363
+ const awaitingTiming = state.awaitingTiming;
14706
15364
  awaitingTiming.push(head);
14707
- if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
15365
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming.held++;
15366
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) {
15367
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
15368
+ }
15369
+ }
15370
+ /** Count a recovered head leaving the queue other than by replay or its source copy. */
15371
+ #leaveAwaitingTiming(head, outcome) {
15372
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming[outcome]++;
14708
15373
  }
14709
15374
  /**
14710
15375
  * Feed again the heads whose timing the FT=1 just admitted declares. That
@@ -14732,6 +15397,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14732
15397
  const state = this.#timingStreams.get(streamKey);
14733
15398
  if (!state) return;
14734
15399
  this.#timingStreams.delete(streamKey);
15400
+ for (const head of state.awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
14735
15401
  this.#pendingTimingSamples -= state.resolver.pendingSampleCount;
14736
15402
  if (this.#pendingTimingSamples < 0) {
14737
15403
  throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");
@@ -17937,7 +18603,18 @@ function keyframeOverlaySsId(header) {
17937
18603
  if (ext?.type !== KEYFRAME_OVERLAY_EXTENSION_TYPE || ext.data.length !== 4) return void 0;
17938
18604
  return new DataView(ext.data.buffer, ext.data.byteOffset, 4).getUint32(0);
17939
18605
  }
18606
+ function overlayBaseSsId(anchor, overlaySsId, restoredPsn, headerPsn) {
18607
+ if (anchor.baseSsId === void 0 || headerPsn !== restoredPsn) return void 0;
18608
+ return serial32Add(anchor.baseSsId, overlaySsId - anchor.overlaySsId | 0);
18609
+ }
18610
+ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
18611
+ if (offset === void 0 || offset !== unstampedOffset) return void 0;
18612
+ return headerPsn + offset >>> 0;
18613
+ }
18614
+ var OVERLAY_ROUTED_LIMIT = 1024;
18615
+ var OVERLAY_PENDING_LIMIT = 256;
17940
18616
  var OVERLAY_OFFSET_MPUS = 16;
18617
+ var OVERLAY_REBUILT_LIMIT = 256;
17941
18618
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
17942
18619
  function assertStreamIdentity(role, stream) {
17943
18620
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -18048,6 +18725,7 @@ var MmtpRouter = class {
18048
18725
  #provenance = /* @__PURE__ */ new Map();
18049
18726
  #onFlowProtected = null;
18050
18727
  #unadmittedListedDrops = 0;
18728
+ #admittedSourceDatagrams = 0;
18051
18729
  #unlistedRepairSetAside = 0;
18052
18730
  #assistBlocks = /* @__PURE__ */ new Map();
18053
18731
  #assistFailures = /* @__PURE__ */ new Map();
@@ -18104,6 +18782,26 @@ var MmtpRouter = class {
18104
18782
  * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
18105
18783
  */
18106
18784
  #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18785
+ /**
18786
+ * Per stream, the SS_ID offset at which a base recovery last showed the
18787
+ * sender's own packet_sequence_number: a recovered packet's header psn
18788
+ * equal to its SS_ID minus that offset. While it equals the stream's
18789
+ * current offset, no hop re-stamps the stream, and a packet's protected psn
18790
+ * names its base SS_ID within unstampedBaseSsId's limits (joint decoding of
18791
+ * an MPU no member of which arrived).
18792
+ */
18793
+ #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18794
+ /**
18795
+ * The same, shown by the overlay alone, before any base recovery did: a
18796
+ * packet it rebuilt whose base copy carries its protected psn
18797
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
18798
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
18799
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
18800
+ * make the base drop a late base copy of a keyframe the overlay never
18801
+ * finished, and lift a block's late-source cut, which nothing before
18802
+ * this offset did.
18803
+ */
18804
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18107
18805
  /**
18108
18806
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
18109
18807
  * not parsed, typically because its overlap copy was parsed first
@@ -18173,7 +18871,9 @@ var MmtpRouter = class {
18173
18871
  recovered: 0,
18174
18872
  restarts: 0,
18175
18873
  unsequencedDropped: 0,
18176
- protectedDropped: 0
18874
+ protectedDropped: 0,
18875
+ baseFed: 0,
18876
+ baseUndetermined: 0
18177
18877
  };
18178
18878
  /** Callback fired when a delta-track FEC block completes or fails. */
18179
18879
  #onDeltaBlockCompleteCb = null;
@@ -18346,7 +19046,7 @@ var MmtpRouter = class {
18346
19046
  const cb = this.#getFrameCallback(packetId);
18347
19047
  if (isVideo && !assembler) {
18348
19048
  if (frameMeta.recovered) {
18349
- this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb);
19049
+ this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb, meta.fecSbn);
18350
19050
  } else {
18351
19051
  this.#routeDirectSourceVideo(packetId, data, frameMeta, cb);
18352
19052
  }
@@ -18379,13 +19079,18 @@ var MmtpRouter = class {
18379
19079
  this.#onDeltaBlockCompleteCb?.(packetId, false);
18380
19080
  }
18381
19081
  };
18382
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
19082
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
18383
19083
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
18384
19084
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
18385
19085
  this.#onDeltaBlockCompleteCb?.(packetId, true);
18386
19086
  }
18387
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18388
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19087
+ if (span === void 0) {
19088
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19089
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19090
+ } else {
19091
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
19092
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
19093
+ }
18389
19094
  };
18390
19095
  }
18391
19096
  }
@@ -18430,8 +19135,9 @@ var MmtpRouter = class {
18430
19135
  }
18431
19136
  /**
18432
19137
  * FEC-recovered source symbols whose reconstructed header named a
18433
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
18434
- * a hop re-stamped the sequence after the sender protected the packet.
19138
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
19139
+ * or, rebuilt by the overlay, than their base copy carries: a hop
19140
+ * re-stamped the sequence after the sender protected the packet.
18435
19141
  */
18436
19142
  get restampedRecoveredSequenceCount() {
18437
19143
  return this.#restampedRecoveredSeqs;
@@ -18610,6 +19316,7 @@ var MmtpRouter = class {
18610
19316
  enableMseAssembler(packetId, config, catalogTrackName) {
18611
19317
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
18612
19318
  const previous = this.#mseAssemblers.get(assemblerKey);
19319
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
18613
19320
  if (previous) {
18614
19321
  previous.flush();
18615
19322
  previous.dispose();
@@ -18736,6 +19443,10 @@ var MmtpRouter = class {
18736
19443
  get keyframeOverlayStats() {
18737
19444
  return { ...this.#overlayStats };
18738
19445
  }
19446
+ /** Recovered FT=2 heads held for their FT=1, and how each left the wait (BLO-53369). */
19447
+ get recoveredHeadsAwaitingTiming() {
19448
+ return this.#parser.recoveredHeadsAwaitingTiming;
19449
+ }
18739
19450
  #isOverlayRepair(repairPacketId, repairTrackName) {
18740
19451
  return this.#overlayLegs.has(repairPacketId) || repairTrackName !== void 0 && this.#overlayRepairNames.has(repairTrackName);
18741
19452
  }
@@ -18756,7 +19467,8 @@ var MmtpRouter = class {
18756
19467
  fec,
18757
19468
  k,
18758
19469
  offsets: /* @__PURE__ */ new Map(),
18759
- moqBlocks: /* @__PURE__ */ new Set()
19470
+ moqBlocks: /* @__PURE__ */ new Set(),
19471
+ rebuilt: /* @__PURE__ */ new Map()
18760
19472
  };
18761
19473
  this.#overlays.set(repairPacketId, inst);
18762
19474
  return () => {
@@ -18786,12 +19498,18 @@ var MmtpRouter = class {
18786
19498
  */
18787
19499
  resetKeyframeOverlays(sourcePacketId, catalogTrackName) {
18788
19500
  for (const inst of this.#overlaysForSource(sourcePacketId, catalogTrackName)) this.#resetOverlay(inst);
19501
+ for (const [name, stream] of this.#streams.get(sourcePacketId) ?? []) {
19502
+ if (catalogTrackName !== void 0 && name !== catalogTrackName) continue;
19503
+ stream.overlayToBase.routed.clear();
19504
+ stream.overlayToBase.pending.clear();
19505
+ }
18789
19506
  }
18790
19507
  #resetOverlay(inst) {
18791
19508
  inst.fec.resetTrack(inst.repairPacketId, inst.streamName);
18792
19509
  inst.last = void 0;
18793
19510
  inst.offsets.clear();
18794
19511
  inst.moqBlocks.clear();
19512
+ inst.rebuilt.clear();
18795
19513
  }
18796
19514
  #overlaysForSource(sourcePacketId, catalogTrackName) {
18797
19515
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -18842,18 +19560,33 @@ var MmtpRouter = class {
18842
19560
  * A source packet that carries a 0x8B01 overlay SS_ID is also a symbol of
18843
19561
  * every overlay installed for its source, at that SS_ID, with the bytes the
18844
19562
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
18845
- * included (7.1, 7.4.3).
18846
- */
18847
- #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source) {
19563
+ * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
19564
+ * FEC reads it.
19565
+ *
19566
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
19567
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
19568
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
19569
+ * the stream unstamped at the SS_ID offset it states, for the release gate
19570
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
19571
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
19572
+ */
19573
+ #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
18848
19574
  if (this.#overlays.size === 0) return;
18849
19575
  const ssId = keyframeOverlaySsId(header);
18850
19576
  if (ssId === void 0) return;
19577
+ let rebuiltPsn;
18851
19578
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
18852
19579
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
19580
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
19581
+ inst.rebuilt.delete(ssId);
18853
19582
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
18854
19583
  if (identity !== null) {
18855
19584
  inst.offsets.delete(identity.mpuSequenceNumber);
18856
- inst.offsets.set(identity.mpuSequenceNumber, ssId - sequenceNumber >>> 0);
19585
+ inst.offsets.set(identity.mpuSequenceNumber, {
19586
+ psnOffset: ssId - sequenceNumber >>> 0,
19587
+ overlaySsId: ssId,
19588
+ ...baseSsId === void 0 ? {} : { baseSsId }
19589
+ });
18857
19590
  if (inst.offsets.size > OVERLAY_OFFSET_MPUS) inst.offsets.delete(inst.offsets.keys().next().value);
18858
19591
  }
18859
19592
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -18875,6 +19608,14 @@ var MmtpRouter = class {
18875
19608
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
18876
19609
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
18877
19610
  }
19611
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
19612
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
19613
+ if (rebuiltPsn !== sequenceNumber) {
19614
+ this.#restampedRecoveredSeqs++;
19615
+ } else if (baseSsId !== void 0) {
19616
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19617
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
19618
+ }
18878
19619
  }
18879
19620
  #noteOverlayMoqBlock(inst, blockStart) {
18880
19621
  inst.moqBlocks.add(blockStart);
@@ -18908,11 +19649,16 @@ var MmtpRouter = class {
18908
19649
  }
18909
19650
  /**
18910
19651
  * Route an overlay-recovered block's packets as source media of the
18911
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
18912
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
18913
- * base re-stamp, no block advance. Each packet's wire sequence is restored
18914
- * from its keyframe's own offset; without one, a stream the base never
18915
- * re-stamped keeps the header's sequence and any other drops the packet.
19652
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
19653
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
19654
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
19655
+ * base FEC recovered does, so it waits behind base frames still in flight,
19656
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
19657
+ * longer than unanchored; one whose base SS_ID is undetermined has no
19658
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
19659
+ * advance. Each packet's wire sequence is restored from its keyframe's own
19660
+ * offset; without one, a stream the base never re-stamped keeps the
19661
+ * header's sequence and any other drops the packet.
18916
19662
  */
18917
19663
  #routeOverlayRecovered(inst, blockStart, recovered) {
18918
19664
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -18932,22 +19678,139 @@ var MmtpRouter = class {
18932
19678
  const streamKey = this.#mediaStreamKey(sourcePacketId, sourceName);
18933
19679
  const restamped = this.#restampedStreams.has(streamKey);
18934
19680
  const restored = /* @__PURE__ */ new Set();
19681
+ const baseSsIds = /* @__PURE__ */ new Map();
19682
+ const gateOnly = /* @__PURE__ */ new Set();
18935
19683
  const symbols = result.symbols.flatMap((sym) => {
18936
- const offset = inst.offsets.get(sym.fragment.mpuSequenceNumber);
18937
- if (offset !== void 0) {
18938
- const packetSequenceNumber = serial32Add(blockStart, sym.index) - offset >>> 0;
19684
+ const overlaySsId = serial32Add(blockStart, sym.index);
19685
+ const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
19686
+ if (anchor !== void 0) {
19687
+ const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
18939
19688
  restored.add(packetSequenceNumber);
18940
- return [{ ...sym, packetSequenceNumber }];
19689
+ const out = { ...sym, packetSequenceNumber };
19690
+ const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
19691
+ if (baseSsId !== void 0) {
19692
+ baseSsIds.set(sym.index, baseSsId);
19693
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19694
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
19695
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
19696
+ }
19697
+ }
19698
+ return [out];
19699
+ }
19700
+ if (!restamped) {
19701
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19702
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
19703
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
19704
+ if (baseSsId !== void 0) {
19705
+ baseSsIds.set(sym.index, baseSsId);
19706
+ if (fedSsId === void 0) gateOnly.add(sym.index);
19707
+ } else {
19708
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
19709
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
19710
+ }
19711
+ return [sym];
18941
19712
  }
18942
- if (!restamped) return [sym];
18943
19713
  this.#overlayStats.unsequencedDropped++;
18944
19714
  return [];
18945
19715
  });
18946
19716
  this.#overlayStats.recovered++;
19717
+ const mpuFirst = /* @__PURE__ */ new Map();
19718
+ for (const sym of symbols) {
19719
+ const ssId = baseSsIds.get(sym.index);
19720
+ const mpu = sym.fragment.mpuSequenceNumber;
19721
+ const first = mpuFirst.get(mpu);
19722
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
19723
+ }
19724
+ const firstSsIds = /* @__PURE__ */ new Map();
19725
+ for (const sym of symbols) {
19726
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
19727
+ }
18947
19728
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
18948
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
19729
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
19730
+ baseSsIds,
19731
+ firstSsIds
18949
19732
  });
18950
19733
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
19734
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
19735
+ }
19736
+ /**
19737
+ * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
19738
+ * its base block too, once its base SS_ID is determined (overlayBaseSsId,
19739
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
19740
+ * base recovery showed; `baseSsIds` holds no other),
19741
+ * so it is fed to the base decoder as a rebuilt source
19742
+ * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
19743
+ * fewer to solve, and its repair can recover the block's other packets.
19744
+ * A base block no repair has stated yet takes it when one does
19745
+ * (#feedPendingRebuilt).
19746
+ *
19747
+ * The overlay route already handled each packet fed (delivered it, or
19748
+ * held an untimed head for its FT=1), so a base recovery routes none of
19749
+ * them again (#routeVerifiedFecSymbols): a second recovered copy of a
19750
+ * held head would wait in the parser for timing its first copy consumed.
19751
+ * Only an overlay block decoded from multicast symbols alone is fed: with
19752
+ * a MoQ symbol in it, the base block's recovery would depend on bytes
19753
+ * that crossed no multicast socket, which the provenance counted from the
19754
+ * block's own arrivals cannot show.
19755
+ */
19756
+ #feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds) {
19757
+ const fec = this.#fecManager;
19758
+ const owner = inst.leg.sourcePacketId;
19759
+ const name = inst.leg.sourceCatalogTrackName;
19760
+ if (!fec?.feedRebuiltSourceSymbol || inst.moqBlocks.has(blockStart)) return;
19761
+ if (this.#classifyPacketId(owner) === null || fec.isTrackConfigured?.(owner) === false) return;
19762
+ const { duplicates, overlayToBase: { routed } } = this.#stream(owner, name);
19763
+ const feeds = [];
19764
+ for (const sym of symbols) {
19765
+ if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
19766
+ const ssId = baseSsIds.get(sym.index);
19767
+ if (ssId === void 0) {
19768
+ this.#overlayStats.baseUndetermined++;
19769
+ continue;
19770
+ }
19771
+ routed.delete(ssId);
19772
+ routed.add(ssId);
19773
+ if (routed.size > OVERLAY_ROUTED_LIMIT) routed.delete(routed.values().next().value);
19774
+ feeds.push([ssId, sym.rawSymbol]);
19775
+ }
19776
+ for (const [ssId, symbolData] of feeds) {
19777
+ if (this.#classifyPacketId(owner) === null) return;
19778
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
19779
+ }
19780
+ }
19781
+ /** Feed one rebuilt source to its base block, or keep it until a repair states that block. */
19782
+ #feedRebuiltToBase(owner, name, ssId, symbolData) {
19783
+ const fec = this.#fecManager;
19784
+ if (!fec?.feedRebuiltSourceSymbol) return;
19785
+ const coords = fec.locateIsoSource?.(owner, name, ssId);
19786
+ if (coords == null) {
19787
+ const pending = this.#stream(owner, name).overlayToBase.pending;
19788
+ pending.delete(ssId);
19789
+ pending.set(ssId, symbolData.slice());
19790
+ if (pending.size > OVERLAY_PENDING_LIMIT) pending.delete(pending.keys().next().value);
19791
+ return;
19792
+ }
19793
+ const fed = fec.feedRebuiltSourceSymbol(owner, ssId, symbolData, name);
19794
+ if (!fed.taken) return;
19795
+ this.#overlayStats.baseFed++;
19796
+ if (fed.recovered === null) return;
19797
+ const sbn = coords.sbn;
19798
+ this.#routeRecoveredBlock(sbn, fed.recovered, owner, name, () => {
19799
+ fec.cancelBlockTimeout(sbn, owner, name);
19800
+ fec.countRecovery(owner, sbn, name);
19801
+ fec.markBlockCompleted(sbn, owner, name);
19802
+ });
19803
+ }
19804
+ /** A repair stated `block`: the rebuilt sources that waited for it join it now. */
19805
+ #feedPendingRebuilt(owner, name, block) {
19806
+ const pending = this.#streams.get(owner)?.get(name)?.overlayToBase.pending;
19807
+ if (pending === void 0 || pending.size === 0) return;
19808
+ for (const [ssId, symbolData] of [...pending]) {
19809
+ if (this.#classifyPacketId(owner) === null) return;
19810
+ if (serial32Distance(block.start, ssId) >= block.length) continue;
19811
+ pending.delete(ssId);
19812
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
19813
+ }
18951
19814
  }
18952
19815
  /** fec-multicast-00 §6.6: report each base block whose RAP MFU fragments
18953
19816
  * the overlay restored, when the keyframe's FT=0 and FT=1 are held too. A
@@ -19087,6 +19950,10 @@ var MmtpRouter = class {
19087
19950
  get unadmittedListedDropCount() {
19088
19951
  return this.#unadmittedListedDrops;
19089
19952
  }
19953
+ /** 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. */
19954
+ get admittedSourceDatagramCount() {
19955
+ return this.#admittedSourceDatagrams;
19956
+ }
19090
19957
  /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
19091
19958
  get unlistedRepairSetAsideCount() {
19092
19959
  return this.#unlistedRepairSetAside;
@@ -19573,6 +20440,8 @@ var MmtpRouter = class {
19573
20440
  )) return;
19574
20441
  fec.noteBlockActivity?.(blockStart, ownerPacketId, catalogTrackName);
19575
20442
  fec.noteRepairGroupLength?.(blockStart, ownerPacketId, repair.rsbLength, catalogTrackName);
20443
+ this.#feedPendingRebuilt(ownerPacketId, catalogTrackName, placement.block);
20444
+ if (this.#classifyPacketId(ownerPacketId) === null) return;
19576
20445
  const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
19577
20446
  const recovered = fec.feedRepairSymbol(
19578
20447
  ownerPacketId,
@@ -19623,7 +20492,7 @@ var MmtpRouter = class {
19623
20492
  catalogTrackName
19624
20493
  )) continue;
19625
20494
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
19626
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
20495
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
19627
20496
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
19628
20497
  }
19629
20498
  if (payload.oversized) continue;
@@ -19710,6 +20579,8 @@ var MmtpRouter = class {
19710
20579
  this.#droppedPreSyncVideo.delete(streamKey);
19711
20580
  this.#latestVideoSeqByStream.delete(streamKey);
19712
20581
  this.#ssIdSeqOffsetByStream.delete(streamKey);
20582
+ this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
20583
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
19713
20584
  this.#multicastRapTwinByStream.delete(streamKey);
19714
20585
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
19715
20586
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -19836,6 +20707,12 @@ var MmtpRouter = class {
19836
20707
  * the outgoing stream stops. The hold is bounded by the incoming stream's
19837
20708
  * own RAP cadence, so no timer is involved.
19838
20709
  *
20710
+ * While the switch is staged, the FEC release gate lets a keyframe the
20711
+ * overlay rebuilt reach it, on either side, when the keyframe did before
20712
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
20713
+ * decides on what each side delivered, and the commit discards the gate's
20714
+ * frames of the outgoing stream.
20715
+ *
19839
20716
  * The commit is one synchronous transition inside the frame path: the
19840
20717
  * outgoing stream's already-admitted frames are released (its queued FEC
19841
20718
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -19886,6 +20763,9 @@ var MmtpRouter = class {
19886
20763
  droppedIncomingFrames: 0
19887
20764
  };
19888
20765
  this.#staged = state;
20766
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
20767
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
20768
+ }
19889
20769
  return {
19890
20770
  cancel: () => {
19891
20771
  if (this.#staged !== state) return false;
@@ -19968,7 +20848,17 @@ var MmtpRouter = class {
19968
20848
  */
19969
20849
  #routeParsedFrame(data, meta) {
19970
20850
  if (this.#classifyPacketId(meta.packetId) === null) return;
19971
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
20851
+ if (this.#staged !== null) {
20852
+ let consumed = false;
20853
+ this.#fecPokeDepth++;
20854
+ try {
20855
+ consumed = this.#interceptSwitchFrame(data, meta);
20856
+ } finally {
20857
+ this.#fecPokeDepth--;
20858
+ this.#flushPendingFecPokes();
20859
+ }
20860
+ if (consumed) return;
20861
+ }
19972
20862
  this.#deliverParsedFrame(data, meta);
19973
20863
  }
19974
20864
  #commitStreamSwitch(state, rap, reason) {
@@ -20120,12 +21010,16 @@ var MmtpRouter = class {
20120
21010
  this.#parser.deferFecRelease(work);
20121
21011
  } finally {
20122
21012
  this.#fecPokeDepth--;
20123
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
20124
- const pokes = [...this.#pendingFecPokes.values()];
20125
- this.#pendingFecPokes.clear();
20126
- for (const poke of pokes) {
20127
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20128
- }
21013
+ this.#flushPendingFecPokes();
21014
+ }
21015
+ }
21016
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
21017
+ #flushPendingFecPokes() {
21018
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
21019
+ const pokes = [...this.#pendingFecPokes.values()];
21020
+ this.#pendingFecPokes.clear();
21021
+ for (const poke of pokes) {
21022
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20129
21023
  }
20130
21024
  }
20131
21025
  }
@@ -20203,6 +21097,14 @@ var MmtpRouter = class {
20203
21097
  onRap: (packetId, catalogTrackName, ssId) => {
20204
21098
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
20205
21099
  },
21100
+ // A staged switch commits on when each side's frames reach it
21101
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
21102
+ // they did unanchored.
21103
+ releaseUnanchored: (packetId, catalogTrackName) => {
21104
+ const staged = this.#staged;
21105
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
21106
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
21107
+ },
20206
21108
  onReleased: (data, meta) => {
20207
21109
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
20208
21110
  const timing = meta.authoredTiming;
@@ -20344,6 +21246,7 @@ var MmtpRouter = class {
20344
21246
  const parsed = this.#parser.parsePacket(packet);
20345
21247
  if (!parsed) return;
20346
21248
  const info = parsed.info;
21249
+ if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
20347
21250
  if (source === "multicast" && !manifestAdmitted) {
20348
21251
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
20349
21252
  }
@@ -20625,7 +21528,8 @@ var MmtpRouter = class {
20625
21528
  parsed.header,
20626
21529
  info.sequenceNumber,
20627
21530
  info.rapFlag,
20628
- source
21531
+ source,
21532
+ fecPayloadId?.ssId
20629
21533
  );
20630
21534
  }
20631
21535
  }
@@ -20651,7 +21555,8 @@ var MmtpRouter = class {
20651
21555
  source: parserOptions?.source,
20652
21556
  deliveryProvenance: parserOptions?.deliveryProvenance,
20653
21557
  catalogTrackName: parserOptions?.catalogTrackName,
20654
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
21558
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
21559
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
20655
21560
  };
20656
21561
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
20657
21562
  else this.#parser.feed(packet, feedOptions);
@@ -20775,7 +21680,8 @@ var MmtpRouter = class {
20775
21680
  if (stream === void 0) {
20776
21681
  stream = {
20777
21682
  key: JSON.stringify([packetId, catalogTrackName ?? null]),
20778
- duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId))
21683
+ duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId)),
21684
+ overlayToBase: { routed: /* @__PURE__ */ new Set(), pending: /* @__PURE__ */ new Map() }
20779
21685
  };
20780
21686
  byName.set(catalogTrackName, stream);
20781
21687
  }
@@ -20890,8 +21796,16 @@ var MmtpRouter = class {
20890
21796
  this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
20891
21797
  this.#emitDirectVideo(packetId, data, meta, cb);
20892
21798
  }
20893
- #routeDirectRecoveredVideo(packetId, data, meta, cb) {
21799
+ #routeDirectRecoveredVideo(packetId, data, meta, cb, fecSbn) {
20894
21800
  const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);
21801
+ if (this.#isFecTrack(packetId)) {
21802
+ const high = this.#deliveredVideoHighWaterByStream.get(streamKey);
21803
+ if (fecSbn !== void 0 || high !== void 0 && authoredAdjacent(high, meta)) {
21804
+ this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
21805
+ this.#emitDirectVideo(packetId, data, meta, cb);
21806
+ return;
21807
+ }
21808
+ }
20895
21809
  this.#enqueueDirectRecoveredVideo(packetId, data, meta);
20896
21810
  const lastSourceTs = this.#lastDirectSourceVideoTsByStream.get(streamKey);
20897
21811
  this.#drainDirectRecoveredVideo(
@@ -21045,6 +21959,13 @@ var MmtpRouter = class {
21045
21959
  * frames by epoch only if pre-protection input ever matters.
21046
21960
  */
21047
21961
  #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete, assisted = false) {
21962
+ const overlayRouted = ownerPacketId == null ? void 0 : this.#streams.get(ownerPacketId)?.get(catalogTrackName)?.overlayToBase.routed;
21963
+ if (overlayRouted !== void 0 && overlayRouted.size > 0) {
21964
+ result = {
21965
+ ...result,
21966
+ symbols: result.symbols.filter((sym) => !overlayRouted.has(this.#fecAnchorForRecovered(blockId, sym.index)))
21967
+ };
21968
+ }
21048
21969
  const entry = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
21049
21970
  const receiver = entry === void 0 || entry === "ambiguous" ? entry : entry.receiver;
21050
21971
  const userAgent = !assisted && entry !== void 0 && entry !== "ambiguous" && entry.protected === true && entry.userAgent === true;
@@ -21101,7 +22022,12 @@ var MmtpRouter = class {
21101
22022
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
21102
22023
  if (ownerPacketId == null) return;
21103
22024
  if (this.#classifyPacketId(ownerPacketId) === null) return;
21104
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
22025
+ const fecSbnOf = (index) => {
22026
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
22027
+ const fecSbn = overlay.baseSsIds.get(index);
22028
+ const fecSbnFirst = overlay.firstSsIds.get(index);
22029
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
22030
+ };
21105
22031
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
21106
22032
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
21107
22033
  if (ssIdSeqOffset !== void 0) {
@@ -21109,7 +22035,10 @@ var MmtpRouter = class {
21109
22035
  ...result,
21110
22036
  symbols: result.symbols.map((sym) => {
21111
22037
  const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
21112
- if (wire === sym.packetSequenceNumber) return sym;
22038
+ if (wire === sym.packetSequenceNumber) {
22039
+ this.#unstampedSsIdSeqOffsetByStream.set(streamKey, ssIdSeqOffset);
22040
+ return sym;
22041
+ }
21113
22042
  this.#restampedRecoveredSeqs++;
21114
22043
  this.#restampedStreams.add(streamKey);
21115
22044
  return { ...sym, packetSequenceNumber: wire };
@@ -21145,6 +22074,29 @@ var MmtpRouter = class {
21145
22074
  }
21146
22075
  );
21147
22076
  }
22077
+ const untimedHead = (sym) => sym.fragmentType === 2 && sym.fragment.fragmentationIndicator === 1 && sym.fragment.movieFragmentSequenceNumber !== void 0 && sym.fragment.sampleNumber !== void 0 && !this.#parser.hasAuthoredTimingFor(
22078
+ ownerPacketId,
22079
+ sym.fragment.mpuSequenceNumber,
22080
+ sym.fragment.movieFragmentSequenceNumber,
22081
+ sym.fragment.sampleNumber,
22082
+ catalogTrackName
22083
+ );
22084
+ for (const sym of result.symbols) {
22085
+ if (!untimedHead(sym) || this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) continue;
22086
+ this.#feedViaParser(
22087
+ sym.rawSymbol,
22088
+ { packetId: ownerPacketId, sequenceNumber: sym.packetSequenceNumber },
22089
+ void 0,
22090
+ {
22091
+ skipFecPayloadId: true,
22092
+ recovered: true,
22093
+ deliveryProvenance,
22094
+ ...fecSbnOf(sym.index),
22095
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
22096
+ }
22097
+ );
22098
+ }
22099
+ result = { ...result, symbols: result.symbols.filter((sym) => !untimedHead(sym)) };
21148
22100
  const gated = this.#isFecTrack(ownerPacketId);
21149
22101
  const assembler = this.#mseAssemblerFor(ownerPacketId, catalogTrackName);
21150
22102
  if (assembler) {
@@ -22621,6 +23573,12 @@ function isNonNegativeSafeInteger(value) {
22621
23573
  function isSymbolCounts(value) {
22622
23574
  return isRecord(value) && hasExactKeys(value, ["multicast", "moq"]) && isNonNegativeSafeInteger(value["multicast"]) && isNonNegativeSafeInteger(value["moq"]);
22623
23575
  }
23576
+ function isSpanFailure(value) {
23577
+ if (!isRecord(value) || !hasExactKeys(value, ["length", "sources"])) return false;
23578
+ const length = value["length"];
23579
+ const sources = value["sources"];
23580
+ return Number.isSafeInteger(length) && length > 0 && isNonNegativeSafeInteger(sources) && sources < length;
23581
+ }
22624
23582
  function isNullableNonNegative(value) {
22625
23583
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
22626
23584
  }
@@ -22640,7 +23598,10 @@ function isRepairLifecycleEvent(value) {
22640
23598
  case "recovered":
22641
23599
  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"]);
22642
23600
  case "failed":
22643
- return hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]);
23601
+ return hasExactKeys(
23602
+ value,
23603
+ "span" in value ? ["version", "type", "block", "blockClass", "symbols", "span"] : ["version", "type", "block", "blockClass", "symbols"]
23604
+ ) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]) && (!("span" in value) || isSpanFailure(value["span"]));
22644
23605
  case "repair-preempted":
22645
23606
  case "repair-deferred":
22646
23607
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
@@ -22849,6 +23810,8 @@ var MulticastManager = class {
22849
23810
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
22850
23811
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
22851
23812
  #repairReleases = /* @__PURE__ */ new Map();
23813
+ /** Protected repair flows owned by each live repair-endpoint release. */
23814
+ #repairProvenanceFlows = /* @__PURE__ */ new Map();
22852
23815
  /** Each source's catalog keyframe overlay, from its `ok` binding. */
22853
23816
  #overlayBindings = /* @__PURE__ */ new Map();
22854
23817
  /** Installed overlay decoders (`setKeyframeOverlayDecoder`), by source. */
@@ -22906,7 +23869,7 @@ var MulticastManager = class {
22906
23869
  onPublisherRestart: (packetId, catalogTrackName) => {
22907
23870
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
22908
23871
  },
22909
- onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
23872
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass, span) => {
22910
23873
  const pathCount = this.#fec.blockPathCount(
22911
23874
  sbn,
22912
23875
  packetId,
@@ -22924,7 +23887,8 @@ var MulticastManager = class {
22924
23887
  symbols: {
22925
23888
  multicast: pathCount?.multicastSymbols ?? 0,
22926
23889
  moq: pathCount?.moqSymbols ?? 0
22927
- }
23890
+ },
23891
+ ...span === void 0 ? {} : { span }
22928
23892
  });
22929
23893
  },
22930
23894
  onFrameGap: (decision) => {
@@ -23012,6 +23976,11 @@ var MulticastManager = class {
23012
23976
  this.#fec.onBlockVanished = (_sbn, packetId, catalogTrackName) => {
23013
23977
  this.#statsFor(packetId, catalogTrackName).vanishedBlocks++;
23014
23978
  };
23979
+ this.#fec.keyframeOverlayTiming = (packetId, catalogTrackName) => {
23980
+ const binding = this.#overlayInstalls.has(packetId) ? this.#overlayBindings.get(packetId) : void 0;
23981
+ if (binding === void 0) return void 0;
23982
+ return catalogTrackName === void 0 || catalogTrackName === binding.sourceCatalogTrackName ? binding.geometry : void 0;
23983
+ };
23015
23984
  this.#fec.onDecoderUnavailable = (event) => {
23016
23985
  this.#emitRepairLifecycle({
23017
23986
  version: 2,
@@ -23514,6 +24483,9 @@ var MulticastManager = class {
23514
24483
  this.#transport.onFailback((reason) => {
23515
24484
  const joined = this.#provenanceJoin;
23516
24485
  if (joined !== null) this.#router.unprotectProvenanceFlow(joined.flow);
24486
+ for (const flows of this.#repairProvenanceFlows.values()) {
24487
+ for (const flow of flows) this.#router.unprotectProvenanceFlow(flow);
24488
+ }
23517
24489
  this.#onFailback?.(reason);
23518
24490
  });
23519
24491
  }
@@ -23548,6 +24520,12 @@ var MulticastManager = class {
23548
24520
  "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
23549
24521
  );
23550
24522
  }
24523
+ if (provenanceFlow !== void 0) {
24524
+ const flow = multicastProvenanceFlowKey(provenanceFlow);
24525
+ if ([...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
24526
+ throw new TypeError(`[MulticastManager] join: provenance flow already registered by a repair endpoint: ${flow}`);
24527
+ }
24528
+ }
23551
24529
  const staged = this.#renditionSwitch;
23552
24530
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
23553
24531
  this.configureFec(config);
@@ -23555,8 +24533,8 @@ var MulticastManager = class {
23555
24533
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
23556
24534
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
23557
24535
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
23558
- this.#releaseProvenanceJoin();
23559
24536
  const provenance = config.provenance;
24537
+ this.#releaseProvenanceJoin();
23560
24538
  const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
23561
24539
  const ingress = protectedTracks === void 0 ? void 0 : {
23562
24540
  tracks: Object.freeze(
@@ -23609,8 +24587,13 @@ var MulticastManager = class {
23609
24587
  * feeds the flow's receiver; media datagrams are held until one admits them.
23610
24588
  */
23611
24589
  #joinProvenance(provenance, ingress) {
24590
+ this.#router.registerProvenanceFlow(ingress, this.#provenanceReceiver(provenance));
24591
+ this.#hookFailback();
24592
+ this.#provenanceJoin = { flow: ingress.flow };
24593
+ }
24594
+ #provenanceReceiver(provenance) {
23612
24595
  const { flow, auth } = provenance;
23613
- const receiver = new BcProvenanceV2Receiver({
24596
+ return new BcProvenanceV2Receiver({
23614
24597
  ...provenance.receiver,
23615
24598
  // The caller's ctx when it passes one, else the catalog's: an explicit
23616
24599
  // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
@@ -23627,9 +24610,6 @@ var MulticastManager = class {
23627
24610
  maxAuthDelayMs: flow.maxAuthDelayMs,
23628
24611
  manifestTimerMs: flow.manifestTimerMs
23629
24612
  });
23630
- this.#router.registerProvenanceFlow(ingress, receiver);
23631
- this.#hookFailback();
23632
- this.#provenanceJoin = { flow: ingress.flow };
23633
24613
  }
23634
24614
  /** Un-protect: drop the flow's hold queues (no expiry counted). */
23635
24615
  #releaseProvenanceJoin() {
@@ -23660,8 +24640,25 @@ var MulticastManager = class {
23660
24640
  * callback delivers must come from a subscription opened on
23661
24641
  * `options.gateway`. A callback that also merges another source (a MoQ or
23662
24642
  * WebSocket repair feed) must not name a native provider here.
24643
+ *
24644
+ * An endpoint's `provenance` makes its group a protected flow of its own
24645
+ * (multicast-02 7.2.7), registered here and released with the group; its
24646
+ * records ride in band on the group's port. On the user-agent path a
24647
+ * flow-less repair group of a protected track is set aside, never read, so
24648
+ * a player joining a protected catalog's repair groups passes it.
23663
24649
  */
23664
24650
  joinRepairEndpoints(endpoints, provider, options) {
24651
+ for (const { provenance, flow, source, group, port } of endpoints) {
24652
+ if (provenance === void 0) continue;
24653
+ if (flow !== void 0) {
24654
+ throw new TypeError("[MulticastManager] joinRepairEndpoints: an endpoint names provenance or flow, never both");
24655
+ }
24656
+ if (!sameIpAddress(source, provenance.flow.source) || !sameIpAddress(group, provenance.flow.groupAddress) || port !== provenance.flow.port) {
24657
+ throw new RangeError(
24658
+ "[MulticastManager] joinRepairEndpoints: provenance flow (S, G, port) must match the endpoint's source, group and port"
24659
+ );
24660
+ }
24661
+ }
23665
24662
  const releases = [];
23666
24663
  let released = false;
23667
24664
  const safely = (each) => {
@@ -23671,17 +24668,36 @@ var MulticastManager = class {
23671
24668
  console.warn("[MulticastManager] repair group release failed", error);
23672
24669
  }
23673
24670
  };
24671
+ const usedFlows = /* @__PURE__ */ new Set();
24672
+ const preparedProvenance = endpoints.map((endpoint) => {
24673
+ if (endpoint.provenance === void 0) return void 0;
24674
+ const flow = multicastProvenanceFlowKey(endpoint.provenance.flow);
24675
+ if (usedFlows.has(flow) || this.#provenanceJoin?.flow === flow || [...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
24676
+ throw new TypeError(`[MulticastManager] joinRepairEndpoints: provenance flow already registered: ${flow}`);
24677
+ }
24678
+ usedFlows.add(flow);
24679
+ return { flow, receiver: this.#provenanceReceiver(endpoint.provenance) };
24680
+ });
24681
+ const provenanceFlows = [];
23674
24682
  const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners.map((owner) => owner.instance !== "keyframe" ? owner : {
23675
24683
  ...owner,
23676
24684
  ownerTrackName: endpoint.tracks.find((t) => t.packetId === owner.ownerPacketId)?.name,
23677
24685
  repairTrackName: endpoint.tracks.find((t) => t.packetId === owner.packetId)?.name
23678
24686
  }));
23679
24687
  this.#applyRepairOwners(repairOwners);
23680
- for (const endpoint of endpoints) {
24688
+ for (const [index, endpoint] of endpoints.entries()) {
24689
+ const flow = endpoint.provenance === void 0 ? endpoint.flow : multicastProvenanceFlowKey(endpoint.provenance.flow);
23681
24690
  const ingress = {
23682
24691
  tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
23683
- ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
24692
+ ...flow === void 0 ? {} : { flow }
23684
24693
  };
24694
+ if (endpoint.provenance !== void 0) {
24695
+ const prepared = preparedProvenance[index];
24696
+ if (prepared === void 0) throw new Error("[MulticastManager] repair provenance preparation missing");
24697
+ this.#router.registerProvenanceFlow(ingress, prepared.receiver);
24698
+ provenanceFlows.push(prepared.flow);
24699
+ releases.push(() => this.#router.releaseProvenanceFlow(flow));
24700
+ }
23685
24701
  let sender;
23686
24702
  const feed = (packet, sourceAddress, ingressToFeed) => {
23687
24703
  if (released) return;
@@ -23711,7 +24727,7 @@ var MulticastManager = class {
23711
24727
  packetIds: endpoint.packetIds,
23712
24728
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
23713
24729
  // A protected repair group's records ride in band on its port (7.2.3).
23714
- ...endpoint.flow === void 0 ? {} : { protected: true }
24730
+ ...flow === void 0 ? {} : { protected: true }
23715
24731
  }, ingress).then((joined) => {
23716
24732
  if (!joined && !released) fail(transport.lastJoinOutcome);
23717
24733
  });
@@ -23720,9 +24736,12 @@ var MulticastManager = class {
23720
24736
  if (released) return;
23721
24737
  released = true;
23722
24738
  this.#repairReleases.delete(release);
24739
+ this.#repairProvenanceFlows.delete(release);
23723
24740
  for (const each of releases.splice(0)) safely(each);
23724
24741
  };
23725
24742
  this.#repairReleases.set(release, repairOwners);
24743
+ this.#repairProvenanceFlows.set(release, provenanceFlows);
24744
+ if (provenanceFlows.length) this.#hookFailback();
23726
24745
  return release;
23727
24746
  }
23728
24747
  #applyRepairOwners(owners) {
@@ -24208,7 +25227,8 @@ var MulticastManager = class {
24208
25227
  blockProfile: parseFecBlockProfile(
24209
25228
  geometry2.blockProfile,
24210
25229
  `tracks[${JSON.stringify(track.name)}].fec keyframe overlay blockProfile`
24211
- )
25230
+ ),
25231
+ geometry: geometry2
24212
25232
  });
24213
25233
  }
24214
25234
  }
@@ -24247,7 +25267,7 @@ var MulticastManager = class {
24247
25267
  for (const [sourcePacketId, install] of [...this.#overlayInstalls]) {
24248
25268
  const before = this.#overlayBindings.get(sourcePacketId);
24249
25269
  const after = overlayBindings.get(sourcePacketId);
24250
- const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => after[key] === before[key]);
25270
+ const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => key === "geometry" || after[key] === before[key]);
24251
25271
  if (!same) install.dispose();
24252
25272
  else if (this.#router.hasKeyframeOverlay(after.repairPacketId)) this.#router.resetKeyframeOverlays(sourcePacketId);
24253
25273
  else install.reattach();
@@ -24304,10 +25324,12 @@ var MulticastManager = class {
24304
25324
  * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
24305
25325
  * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
24306
25326
  * pending hole and reported here, and `closeIsoHoles` must be called for it
24307
- * once its range FETCH ends (or none is sent).
25327
+ * once its range FETCH ends (or none is sent). `onExpired` is told of a
25328
+ * pending hole the stream runs past the locator's horizon: returning true,
25329
+ * the caller closes it (`closeIsoHoles`); otherwise it is discarded.
24308
25330
  */
24309
- onUndelimitedLoss(cb) {
24310
- this.#fec.setUndelimitedLossHandler(cb);
25331
+ onUndelimitedLoss(cb, onExpired) {
25332
+ this.#fec.setUndelimitedLossHandler(cb, onExpired ?? null);
24311
25333
  }
24312
25334
  /**
24313
25335
  * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
@@ -24543,7 +25565,8 @@ var MulticastManager = class {
24543
25565
  "stream" in event ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
24544
25566
  ...event,
24545
25567
  block: Object.freeze({ ...event.block }),
24546
- ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {}
25568
+ ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {},
25569
+ ..."span" in event && event.span !== void 0 ? { span: Object.freeze({ ...event.span }) } : {}
24547
25570
  }
24548
25571
  );
24549
25572
  if (this.#logRepairLifecycle) {