@blockcast/mmt-container 2.2.0-main.a88c3a0aa4f3 → 2.2.0-main.aee8d33d2cc8

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 (118) hide show
  1. package/README.md +34 -19
  2. package/dist/block-policy.d.ts +55 -13
  3. package/dist/block-policy.d.ts.map +1 -1
  4. package/dist/block-policy.js +104 -32
  5. package/dist/block-policy.js.map +2 -2
  6. package/dist/browser-runtime.js +2094 -385
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.js.map +2 -2
  9. package/dist/catalog-fec-params.d.ts +18 -2
  10. package/dist/catalog-fec-params.d.ts.map +1 -1
  11. package/dist/catalog-fec-params.js +29 -1
  12. package/dist/catalog-fec-params.js.map +2 -2
  13. package/dist/catalog-network-source.js.map +2 -2
  14. package/dist/cmaf-block-assembler.js +92 -1
  15. package/dist/cmaf-block-assembler.js.map +2 -2
  16. package/dist/cmcd-producer.d.ts +60 -47
  17. package/dist/cmcd-producer.d.ts.map +1 -1
  18. package/dist/cmcd-producer.js +138 -109
  19. package/dist/cmcd-producer.js.map +2 -2
  20. package/dist/codec-utils.d.ts.map +1 -1
  21. package/dist/codec-utils.js +92 -1
  22. package/dist/codec-utils.js.map +2 -2
  23. package/dist/delivery-catalog.js +26 -16
  24. package/dist/delivery-catalog.js.map +2 -2
  25. package/dist/delta-fallback-config.js +5 -1
  26. package/dist/delta-fallback-config.js.map +3 -3
  27. package/dist/fec-manager.d.ts +114 -15
  28. package/dist/fec-manager.d.ts.map +1 -1
  29. package/dist/fec-manager.js +639 -95
  30. package/dist/fec-manager.js.map +2 -2
  31. package/dist/fec-state.js +5 -1
  32. package/dist/fec-state.js.map +2 -2
  33. package/dist/fec-worker-setup.d.ts +1 -1
  34. package/dist/fec-worker-setup.js +1 -1
  35. package/dist/fec-worker-setup.js.map +2 -2
  36. package/dist/held-layer-admission.js.map +2 -2
  37. package/dist/index.d.ts +6 -5
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +12 -2
  40. package/dist/index.js.map +2 -2
  41. package/dist/iso-block-locator.d.ts +48 -13
  42. package/dist/iso-block-locator.d.ts.map +1 -1
  43. package/dist/iso-block-locator.js +97 -25
  44. package/dist/iso-block-locator.js.map +2 -2
  45. package/dist/iso-bmff-timing.d.ts +10 -1
  46. package/dist/iso-bmff-timing.d.ts.map +1 -1
  47. package/dist/iso-bmff-timing.js +36 -2
  48. package/dist/iso-bmff-timing.js.map +2 -2
  49. package/dist/media-router.js.map +1 -1
  50. package/dist/mfu-reassembler.js +12 -19
  51. package/dist/mfu-reassembler.js.map +2 -2
  52. package/dist/mmtp-container-parser.d.ts +106 -12
  53. package/dist/mmtp-container-parser.d.ts.map +1 -1
  54. package/dist/mmtp-container-parser.js +324 -46
  55. package/dist/mmtp-container-parser.js.map +2 -2
  56. package/dist/mmtp-container-parser.no-modules.js +466 -66
  57. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  58. package/dist/mmtp-decode-pipeline.js +323 -46
  59. package/dist/mmtp-decode-pipeline.js.map +2 -2
  60. package/dist/mmtp-fec-session.d.ts +41 -3
  61. package/dist/mmtp-fec-session.d.ts.map +1 -1
  62. package/dist/mmtp-fec-session.js +118 -13
  63. package/dist/mmtp-fec-session.js.map +3 -3
  64. package/dist/mmtp-router.d.ts +36 -8
  65. package/dist/mmtp-router.d.ts.map +1 -1
  66. package/dist/mmtp-router.js +716 -100
  67. package/dist/mmtp-router.js.map +3 -3
  68. package/dist/multicast-auth-catalog.js.map +2 -2
  69. package/dist/multicast-input.js.map +2 -2
  70. package/dist/multicast-manager.d.ts +28 -3
  71. package/dist/multicast-manager.d.ts.map +1 -1
  72. package/dist/multicast-manager.js +1451 -215
  73. package/dist/multicast-manager.js.map +3 -3
  74. package/dist/multicast-transport.js +28 -18
  75. package/dist/multicast-transport.js.map +2 -2
  76. package/dist/multicast-unwrap.js +12 -19
  77. package/dist/multicast-unwrap.js.map +2 -2
  78. package/dist/no-modules.d.ts +1 -0
  79. package/dist/no-modules.d.ts.map +1 -1
  80. package/dist/no-modules.js +463 -64
  81. package/dist/no-modules.js.map +4 -4
  82. package/dist/repair-fetch.d.ts +38 -8
  83. package/dist/repair-fetch.d.ts.map +1 -1
  84. package/dist/repair-fetch.js +286 -27
  85. package/dist/repair-fetch.js.map +3 -3
  86. package/dist/repair-layer-subscriptions.d.ts +82 -0
  87. package/dist/repair-layer-subscriptions.d.ts.map +1 -0
  88. package/dist/repair-layer-subscriptions.js +192 -0
  89. package/dist/repair-layer-subscriptions.js.map +7 -0
  90. package/dist/signaling.js.map +2 -2
  91. package/dist/timestamp-codec.js +12 -19
  92. package/dist/timestamp-codec.js.map +2 -2
  93. package/dist/track-session.d.ts +1 -1
  94. package/dist/track-session.d.ts.map +1 -1
  95. package/dist/track-session.js +1 -0
  96. package/dist/track-session.js.map +2 -2
  97. package/dist/wasm-mfu-reassembler.js.map +2 -2
  98. package/dist/wasm-mmtp-container-parser.js +323 -46
  99. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  100. package/package.json +8 -5
  101. package/schemas/catalog.schema.json +4 -0
  102. package/src/block-policy.ts +216 -52
  103. package/src/catalog-fec-params.ts +37 -1
  104. package/src/cmcd-producer.ts +189 -179
  105. package/src/codec-utils.ts +121 -1
  106. package/src/fec-manager.ts +619 -37
  107. package/src/fec-worker-setup.ts +2 -2
  108. package/src/index.ts +22 -2
  109. package/src/iso-block-locator.ts +133 -31
  110. package/src/iso-bmff-timing.ts +40 -1
  111. package/src/mmtp-container-parser.ts +353 -32
  112. package/src/mmtp-fec-session.ts +115 -15
  113. package/src/mmtp-router.ts +618 -44
  114. package/src/multicast-manager.ts +139 -16
  115. package/src/no-modules.ts +3 -0
  116. package/src/repair-fetch.ts +366 -50
  117. package/src/repair-layer-subscriptions.ts +261 -0
  118. package/src/track-session.ts +4 -1
@@ -171,30 +171,26 @@ function isEmptyOrExactLegacyTrailer(payload, start, end) {
171
171
  const authLength = view2.getUint16(2, false);
172
172
  return start + LEGACY_TRAILER_HEADER_SIZE + authLength === end;
173
173
  }
174
- function resolveDeclaredTrailers(payload, declaredEnd, fecType, options, rapFlag = false) {
174
+ function resolveDeclaredTrailers(payload, declaredEnd, fecType, options) {
175
175
  if (declaredEnd > payload.length)
176
176
  return null;
177
177
  if (options?.skipFecId) {
178
- return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false, hasOverlayFecId: false } : null;
178
+ return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false } : null;
179
179
  }
180
- const overlay = options?.overlayDeclared === true && rapFlag;
181
180
  if (fecType === 1) {
182
- const fecStart = payload.length - sourceFecTrailerSize(overlay);
181
+ const fecStart = payload.length - SOURCE_FEC_PAYLOAD_ID_SIZE;
183
182
  if (fecStart < declaredEnd || !isEmptyOrExactLegacyTrailer(payload, declaredEnd, fecStart)) {
184
183
  return null;
185
184
  }
186
- return { hasFecId: true, hasOverlayFecId: overlay };
185
+ return { hasFecId: true };
187
186
  }
188
- if (fecType !== 0 || overlay)
187
+ if (fecType !== 0)
189
188
  return null;
190
189
  if (isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)) {
191
- return { hasFecId: false, hasOverlayFecId: false };
190
+ return { hasFecId: false };
192
191
  }
193
192
  return null;
194
193
  }
195
- function sourceFecTrailerSize(overlay) {
196
- return overlay ? 2 * SOURCE_FEC_PAYLOAD_ID_SIZE : SOURCE_FEC_PAYLOAD_ID_SIZE;
197
- }
198
194
  function planMfuExtraction(mmtpPacket, options, parsedHeader) {
199
195
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) {
200
196
  return {
@@ -247,11 +243,11 @@ function planMfuExtraction(mmtpPacket, options, parsedHeader) {
247
243
  if ("rejection" in layoutResult)
248
244
  return layoutResult;
249
245
  const { layout } = layoutResult;
250
- const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options, header.rapFlag);
246
+ const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options);
251
247
  if (!trailerLayout) {
252
248
  if (!options?.skipFecId && header.fecType === 1) {
253
249
  const observed = payload.length - layout.dataEnd;
254
- const expected = sourceFecTrailerSize(options?.overlayDeclared === true && header.rapFlag);
250
+ const expected = SOURCE_FEC_PAYLOAD_ID_SIZE;
255
251
  if (observed !== expected) {
256
252
  return {
257
253
  rejection: {
@@ -283,13 +279,10 @@ function extractPlannedMfu(mmtpPacket, result) {
283
279
  const mfuDuHeader = mfuDuHeaderPresent && mpu.timedFlag === 1 ? parseTimedMfuDuHeader(payload, MPU_HEADER_SIZE) : null;
284
280
  const itemId = mfuDuHeaderPresent && mpu.timedFlag === 0 ? new DataView(payload.buffer, payload.byteOffset + MPU_HEADER_SIZE, 4).getUint32(0, false) : null;
285
281
  const data = payload.subarray(mfuOffset, dataEnd);
286
- const trailerStart = mmtpPacket.length - sourceFecTrailerSize(trailerLayout.hasOverlayFecId);
287
- const ssIdAt = (offset) => ({
288
- ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + offset, 4).getUint32(0, false)
289
- });
290
- const fecPayloadId = trailerLayout.hasFecId ? ssIdAt(trailerStart) : null;
291
- const overlayFecPayloadId = trailerLayout.hasOverlayFecId ? ssIdAt(trailerStart + SOURCE_FEC_PAYLOAD_ID_SIZE) : null;
292
- return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId, overlayFecPayloadId };
282
+ const fecPayloadId = trailerLayout.hasFecId ? {
283
+ ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE, 4).getUint32(0, false)
284
+ } : null;
285
+ return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId };
293
286
  }
294
287
  function sourceFecPayloadIdOf(mmtpPacket, header) {
295
288
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE)
@@ -961,13 +954,17 @@ function fecCatalogTracks(catalog) {
961
954
  });
962
955
  return { tracks, pointers };
963
956
  }
964
- function resolveFecBindings(catalog, receiver = RUNTIME_FEC_RECEIVER) {
957
+ function runtimeView(catalog, receiver) {
965
958
  const { tracks, pointers } = fecCatalogTracks(catalog);
966
959
  const report = validateFecCatalog({ tracks }, receiver);
967
960
  const at = (path) => {
968
961
  const m = /^\/tracks\/(\d+)(.*)$/.exec(path);
969
962
  return m ? pointers[Number(m[1])] + m[2] : path;
970
963
  };
964
+ return { tracks, pointers, report, at };
965
+ }
966
+ function resolveFecBindings(catalog, receiver = RUNTIME_FEC_RECEIVER) {
967
+ const { tracks, pointers, report, at } = runtimeView(catalog, receiver);
971
968
  const trackAt = (i) => recordOf(tracks[i]) ?? {};
972
969
  const nameAt = (i) => i === null ? void 0 : trackAt(i)["name"];
973
970
  const why = (i) => Object.freeze({
@@ -1196,6 +1193,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
1196
1193
  this.#heldEvicted = 0;
1197
1194
  /** Pending holes (see `deferIncompleteGaps`): unstated, sources still held. */
1198
1195
  this.#holes = [];
1196
+ /** Holes the horizon passed while pending: sources held until closed. */
1197
+ this.#expired = [];
1198
+ /** Of `#expired`, those `takeExpiredHoles` has not handed out yet. */
1199
+ this.#newlyExpired = [];
1200
+ /**
1201
+ * Spans closed from expired holes: behind the horizon, so kept only for
1202
+ * `locate` while their sources are fed, until the next retirement.
1203
+ */
1204
+ this.#closedBehind = [];
1199
1205
  /**
1200
1206
  * Keep a gap that is missing a source as a pending hole rather than a span,
1201
1207
  * so a repair FETCHed for it (draft-ramadan-moq-fec §7.5) can still state
@@ -1217,7 +1223,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
1217
1223
  #retentionBlocks;
1218
1224
  #heldEvicted;
1219
1225
  #newest;
1226
+ #newestSource;
1220
1227
  #holes;
1228
+ #expired;
1229
+ #newlyExpired;
1230
+ #closedBehind;
1221
1231
  static #checkedRetention(retentionBlocks) {
1222
1232
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
1223
1233
  throw new Error(
@@ -1254,6 +1264,21 @@ var IsoBlockLocator = class _IsoBlockLocator {
1254
1264
  observe(position) {
1255
1265
  if (this.#newest === void 0 || serial32Precedes(this.#newest, position)) this.#newest = position;
1256
1266
  }
1267
+ /**
1268
+ * The newest source SS_ID noted with `noteSource` (RFC 1982 order). Unlike
1269
+ * `newest`, a repair never moves it: a repair can run ahead of its sources,
1270
+ * a source cannot run ahead of the sources sent before it except by
1271
+ * reordering.
1272
+ */
1273
+ get newestSource() {
1274
+ return this.#newestSource;
1275
+ }
1276
+ /** Note a received source's SS_ID; true when it is the newest one yet. */
1277
+ noteSource(ssId) {
1278
+ if (this.#newestSource !== void 0 && !serial32Precedes(this.#newestSource, ssId)) return false;
1279
+ this.#newestSource = ssId;
1280
+ return true;
1281
+ }
1257
1282
  /** Held sources evicted by `heldCapacity` (never by the horizon itself). */
1258
1283
  get heldEvicted() {
1259
1284
  return this.#heldEvicted;
@@ -1272,17 +1297,29 @@ var IsoBlockLocator = class _IsoBlockLocator {
1272
1297
  }
1273
1298
  /** The known block or span containing `ssId`, with its ESI. */
1274
1299
  locate(ssId) {
1275
- for (let i = this.#blocks.length - 1; i >= 0; i--) {
1276
- const block = this.#blocks[i];
1277
- if (isoBlockContains(block.start, block.length, ssId)) {
1278
- return { block, esi: serial32Distance(block.start, ssId) };
1300
+ for (const blocks of [this.#blocks, this.#closedBehind]) {
1301
+ for (let i = blocks.length - 1; i >= 0; i--) {
1302
+ const block = blocks[i];
1303
+ if (isoBlockContains(block.start, block.length, ssId)) {
1304
+ return { block, esi: serial32Distance(block.start, ssId) };
1305
+ }
1279
1306
  }
1280
1307
  }
1281
1308
  return null;
1282
1309
  }
1283
- /** Number of pending holes. */
1310
+ /** Number of holes not closed yet, pending or past the horizon. */
1284
1311
  get holeCount() {
1285
- return this.#holes.length;
1312
+ return this.#holes.length + this.#expired.length;
1313
+ }
1314
+ /**
1315
+ * The pending holes the horizon has passed since the last call, in the
1316
+ * order it passed them. Each is no longer pending: no repair states a block
1317
+ * in it (that repair is `stale`, as for a span the horizon retired) and the
1318
+ * release gate does not wait for it. Its owner must close it
1319
+ * (`closeHolesWithin`), which turns it into a span that is not kept here.
1320
+ */
1321
+ takeExpiredHoles() {
1322
+ return this.#newlyExpired.splice(0);
1286
1323
  }
1287
1324
  /** The stated block (never a span) ending exactly at `end`. */
1288
1325
  blockEndingAt(end) {
@@ -1338,9 +1375,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
1338
1375
  /**
1339
1376
  * Apply one repair symbol's `(SS_Start, SSB_length)`. The first repair of a
1340
1377
  * block states its range and places every held source in it; later repair
1341
- * symbols of the same block change nothing. A range that contradicts a
1342
- * known block (a different length, or an overlap with another block or a
1343
- * span) fails closed: the repair symbol is dropped and no block changes.
1378
+ * symbols of the same block change nothing. A repair whose range is exactly
1379
+ * a repair-less span states that span's one block. A range that contradicts
1380
+ * a known block (a different length, or an overlap with another block or
1381
+ * with part of a span) fails closed: the repair symbol is dropped and no
1382
+ * block changes.
1344
1383
  * A newly stated block retires behind its SS_Start (see the class note).
1345
1384
  * A block so far past `newest` that stating it would retire the position
1346
1385
  * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
@@ -1359,7 +1398,16 @@ var IsoBlockLocator = class _IsoBlockLocator {
1359
1398
  const known = this.blockAt(start);
1360
1399
  if (known !== void 0) {
1361
1400
  if (known.span) {
1362
- return { status: "overlap", reason: `repair block ${start}+${length} falls inside a repair-less span` };
1401
+ if (known.length === length) {
1402
+ const block2 = { start, length, span: false };
1403
+ this.#blocks[this.#blocks.indexOf(known)] = block2;
1404
+ return { status: "placed", block: block2, placed: [] };
1405
+ }
1406
+ return length < known.length ? {
1407
+ status: "overlap",
1408
+ reason: `repair block ${start}+${length} is only the first block of repair-less span ${known.start}+${known.length}`,
1409
+ ofSpan: known
1410
+ } : { status: "overlap", reason: `repair block ${start}+${length} runs past repair-less span ${known.start}+${known.length}` };
1363
1411
  }
1364
1412
  if (known.length !== length) {
1365
1413
  return {
@@ -1427,18 +1475,28 @@ var IsoBlockLocator = class _IsoBlockLocator {
1427
1475
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
1428
1476
  }
1429
1477
  /**
1430
- * Turn every pending hole inside `[start, start + length)` into a
1431
- * repair-less span, claiming its held sources: its range FETCH ended, so
1432
- * nothing more will state its blocks. Returns the spans, in SS_ID order.
1478
+ * Turn every hole inside `[start, start + length)` into a repair-less span,
1479
+ * claiming its held sources: its range FETCH ended, so nothing more will
1480
+ * state its blocks. A hole the horizon passed (`takeExpiredHoles`) leaves a
1481
+ * span that is not kept among the blocks, as the horizon would retire it at
1482
+ * once; only `locate` finds it, until the next retirement, so its sources
1483
+ * can be fed. Returns the spans, in SS_ID order.
1433
1484
  */
1434
1485
  closeHolesWithin(start, length) {
1435
1486
  const closed = [];
1436
- for (const hole of [...this.#holes]) {
1437
- if (!isoBlockContains(start, length, hole.start)) continue;
1438
- this.#holes.splice(this.#holes.indexOf(hole), 1);
1439
- const spanBlock = { start: hole.start, length: hole.length, span: true };
1440
- closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
1441
- this.#blocks.push(spanBlock);
1487
+ for (const holes of [this.#holes, this.#expired]) {
1488
+ for (const hole of [...holes]) {
1489
+ if (!isoBlockContains(start, length, hole.start)) continue;
1490
+ holes.splice(holes.indexOf(hole), 1);
1491
+ const spanBlock = { start: hole.start, length: hole.length, span: true };
1492
+ closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
1493
+ if (holes === this.#holes) {
1494
+ this.#blocks.push(spanBlock);
1495
+ } else {
1496
+ this.#closedBehind.push(spanBlock);
1497
+ if (this.#newlyExpired.includes(hole)) this.#newlyExpired.splice(this.#newlyExpired.indexOf(hole), 1);
1498
+ }
1499
+ }
1442
1500
  }
1443
1501
  return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
1444
1502
  }
@@ -1452,15 +1510,17 @@ var IsoBlockLocator = class _IsoBlockLocator {
1452
1510
  return void 0;
1453
1511
  }
1454
1512
  /**
1455
- * Retire every block and span whose last SS_ID, and every held source,
1456
- * lies more than `retentionBlocks` blocks behind `position`, with the shared
1457
- * lower-bound metric (`isoBlocksBehindLowerBound`) every ISO interleave
1458
- * horizon uses. Returns the retired block starts.
1513
+ * Retire every block and span whose last SS_ID, and every held source
1514
+ * outside a hole, lies more than `retentionBlocks` blocks behind
1515
+ * `position`, with the shared lower-bound metric (`isoBlocksBehindLowerBound`)
1516
+ * every ISO interleave horizon uses; a pending hole so far behind expires
1517
+ * (`takeExpiredHoles`). Returns the retired block starts.
1459
1518
  */
1460
1519
  retireBehind(position) {
1461
1520
  this.observe(position);
1462
1521
  const horizon = this.#retentionBlocks;
1463
1522
  const retired = [];
1523
+ this.#closedBehind.length = 0;
1464
1524
  for (let i = this.#blocks.length - 1; i >= 0; i--) {
1465
1525
  const block = this.#blocks[i];
1466
1526
  const last = serial32Add(block.start, block.length - 1);
@@ -1472,10 +1532,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
1472
1532
  for (let i = this.#holes.length - 1; i >= 0; i--) {
1473
1533
  const hole = this.#holes[i];
1474
1534
  const last = serial32Add(hole.start, hole.length - 1);
1475
- if (isoBlocksBehindLowerBound(last, position, this.#kMax) > horizon) this.#holes.splice(i, 1);
1535
+ if (isoBlocksBehindLowerBound(last, position, this.#kMax) <= horizon) continue;
1536
+ this.#holes.splice(i, 1);
1537
+ this.#expired.push(hole);
1538
+ this.#newlyExpired.push(hole);
1476
1539
  }
1477
1540
  for (const ssId of [...this.#held.keys()]) {
1478
- if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon) this.#held.delete(ssId);
1541
+ 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))) {
1542
+ this.#held.delete(ssId);
1543
+ }
1479
1544
  }
1480
1545
  return retired;
1481
1546
  }
@@ -1483,9 +1548,13 @@ var IsoBlockLocator = class _IsoBlockLocator {
1483
1548
  reset() {
1484
1549
  this.#blocks.length = 0;
1485
1550
  this.#holes.length = 0;
1551
+ this.#expired.length = 0;
1552
+ this.#newlyExpired.length = 0;
1553
+ this.#closedBehind.length = 0;
1486
1554
  this.#held.clear();
1487
1555
  this.#coverageEnd = void 0;
1488
1556
  this.#newest = void 0;
1557
+ this.#newestSource = void 0;
1489
1558
  }
1490
1559
  #claim(block) {
1491
1560
  const placed = [];
@@ -1593,8 +1662,9 @@ function keyframeIntervalMediaTicks(geometry2, mediaTimescale) {
1593
1662
  return scaled / divisor;
1594
1663
  }
1595
1664
  function compareDataUnitStarts(a, b) {
1596
- return a.movieFragment - b.movieFragment || a.idx - b.idx || a.offset - b.offset;
1665
+ return a.movieFragment - b.movieFragment | 0 || a.idx - b.idx || a.offset - b.offset;
1597
1666
  }
1667
+ var UNPLACED = { rapNotMpuStart: false };
1598
1668
  var BlockClassifier = class {
1599
1669
  #geometry;
1600
1670
  #mode;
@@ -1617,8 +1687,23 @@ var BlockClassifier = class {
1617
1687
  #mpuSbnSpans = /* @__PURE__ */ new Map();
1618
1688
  #dataUnitStarts = /* @__PURE__ */ new Map();
1619
1689
  #highestMpu = null;
1620
- /** MPU → movie_fragment_sequence_number observed in it. */
1621
- #mpuFragments = /* @__PURE__ */ new Map();
1690
+ /**
1691
+ * P3 layout, kept for the MPUs within the classification horizon and valid
1692
+ * within one continuous SBN sequence (`noteSourceDiscontinuity`).
1693
+ */
1694
+ #mpus = /* @__PURE__ */ new Map();
1695
+ /** An MPU of this sequence showed two movie fragments: each frame is one. */
1696
+ #fragmentPerFrame = false;
1697
+ /** A DU header of this sequence stated sample_number above 1. */
1698
+ #multiSampleFragment = false;
1699
+ /**
1700
+ * The anchor received last, whether or not its MPU is still in the
1701
+ * horizon. Each new anchor, and the anchor of every DU header's MPU, is
1702
+ * checked against it.
1703
+ */
1704
+ #lastAnchor = null;
1705
+ /** Two anchors were exactly G fragments per MPU apart. */
1706
+ #fragmentsProven = false;
1622
1707
  #lastRap = null;
1623
1708
  constructor(geometry2) {
1624
1709
  this.#geometry = geometry2;
@@ -1648,7 +1733,7 @@ var BlockClassifier = class {
1648
1733
  this.#geometry = geometry2;
1649
1734
  this.#blocks.clear();
1650
1735
  this.#clearContiguityLedger();
1651
- this.#mpuFragments.clear();
1736
+ this.#clearMpuLayout();
1652
1737
  this.#lastRap = null;
1653
1738
  this.#mpuBoundsRaps = true;
1654
1739
  if (geometry2.trackKind === "video" && geometry2.mode === "all-protected") {
@@ -1682,11 +1767,13 @@ var BlockClassifier = class {
1682
1767
  /**
1683
1768
  * The stream's SBN sequence restarted (FECManager source discontinuity:
1684
1769
  * a publisher restart, or the SS_ID space wrapped). Authored order and SBN
1685
- * order are comparable only within one continuous sequence, so the P1
1686
- * ledger starts again.
1770
+ * order are comparable only within one continuous sequence, and a
1771
+ * restarted publisher numbers MPUs and movie fragments again, so the P1
1772
+ * ledger and the P3 layout start again.
1687
1773
  */
1688
1774
  noteSourceDiscontinuity() {
1689
1775
  this.#clearContiguityLedger();
1776
+ this.#clearMpuLayout();
1690
1777
  }
1691
1778
  /** Register a block that exists without evidence (a vanished block). */
1692
1779
  touch(sbn) {
@@ -1705,16 +1792,16 @@ var BlockClassifier = class {
1705
1792
  if (this.#geometry.trackKind === "audio") return [];
1706
1793
  const changes = [];
1707
1794
  const block = this.#blockFor(sbn);
1795
+ const placement = this.#place(evidence);
1708
1796
  if (evidence.rap) block.rapSeen = true;
1709
1797
  if (evidence.mpu !== void 0) block.mpus.add(evidence.mpu);
1710
- if (evidence.idx !== void 0) {
1711
- block.idxMin = block.idxMin === void 0 ? evidence.idx : Math.min(block.idxMin, evidence.idx);
1712
- block.idxMax = block.idxMax === void 0 ? evidence.idx : Math.max(block.idxMax, evidence.idx);
1798
+ const { position } = placement;
1799
+ if (position !== void 0) {
1800
+ block.positionMin = block.positionMin === void 0 ? position : Math.min(block.positionMin, position);
1801
+ block.positionMax = block.positionMax === void 0 ? position : Math.max(block.positionMax, position);
1713
1802
  }
1714
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
1715
- this.#mpuBoundsRaps = false;
1716
- }
1717
- const violation = this.#checkInvariants(sbn, block, evidence);
1803
+ if (placement.rapNotMpuStart) this.#mpuBoundsRaps = false;
1804
+ const violation = this.#checkInvariants(sbn, block, evidence, placement);
1718
1805
  if (violation !== null) changes.push(...this.#disable(violation));
1719
1806
  const next = this.#classify(block);
1720
1807
  if (next !== block.cls && this.#allowed(block.cls, next)) {
@@ -1767,35 +1854,89 @@ var BlockClassifier = class {
1767
1854
  }
1768
1855
  return block;
1769
1856
  }
1770
- #checkInvariants(sbn, block, evidence) {
1857
+ #checkInvariants(sbn, block, evidence, placement) {
1771
1858
  if (this.#mode === "all-protected" || this.#geometry.trackKind !== "video") return null;
1772
1859
  const geometry2 = this.#geometry;
1773
1860
  if (geometry2.mode !== "classifying") return null;
1774
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
1775
- return "rap-not-mpu-start";
1776
- }
1777
- if (evidence.idx !== void 0 && evidence.idx >= geometry2.gopFrames) {
1861
+ if (placement.rapNotMpuStart) return "rap-not-mpu-start";
1862
+ if (placement.position !== void 0 && placement.position >= geometry2.gopFrames) {
1778
1863
  return "mpu-longer-than-gop";
1779
1864
  }
1780
- if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0 && block.idxMax - block.idxMin >= geometry2.interleaveUnits) {
1865
+ if (block.mpus.size === 1 && block.positionMin !== void 0 && block.positionMax !== void 0 && block.positionMax - block.positionMin >= geometry2.interleaveUnits) {
1781
1866
  return "block-wider-than-interleave";
1782
1867
  }
1783
- if (evidence.mpu !== void 0 && evidence.movieFragment !== void 0) {
1784
- const fragment = this.#mpuFragments.get(evidence.mpu);
1785
- if (fragment === void 0) {
1786
- this.#mpuFragments.set(evidence.mpu, evidence.movieFragment);
1787
- for (const mpu of this.#mpuFragments.keys()) {
1788
- if (mpu + 1 < evidence.mpu) this.#mpuFragments.delete(mpu);
1789
- }
1790
- } else if (fragment !== evidence.movieFragment) {
1791
- return "mpu-multiple-fragments";
1792
- }
1793
- }
1868
+ if (placement.violation !== void 0) return placement.violation;
1794
1869
  if (evidence.mpu !== void 0 && this.#contradictsAuthoredOrder(sbn, evidence.mpu, evidence)) {
1795
1870
  return "block-not-contiguous";
1796
1871
  }
1797
1872
  return null;
1798
1873
  }
1874
+ /**
1875
+ * The MPU position a source symbol's DU header proves (P3), and what it
1876
+ * refutes. Runs in every mode: mpuBoundsRaps needs its RAP verdict.
1877
+ */
1878
+ #place(evidence) {
1879
+ const { mpu, idx, movieFragment: fragment } = evidence;
1880
+ if (idx === void 0) return UNPLACED;
1881
+ const bySample = { position: idx, rapNotMpuStart: evidence.rap && idx !== 0 };
1882
+ if (mpu === void 0 || fragment === void 0) {
1883
+ return this.#fragmentPerFrame && !this.#multiSampleFragment ? { rapNotMpuStart: bySample.rapNotMpuStart } : bySample;
1884
+ }
1885
+ let layout = this.#mpus.get(mpu);
1886
+ if (layout === void 0) {
1887
+ layout = { low: fragment };
1888
+ this.#mpus.set(mpu, layout);
1889
+ for (const other of this.#mpus.keys()) {
1890
+ if (other + 1 < mpu) this.#mpus.delete(other);
1891
+ }
1892
+ } else if (fragment !== layout.low) {
1893
+ this.#fragmentPerFrame = true;
1894
+ if ((fragment - layout.low | 0) < 0) layout.low = fragment;
1895
+ }
1896
+ if (idx !== 0) this.#multiSampleFragment = true;
1897
+ let arrival;
1898
+ if (evidence.rap && layout.anchor === void 0) {
1899
+ layout.anchor = fragment;
1900
+ arrival = this.#anchorDrift(mpu, fragment);
1901
+ if (arrival === 0 && this.#lastAnchor?.mpu !== mpu) this.#fragmentsProven = true;
1902
+ this.#lastAnchor = { mpu, fragment };
1903
+ }
1904
+ if (!this.#fragmentPerFrame) return bySample;
1905
+ if (this.#multiSampleFragment) return { ...bySample, violation: "mpu-multiple-fragments" };
1906
+ const { anchor } = layout;
1907
+ if (anchor === void 0) return UNPLACED;
1908
+ const drift = arrival ?? this.#anchorDrift(mpu, anchor);
1909
+ const offset = fragment - anchor | 0;
1910
+ return {
1911
+ ...offset === 0 || offset > 0 && this.#fragmentsProven ? { position: offset } : {},
1912
+ rapNotMpuStart: evidence.rap && offset !== 0 || (layout.low - anchor | 0) < 0 || // Fragments count frames: an anchor arriving past the spacing is a
1913
+ // RAP inside its MPU, or an earlier MPU outran G.
1914
+ arrival !== void 0 && arrival > 0 && this.#fragmentsProven,
1915
+ ...drift === void 0 || drift === 0 ? {} : { violation: "rap-spacing-mismatch" }
1916
+ };
1917
+ }
1918
+ /**
1919
+ * How many fragments MPU m's anchor `fragment` lies past the start that
1920
+ * the anchor received last predicts for MPU m: one frame per fragment and
1921
+ * G frames per MPU put the anchors of MPUs m and m' exactly G * (m - m')
1922
+ * fragments apart, modulo 2^32. Undefined without a last anchor, a
1923
+ * cadence, or this layout.
1924
+ */
1925
+ #anchorDrift(mpu, fragment) {
1926
+ const geometry2 = this.#geometry;
1927
+ const last = this.#lastAnchor;
1928
+ if (last === null || !this.#fragmentPerFrame || this.#multiSampleFragment || geometry2.trackKind !== "video" || geometry2.mode !== "classifying") {
1929
+ return void 0;
1930
+ }
1931
+ return fragment - last.fragment - geometry2.gopFrames * (mpu - last.mpu) | 0;
1932
+ }
1933
+ #clearMpuLayout() {
1934
+ this.#mpus.clear();
1935
+ this.#fragmentPerFrame = false;
1936
+ this.#multiSampleFragment = false;
1937
+ this.#lastAnchor = null;
1938
+ this.#fragmentsProven = false;
1939
+ }
1799
1940
  #clearContiguityLedger() {
1800
1941
  this.#mpuSbnSpans.clear();
1801
1942
  this.#dataUnitStarts.clear();
@@ -1895,9 +2036,9 @@ var BlockClassifier = class {
1895
2036
  if (this.#mode === "all-protected") return "unknown";
1896
2037
  const geometry2 = this.#geometry;
1897
2038
  if (geometry2.trackKind !== "video" || geometry2.mode !== "classifying") return "unknown";
1898
- if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0) {
2039
+ if (block.mpus.size === 1 && block.positionMin !== void 0 && block.positionMax !== void 0) {
1899
2040
  const span = geometry2.interleaveUnits - 1;
1900
- if (block.idxMax - span >= 1 && block.idxMin + span <= geometry2.gopFrames - 1) {
2041
+ if (block.positionMax - span >= 1 && block.positionMin + span <= geometry2.gopFrames - 1) {
1901
2042
  return "delta";
1902
2043
  }
1903
2044
  }
@@ -2074,6 +2215,7 @@ var WORKER_ERROR_LOG_CAP = 5;
2074
2215
  var WORKER_ERROR_KIND_CAP = 32;
2075
2216
  var WORKER_ERROR_OVERFLOW_KIND = "other";
2076
2217
  var STARTUP_REPAIR_WAIT_SOURCE_BOUNDARIES = 2;
2218
+ var NOT_TAKEN = Object.freeze({ taken: false, recovered: null });
2077
2219
  function isMulticastSymbolDelivery(value) {
2078
2220
  return value === "datagram" || value === "ordered-relay";
2079
2221
  }
@@ -2167,10 +2309,18 @@ var FECManager = class _FECManager {
2167
2309
  // 'pending' forever, which would park every later frame of its stream in
2168
2310
  // the in-order release gate. Each entry owns its handle; the callback
2169
2311
  // checks it still owns the key, so a settled or reset key is never touched.
2312
+ /**
2313
+ * Per owed Worker cleanup: the bound on its acknowledgement, when its block
2314
+ * was due, and when its cleanup was asked for (see `onCleanupComplete`).
2315
+ */
2170
2316
  this.#pendingWorkerCleanupBounds = /* @__PURE__ */ new Map();
2171
2317
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
2172
2318
  this.#blockSourceCounts = /* @__PURE__ */ new Map();
2173
2319
  this.#blockSourceEsis = /* @__PURE__ */ new Map();
2320
+ // Source ESIs per block that another FEC instance rebuilt and fed in
2321
+ // (feedRebuiltSourceSymbol). Kept apart from #blockSourceEsis: they are
2322
+ // not network arrivals and never make a block clean.
2323
+ this.#blockRebuiltEsis = /* @__PURE__ */ new Map();
2174
2324
  // Authored SSB_length per block (ISO/IEC 23008-1 §C.5.3), learned from the
2175
2325
  // first repair symbol. The FFmpeg moq_mmt publisher closes a block every D
2176
2326
  // media units, usually before it holds K symbols; under iso-ssbg1-v1
@@ -2179,10 +2329,14 @@ var FECManager = class _FECManager {
2179
2329
  // SSB_length source arrivals and recoverable from SSB_length received
2180
2330
  // symbols; waiting for K fails every one of them.
2181
2331
  this.#blockAuthoredLengths = /* @__PURE__ */ new Map();
2332
+ // Keys whose authored length is a repair-less span's (#openIsoSpan), until
2333
+ // a repair states the block there or the span resolves.
2334
+ this.#isoSpanKeys = /* @__PURE__ */ new Set();
2182
2335
  this.#ssbLengthConflictCount = 0;
2183
2336
  this.#blockRepairRsIds = /* @__PURE__ */ new Map();
2184
2337
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
2185
- // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
2338
+ // symbols its repair group carries; 0 for a repair-less span no repair can
2339
+ // state (#openIsoSpan). Same lifecycle as #blockRepairRsIds.
2186
2340
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
2187
2341
  /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
2188
2342
  this.#heldLayerStates = /* @__PURE__ */ new Map();
@@ -2299,6 +2453,10 @@ var FECManager = class _FECManager {
2299
2453
  // ── Keyframe-protected repair policy (block-policy.ts) ──
2300
2454
  // One classifier per physical stream, built from that stream's geometry.
2301
2455
  this.#classifiers = /* @__PURE__ */ new Map();
2456
+ // A stream without catalog timing has no classifier, so the last RAP it
2457
+ // released stands in for one: "an MPU boundary bounds its RAPs" holds until
2458
+ // a second RAP is released inside one MPU (BLO-52085).
2459
+ this.#noSpanRaps = /* @__PURE__ */ new Map();
2302
2460
  // Geometry a stream-scoped configuration gave one stream (streamKey). ABR
2303
2461
  // rungs can share a packetId with a different framerate or GOP, so the
2304
2462
  // packet-level geometry is only the geometry of a packet whose streams
@@ -2366,13 +2524,17 @@ var FECManager = class _FECManager {
2366
2524
  this.#workerErrorCounts = /* @__PURE__ */ new Map();
2367
2525
  this.#decoderUnavailableEvents = 0;
2368
2526
  this.#repairSymbolSizeMismatchCount = 0;
2527
+ this.#unlistedRepairTrackRefusals = 0;
2369
2528
  // Event callbacks — block lifecycle notifications for MmtpRouter wiring.
2370
2529
  // NOTE: For sync WASM path, recovery routing is handled by MmtpRouter from
2371
2530
  // feedSourceSymbol/feedRepairSymbol return values. For Worker path, recovery
2372
2531
  // arrives via onBlockRecovered callback.
2373
2532
  this.onBlockStarted = null;
2374
2533
  this.onBlockComplete = null;
2375
- /** A block reached its fail bound. `blockClass` is its class at failure. */
2534
+ /**
2535
+ * A block reached its fail bound. `blockClass` is its class at failure.
2536
+ * `span` is set when what failed is a repair-less span starting at `sbn`.
2537
+ */
2376
2538
  this.onBlockFailed = null;
2377
2539
  /**
2378
2540
  * Fired once per stream when its Worker decoder stops being routable.
@@ -2414,12 +2576,24 @@ var FECManager = class _FECManager {
2414
2576
  * for it, which it must be.
2415
2577
  */
2416
2578
  this.#onUndelimitedLoss = null;
2579
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
2580
+ this.#onIsoHoleExpired = null;
2417
2581
  /** A block every symbol of which vanished was created by SBN evidence. */
2418
2582
  this.onBlockVanished = null;
2419
2583
  /** A block reached a terminal state (completed, recovered, or failed). */
2420
2584
  this.onBlockResolved = null;
2421
2585
  /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
2422
2586
  this.onSourceDiscontinuity = null;
2587
+ /**
2588
+ * The span and tolerance the catalog states for a keyframe overlay
2589
+ * installed over a source track (draft-ramadan-moq-mmt-02 7.4.1: the
2590
+ * overlay instance's own interleaveDepthMs and reorderToleranceMs), or
2591
+ * undefined while none is installed. A stated block only a late source
2592
+ * can complete, and a frame whose gap may hide a RAP behind a span only a
2593
+ * late source can fill, also wait for that overlay's repair
2594
+ * (#overlayLateWaitMs).
2595
+ */
2596
+ this.keyframeOverlayTiming = null;
2423
2597
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
2424
2598
  /**
2425
2599
  * A recovered source symbol. Return false when admission refused the
@@ -2456,7 +2630,9 @@ var FECManager = class _FECManager {
2456
2630
  #pendingWorkerCleanupBounds;
2457
2631
  #blockSourceCounts;
2458
2632
  #blockSourceEsis;
2633
+ #blockRebuiltEsis;
2459
2634
  #blockAuthoredLengths;
2635
+ #isoSpanKeys;
2460
2636
  #ssbLengthConflictCount;
2461
2637
  #blockRepairRsIds;
2462
2638
  #blockRsbLengths;
@@ -2498,6 +2674,7 @@ var FECManager = class _FECManager {
2498
2674
  #orderedFrontiers;
2499
2675
  #orderedPendingBlocks;
2500
2676
  #classifiers;
2677
+ #noSpanRaps;
2501
2678
  #streamGeometries;
2502
2679
  #failedBlocks;
2503
2680
  #resolvedBlockClasses;
@@ -2521,7 +2698,9 @@ var FECManager = class _FECManager {
2521
2698
  #workerErrorCounts;
2522
2699
  #decoderUnavailableEvents;
2523
2700
  #repairSymbolSizeMismatchCount;
2701
+ #unlistedRepairTrackRefusals;
2524
2702
  #onUndelimitedLoss;
2703
+ #onIsoHoleExpired;
2525
2704
  #encodeTrackName(catalogTrackName) {
2526
2705
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
2527
2706
  if (encoded === void 0) {
@@ -2993,7 +3172,10 @@ var FECManager = class _FECManager {
2993
3172
  timer.handle = null;
2994
3173
  this.#requestRepair(sbn, packetId, catalogTrackName);
2995
3174
  };
2996
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
3175
+ timer.handle = setTimeout(
3176
+ onFire,
3177
+ this.#receiptAtMs === void 0 ? Math.max(0, deadlineMs - performance.now()) : this.#receiptTimerDelayMs(deadlineMs, 0)
3178
+ );
2997
3179
  this.#repairDeadlines.set(key, timer);
2998
3180
  }
2999
3181
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -3137,8 +3319,14 @@ var FECManager = class _FECManager {
3137
3319
  * Vanished blocks are not enumerated here: their starts are unknown until a
3138
3320
  * repair states them. The SS_IDs between two stated blocks become one
3139
3321
  * repair-less span when the later block's repair arrives (placeIsoRepair).
3322
+ *
3323
+ * A `held` source arrived before its block was known and is fed only now
3324
+ * that a repair, a span or a closed hole placed it: how far its block start
3325
+ * then lies behind the frontier measures how long the receiver held it, not
3326
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
3327
+ * it (BLO-52085).
3140
3328
  */
3141
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
3329
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn, held = false) {
3142
3330
  const streamKey = this.#streamKey(packetId, catalogTrackName);
3143
3331
  const now = performance.now();
3144
3332
  const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
@@ -3159,6 +3347,7 @@ var FECManager = class _FECManager {
3159
3347
  };
3160
3348
  const discontinuity = () => {
3161
3349
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity();
3350
+ this.#noSpanRaps.delete(streamKey);
3162
3351
  this.#highestSbn.set(streamKey, { sbn, atMs: now });
3163
3352
  this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
3164
3353
  if (psn === void 0) this.#sourceAnchors.delete(streamKey);
@@ -3176,7 +3365,7 @@ var FECManager = class _FECManager {
3176
3365
  return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
3177
3366
  };
3178
3367
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
3179
- 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))) {
3368
+ 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))) {
3180
3369
  discontinuity();
3181
3370
  return;
3182
3371
  }
@@ -3438,17 +3627,21 @@ var FECManager = class _FECManager {
3438
3627
  this.#blockWaitDeadlinesMs.delete(key);
3439
3628
  this.#repairHoldUntilMs.delete(key);
3440
3629
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
3441
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName);
3630
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs);
3442
3631
  };
3443
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)));
3632
+ timer.handle = setTimeout(
3633
+ onFire,
3634
+ this.#receiptAtMs === void 0 ? Math.max(1, Math.ceil(deadlineMs - nowMs)) : this.#receiptTimerDelayMs(deadlineMs, 1)
3635
+ );
3444
3636
  this.#activeBlocks.set(key, timer);
3445
3637
  this.#indexBlockKey(key, sbn, packetId);
3446
3638
  }
3447
3639
  /**
3448
3640
  * Hand a block whose delivery is over to its decoder for finalization: the
3449
- * datagram deadline fired, or the ordered relay moved past it.
3641
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
3642
+ * is when it was due: its deadline, or now.
3450
3643
  */
3451
- #finalizeExpiredBlock(sbn, packetId, catalogTrackName) {
3644
+ #finalizeExpiredBlock(sbn, packetId, catalogTrackName, dueAtMs = performance.now()) {
3452
3645
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
3453
3646
  if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
3454
3647
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -3464,7 +3657,7 @@ var FECManager = class _FECManager {
3464
3657
  if (workerClient) {
3465
3658
  this.#pendingWorkerCleanups.add(key);
3466
3659
  this.#pendingWorkerCleanupClients.set(key, workerClient);
3467
- this.#boundOwedCleanup(key, packetId, workerClient);
3660
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs);
3468
3661
  workerClient.cleanup(sbn);
3469
3662
  } else {
3470
3663
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
@@ -3571,6 +3764,9 @@ var FECManager = class _FECManager {
3571
3764
  }
3572
3765
  if (policyChanged) {
3573
3766
  this.#bumpEpoch(packetId);
3767
+ for (const key of [...this.#noSpanRaps.keys()]) {
3768
+ if (this.#belongsToPacket(key, packetId)) this.#noSpanRaps.delete(key);
3769
+ }
3574
3770
  for (const [key, classifier] of [...this.#classifiers]) {
3575
3771
  if (!this.#belongsToPacket(key, packetId)) continue;
3576
3772
  const stream = this.#parseStreamKey(key);
@@ -3671,6 +3867,7 @@ var FECManager = class _FECManager {
3671
3867
  packetId
3672
3868
  })),
3673
3869
  repairSymbolSizeMismatches: this.#repairSymbolSizeMismatchCount,
3870
+ unlistedRepairTrackRefusals: this.#unlistedRepairTrackRefusals,
3674
3871
  repairObjectRejects: [...this.#repairObjectRejects.values()].map((r) => ({ ...r })),
3675
3872
  workerErrors: Object.fromEntries(this.#workerErrorCounts)
3676
3873
  };
@@ -3773,7 +3970,9 @@ var FECManager = class _FECManager {
3773
3970
  }
3774
3971
  resetMap(this.#blockSourceCounts);
3775
3972
  resetMap(this.#blockSourceEsis);
3973
+ resetMap(this.#blockRebuiltEsis);
3776
3974
  resetMap(this.#blockAuthoredLengths);
3975
+ resetSet(this.#isoSpanKeys);
3777
3976
  resetMap(this.#blockRepairRsIds);
3778
3977
  resetMap(this.#blockRsbLengths);
3779
3978
  resetMap(this.#heldLayerStates);
@@ -3806,6 +4005,7 @@ var FECManager = class _FECManager {
3806
4005
  resetMap(this.#isoLocators);
3807
4006
  resetMap(this.#sourceAnchors);
3808
4007
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName));
4008
+ this.#noSpanRaps.delete(this.#streamKey(packetId, catalogTrackName));
3809
4009
  this.#bumpEpoch(packetId);
3810
4010
  for (const [sbn, keys] of this.#blockKeysBySbn) {
3811
4011
  for (const key of keys.keys()) {
@@ -3896,7 +4096,9 @@ var FECManager = class _FECManager {
3896
4096
  dropMap(this.#pendingWorkerCleanupClients);
3897
4097
  dropMap(this.#blockSourceCounts);
3898
4098
  dropMap(this.#blockSourceEsis);
4099
+ dropMap(this.#blockRebuiltEsis);
3899
4100
  dropMap(this.#blockAuthoredLengths);
4101
+ dropSet(this.#isoSpanKeys);
3900
4102
  dropMap(this.#blockRepairRsIds);
3901
4103
  dropMap(this.#blockRsbLengths);
3902
4104
  dropMap(this.#blockPathCounts);
@@ -3912,6 +4114,7 @@ var FECManager = class _FECManager {
3912
4114
  dropMap(this.#isoLocators);
3913
4115
  dropMap(this.#sourceAnchors);
3914
4116
  dropMap(this.#classifiers);
4117
+ dropMap(this.#noSpanRaps);
3915
4118
  dropMap(this.#streamGeometries);
3916
4119
  dropSet(this.#pendingWorkerCleanups);
3917
4120
  dropSet(this.#completedBlocks);
@@ -4057,6 +4260,9 @@ var FECManager = class _FECManager {
4057
4260
  this.#unindexBlockKey(key);
4058
4261
  }
4059
4262
  }
4263
+ if (isSourceSymbol && source === "multicast") {
4264
+ this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), sbn + esi >>> 0, packetId, catalogTrackName);
4265
+ }
4060
4266
  return true;
4061
4267
  }
4062
4268
  #observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName) {
@@ -4166,8 +4372,10 @@ var FECManager = class _FECManager {
4166
4372
  }
4167
4373
  /**
4168
4374
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
4169
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
4170
- * Undefined for a block that is not open.
4375
+ * (SSB_length) and RSB_length (each undefined until a repair stated it; a
4376
+ * repair-less span states its length, and RSB_length 0 when it is longer
4377
+ * than K, since no repair can reach it). Undefined for a block that is not
4378
+ * open.
4171
4379
  */
4172
4380
  blockSymbolCounts(sbn, packetId, catalogTrackName) {
4173
4381
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -4235,8 +4443,9 @@ var FECManager = class _FECManager {
4235
4443
  return true;
4236
4444
  }
4237
4445
  /**
4238
- * Drop a block's repair hold: its FETCH ended without delivering. The block
4239
- * falls back to its multicast wait, which may already have passed.
4446
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
4447
+ * back only a repair that cannot complete it. The block falls back to its
4448
+ * multicast wait, which may already have passed.
4240
4449
  */
4241
4450
  releaseRepairHold(sbn, packetId, catalogTrackName) {
4242
4451
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -4282,7 +4491,7 @@ var FECManager = class _FECManager {
4282
4491
  }
4283
4492
  const trackConfig = this.#trackConfigs.get(packetId);
4284
4493
  if (trackConfig === void 0) return void 0;
4285
- return Math.max(1, trackConfig.timeoutMs - this.#repairDeadlineMs(trackConfig));
4494
+ return Math.max(1, this.#repairGraceMs(trackConfig, this.#multicastWaitMs(trackConfig)));
4286
4495
  }
4287
4496
  /** True once configureTrack/setFecDecoder/setFecWorker configured this packetId. */
4288
4497
  // -----------------------------------------------------------------------
@@ -4374,6 +4583,8 @@ var FECManager = class _FECManager {
4374
4583
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
4375
4584
  const evictedBefore = locator.heldEvicted;
4376
4585
  const held = locator.hold(ssId, source);
4586
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
4587
+ if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
4377
4588
  const evicted = locator.heldEvicted - evictedBefore;
4378
4589
  if (evicted > 0) {
4379
4590
  const before = this.#isoHeldEvictedCount;
@@ -4394,17 +4605,20 @@ var FECManager = class _FECManager {
4394
4605
  * contradicts a known block is refused (counted) and must be dropped.
4395
4606
  */
4396
4607
  placeIsoRepair(packetId, catalogTrackName, ssStart, ssbLength) {
4397
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength);
4608
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
4609
+ const placement = locator.placeRepair(ssStart, ssbLength);
4610
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
4398
4611
  if (placement.status !== "placed") {
4399
4612
  this.#isoRepairRefusedCount++;
4400
4613
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
4401
4614
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`);
4402
4615
  }
4616
+ if (placement.ofSpan !== void 0) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName);
4403
4617
  return placement;
4404
4618
  }
4619
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName));
4405
4620
  if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
4406
4621
  if (placement.hole !== void 0) {
4407
- const locator = this.#isoLocatorFor(packetId, catalogTrackName);
4408
4622
  const hole = placement.hole.block;
4409
4623
  const previous = locator.blockEndingAt(hole.start);
4410
4624
  const loss = {
@@ -4425,17 +4639,29 @@ var FECManager = class _FECManager {
4425
4639
  * `handler`, instead of a repair-less span; null restores spans. Set by the
4426
4640
  * range repair scheduler; applies to every stream from its next gap. The
4427
4641
  * handler and the deferral are one setting, so no hole is ever created with
4428
- * nobody to close it.
4642
+ * nobody to close it. `onExpired` is told of each pending hole the stream
4643
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
4644
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
4645
+ * reported; otherwise the hole is discarded with its sources.
4429
4646
  */
4430
- setUndelimitedLossHandler(handler) {
4647
+ setUndelimitedLossHandler(handler, onExpired = null) {
4431
4648
  this.#onUndelimitedLoss = handler;
4649
+ this.#onIsoHoleExpired = handler === null ? null : onExpired;
4432
4650
  this.#deferIsoGaps = handler !== null;
4433
4651
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
4434
4652
  }
4653
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
4654
+ #settleExpiredIsoHoles(locator, packetId, catalogTrackName) {
4655
+ for (const hole of locator.takeExpiredHoles()) {
4656
+ const expired = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length };
4657
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length);
4658
+ }
4659
+ }
4435
4660
  /**
4436
- * The range repair for a hole ended: every hole still pending inside
4437
- * `[start, start + length)` becomes a repair-less span. Returns those spans
4438
- * with the held sources they placed, for the caller to feed (MmtpRouter).
4661
+ * The range repair for a hole ended: every hole inside `[start, start +
4662
+ * length)`, pending or expired, becomes a repair-less span. Returns those
4663
+ * spans with the held sources they placed, for the caller to feed
4664
+ * (MmtpRouter).
4439
4665
  */
4440
4666
  closeIsoHoles(packetId, catalogTrackName, start, length) {
4441
4667
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
@@ -4451,10 +4677,25 @@ var FECManager = class _FECManager {
4451
4677
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
4452
4678
  * SS_ID of which vanished resolves through its deadline like any vanished
4453
4679
  * block.
4680
+ *
4681
+ * A span longer than K holds more than one block (SSB_length <= K), and the
4682
+ * locator states no block inside a span, only one exactly its range
4683
+ * (IsoBlockLocator.placeRepair): no repair, multicast or FETCHed, can ever
4684
+ * reach it. Its repair group is empty, so the repair scheduler FETCHes no
4685
+ * Group of it (group-cannot-complete). Every span still keeps its whole
4686
+ * wait (#lateSourceWaitMs): failing it early released the frames behind it
4687
+ * past a keyframe the overlay was still rebuilding (BLO-52085). The release
4688
+ * gate lets those frames go once only a late source can fill the gap
4689
+ * before them, as long after they arrived as the gap's decision allows
4690
+ * (isoRepairlessWaitMs).
4454
4691
  */
4455
4692
  #openIsoSpan(span, packetId, catalogTrackName) {
4456
4693
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
4457
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
4694
+ if (!this.#blockAuthoredLengths.has(key)) {
4695
+ this.#blockAuthoredLengths.set(key, span.block.length);
4696
+ this.#isoSpanKeys.add(key);
4697
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0);
4698
+ }
4458
4699
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
4459
4700
  }
4460
4701
  /**
@@ -4492,6 +4733,62 @@ var FECManager = class _FECManager {
4492
4733
  }
4493
4734
  return lost;
4494
4735
  }
4736
+ /**
4737
+ * The release gate's wait, from a frame's arrival, for the SS_IDs strictly
4738
+ * between two released frames' SS_IDs once only a late source can still
4739
+ * fill them, else undefined. That is when every one missing (neither
4740
+ * arrived nor held) lies in a repair-less span longer than K, which no
4741
+ * repair can state a block of (#openIsoSpan), or in a stated block its
4742
+ * own repair group cannot complete every SS_ID of which it misses lies
4743
+ * between them (so the gap's decision covers all it lost), and a multicast
4744
+ * source at or past `toSsId` arrived, so each is lost or reordered behind
4745
+ * it (a MoQ source shows nothing: MoQ streams overtake one another). The
4746
+ * span or block itself keeps its own wait.
4747
+ *
4748
+ * The wait is the late-symbol allowance, unless `rapMayHide`: the gap may
4749
+ * hold a RAP packet an installed keyframe overlay can still rebuild (its
4750
+ * decision stalls, or it ends at a RAP that may lie past a whole MPU).
4751
+ * Then the frame waits as a stated block its group cannot complete does
4752
+ * (#overlayLateWaitMs): the allowance alone with no overlay installed, the
4753
+ * overlay's span plus the larger of the allowance and its tolerance, or,
4754
+ * for an overlay that states no span, the span's whole wait (undefined).
4755
+ * So does `rapNext` (the gap ends at the RAP that opens the next MPU) when
4756
+ * the gap holds a stated block's loss.
4757
+ */
4758
+ isoRepairlessWaitMs(packetId, catalogTrackName, fromSsId, toSsId, rapMayHide = false, rapNext = false) {
4759
+ const config = this.#trackConfigs.get(packetId);
4760
+ if (config === void 0 || !_FECManager.#hasCatalogTiming(config)) return void 0;
4761
+ const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
4762
+ if (locator === void 0 || !locator.coversBetween(fromSsId, toSsId)) return void 0;
4763
+ const newestSource = locator.newestSource;
4764
+ if (newestSource === void 0 || serial32Precedes(newestSource, toSsId)) return void 0;
4765
+ let repairless = false;
4766
+ let stated = false;
4767
+ for (const block of locator.blocksBetween(fromSsId, toSsId)) {
4768
+ const key = this.#blockKey(block.start, packetId, catalogTrackName);
4769
+ if (this.#completedBlocks.has(key)) continue;
4770
+ if (block.span && block.length > locator.kMax) {
4771
+ repairless = true;
4772
+ continue;
4773
+ }
4774
+ const received = this.#blockSourceEsis.get(key);
4775
+ const rebuilt = this.#blockRebuiltEsis.get(key);
4776
+ let missesInGap = false;
4777
+ let missesOutside = false;
4778
+ for (let esi = 0; esi < block.length; esi++) {
4779
+ const ssId = serial32Add(block.start, esi);
4780
+ if (received?.has(esi) || locator.isHeld(ssId)) continue;
4781
+ if (serial32Precedes(fromSsId, ssId) && serial32Precedes(ssId, toSsId)) missesInGap = true;
4782
+ else if (!rebuilt?.has(esi)) missesOutside = true;
4783
+ }
4784
+ if (!missesInGap) continue;
4785
+ if (missesOutside || block.span || !this.#groupCannotComplete(key)) return void 0;
4786
+ repairless = stated = true;
4787
+ }
4788
+ if (!repairless) return void 0;
4789
+ const waitMs = rapMayHide || stated && rapNext ? this.#overlayLateWaitMs(packetId, catalogTrackName, config) : this.#multicastWaitMs(config) - config.interleaveDepthMs;
4790
+ return waitMs === void 0 ? void 0 : Math.max(0, waitMs);
4791
+ }
4495
4792
  /**
4496
4793
  * iso-ssbg1-v1 block location: repair symbols it refused, oversize sources,
4497
4794
  * the sources held now for a block no repair has stated yet, and the held
@@ -4542,11 +4839,14 @@ var FECManager = class _FECManager {
4542
4839
  /**
4543
4840
  * Whether an MPU boundary still bounds this stream's RAPs (see
4544
4841
  * `BlockClassifier.mpuBoundsRaps`). Gap decisions drop MPU evidence once
4545
- * it does not. A stream with no classifier yet has shown nothing against it.
4842
+ * it does not. A stream with no classifier yet has shown nothing against it,
4843
+ * and neither has a stream without catalog timing until it releases two
4844
+ * RAPs inside one MPU.
4546
4845
  */
4547
4846
  mpuBoundsRapsFor(packetId, catalogTrackName) {
4548
- if (!this.#hasCatalogTimingForPacket(packetId)) return false;
4549
- return this.#classifiers.get(this.#streamKey(packetId, catalogTrackName))?.mpuBoundsRaps ?? true;
4847
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
4848
+ if (!this.#hasCatalogTimingForPacket(packetId)) return this.#noSpanRaps.get(streamKey)?.inside !== true;
4849
+ return this.#classifiers.get(streamKey)?.mpuBoundsRaps ?? true;
4550
4850
  }
4551
4851
  /** A block's class now, or frozen at its resolution. */
4552
4852
  blockClassFor(sbn, packetId, catalogTrackName) {
@@ -4572,7 +4872,14 @@ var FECManager = class _FECManager {
4572
4872
  * invariant (consecutive MPUs exactly one keyframe interval apart).
4573
4873
  */
4574
4874
  noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale) {
4575
- if (!this.#trackConfigs.has(packetId) || !this.#hasCatalogTimingForPacket(packetId)) return;
4875
+ if (!this.#trackConfigs.has(packetId)) return;
4876
+ if (!this.#hasCatalogTimingForPacket(packetId)) {
4877
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
4878
+ const last = this.#noSpanRaps.get(streamKey);
4879
+ const inside = last?.inside === true || last?.mpu === mpu && last.presentationTime !== presentationTime;
4880
+ this.#noSpanRaps.set(streamKey, { mpu, presentationTime, inside });
4881
+ return;
4882
+ }
4576
4883
  this.#applyClassifierChanges(
4577
4884
  packetId,
4578
4885
  catalogTrackName,
@@ -4785,11 +5092,14 @@ var FECManager = class _FECManager {
4785
5092
  });
4786
5093
  client.onCleanupComplete((sbn) => {
4787
5094
  if (this.#releasedWorkerClients.has(client)) return;
4788
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
5095
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
5096
+ const cleanupKeys = owed.filter((key) => {
4789
5097
  const block = this.#parseBlockKey(key);
4790
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
5098
+ return block.packetId === packetId && block.sbn === sbn;
4791
5099
  });
4792
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
5100
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
5101
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
5102
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
4793
5103
  });
4794
5104
  client.onError((msg, code) => {
4795
5105
  const requestedKind = code ?? msg;
@@ -4859,9 +5169,11 @@ var FECManager = class _FECManager {
4859
5169
  * fail deadline already passed, so failing it is the decision that deadline
4860
5170
  * made. A late ack then finds nothing owed and is a no-op.
4861
5171
  */
4862
- #boundOwedCleanup(key, packetId, client) {
5172
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
4863
5173
  this.#clearOwedCleanupBound(key);
4864
5174
  const bound = {
5175
+ dueAtMs,
5176
+ askedAtMs: performance.now(),
4865
5177
  handle: setTimeout(() => {
4866
5178
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
4867
5179
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -4959,7 +5271,15 @@ var FECManager = class _FECManager {
4959
5271
  this.#isoSourceOversizeCount++;
4960
5272
  return null;
4961
5273
  }
4962
- const sbn = located.block.start;
5274
+ return this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, located.block.start);
5275
+ }
5276
+ /**
5277
+ * Hand one placed source symbol to the stream's decoder: its Worker, which
5278
+ * answers through onFrame (null here), or its synchronous decoder, whose
5279
+ * recovered block is returned. `sbn` is the SS_Start of the block a repair
5280
+ * stated for `ssId`.
5281
+ */
5282
+ #feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn) {
4963
5283
  const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
4964
5284
  const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey);
4965
5285
  const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
@@ -4988,6 +5308,74 @@ var FECManager = class _FECManager {
4988
5308
  }
4989
5309
  return recovered;
4990
5310
  }
5311
+ /**
5312
+ * Feed a source symbol of this stream that another FEC instance over the
5313
+ * same packets rebuilt: a keyframe overlay recovery whose base SS_ID the
5314
+ * caller determined (draft-ramadan-moq-mmt-02 7.1, 7.4.4; joint decoding,
5315
+ * BLO-52085). It joins its block's decoder as a received source would, so
5316
+ * it reduces the erasures the block still has to solve, but it is not a
5317
+ * network arrival: no transport accounting, no classification evidence,
5318
+ * no deadline refresh, and it never makes a block clean.
5319
+ *
5320
+ * Only a block a repair stated takes one (a repair-less span has no
5321
+ * decoder block). A block that is terminal, or already holds that source,
5322
+ * does not. The symbol is the exact protected packet, unpadded, as
5323
+ * feedSourceSymbol takes it.
5324
+ *
5325
+ * `recovered` is the block the synchronous decoder completed with it; the
5326
+ * caller routes it and completes the block, as for any recovery. When
5327
+ * every source of the block is then present, received or rebuilt, and no
5328
+ * decoder returned it (a Worker answers asynchronously, and reports such a
5329
+ * block as clean on its own side), the block is completed here as
5330
+ * recovered, with nothing left to route.
5331
+ */
5332
+ feedRebuiltSourceSymbol(packetId, ssId, symbolData, catalogTrackName) {
5333
+ if (!this.#hasBlockProfile(packetId)) return NOT_TAKEN;
5334
+ const located = this.#isoLocatorFor(packetId, catalogTrackName).locate(ssId);
5335
+ if (located === null || located.block.span) return NOT_TAKEN;
5336
+ if (!ssbg1FitsSymbol(symbolData.byteLength, this.#trackConfig(packetId).symbolSize)) return NOT_TAKEN;
5337
+ const sbn = located.block.start;
5338
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
5339
+ if (this.#completedBlocks.has(key) || this.#blockSourceEsis.get(key)?.has(located.esi)) return NOT_TAKEN;
5340
+ let rebuilt = this.#blockRebuiltEsis.get(key);
5341
+ if (rebuilt?.has(located.esi)) return NOT_TAKEN;
5342
+ if (rebuilt === void 0) {
5343
+ rebuilt = /* @__PURE__ */ new Set();
5344
+ this.#blockRebuiltEsis.set(key, rebuilt);
5345
+ }
5346
+ const config = this.#trackConfigs.get(packetId);
5347
+ const wasShort = config !== void 0 && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) !== void 0;
5348
+ rebuilt.add(located.esi);
5349
+ const recovered = this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn);
5350
+ if (recovered === null && !this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName)) {
5351
+ if (wasShort && this.#activeBlocks.has(key) && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) === void 0) {
5352
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, this.#multicastWaitMs(config));
5353
+ }
5354
+ }
5355
+ return { taken: true, recovered };
5356
+ }
5357
+ /**
5358
+ * A block that holds every one of its `length` sources, received or
5359
+ * rebuilt by another instance, with at least one rebuilt, is recovered:
5360
+ * every packet of it was delivered, by its own arrival or by the instance
5361
+ * that rebuilt it, so nothing is routed. Returns whether it completed it.
5362
+ */
5363
+ #completeWhenSourcesPresent(key, sbn, length, packetId, catalogTrackName) {
5364
+ const rebuilt = this.#blockRebuiltEsis.get(key);
5365
+ if (rebuilt === void 0 || this.#completedBlocks.has(key)) return false;
5366
+ let present = rebuilt.size;
5367
+ for (const esi of this.#blockSourceEsis.get(key) ?? []) if (!rebuilt.has(esi)) present++;
5368
+ if (present < length) return false;
5369
+ this.#traceLifecycle("recovered", sbn, packetId, catalogTrackName);
5370
+ this.countRecovery(packetId, sbn, catalogTrackName);
5371
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
5372
+ if (catalogTrackName === void 0) {
5373
+ this.onBlockComplete?.(sbn, packetId);
5374
+ } else {
5375
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName);
5376
+ }
5377
+ return true;
5378
+ }
4991
5379
  /**
4992
5380
  * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
4993
5381
  * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
@@ -5049,7 +5437,10 @@ var FECManager = class _FECManager {
5049
5437
  this.#layerAnchorHorizon(packetId),
5050
5438
  this.#sourceFrontiers.get(streamKey)?.sbn
5051
5439
  );
5052
- if (verdict === "discard") return false;
5440
+ if (verdict === "discard") {
5441
+ this.#unlistedRepairTrackRefusals++;
5442
+ return false;
5443
+ }
5053
5444
  if (verdict !== void 0) {
5054
5445
  this.#failClosed(streamKey, verdict, packetId, catalogTrackName);
5055
5446
  return false;
@@ -5190,8 +5581,115 @@ var FECManager = class _FECManager {
5190
5581
  this.#completeCleanBlock(blockKey, sbn, packetId, catalogTrackName);
5191
5582
  return null;
5192
5583
  }
5584
+ if (recovered === null) this.#shortenUnrecoverableWait(blockKey, sbn, packetId, catalogTrackName);
5193
5585
  return recovered;
5194
5586
  }
5587
+ /**
5588
+ * A first-arrival multicast source, held or placed. A datagram flow keeps
5589
+ * its sources in send order, so one that moves the stream's newest source
5590
+ * position past a block leaves the sources that block still misses
5591
+ * reordered behind it at best: it shortens the wait of every block it
5592
+ * passed that only a late source can complete. MoQ is left out: its streams
5593
+ * can overtake one another, so a MoQ source shows nothing about the sources
5594
+ * sent before it.
5595
+ */
5596
+ #noteMulticastSource(locator, ssId, packetId, catalogTrackName) {
5597
+ const previous = locator.newestSource;
5598
+ if (!locator.noteSource(ssId) || previous === void 0) return;
5599
+ for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
5600
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
5601
+ this.#shortenUnrecoverableWait(
5602
+ this.#blockKey(block.start, packetId, catalogTrackName),
5603
+ block.start,
5604
+ packetId,
5605
+ catalogTrackName
5606
+ );
5607
+ }
5608
+ }
5609
+ /**
5610
+ * The wait of a block that only a late source can complete (BLO-52085): a
5611
+ * repair stated it, its received sources plus every symbol its repair group
5612
+ * carries (RSB_length) are short of K' (the repair scheduler's
5613
+ * group-cannot-complete), and a later source of the stream has arrived, so
5614
+ * a source it misses is lost or reordered behind that one. The span, which
5615
+ * covers repair symbols paced after its sources, buys it nothing: it waits
5616
+ * the late-symbol allowance alone, the multicast wait less the span (the
5617
+ * catalog tolerance or the measured delivery gap). Undefined for any other
5618
+ * block. While a keyframe overlay is installed, the block waits for its
5619
+ * repair too (#overlayLateWaitMs). A repair-less span keeps its whole
5620
+ * wait, even one longer than K whose group is empty (#openIsoSpan): its
5621
+ * resolution is what releases the frames behind it, and failing it early
5622
+ * released them past a keyframe the overlay was still rebuilding, which
5623
+ * then arrived stale. The release gate lets them go instead
5624
+ * (isoRepairlessWaitMs).
5625
+ */
5626
+ #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
5627
+ if (this.#isoSpanKeys.has(key) || !this.#groupCannotComplete(key)) return void 0;
5628
+ const authoredLength = this.#blockAuthoredLengths.get(key);
5629
+ const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
5630
+ if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
5631
+ return void 0;
5632
+ }
5633
+ return this.#overlayLateWaitMs(packetId, catalogTrackName, config);
5634
+ }
5635
+ /**
5636
+ * A repair stated the block, and its sources plus every symbol its repair
5637
+ * group carries (RSB_length) are short of its SSB_length.
5638
+ */
5639
+ #groupCannotComplete(key) {
5640
+ const authoredLength = this.#blockAuthoredLengths.get(key);
5641
+ const rsbLength = this.#blockRsbLengths.get(key);
5642
+ if (authoredLength === void 0 || rsbLength === void 0) return false;
5643
+ let present = this.#blockSourceCounts.get(key) ?? 0;
5644
+ const received = this.#blockSourceEsis.get(key);
5645
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
5646
+ return present + rsbLength < authoredLength;
5647
+ }
5648
+ /**
5649
+ * How long a loss only a late source or an installed keyframe overlay can
5650
+ * still fill waits once a later source passed it: the late-symbol
5651
+ * allowance alone (the multicast wait less the span) while no overlay is
5652
+ * installed. An installed one (keyframeOverlayTiming) may still rebuild a
5653
+ * RAP packet the loss took: a second FEC instance over the same packets
5654
+ * (draft-ramadan-moq-mmt-02 7.4), whose repair is paced across its own
5655
+ * span, unrelated to the base's. That packet can complete a stated block
5656
+ * (feedRebuiltSourceSymbol), or play behind a span; giving the loss up
5657
+ * first lets the release gate pass the keyframe, whose rebuild then lands
5658
+ * stale. The overlay repair of a packet the loss took goes out within the
5659
+ * overlay's span of that packet (fec-core-00 9.3), and the later source was
5660
+ * sent after it, so the loss waits that span plus the larger of the
5661
+ * allowance and the overlay's own tolerance. An overlay that states no
5662
+ * span (its block may then span keyframes), or one whose wait is not
5663
+ * shorter than the whole multicast wait, leaves the whole wait: undefined.
5664
+ */
5665
+ #overlayLateWaitMs(packetId, catalogTrackName, config) {
5666
+ const waitMs = this.#multicastWaitMs(config);
5667
+ const allowanceMs = waitMs - config.interleaveDepthMs;
5668
+ const overlay = this.keyframeOverlayTiming?.(packetId, catalogTrackName);
5669
+ if (overlay === void 0) return allowanceMs;
5670
+ const overlaySpanMs = overlay.interleaveDepthMs ?? 0;
5671
+ const overlayWaitMs = overlaySpanMs + Math.max(allowanceMs, overlay.reorderToleranceMs ?? 0);
5672
+ return overlaySpanMs > 0 && overlayWaitMs < waitMs ? overlayWaitMs : void 0;
5673
+ }
5674
+ /**
5675
+ * Bring an open block's wait in to its late-source wait, when it has one.
5676
+ * Never later than it is armed: only a source can complete such a block,
5677
+ * so a repair of its group (paced across the span) must not keep it open.
5678
+ */
5679
+ #shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName) {
5680
+ if (!this.#activeBlocks.has(key)) return;
5681
+ const config = this.#trackConfigs.get(packetId);
5682
+ if (config === void 0) return;
5683
+ const waitMs = this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config);
5684
+ if (waitMs === void 0) return;
5685
+ const armedAtMs = this.#blockWaitDeadlinesMs.get(key);
5686
+ this.#armBlockTimeout(
5687
+ sbn,
5688
+ packetId,
5689
+ catalogTrackName,
5690
+ armedAtMs === void 0 ? waitMs : Math.min(waitMs, armedAtMs - this.#receiptNow())
5691
+ );
5692
+ }
5195
5693
  /**
5196
5694
  * Record a block's authored SSB_length from a repair symbol. Returns false,
5197
5695
  * leaving the block unchanged, when the symbol contradicts the block: a
@@ -5289,12 +5787,13 @@ var FECManager = class _FECManager {
5289
5787
  * the inactivity deadline on each symbol, records the symbol's in-band
5290
5788
  * classification evidence, and marks the block clean when all of its
5291
5789
  * authored source symbols arrived: the SSB_length a repair symbol declared,
5292
- * otherwise K.
5790
+ * otherwise K. `held` marks a source held unplaced since it arrived and
5791
+ * placed only now (see #noteSbnSeen).
5293
5792
  *
5294
5793
  * Throws for a packetId that was never configured, so a classified block
5295
5794
  * never reads the manager-global K or timeout.
5296
5795
  */
5297
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
5796
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
5298
5797
  const trackConfig = this.#trackConfigs.get(packetId);
5299
5798
  if (trackConfig === void 0) {
5300
5799
  throw new Error(
@@ -5310,7 +5809,8 @@ var FECManager = class _FECManager {
5310
5809
  catalogTrackName,
5311
5810
  "source",
5312
5811
  evidence.packetSequenceNumber,
5313
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
5812
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
5813
+ held
5314
5814
  );
5315
5815
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
5316
5816
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -5346,6 +5846,15 @@ var FECManager = class _FECManager {
5346
5846
  this.#completeCleanBlock(key, sbn, packetId, catalogTrackName);
5347
5847
  return;
5348
5848
  }
5849
+ if (this.#blockRebuiltEsis.has(key) && this.#completeWhenSourcesPresent(
5850
+ key,
5851
+ sbn,
5852
+ this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? authoredLength,
5853
+ packetId,
5854
+ catalogTrackName
5855
+ )) {
5856
+ return;
5857
+ }
5349
5858
  this.noteBlockActivity(sbn, packetId, catalogTrackName, true);
5350
5859
  }
5351
5860
  #completeCleanBlock(key, sbn, packetId, catalogTrackName) {
@@ -5354,7 +5863,9 @@ var FECManager = class _FECManager {
5354
5863
  this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
5355
5864
  this.#blockSourceCounts.delete(key);
5356
5865
  this.#blockSourceEsis.delete(key);
5866
+ this.#blockRebuiltEsis.delete(key);
5357
5867
  this.#blockAuthoredLengths.delete(key);
5868
+ this.#isoSpanKeys.delete(key);
5358
5869
  this.#blockRepairRsIds.delete(key);
5359
5870
  this.#blockRsbLengths.delete(key);
5360
5871
  this.#markTerminal(key, sbn, packetId, true);
@@ -5385,6 +5896,19 @@ var FECManager = class _FECManager {
5385
5896
  #receiptNow() {
5386
5897
  return this.#receiptAtMs ?? performance.now();
5387
5898
  }
5899
+ /**
5900
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
5901
+ * scope: counted from the receipt time, as the timer of a symbol fed when
5902
+ * it was received was, less the whole ms since. So it fires on the tick
5903
+ * that timer would have, never later than a delay counted from now, and
5904
+ * its handler still re-arms a timer that fires before its deadline.
5905
+ * Counted from now, a deadline set from the receipt time is rounded up
5906
+ * from another fraction of a ms (BLO-52085).
5907
+ */
5908
+ #receiptTimerDelayMs(deadlineMs, minMs) {
5909
+ const receivedAtMs = this.#receiptAtMs;
5910
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
5911
+ }
5388
5912
  /**
5389
5913
  * A held packet admitted late arms from its (earlier) receipt time; that
5390
5914
  * never pulls in a deadline later activity already armed. Outside a
@@ -5420,10 +5944,20 @@ var FECManager = class _FECManager {
5420
5944
  this.#repairDeadlineMs(trackConfig)
5421
5945
  );
5422
5946
  }
5423
- this.#armBlockTimeout(sbn, packetId, catalogTrackName, timeoutMs);
5947
+ if (!sourceProgress && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) !== void 0) {
5948
+ this.#shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName);
5949
+ return;
5950
+ }
5951
+ this.#armBlockTimeout(
5952
+ sbn,
5953
+ packetId,
5954
+ catalogTrackName,
5955
+ this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) ?? timeoutMs
5956
+ );
5424
5957
  }
5425
5958
  #failBlock(sbn, packetId, catalogTrackName) {
5426
5959
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
5960
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
5427
5961
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
5428
5962
  this.#clearRepairDeadline(key);
5429
5963
  this.#clearBlockTimer(key);
@@ -5433,6 +5967,7 @@ var FECManager = class _FECManager {
5433
5967
  }
5434
5968
  this.#blockSourceCounts.delete(key);
5435
5969
  this.#blockSourceEsis.delete(key);
5970
+ this.#blockRebuiltEsis.delete(key);
5436
5971
  this.#blockAuthoredLengths.delete(key);
5437
5972
  this.#blockRepairRsIds.delete(key);
5438
5973
  this.#blockRsbLengths.delete(key);
@@ -5442,7 +5977,8 @@ var FECManager = class _FECManager {
5442
5977
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
5443
5978
  this.#fecStats.blocksFailed++;
5444
5979
  this.#statsForPacket(packetId).blocksFailed++;
5445
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5980
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5981
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
5446
5982
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
5447
5983
  }
5448
5984
  /**
@@ -5471,7 +6007,9 @@ var FECManager = class _FECManager {
5471
6007
  this.#retireBlockClass(key, block.sbn, block.packetId, block.catalogTrackName);
5472
6008
  this.#blockSourceCounts.delete(key);
5473
6009
  this.#blockSourceEsis.delete(key);
6010
+ this.#blockRebuiltEsis.delete(key);
5474
6011
  this.#blockAuthoredLengths.delete(key);
6012
+ this.#isoSpanKeys.delete(key);
5475
6013
  this.#blockRepairRsIds.delete(key);
5476
6014
  this.#blockRsbLengths.delete(key);
5477
6015
  this.#clearBlockTimer(key);
@@ -5562,7 +6100,9 @@ var FECManager = class _FECManager {
5562
6100
  this.#blockKeysBySbn.clear();
5563
6101
  this.#blockSourceCounts.clear();
5564
6102
  this.#blockSourceEsis.clear();
6103
+ this.#blockRebuiltEsis.clear();
5565
6104
  this.#blockAuthoredLengths.clear();
6105
+ this.#isoSpanKeys.clear();
5566
6106
  this.#blockRepairRsIds.clear();
5567
6107
  this.#blockRsbLengths.clear();
5568
6108
  this.#heldLayerStates.clear();
@@ -5587,6 +6127,7 @@ var FECManager = class _FECManager {
5587
6127
  this.#blockAnchorsMs.clear();
5588
6128
  this.#blockCatalogTrackNames.clear();
5589
6129
  this.#classifiers.clear();
6130
+ this.#noSpanRaps.clear();
5590
6131
  this.#streamGeometries.clear();
5591
6132
  this.#failedBlocks.clear();
5592
6133
  this.#resolvedBlockClasses.clear();
@@ -6940,9 +7481,9 @@ async function openSubscription(rx, openedPromise, options, packetIds) {
6940
7481
  } catch (error) {
6941
7482
  throw new MulticastError("subscription-failed", "MulticastReceiver did not open", error);
6942
7483
  }
6943
- if (rx.integrityScheme !== INTEGRITY_SCHEME) {
7484
+ if (opened.integrityScheme !== INTEGRITY_SCHEME) {
6944
7485
  await rx.close();
6945
- throw unsupported(`integrity scheme ${String(rx.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
7486
+ throw unsupported(`integrity scheme ${String(opened.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
6946
7487
  }
6947
7488
  const events = new EventTarget();
6948
7489
  let state = "connected";
@@ -7061,14 +7602,15 @@ var MOQT_PUBLISHER_PRIORITY = Object.freeze({
7061
7602
  });
7062
7603
 
7063
7604
  // node_modules/@blockcast/mmt-transport/dist/amt-gateway.js
7605
+ var MAX_PENDING_PACKETS = 256;
7064
7606
  var AMTGatewayManager = class {
7065
7607
  subscriptions = /* @__PURE__ */ new Map();
7066
7608
  messageHandler;
7609
+ messageListenerRegistered = false;
7067
7610
  pendingPackets = /* @__PURE__ */ new Map();
7068
7611
  constructor() {
7069
7612
  this.messageHandler = (event) => {
7070
7613
  const data = event.data;
7071
- console.log(`[AMT] SW message received:`, data.type);
7072
7614
  if (data.type === "UDP_PACKET") {
7073
7615
  this.handlePacket(data);
7074
7616
  } else if (data.type === "SOCKET_ERROR") {
@@ -7077,12 +7619,22 @@ var AMTGatewayManager = class {
7077
7619
  console.log(`[AMT SW Debug] ${data.message}`);
7078
7620
  }
7079
7621
  };
7080
- if (typeof navigator !== "undefined" && navigator.serviceWorker) {
7081
- navigator.serviceWorker.addEventListener("message", this.messageHandler);
7082
- console.log("[AMT] Registered service worker message handler");
7083
- } else {
7084
- console.warn("[AMT] Service worker not available");
7622
+ }
7623
+ ensureMessageListener() {
7624
+ if (this.messageListenerRegistered || typeof navigator === "undefined" || !navigator.serviceWorker || !this.messageHandler) {
7625
+ return;
7085
7626
  }
7627
+ navigator.serviceWorker.addEventListener("message", this.messageHandler);
7628
+ this.messageListenerRegistered = true;
7629
+ console.log("[AMT] Registered service worker message handler");
7630
+ }
7631
+ removeMessageListener() {
7632
+ if (!this.messageListenerRegistered)
7633
+ return;
7634
+ if (this.messageHandler && typeof navigator !== "undefined" && navigator.serviceWorker) {
7635
+ navigator.serviceWorker.removeEventListener("message", this.messageHandler);
7636
+ }
7637
+ this.messageListenerRegistered = false;
7086
7638
  }
7087
7639
  /**
7088
7640
  * Subscribe via AMT tunnel
@@ -7092,6 +7644,7 @@ var AMTGatewayManager = class {
7092
7644
  if (config.protected) {
7093
7645
  throw new Error("AMTGatewayManager refuses a protected join: it reports no per-datagram sender (multicast-02 7.2.7)");
7094
7646
  }
7647
+ this.ensureMessageListener();
7095
7648
  const keyStr = this.getKeyString(key);
7096
7649
  if (this.subscriptions.has(keyStr)) {
7097
7650
  console.log(`[AMT] Reusing existing subscription to ${keyStr}`);
@@ -7127,6 +7680,8 @@ var AMTGatewayManager = class {
7127
7680
  this.subscriptions.delete(keyStr);
7128
7681
  this.pendingPackets.delete(subscription.subscriptionId);
7129
7682
  }
7683
+ if (this.subscriptions.size === 0)
7684
+ this.removeMessageListener();
7130
7685
  throw new Error(`Failed to subscribe via AMT: ${error instanceof Error ? error.message : String(error)}`);
7131
7686
  }
7132
7687
  }
@@ -7148,6 +7703,8 @@ var AMTGatewayManager = class {
7148
7703
  } finally {
7149
7704
  this.subscriptions.delete(handle);
7150
7705
  this.pendingPackets.delete(subscription.subscriptionId);
7706
+ if (this.subscriptions.size === 0)
7707
+ this.removeMessageListener();
7151
7708
  }
7152
7709
  }
7153
7710
  /**
@@ -7164,14 +7721,12 @@ var AMTGatewayManager = class {
7164
7721
  if (!subscriptionId)
7165
7722
  return;
7166
7723
  const subscription = this.subscriptions.get(subscriptionId);
7167
- if (!subscription) {
7168
- console.warn(`[AMT] Received packet for unknown subscription: ${subscriptionId}`);
7724
+ if (!subscription)
7169
7725
  return;
7170
- }
7171
7726
  if (!subscription.handshakeComplete) {
7172
7727
  const queue = this.pendingPackets.get(subscriptionId);
7173
7728
  const packetData2 = data;
7174
- if (queue) {
7729
+ if (queue && queue.length < MAX_PENDING_PACKETS) {
7175
7730
  queue.push({
7176
7731
  data: packetData2.data,
7177
7732
  remoteAddress: packetData2.remoteAddress,
@@ -7197,19 +7752,15 @@ var AMTGatewayManager = class {
7197
7752
  if (!subscriptionId)
7198
7753
  return;
7199
7754
  const subscription = this.subscriptions.get(subscriptionId);
7200
- if (!subscription) {
7201
- console.warn(`[AMT] Received error for unknown subscription: ${subscriptionId}`);
7755
+ if (!subscription)
7202
7756
  return;
7203
- }
7204
7757
  subscription.config.onError(new Error(error || "Unknown error"));
7205
7758
  }
7206
7759
  /**
7207
7760
  * Cleanup on destroy
7208
7761
  */
7209
7762
  destroy() {
7210
- if (this.messageHandler && typeof navigator !== "undefined" && navigator.serviceWorker) {
7211
- navigator.serviceWorker.removeEventListener("message", this.messageHandler);
7212
- }
7763
+ this.removeMessageListener();
7213
7764
  const handles = Array.from(this.subscriptions.keys());
7214
7765
  for (const handle of handles) {
7215
7766
  this.unsubscribe(handle).catch((err) => {
@@ -10268,9 +10819,10 @@ function isH264IntraSlice(nal) {
10268
10819
  const sliceType = readH264SliceType(nal);
10269
10820
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
10270
10821
  }
10822
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
10271
10823
  function readH264SliceType(nal) {
10272
10824
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
10273
- const rbsp = removeEmulationPrevention(nal.subarray(1));
10825
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
10274
10826
  const state = { bitOffset: 0 };
10275
10827
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
10276
10828
  return readUnsignedExpGolomb(rbsp, state);
@@ -10417,6 +10969,96 @@ if (void 0) {
10417
10969
  ]))).toBe(false);
10418
10970
  });
10419
10971
  });
10972
+ describe("readH264SliceType", () => {
10973
+ const wholeNalSliceType = (nal) => {
10974
+ if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
10975
+ const rbsp = removeEmulationPrevention(nal.subarray(1));
10976
+ const state = { bitOffset: 0 };
10977
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null;
10978
+ return readUnsignedExpGolomb(rbsp, state);
10979
+ };
10980
+ const hex2 = (text2) => Uint8Array.from(text2.match(/../g), (byte) => parseInt(byte, 16));
10981
+ const ue = (value) => {
10982
+ const code = (value + 1).toString(2);
10983
+ return "0".repeat(code.length - 1) + code;
10984
+ };
10985
+ const sliceNal = (bits) => {
10986
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, "0").match(/.{8}/g);
10987
+ const nal = [1];
10988
+ let zeros = 0;
10989
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
10990
+ if (zeros >= 2 && byte <= 3) {
10991
+ nal.push(3);
10992
+ zeros = 0;
10993
+ }
10994
+ nal.push(byte);
10995
+ zeros = byte === 0 ? zeros + 1 : 0;
10996
+ }
10997
+ return Uint8Array.from(nal);
10998
+ };
10999
+ const x264Slices = [
11000
+ ["64x48 P", hex2("419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176"), 5, false],
11001
+ ["64x48 B", hex2("419e414212fffeeade283707cb70f7"), 6, false],
11002
+ ["64x48 non-IDR I", hex2(
11003
+ "4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39a527e23eb34c8167fd"
11004
+ ), 7, true],
11005
+ ["1280x720 B, escape at byte 10", hex2(
11006
+ "01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e19b75d92170917306190f262fd58268702db2eff86a9651e48"
11007
+ ), 6, false],
11008
+ ["1280x720 P, escape at byte 15", hex2(
11009
+ "41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f02c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e85302da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3"
11010
+ ), 5, false],
11011
+ ["1280x720 B, escape at byte 22", hex2("01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352"), 6, false],
11012
+ ["7680x4320 IDR, first_mb_in_slice 97440", hex2(
11013
+ "650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9"
11014
+ ), null, true],
11015
+ ["7680x4320 P, first_mb_in_slice 32640", hex2(
11016
+ "410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020"
11017
+ ), 5, false],
11018
+ ["7680x4320 P, first_mb_in_slice 97440", hex2(
11019
+ "410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806"
11020
+ ), 5, false]
11021
+ ];
11022
+ const syntheticSlices = [
11023
+ ["an escape inside first_mb_in_slice", sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
11024
+ ["an escape between the fields", sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
11025
+ ["an escape inside slice_type", sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
11026
+ ["the longest fields, five escapes", sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
11027
+ ["the largest values", sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
11028
+ ["31 leading zeros in first_mb_in_slice", sliceNal(`${"0".repeat(31)}1`), null],
11029
+ ["31 leading zeros in slice_type", sliceNal(`1${"0".repeat(31)}1`), null],
11030
+ ["escapes running past the slice header", sliceNal(ue(0) + ue(5) + "0".repeat(400)), 5]
11031
+ ];
11032
+ test("reads the slice_type of real and synthetic slices", () => {
11033
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
11034
+ expect(readH264SliceType(nal), name).toBe(sliceType);
11035
+ }
11036
+ });
11037
+ test("matches the whole-NAL unescape at every truncation", () => {
11038
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
11039
+ for (let end = 0; end <= nal.length; end++) {
11040
+ const cut = nal.subarray(0, end);
11041
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut));
11042
+ }
11043
+ }
11044
+ });
11045
+ test("matches the whole-NAL unescape on zero-heavy NAL units", () => {
11046
+ const bytes = [0, 0, 0, 3, 1, 2, 128, 255];
11047
+ let seed = 1;
11048
+ const next = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) >>> 16;
11049
+ for (let i = 0; i < 5e3; i++) {
11050
+ const nal = new Uint8Array(2 + next() % 63);
11051
+ nal[0] = 65;
11052
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length];
11053
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal));
11054
+ }
11055
+ });
11056
+ test("classifies the x264 slices as keyframes or not", () => {
11057
+ for (const [name, nal, , keyframe] of x264Slices) {
11058
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe);
11059
+ }
11060
+ });
11061
+ });
10420
11062
  describe("avccToAnnexB", () => {
10421
11063
  test("converts with SPS/PPS on keyframe", () => {
10422
11064
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -13118,9 +13760,21 @@ var IsoBmffTimingResolver = class {
13118
13760
  }
13119
13761
  #track = null;
13120
13762
  #fragments = /* @__PURE__ */ new Map();
13763
+ /** First sample of each pending fragment, kept in `#delivered` with its sample count. */
13764
+ #firstSamples = /* @__PURE__ */ new Map();
13765
+ /**
13766
+ * First sample and sample count of the newest fragments whose every slot was
13767
+ * cleared. Abandonment counts: `releaseSample` clears a slot too, which
13768
+ * matches the combiner, since it retires an abandoned sample as well.
13769
+ */
13770
+ #delivered = /* @__PURE__ */ new Map();
13121
13771
  #pendingSamples = 0;
13122
13772
  #evictedSamples = 0;
13123
13773
  #lastMovieFragmentRejection = null;
13774
+ /** True once an FT=0 has bound the track that FT=1 timing is read against. */
13775
+ get initialized() {
13776
+ return this.#track !== null;
13777
+ }
13124
13778
  get pendingSampleCount() {
13125
13779
  return this.#pendingSamples;
13126
13780
  }
@@ -13144,7 +13798,14 @@ var IsoBmffTimingResolver = class {
13144
13798
  this.#track = timing;
13145
13799
  return true;
13146
13800
  }
13147
- addMovieFragment(mpuSequenceNumber, data, additionalSampleLimit = this.maxPendingSamples) {
13801
+ /**
13802
+ * `recovered` marks an FEC-recovered copy. A recovered block hands back
13803
+ * every FT=1 it holds, the received ones included, so a recovered copy of a
13804
+ * fragment whose samples are all done is a duplicate: admitting it again
13805
+ * would charge stale timing and could displace the live MPU's. A source
13806
+ * copy is still admitted again (a rendition switch re-arms timing that way).
13807
+ */
13808
+ addMovieFragment(mpuSequenceNumber, data, additionalSampleLimit = this.maxPendingSamples, recovered = false) {
13148
13809
  this.#lastMovieFragmentRejection = null;
13149
13810
  if (!Number.isInteger(additionalSampleLimit) || additionalSampleLimit < 0) {
13150
13811
  this.#lastMovieFragmentRejection = "invalid";
@@ -13170,6 +13831,8 @@ var IsoBmffTimingResolver = class {
13170
13831
  (sample, index) => sample !== null && sameSample(sample, parsed.samples[index])
13171
13832
  );
13172
13833
  }
13834
+ const delivered = recovered ? this.#delivered.get(key) : void 0;
13835
+ if (delivered && delivered.sampleCount === parsed.samples.length && sameSample(delivered.first, parsed.samples[0])) return true;
13173
13836
  let freed = 0;
13174
13837
  while (this.#fragments.size > 0 && (this.#pendingSamples + parsed.samples.length > this.maxPendingSamples || parsed.samples.length - freed > additionalSampleLimit)) {
13175
13838
  freed += this.#evictOldestFragment();
@@ -13183,6 +13846,7 @@ var IsoBmffTimingResolver = class {
13183
13846
  return false;
13184
13847
  }
13185
13848
  this.#fragments.set(key, [...parsed.samples]);
13849
+ this.#firstSamples.set(key, parsed.samples[0]);
13186
13850
  this.#pendingSamples += parsed.samples.length;
13187
13851
  return true;
13188
13852
  }
@@ -13240,6 +13904,7 @@ var IsoBmffTimingResolver = class {
13240
13904
  let live = 0;
13241
13905
  for (const sample of samples) if (sample !== null) live++;
13242
13906
  this.#fragments.delete(oldest);
13907
+ this.#firstSamples.delete(oldest);
13243
13908
  this.#pendingSamples -= live;
13244
13909
  this.#evictedSamples += live;
13245
13910
  return live;
@@ -13255,12 +13920,23 @@ var IsoBmffTimingResolver = class {
13255
13920
  if (!samples || !samples[index]) return false;
13256
13921
  samples[index] = null;
13257
13922
  this.#pendingSamples--;
13258
- if (samples.every((value) => value === null)) this.#fragments.delete(key);
13923
+ if (samples.every((value) => value === null)) {
13924
+ this.#fragments.delete(key);
13925
+ const first = this.#firstSamples.get(key);
13926
+ this.#firstSamples.delete(key);
13927
+ this.#delivered.delete(key);
13928
+ this.#delivered.set(key, { first, sampleCount: samples.length });
13929
+ if (this.#delivered.size > this.maxPendingSamples) {
13930
+ this.#delivered.delete(this.#delivered.keys().next().value);
13931
+ }
13932
+ }
13259
13933
  return true;
13260
13934
  }
13261
13935
  reset() {
13262
13936
  this.#track = null;
13263
13937
  this.#fragments.clear();
13938
+ this.#firstSamples.clear();
13939
+ this.#delivered.clear();
13264
13940
  this.#pendingSamples = 0;
13265
13941
  }
13266
13942
  };
@@ -13430,6 +14106,9 @@ function authoredGap(before, after) {
13430
14106
  function ssIdAfter(a, b) {
13431
14107
  return (a - b | 0) > 0;
13432
14108
  }
14109
+ function holdsRebuilt(stream) {
14110
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
14111
+ }
13433
14112
  var FecReleaseSequencer = class {
13434
14113
  #streams = /* @__PURE__ */ new Map();
13435
14114
  #gate;
@@ -13492,6 +14171,7 @@ var FecReleaseSequencer = class {
13492
14171
  stream.lastSbn = void 0;
13493
14172
  stream.discontinuity = false;
13494
14173
  stream.rapSsId = void 0;
14174
+ stream.sourced = false;
13495
14175
  }
13496
14176
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
13497
14177
  this.#recordStat("droppedStale");
@@ -13518,6 +14198,7 @@ var FecReleaseSequencer = class {
13518
14198
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
13519
14199
  else hi = mid;
13520
14200
  }
14201
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
13521
14202
  stream.buf.splice(lo, 0, frame);
13522
14203
  this.#drainUnlessDeferred(stream);
13523
14204
  }
@@ -13553,6 +14234,41 @@ var FecReleaseSequencer = class {
13553
14234
  }
13554
14235
  return false;
13555
14236
  }
14237
+ /**
14238
+ * These streams' sink is being replaced by one that has seen no source
14239
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
14240
+ * release to the sink being replaced the frames the unanchored path had
14241
+ * already released to it (#cursorPassed): there they waited in its queue,
14242
+ * which its replacement flushes. A stream that holds none is not drained:
14243
+ * it holds nothing the anchor kept back, and a drain would still force out
14244
+ * a frame held past the hold limit, which before the anchor waited for the
14245
+ * next push. Then treat the streams as unsourced until a source frame is
14246
+ * released.
14247
+ */
14248
+ unsource(packetId, catalogTrackName) {
14249
+ for (const stream of this.#streams.values()) {
14250
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
14251
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
14252
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
14253
+ else this.#drain(stream, true);
14254
+ }
14255
+ stream.sourced = false;
14256
+ }
14257
+ }
14258
+ }
14259
+ /**
14260
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
14261
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
14262
+ * packetId.
14263
+ */
14264
+ holdsRebuilt(packetId, catalogTrackName) {
14265
+ for (const stream of this.#streams.values()) {
14266
+ if (stream.packetId !== packetId) continue;
14267
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
14268
+ if (holdsRebuilt(stream)) return true;
14269
+ }
14270
+ return false;
14271
+ }
13556
14272
  /** Re-evaluate held gaps after FEC state changed. */
13557
14273
  poke(streamKey) {
13558
14274
  if (streamKey !== void 0) {
@@ -13644,16 +14360,32 @@ var FecReleaseSequencer = class {
13644
14360
  last: null,
13645
14361
  lastSbn: void 0,
13646
14362
  discontinuity: false,
13647
- rapSsId: void 0
14363
+ rapSsId: void 0,
14364
+ sourced: false,
14365
+ draining: 0
13648
14366
  };
13649
14367
  this.#streams.set(streamKey, stream);
13650
14368
  }
13651
14369
  return stream;
13652
14370
  }
13653
- #drain(stream) {
14371
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
14372
+ #drain(stream, asUnanchored = false) {
14373
+ stream.draining++;
14374
+ try {
14375
+ this.#drainLoop(stream, asUnanchored);
14376
+ } finally {
14377
+ stream.draining--;
14378
+ }
14379
+ }
14380
+ #drainLoop(stream, asUnanchored) {
13654
14381
  while (stream.buf.length > 0 && stream.last !== null) {
13655
14382
  const head = stream.buf[0];
13656
14383
  const last = stream.last;
14384
+ if (compareFrameOrder(head, last) <= 0) {
14385
+ stream.buf.shift();
14386
+ this.#release(stream, head, void 0);
14387
+ continue;
14388
+ }
13657
14389
  if (stream.discontinuity) {
13658
14390
  stream.discontinuity = false;
13659
14391
  stream.buf.shift();
@@ -13667,9 +14399,10 @@ var FecReleaseSequencer = class {
13667
14399
  }
13668
14400
  const headSbn = head.meta.fecSbn;
13669
14401
  const from = stream.lastSbn ?? headSbn;
13670
- const to = headSbn ?? stream.lastSbn;
14402
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
13671
14403
  let lost = [];
13672
14404
  const unanchored = from === void 0 && to === void 0;
14405
+ let unresolved = false;
13673
14406
  if (from !== void 0 && to !== void 0) {
13674
14407
  const resolved = this.#gate.resolvedLoss(
13675
14408
  stream.packetId,
@@ -13678,7 +14411,8 @@ var FecReleaseSequencer = class {
13678
14411
  Math.max(from, to),
13679
14412
  from
13680
14413
  );
13681
- if (resolved === null) {
14414
+ unresolved = resolved === null;
14415
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored) && !this.#unrepairableWaitOver(stream, last, head, from, to)) {
13682
14416
  const heldMs = performance.now() - head.arrivedAtMs;
13683
14417
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
13684
14418
  this.#recordStat("forcedWindowFlushes");
@@ -13686,22 +14420,69 @@ var FecReleaseSequencer = class {
13686
14420
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
13687
14421
  continue;
13688
14422
  }
13689
- lost = resolved;
14423
+ lost = resolved ?? [];
13690
14424
  }
13691
14425
  stream.buf.shift();
13692
14426
  this.#release(
13693
14427
  stream,
13694
14428
  head,
13695
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
14429
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
13696
14430
  );
13697
14431
  }
13698
14432
  }
14433
+ /**
14434
+ * The head has waited out a gap only a late source can still fill
14435
+ * (FecReleaseGate.unrepairableWaitMs). Not yet: the gate is asked to poke
14436
+ * the stream when it has (`wakeAt`), since no packet may come by then.
14437
+ */
14438
+ #unrepairableWaitOver(stream, last, head, from, to) {
14439
+ const waitMs = this.#gate.unrepairableWaitMs?.(last, head, from, to);
14440
+ if (waitMs === void 0) return false;
14441
+ const atMs = head.arrivedAtMs + waitMs;
14442
+ if (performance.now() >= atMs) return true;
14443
+ this.#gate.wakeAt?.(stream.packetId, stream.catalogTrackName, atMs);
14444
+ return false;
14445
+ }
14446
+ /**
14447
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
14448
+ * source cursor holds it unanchored, and neither does a later frame behind
14449
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
14450
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
14451
+ * like each frame that arrived in front of it since (stale there). The head
14452
+ * then goes, decided as it would be unanchored, once a frame the base path
14453
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
14454
+ * marked one: the base path has passed that one, so a frame still missing
14455
+ * before it can only come from a repair. It also goes while no source frame
14456
+ * has been released, when the direct path shows a recovered frame at once.
14457
+ * And it goes at once while a staged switch decides on when frames arrive
14458
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
14459
+ * sink being replaced: unanchored, it had already reached the sink.
14460
+ * The scan also writes: the `passed` marks it sets stay on the frames,
14461
+ * and push marks a frame it inserts in front of a marked one from them.
14462
+ */
14463
+ #cursorPassed(stream, asUnanchored) {
14464
+ let at = -1;
14465
+ for (let i = 0; i < stream.buf.length; i++) {
14466
+ const frame = stream.buf[i];
14467
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
14468
+ frame.passed = true;
14469
+ if (at < 0) at = i;
14470
+ } else if (frame.passed !== true) break;
14471
+ }
14472
+ if (at < 0) return false;
14473
+ 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));
14474
+ }
13699
14475
  #release(stream, frame, decision) {
14476
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
14477
+ if (stale) this.#recordStat("droppedStale");
13700
14478
  if (decision) frame.meta.gapBefore = decision;
13701
14479
  stream.last = frame;
13702
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
14480
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
14481
+ stream.lastSbn = frame.meta.fecSbn;
14482
+ }
14483
+ if (frame.meta.recovered !== true) stream.sourced = true;
13703
14484
  this.#gate.onReleased?.(frame.data, frame.meta);
13704
- this.#emit(frame.data, frame.meta);
14485
+ if (!stale) this.#emit(frame.data, frame.meta);
13705
14486
  }
13706
14487
  };
13707
14488
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -13742,6 +14523,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
13742
14523
  this.#reclaimedTimingSamples = 0;
13743
14524
  this.#evictedTimingSamples = 0;
13744
14525
  this.#rejectedMovieFragments = 0;
14526
+ this.#recoveredHeadsAwaitingTiming = {
14527
+ held: 0,
14528
+ expired: 0,
14529
+ discarded: 0,
14530
+ superseded: 0
14531
+ };
13745
14532
  this.#sequencers = /* @__PURE__ */ new Map();
13746
14533
  this.#fecGate = null;
13747
14534
  this.#fecSequencer = null;
@@ -13850,6 +14637,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
13850
14637
  #reclaimedTimingSamples;
13851
14638
  #evictedTimingSamples;
13852
14639
  #rejectedMovieFragments;
14640
+ #recoveredHeadsAwaitingTiming;
13853
14641
  #sequencers;
13854
14642
  #fecGate;
13855
14643
  #fecSequencer;
@@ -13955,11 +14743,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
13955
14743
  /**
13956
14744
  * Typed view of the ISO-BMFF timing-sample budget.
13957
14745
  *
13958
- * This is the acceptance signal for the budget ratchet: `pending` walking
13959
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
13960
- * and it is observable here rather than only as media silently stopping.
13961
- * Per repo policy this is a producer-owned counter -- never infer budget
13962
- * state by parsing logs.
14746
+ * Each stream admits timing against its own window of `capacity` slots
14747
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
14748
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
14749
+ * timing a stream declared and never delivered shows up there. `pending`
14750
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
14751
+ * a producer-owned counter -- never infer budget state by parsing logs.
13963
14752
  */
13964
14753
  get timingBudgetStats() {
13965
14754
  return {
@@ -13970,6 +14759,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
13970
14759
  rejectedMovieFragments: this.#rejectedMovieFragments
13971
14760
  };
13972
14761
  }
14762
+ /** Recovered heads parked for FT=1 timing (BLO-53369). Survives dispose(). */
14763
+ get recoveredHeadsAwaitingTiming() {
14764
+ let pending = 0;
14765
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
14766
+ for (const head of awaitingTiming) if (head.options?.recovered) pending++;
14767
+ }
14768
+ return { ...this.#recoveredHeadsAwaitingTiming, pending };
14769
+ }
13973
14770
  get reorderStats() {
13974
14771
  let bufferedFrames = this.#fecSequencer?.buffered ?? 0;
13975
14772
  for (const { sequencer } of this.#sequencers.values()) bufferedFrames += sequencer.buffered;
@@ -14011,6 +14808,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
14011
14808
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
14012
14809
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
14013
14810
  }
14811
+ /** See FecReleaseSequencer.unsource. */
14812
+ unsourceFecRelease(packetId, catalogTrackName) {
14813
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
14814
+ }
14815
+ /** See FecReleaseSequencer.holdsRebuilt. */
14816
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
14817
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
14818
+ }
14014
14819
  /** Re-evaluate held gaps after FEC block state changed. */
14015
14820
  pokeFecRelease(packetId, catalogTrackName) {
14016
14821
  if (!this.#fecSequencer) return;
@@ -14143,7 +14948,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14143
14948
  const now = Date.now();
14144
14949
  for (const { awaitingTiming } of this.#timingStreams.values()) {
14145
14950
  while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
14146
- awaitingTiming.shift();
14951
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
14147
14952
  }
14148
14953
  }
14149
14954
  }
@@ -14261,11 +15066,16 @@ var MmtpContainerParser = class _MmtpContainerParser {
14261
15066
  if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
14262
15067
  return this.#drop("fragment-unexpected-fragmentation");
14263
15068
  const resolver2 = this.#timingResolver(streamKey, info.packetId, false);
14264
- if (!resolver2) return this.#drop("fragment-no-resolver");
15069
+ if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
14265
15070
  const pendingBefore = resolver2.pendingSampleCount;
14266
15071
  const evictedBefore = resolver2.evictedSampleCount;
14267
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
14268
- const admitted = resolver2.addMovieFragment(mpu.mpuSequenceNumber, data, remaining);
15072
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
15073
+ const admitted = resolver2.addMovieFragment(
15074
+ mpu.mpuSequenceNumber,
15075
+ data,
15076
+ remaining,
15077
+ options?.recovered === true
15078
+ );
14269
15079
  this.#pendingTimingSamples += resolver2.pendingSampleCount - pendingBefore;
14270
15080
  this.#evictedTimingSamples += resolver2.evictedSampleCount - evictedBefore;
14271
15081
  if (!admitted) {
@@ -14285,7 +15095,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14285
15095
  };
14286
15096
  }
14287
15097
  if (fragmentType !== 2) return this.#drop("unknown-fragment-type");
14288
- const resolver = this.#timingResolver(streamKey, info.packetId, false);
15098
+ const resolver = this.#timingResolver(streamKey, info.packetId, true);
14289
15099
  if (!resolver) return this.#drop("mfu-no-resolver");
14290
15100
  if (!Number.isSafeInteger(data.byteLength) || data.byteLength <= 0)
14291
15101
  return this.#drop("mfu-empty-payload");
@@ -14306,6 +15116,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14306
15116
  mpuSequenceNumber: mpu.mpuSequenceNumber,
14307
15117
  movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
14308
15118
  sampleNumber: mfuDuHeader.sampleNumber,
15119
+ sequenceNumber: info.sequenceNumber,
14309
15120
  arrivedAt: Date.now()
14310
15121
  });
14311
15122
  return this.#drop("mfu-sample-timing-missing");
@@ -14331,7 +15142,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14331
15142
  info,
14332
15143
  resolver,
14333
15144
  options?.recovered === true,
14334
- options?.fecSbn
15145
+ options?.fecSbn,
15146
+ options?.fecSbnFirst
14335
15147
  );
14336
15148
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
14337
15149
  }
@@ -14424,7 +15236,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
14424
15236
  info,
14425
15237
  resolver,
14426
15238
  options?.recovered === true,
14427
- options?.fecSbn
15239
+ options?.fecSbn,
15240
+ options?.fecSbnFirst
14428
15241
  );
14429
15242
  if (outcome.record !== void 0) return outcome.record;
14430
15243
  return this.#drop(outcome.reason);
@@ -14444,7 +15257,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14444
15257
  * attribution exists to keep readable. Leaving the choice at the call site
14445
15258
  * is what keeps both true.
14446
15259
  */
14447
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
15260
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
14448
15261
  const timing = resolver.sampleTiming(
14449
15262
  combined.mpuSequenceNumber,
14450
15263
  combined.movieFragmentSequenceNumber,
@@ -14461,6 +15274,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14461
15274
  );
14462
15275
  if (!meta) return { reason: "combined-meta-build-failed" };
14463
15276
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
15277
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
14464
15278
  if (!resolver.consumeSample(
14465
15279
  combined.mpuSequenceNumber,
14466
15280
  combined.movieFragmentSequenceNumber,
@@ -14629,6 +15443,10 @@ var MmtpContainerParser = class _MmtpContainerParser {
14629
15443
  }
14630
15444
  this.#emitFrame(data, meta);
14631
15445
  }
15446
+ /** Whether FT=1 metadata already names this sample, without claiming it. */
15447
+ hasAuthoredTimingFor(packetId, mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber, catalogTrackName) {
15448
+ return this.#timingResolver(this.#streamKey(packetId, catalogTrackName), packetId, false)?.sampleTiming(mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber) != null;
15449
+ }
14632
15450
  /**
14633
15451
  * Claim and return the authored timing for a recovered sample. Recovery does
14634
15452
  * not pass through the ordinary `feed()` completion path, so it must retire
@@ -14690,6 +15508,9 @@ var MmtpContainerParser = class _MmtpContainerParser {
14690
15508
  for (const { sequencer } of this.#sequencers.values()) sequencer.discard();
14691
15509
  this.#sequencers.clear();
14692
15510
  this.#fecSequencer?.discard();
15511
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
15512
+ for (const head of awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
15513
+ }
14693
15514
  this.#timingStreams.clear();
14694
15515
  this.#pendingTimingSamples = 0;
14695
15516
  this.#reliableMoqStartupGate.clear();
@@ -14708,10 +15529,23 @@ var MmtpContainerParser = class _MmtpContainerParser {
14708
15529
  return resolver;
14709
15530
  }
14710
15531
  #awaitTiming(streamKey, head) {
14711
- const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
14712
- if (!awaitingTiming) return;
15532
+ const state = this.#timingStreams.get(streamKey);
15533
+ if (!state) return;
15534
+ if (!head.options?.recovered) {
15535
+ const kept = state.awaitingTiming.filter((queued) => !queued.options?.recovered || queued.sequenceNumber !== head.sequenceNumber);
15536
+ this.#recoveredHeadsAwaitingTiming.superseded += state.awaitingTiming.length - kept.length;
15537
+ state.awaitingTiming = kept;
15538
+ }
15539
+ const awaitingTiming = state.awaitingTiming;
14713
15540
  awaitingTiming.push(head);
14714
- if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
15541
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming.held++;
15542
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) {
15543
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
15544
+ }
15545
+ }
15546
+ /** Count a recovered head leaving the queue other than by replay or its source copy. */
15547
+ #leaveAwaitingTiming(head, outcome) {
15548
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming[outcome]++;
14715
15549
  }
14716
15550
  /**
14717
15551
  * Feed again the heads whose timing the FT=1 just admitted declares. That
@@ -14739,6 +15573,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
14739
15573
  const state = this.#timingStreams.get(streamKey);
14740
15574
  if (!state) return;
14741
15575
  this.#timingStreams.delete(streamKey);
15576
+ for (const head of state.awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
14742
15577
  this.#pendingTimingSamples -= state.resolver.pendingSampleCount;
14743
15578
  if (this.#pendingTimingSamples < 0) {
14744
15579
  throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");
@@ -17944,7 +18779,18 @@ function keyframeOverlaySsId(header) {
17944
18779
  if (ext?.type !== KEYFRAME_OVERLAY_EXTENSION_TYPE || ext.data.length !== 4) return void 0;
17945
18780
  return new DataView(ext.data.buffer, ext.data.byteOffset, 4).getUint32(0);
17946
18781
  }
18782
+ function overlayBaseSsId(anchor, overlaySsId, restoredPsn, headerPsn) {
18783
+ if (anchor.baseSsId === void 0 || headerPsn !== restoredPsn) return void 0;
18784
+ return serial32Add(anchor.baseSsId, overlaySsId - anchor.overlaySsId | 0);
18785
+ }
18786
+ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
18787
+ if (offset === void 0 || offset !== unstampedOffset) return void 0;
18788
+ return headerPsn + offset >>> 0;
18789
+ }
18790
+ var OVERLAY_ROUTED_LIMIT = 1024;
18791
+ var OVERLAY_PENDING_LIMIT = 256;
17947
18792
  var OVERLAY_OFFSET_MPUS = 16;
18793
+ var OVERLAY_REBUILT_LIMIT = 256;
17948
18794
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
17949
18795
  function assertStreamIdentity(role, stream) {
17950
18796
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -18055,6 +18901,7 @@ var MmtpRouter = class {
18055
18901
  #provenance = /* @__PURE__ */ new Map();
18056
18902
  #onFlowProtected = null;
18057
18903
  #unadmittedListedDrops = 0;
18904
+ #admittedSourceDatagrams = 0;
18058
18905
  #unlistedRepairSetAside = 0;
18059
18906
  #assistBlocks = /* @__PURE__ */ new Map();
18060
18907
  #assistFailures = /* @__PURE__ */ new Map();
@@ -18111,6 +18958,26 @@ var MmtpRouter = class {
18111
18958
  * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
18112
18959
  */
18113
18960
  #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18961
+ /**
18962
+ * Per stream, the SS_ID offset at which a base recovery last showed the
18963
+ * sender's own packet_sequence_number: a recovered packet's header psn
18964
+ * equal to its SS_ID minus that offset. While it equals the stream's
18965
+ * current offset, no hop re-stamps the stream, and a packet's protected psn
18966
+ * names its base SS_ID within unstampedBaseSsId's limits (joint decoding of
18967
+ * an MPU no member of which arrived).
18968
+ */
18969
+ #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18970
+ /**
18971
+ * The same, shown by the overlay alone, before any base recovery did: a
18972
+ * packet it rebuilt whose base copy carries its protected psn
18973
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
18974
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
18975
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
18976
+ * make the base drop a late base copy of a keyframe the overlay never
18977
+ * finished, and lift a block's late-source cut, which nothing before
18978
+ * this offset did.
18979
+ */
18980
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18114
18981
  /**
18115
18982
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
18116
18983
  * not parsed, typically because its overlap copy was parsed first
@@ -18156,6 +19023,8 @@ var MmtpRouter = class {
18156
19023
  // end: a synchronous recovery completes its block BEFORE routing the
18157
19024
  // recovered frames, and releasing a held gap in between would strand them.
18158
19025
  #fecPokeDepth = 0;
19026
+ /** FecReleaseGate.wakeAt timers, by media stream key. */
19027
+ #fecWakes = /* @__PURE__ */ new Map();
18159
19028
  #pendingFecPokes = /* @__PURE__ */ new Map();
18160
19029
  // ── Phase 14: per-role packetId dispatch (D-26, D-27, D-28) ───────
18161
19030
  /** Maps packetId → TrackRole. Default: 'single' when absent (legacy path). */
@@ -18180,7 +19049,9 @@ var MmtpRouter = class {
18180
19049
  recovered: 0,
18181
19050
  restarts: 0,
18182
19051
  unsequencedDropped: 0,
18183
- protectedDropped: 0
19052
+ protectedDropped: 0,
19053
+ baseFed: 0,
19054
+ baseUndetermined: 0
18184
19055
  };
18185
19056
  /** Callback fired when a delta-track FEC block completes or fails. */
18186
19057
  #onDeltaBlockCompleteCb = null;
@@ -18353,7 +19224,7 @@ var MmtpRouter = class {
18353
19224
  const cb = this.#getFrameCallback(packetId);
18354
19225
  if (isVideo && !assembler) {
18355
19226
  if (frameMeta.recovered) {
18356
- this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb);
19227
+ this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb, meta.fecSbn);
18357
19228
  } else {
18358
19229
  this.#routeDirectSourceVideo(packetId, data, frameMeta, cb);
18359
19230
  }
@@ -18386,13 +19257,18 @@ var MmtpRouter = class {
18386
19257
  this.#onDeltaBlockCompleteCb?.(packetId, false);
18387
19258
  }
18388
19259
  };
18389
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
19260
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
18390
19261
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
18391
19262
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
18392
19263
  this.#onDeltaBlockCompleteCb?.(packetId, true);
18393
19264
  }
18394
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
18395
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19265
+ if (span === void 0) {
19266
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19267
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
19268
+ } else {
19269
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
19270
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
19271
+ }
18396
19272
  };
18397
19273
  }
18398
19274
  }
@@ -18437,8 +19313,9 @@ var MmtpRouter = class {
18437
19313
  }
18438
19314
  /**
18439
19315
  * FEC-recovered source symbols whose reconstructed header named a
18440
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
18441
- * a hop re-stamped the sequence after the sender protected the packet.
19316
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
19317
+ * or, rebuilt by the overlay, than their base copy carries: a hop
19318
+ * re-stamped the sequence after the sender protected the packet.
18442
19319
  */
18443
19320
  get restampedRecoveredSequenceCount() {
18444
19321
  return this.#restampedRecoveredSeqs;
@@ -18617,6 +19494,7 @@ var MmtpRouter = class {
18617
19494
  enableMseAssembler(packetId, config, catalogTrackName) {
18618
19495
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
18619
19496
  const previous = this.#mseAssemblers.get(assemblerKey);
19497
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
18620
19498
  if (previous) {
18621
19499
  previous.flush();
18622
19500
  previous.dispose();
@@ -18743,6 +19621,10 @@ var MmtpRouter = class {
18743
19621
  get keyframeOverlayStats() {
18744
19622
  return { ...this.#overlayStats };
18745
19623
  }
19624
+ /** Recovered FT=2 heads held for their FT=1, and how each left the wait (BLO-53369). */
19625
+ get recoveredHeadsAwaitingTiming() {
19626
+ return this.#parser.recoveredHeadsAwaitingTiming;
19627
+ }
18746
19628
  #isOverlayRepair(repairPacketId, repairTrackName) {
18747
19629
  return this.#overlayLegs.has(repairPacketId) || repairTrackName !== void 0 && this.#overlayRepairNames.has(repairTrackName);
18748
19630
  }
@@ -18763,7 +19645,8 @@ var MmtpRouter = class {
18763
19645
  fec,
18764
19646
  k,
18765
19647
  offsets: /* @__PURE__ */ new Map(),
18766
- moqBlocks: /* @__PURE__ */ new Set()
19648
+ moqBlocks: /* @__PURE__ */ new Set(),
19649
+ rebuilt: /* @__PURE__ */ new Map()
18767
19650
  };
18768
19651
  this.#overlays.set(repairPacketId, inst);
18769
19652
  return () => {
@@ -18793,12 +19676,18 @@ var MmtpRouter = class {
18793
19676
  */
18794
19677
  resetKeyframeOverlays(sourcePacketId, catalogTrackName) {
18795
19678
  for (const inst of this.#overlaysForSource(sourcePacketId, catalogTrackName)) this.#resetOverlay(inst);
19679
+ for (const [name, stream] of this.#streams.get(sourcePacketId) ?? []) {
19680
+ if (catalogTrackName !== void 0 && name !== catalogTrackName) continue;
19681
+ stream.overlayToBase.routed.clear();
19682
+ stream.overlayToBase.pending.clear();
19683
+ }
18796
19684
  }
18797
19685
  #resetOverlay(inst) {
18798
19686
  inst.fec.resetTrack(inst.repairPacketId, inst.streamName);
18799
19687
  inst.last = void 0;
18800
19688
  inst.offsets.clear();
18801
19689
  inst.moqBlocks.clear();
19690
+ inst.rebuilt.clear();
18802
19691
  }
18803
19692
  #overlaysForSource(sourcePacketId, catalogTrackName) {
18804
19693
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -18849,18 +19738,33 @@ var MmtpRouter = class {
18849
19738
  * A source packet that carries a 0x8B01 overlay SS_ID is also a symbol of
18850
19739
  * every overlay installed for its source, at that SS_ID, with the bytes the
18851
19740
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
18852
- * included (7.1, 7.4.3).
18853
- */
18854
- #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source) {
19741
+ * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
19742
+ * FEC reads it.
19743
+ *
19744
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
19745
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
19746
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
19747
+ * the stream unstamped at the SS_ID offset it states, for the release gate
19748
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
19749
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
19750
+ */
19751
+ #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
18855
19752
  if (this.#overlays.size === 0) return;
18856
19753
  const ssId = keyframeOverlaySsId(header);
18857
19754
  if (ssId === void 0) return;
19755
+ let rebuiltPsn;
18858
19756
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
18859
19757
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
19758
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
19759
+ inst.rebuilt.delete(ssId);
18860
19760
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
18861
19761
  if (identity !== null) {
18862
19762
  inst.offsets.delete(identity.mpuSequenceNumber);
18863
- inst.offsets.set(identity.mpuSequenceNumber, ssId - sequenceNumber >>> 0);
19763
+ inst.offsets.set(identity.mpuSequenceNumber, {
19764
+ psnOffset: ssId - sequenceNumber >>> 0,
19765
+ overlaySsId: ssId,
19766
+ ...baseSsId === void 0 ? {} : { baseSsId }
19767
+ });
18864
19768
  if (inst.offsets.size > OVERLAY_OFFSET_MPUS) inst.offsets.delete(inst.offsets.keys().next().value);
18865
19769
  }
18866
19770
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -18882,6 +19786,14 @@ var MmtpRouter = class {
18882
19786
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
18883
19787
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
18884
19788
  }
19789
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
19790
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
19791
+ if (rebuiltPsn !== sequenceNumber) {
19792
+ this.#restampedRecoveredSeqs++;
19793
+ } else if (baseSsId !== void 0) {
19794
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19795
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
19796
+ }
18885
19797
  }
18886
19798
  #noteOverlayMoqBlock(inst, blockStart) {
18887
19799
  inst.moqBlocks.add(blockStart);
@@ -18915,11 +19827,16 @@ var MmtpRouter = class {
18915
19827
  }
18916
19828
  /**
18917
19829
  * Route an overlay-recovered block's packets as source media of the
18918
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
18919
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
18920
- * base re-stamp, no block advance. Each packet's wire sequence is restored
18921
- * from its keyframe's own offset; without one, a stream the base never
18922
- * re-stamped keeps the header's sequence and any other drops the packet.
19830
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
19831
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
19832
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
19833
+ * base FEC recovered does, so it waits behind base frames still in flight,
19834
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
19835
+ * longer than unanchored; one whose base SS_ID is undetermined has no
19836
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
19837
+ * advance. Each packet's wire sequence is restored from its keyframe's own
19838
+ * offset; without one, a stream the base never re-stamped keeps the
19839
+ * header's sequence and any other drops the packet.
18923
19840
  */
18924
19841
  #routeOverlayRecovered(inst, blockStart, recovered) {
18925
19842
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -18939,22 +19856,139 @@ var MmtpRouter = class {
18939
19856
  const streamKey = this.#mediaStreamKey(sourcePacketId, sourceName);
18940
19857
  const restamped = this.#restampedStreams.has(streamKey);
18941
19858
  const restored = /* @__PURE__ */ new Set();
19859
+ const baseSsIds = /* @__PURE__ */ new Map();
19860
+ const gateOnly = /* @__PURE__ */ new Set();
18942
19861
  const symbols = result.symbols.flatMap((sym) => {
18943
- const offset = inst.offsets.get(sym.fragment.mpuSequenceNumber);
18944
- if (offset !== void 0) {
18945
- const packetSequenceNumber = serial32Add(blockStart, sym.index) - offset >>> 0;
19862
+ const overlaySsId = serial32Add(blockStart, sym.index);
19863
+ const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
19864
+ if (anchor !== void 0) {
19865
+ const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
18946
19866
  restored.add(packetSequenceNumber);
18947
- return [{ ...sym, packetSequenceNumber }];
19867
+ const out = { ...sym, packetSequenceNumber };
19868
+ const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
19869
+ if (baseSsId !== void 0) {
19870
+ baseSsIds.set(sym.index, baseSsId);
19871
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19872
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
19873
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
19874
+ }
19875
+ }
19876
+ return [out];
19877
+ }
19878
+ if (!restamped) {
19879
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
19880
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
19881
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
19882
+ if (baseSsId !== void 0) {
19883
+ baseSsIds.set(sym.index, baseSsId);
19884
+ if (fedSsId === void 0) gateOnly.add(sym.index);
19885
+ } else {
19886
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
19887
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
19888
+ }
19889
+ return [sym];
18948
19890
  }
18949
- if (!restamped) return [sym];
18950
19891
  this.#overlayStats.unsequencedDropped++;
18951
19892
  return [];
18952
19893
  });
18953
19894
  this.#overlayStats.recovered++;
19895
+ const mpuFirst = /* @__PURE__ */ new Map();
19896
+ for (const sym of symbols) {
19897
+ const ssId = baseSsIds.get(sym.index);
19898
+ const mpu = sym.fragment.mpuSequenceNumber;
19899
+ const first = mpuFirst.get(mpu);
19900
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
19901
+ }
19902
+ const firstSsIds = /* @__PURE__ */ new Map();
19903
+ for (const sym of symbols) {
19904
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
19905
+ }
18954
19906
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
18955
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
19907
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
19908
+ baseSsIds,
19909
+ firstSsIds
18956
19910
  });
18957
19911
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
19912
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
19913
+ }
19914
+ /**
19915
+ * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
19916
+ * its base block too, once its base SS_ID is determined (overlayBaseSsId,
19917
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
19918
+ * base recovery showed; `baseSsIds` holds no other),
19919
+ * so it is fed to the base decoder as a rebuilt source
19920
+ * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
19921
+ * fewer to solve, and its repair can recover the block's other packets.
19922
+ * A base block no repair has stated yet takes it when one does
19923
+ * (#feedPendingRebuilt).
19924
+ *
19925
+ * The overlay route already handled each packet fed (delivered it, or
19926
+ * held an untimed head for its FT=1), so a base recovery routes none of
19927
+ * them again (#routeVerifiedFecSymbols): a second recovered copy of a
19928
+ * held head would wait in the parser for timing its first copy consumed.
19929
+ * Only an overlay block decoded from multicast symbols alone is fed: with
19930
+ * a MoQ symbol in it, the base block's recovery would depend on bytes
19931
+ * that crossed no multicast socket, which the provenance counted from the
19932
+ * block's own arrivals cannot show.
19933
+ */
19934
+ #feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds) {
19935
+ const fec = this.#fecManager;
19936
+ const owner = inst.leg.sourcePacketId;
19937
+ const name = inst.leg.sourceCatalogTrackName;
19938
+ if (!fec?.feedRebuiltSourceSymbol || inst.moqBlocks.has(blockStart)) return;
19939
+ if (this.#classifyPacketId(owner) === null || fec.isTrackConfigured?.(owner) === false) return;
19940
+ const { duplicates, overlayToBase: { routed } } = this.#stream(owner, name);
19941
+ const feeds = [];
19942
+ for (const sym of symbols) {
19943
+ if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
19944
+ const ssId = baseSsIds.get(sym.index);
19945
+ if (ssId === void 0) {
19946
+ this.#overlayStats.baseUndetermined++;
19947
+ continue;
19948
+ }
19949
+ routed.delete(ssId);
19950
+ routed.add(ssId);
19951
+ if (routed.size > OVERLAY_ROUTED_LIMIT) routed.delete(routed.values().next().value);
19952
+ feeds.push([ssId, sym.rawSymbol]);
19953
+ }
19954
+ for (const [ssId, symbolData] of feeds) {
19955
+ if (this.#classifyPacketId(owner) === null) return;
19956
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
19957
+ }
19958
+ }
19959
+ /** Feed one rebuilt source to its base block, or keep it until a repair states that block. */
19960
+ #feedRebuiltToBase(owner, name, ssId, symbolData) {
19961
+ const fec = this.#fecManager;
19962
+ if (!fec?.feedRebuiltSourceSymbol) return;
19963
+ const coords = fec.locateIsoSource?.(owner, name, ssId);
19964
+ if (coords == null) {
19965
+ const pending = this.#stream(owner, name).overlayToBase.pending;
19966
+ pending.delete(ssId);
19967
+ pending.set(ssId, symbolData.slice());
19968
+ if (pending.size > OVERLAY_PENDING_LIMIT) pending.delete(pending.keys().next().value);
19969
+ return;
19970
+ }
19971
+ const fed = fec.feedRebuiltSourceSymbol(owner, ssId, symbolData, name);
19972
+ if (!fed.taken) return;
19973
+ this.#overlayStats.baseFed++;
19974
+ if (fed.recovered === null) return;
19975
+ const sbn = coords.sbn;
19976
+ this.#routeRecoveredBlock(sbn, fed.recovered, owner, name, () => {
19977
+ fec.cancelBlockTimeout(sbn, owner, name);
19978
+ fec.countRecovery(owner, sbn, name);
19979
+ fec.markBlockCompleted(sbn, owner, name);
19980
+ });
19981
+ }
19982
+ /** A repair stated `block`: the rebuilt sources that waited for it join it now. */
19983
+ #feedPendingRebuilt(owner, name, block) {
19984
+ const pending = this.#streams.get(owner)?.get(name)?.overlayToBase.pending;
19985
+ if (pending === void 0 || pending.size === 0) return;
19986
+ for (const [ssId, symbolData] of [...pending]) {
19987
+ if (this.#classifyPacketId(owner) === null) return;
19988
+ if (serial32Distance(block.start, ssId) >= block.length) continue;
19989
+ pending.delete(ssId);
19990
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
19991
+ }
18958
19992
  }
18959
19993
  /** fec-multicast-00 §6.6: report each base block whose RAP MFU fragments
18960
19994
  * the overlay restored, when the keyframe's FT=0 and FT=1 are held too. A
@@ -19094,6 +20128,10 @@ var MmtpRouter = class {
19094
20128
  get unadmittedListedDropCount() {
19095
20129
  return this.#unadmittedListedDrops;
19096
20130
  }
20131
+ /** 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. */
20132
+ get admittedSourceDatagramCount() {
20133
+ return this.#admittedSourceDatagrams;
20134
+ }
19097
20135
  /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
19098
20136
  get unlistedRepairSetAsideCount() {
19099
20137
  return this.#unlistedRepairSetAside;
@@ -19580,6 +20618,8 @@ var MmtpRouter = class {
19580
20618
  )) return;
19581
20619
  fec.noteBlockActivity?.(blockStart, ownerPacketId, catalogTrackName);
19582
20620
  fec.noteRepairGroupLength?.(blockStart, ownerPacketId, repair.rsbLength, catalogTrackName);
20621
+ this.#feedPendingRebuilt(ownerPacketId, catalogTrackName, placement.block);
20622
+ if (this.#classifyPacketId(ownerPacketId) === null) return;
19583
20623
  const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
19584
20624
  const recovered = fec.feedRepairSymbol(
19585
20625
  ownerPacketId,
@@ -19630,7 +20670,7 @@ var MmtpRouter = class {
19630
20670
  catalogTrackName
19631
20671
  )) continue;
19632
20672
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
19633
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
20673
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
19634
20674
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
19635
20675
  }
19636
20676
  if (payload.oversized) continue;
@@ -19717,6 +20757,8 @@ var MmtpRouter = class {
19717
20757
  this.#droppedPreSyncVideo.delete(streamKey);
19718
20758
  this.#latestVideoSeqByStream.delete(streamKey);
19719
20759
  this.#ssIdSeqOffsetByStream.delete(streamKey);
20760
+ this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
20761
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
19720
20762
  this.#multicastRapTwinByStream.delete(streamKey);
19721
20763
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
19722
20764
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -19843,6 +20885,12 @@ var MmtpRouter = class {
19843
20885
  * the outgoing stream stops. The hold is bounded by the incoming stream's
19844
20886
  * own RAP cadence, so no timer is involved.
19845
20887
  *
20888
+ * While the switch is staged, the FEC release gate lets a keyframe the
20889
+ * overlay rebuilt reach it, on either side, when the keyframe did before
20890
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
20891
+ * decides on what each side delivered, and the commit discards the gate's
20892
+ * frames of the outgoing stream.
20893
+ *
19846
20894
  * The commit is one synchronous transition inside the frame path: the
19847
20895
  * outgoing stream's already-admitted frames are released (its queued FEC
19848
20896
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -19893,6 +20941,9 @@ var MmtpRouter = class {
19893
20941
  droppedIncomingFrames: 0
19894
20942
  };
19895
20943
  this.#staged = state;
20944
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
20945
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
20946
+ }
19896
20947
  return {
19897
20948
  cancel: () => {
19898
20949
  if (this.#staged !== state) return false;
@@ -19975,7 +21026,17 @@ var MmtpRouter = class {
19975
21026
  */
19976
21027
  #routeParsedFrame(data, meta) {
19977
21028
  if (this.#classifyPacketId(meta.packetId) === null) return;
19978
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
21029
+ if (this.#staged !== null) {
21030
+ let consumed = false;
21031
+ this.#fecPokeDepth++;
21032
+ try {
21033
+ consumed = this.#interceptSwitchFrame(data, meta);
21034
+ } finally {
21035
+ this.#fecPokeDepth--;
21036
+ this.#flushPendingFecPokes();
21037
+ }
21038
+ if (consumed) return;
21039
+ }
19979
21040
  this.#deliverParsedFrame(data, meta);
19980
21041
  }
19981
21042
  #commitStreamSwitch(state, rap, reason) {
@@ -20024,6 +21085,8 @@ var MmtpRouter = class {
20024
21085
  this.#disposed = true;
20025
21086
  this.#staged = null;
20026
21087
  this.cancelKeyframeLostTimer();
21088
+ for (const { timer } of this.#fecWakes.values()) clearTimeout(timer);
21089
+ this.#fecWakes.clear();
20027
21090
  this.#parser.dispose();
20028
21091
  this.#streams.clear();
20029
21092
  this.#trackPacketCallbacks.clear();
@@ -20127,12 +21190,16 @@ var MmtpRouter = class {
20127
21190
  this.#parser.deferFecRelease(work);
20128
21191
  } finally {
20129
21192
  this.#fecPokeDepth--;
20130
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
20131
- const pokes = [...this.#pendingFecPokes.values()];
20132
- this.#pendingFecPokes.clear();
20133
- for (const poke of pokes) {
20134
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20135
- }
21193
+ this.#flushPendingFecPokes();
21194
+ }
21195
+ }
21196
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
21197
+ #flushPendingFecPokes() {
21198
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
21199
+ const pokes = [...this.#pendingFecPokes.values()];
21200
+ this.#pendingFecPokes.clear();
21201
+ for (const poke of pokes) {
21202
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
20136
21203
  }
20137
21204
  }
20138
21205
  }
@@ -20201,6 +21268,31 @@ var MmtpRouter = class {
20201
21268
  if (!fec?.terminalRetentionMsForPacket) return Infinity;
20202
21269
  return fec.terminalRetentionMsForPacket(packetId) ?? 0;
20203
21270
  },
21271
+ // Once no repair can fill a gap (FECManager.isoRepairlessWaitMs: only a
21272
+ // late source can), its frame waits the late-symbol allowance when the
21273
+ // gap holds no RAP an installed keyframe overlay could still rebuild:
21274
+ // lost deltas of one MPU (delta-lost), the tail of the MPU before a RAP
21275
+ // that opens the next one while MPU boundaries bound RAPs (rap-next,
21276
+ // unless the gap holds a stated block's loss: the overlay may rebuild
21277
+ // that MPU's FT=0, and the block's group then complete it), or
21278
+ // an audio gap. A gap that may hold one (rap-lost, rap-unknown, or any
21279
+ // other rap-next, whose gap may hold a whole MPU and the keyframe the
21280
+ // overlay protects) waits for that overlay's repair too (BLO-52085
21281
+ // D4). The FEC check comes first: most held gaps are not behind such a
21282
+ // span, and deciding one scans both frames' bitstreams.
21283
+ unrepairableWaitMs: (before, after, fromSbn, toSbn) => {
21284
+ const fec = this.#fecManager;
21285
+ const { packetId, catalogTrackName } = after.meta;
21286
+ const allowanceMs = fec?.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn);
21287
+ if (!fec || allowanceMs === void 0) return void 0;
21288
+ const decision = this.#decideGap(before, after, [], false);
21289
+ const mpu = before.meta.mpuSequenceNumber;
21290
+ const intoNextMpu = decision.reason === "rap-next" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu + 1 >>> 0 && fec.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
21291
+ if (decision.action === "stall" || decision.reason === "rap-next" && !intoNextMpu) {
21292
+ return fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, true);
21293
+ }
21294
+ return decision.reason === "rap-next" ? fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, true) : allowanceMs;
21295
+ },
20204
21296
  decide: (before, after, lostBlocks, discontinuity) => {
20205
21297
  const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
20206
21298
  this.#onFrameGap?.(decision);
@@ -20210,6 +21302,28 @@ var MmtpRouter = class {
20210
21302
  onRap: (packetId, catalogTrackName, ssId) => {
20211
21303
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
20212
21304
  },
21305
+ // One timer per stream, at the earliest wake asked: its drain re-arms
21306
+ // for the next frame still waiting.
21307
+ wakeAt: (packetId, catalogTrackName, atMs) => {
21308
+ if (this.#disposed) return;
21309
+ const key = this.#mediaStreamKey(packetId, catalogTrackName);
21310
+ const armed = this.#fecWakes.get(key);
21311
+ if (armed !== void 0 && armed.atMs <= atMs) return;
21312
+ if (armed !== void 0) clearTimeout(armed.timer);
21313
+ const timer = setTimeout(() => {
21314
+ this.#fecWakes.delete(key);
21315
+ this.#requestFecPoke(packetId, catalogTrackName);
21316
+ }, Math.max(0, Math.ceil(atMs - performance.now())));
21317
+ this.#fecWakes.set(key, { atMs, timer });
21318
+ },
21319
+ // A staged switch commits on when each side's frames reach it
21320
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
21321
+ // they did unanchored.
21322
+ releaseUnanchored: (packetId, catalogTrackName) => {
21323
+ const staged = this.#staged;
21324
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
21325
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
21326
+ },
20213
21327
  onReleased: (data, meta) => {
20214
21328
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
20215
21329
  const timing = meta.authoredTiming;
@@ -20237,7 +21351,7 @@ var MmtpRouter = class {
20237
21351
  #decideGap(before, after, lostBlocks, discontinuity) {
20238
21352
  const { packetId, catalogTrackName } = after.meta;
20239
21353
  const trackKind = this.#classifyPacketId(packetId) === false ? "audio" : "video";
20240
- const positionsTrusted = this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying";
21354
+ const positionsTrusted = this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying" && before.meta.movieFragmentSequenceNumber === after.meta.movieFragmentSequenceNumber;
20241
21355
  const mpuTrusted = this.#fecManager?.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
20242
21356
  const evidence = (frame) => {
20243
21357
  const timing = frame.meta.authoredTiming;
@@ -20351,6 +21465,7 @@ var MmtpRouter = class {
20351
21465
  const parsed = this.#parser.parsePacket(packet);
20352
21466
  if (!parsed) return;
20353
21467
  const info = parsed.info;
21468
+ if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
20354
21469
  if (source === "multicast" && !manifestAdmitted) {
20355
21470
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
20356
21471
  }
@@ -20632,7 +21747,8 @@ var MmtpRouter = class {
20632
21747
  parsed.header,
20633
21748
  info.sequenceNumber,
20634
21749
  info.rapFlag,
20635
- source
21750
+ source,
21751
+ fecPayloadId?.ssId
20636
21752
  );
20637
21753
  }
20638
21754
  }
@@ -20658,7 +21774,8 @@ var MmtpRouter = class {
20658
21774
  source: parserOptions?.source,
20659
21775
  deliveryProvenance: parserOptions?.deliveryProvenance,
20660
21776
  catalogTrackName: parserOptions?.catalogTrackName,
20661
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
21777
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
21778
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
20662
21779
  };
20663
21780
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
20664
21781
  else this.#parser.feed(packet, feedOptions);
@@ -20782,7 +21899,8 @@ var MmtpRouter = class {
20782
21899
  if (stream === void 0) {
20783
21900
  stream = {
20784
21901
  key: JSON.stringify([packetId, catalogTrackName ?? null]),
20785
- duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId))
21902
+ duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId)),
21903
+ overlayToBase: { routed: /* @__PURE__ */ new Set(), pending: /* @__PURE__ */ new Map() }
20786
21904
  };
20787
21905
  byName.set(catalogTrackName, stream);
20788
21906
  }
@@ -20897,8 +22015,16 @@ var MmtpRouter = class {
20897
22015
  this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
20898
22016
  this.#emitDirectVideo(packetId, data, meta, cb);
20899
22017
  }
20900
- #routeDirectRecoveredVideo(packetId, data, meta, cb) {
22018
+ #routeDirectRecoveredVideo(packetId, data, meta, cb, fecSbn) {
20901
22019
  const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);
22020
+ if (this.#isFecTrack(packetId)) {
22021
+ const high = this.#deliveredVideoHighWaterByStream.get(streamKey);
22022
+ if (fecSbn !== void 0 || high !== void 0 && authoredAdjacent(high, meta)) {
22023
+ this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
22024
+ this.#emitDirectVideo(packetId, data, meta, cb);
22025
+ return;
22026
+ }
22027
+ }
20902
22028
  this.#enqueueDirectRecoveredVideo(packetId, data, meta);
20903
22029
  const lastSourceTs = this.#lastDirectSourceVideoTsByStream.get(streamKey);
20904
22030
  this.#drainDirectRecoveredVideo(
@@ -21052,6 +22178,13 @@ var MmtpRouter = class {
21052
22178
  * frames by epoch only if pre-protection input ever matters.
21053
22179
  */
21054
22180
  #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete, assisted = false) {
22181
+ const overlayRouted = ownerPacketId == null ? void 0 : this.#streams.get(ownerPacketId)?.get(catalogTrackName)?.overlayToBase.routed;
22182
+ if (overlayRouted !== void 0 && overlayRouted.size > 0) {
22183
+ result = {
22184
+ ...result,
22185
+ symbols: result.symbols.filter((sym) => !overlayRouted.has(this.#fecAnchorForRecovered(blockId, sym.index)))
22186
+ };
22187
+ }
21055
22188
  const entry = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
21056
22189
  const receiver = entry === void 0 || entry === "ambiguous" ? entry : entry.receiver;
21057
22190
  const userAgent = !assisted && entry !== void 0 && entry !== "ambiguous" && entry.protected === true && entry.userAgent === true;
@@ -21108,7 +22241,12 @@ var MmtpRouter = class {
21108
22241
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
21109
22242
  if (ownerPacketId == null) return;
21110
22243
  if (this.#classifyPacketId(ownerPacketId) === null) return;
21111
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
22244
+ const fecSbnOf = (index) => {
22245
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
22246
+ const fecSbn = overlay.baseSsIds.get(index);
22247
+ const fecSbnFirst = overlay.firstSsIds.get(index);
22248
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
22249
+ };
21112
22250
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
21113
22251
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
21114
22252
  if (ssIdSeqOffset !== void 0) {
@@ -21116,7 +22254,10 @@ var MmtpRouter = class {
21116
22254
  ...result,
21117
22255
  symbols: result.symbols.map((sym) => {
21118
22256
  const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
21119
- if (wire === sym.packetSequenceNumber) return sym;
22257
+ if (wire === sym.packetSequenceNumber) {
22258
+ this.#unstampedSsIdSeqOffsetByStream.set(streamKey, ssIdSeqOffset);
22259
+ return sym;
22260
+ }
21120
22261
  this.#restampedRecoveredSeqs++;
21121
22262
  this.#restampedStreams.add(streamKey);
21122
22263
  return { ...sym, packetSequenceNumber: wire };
@@ -21152,6 +22293,29 @@ var MmtpRouter = class {
21152
22293
  }
21153
22294
  );
21154
22295
  }
22296
+ const untimedHead = (sym) => sym.fragmentType === 2 && sym.fragment.fragmentationIndicator === 1 && sym.fragment.movieFragmentSequenceNumber !== void 0 && sym.fragment.sampleNumber !== void 0 && !this.#parser.hasAuthoredTimingFor(
22297
+ ownerPacketId,
22298
+ sym.fragment.mpuSequenceNumber,
22299
+ sym.fragment.movieFragmentSequenceNumber,
22300
+ sym.fragment.sampleNumber,
22301
+ catalogTrackName
22302
+ );
22303
+ for (const sym of result.symbols) {
22304
+ if (!untimedHead(sym) || this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) continue;
22305
+ this.#feedViaParser(
22306
+ sym.rawSymbol,
22307
+ { packetId: ownerPacketId, sequenceNumber: sym.packetSequenceNumber },
22308
+ void 0,
22309
+ {
22310
+ skipFecPayloadId: true,
22311
+ recovered: true,
22312
+ deliveryProvenance,
22313
+ ...fecSbnOf(sym.index),
22314
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
22315
+ }
22316
+ );
22317
+ }
22318
+ result = { ...result, symbols: result.symbols.filter((sym) => !untimedHead(sym)) };
21155
22319
  const gated = this.#isFecTrack(ownerPacketId);
21156
22320
  const assembler = this.#mseAssemblerFor(ownerPacketId, catalogTrackName);
21157
22321
  if (assembler) {
@@ -22628,6 +23792,12 @@ function isNonNegativeSafeInteger(value) {
22628
23792
  function isSymbolCounts(value) {
22629
23793
  return isRecord(value) && hasExactKeys(value, ["multicast", "moq"]) && isNonNegativeSafeInteger(value["multicast"]) && isNonNegativeSafeInteger(value["moq"]);
22630
23794
  }
23795
+ function isSpanFailure(value) {
23796
+ if (!isRecord(value) || !hasExactKeys(value, ["length", "sources"])) return false;
23797
+ const length = value["length"];
23798
+ const sources = value["sources"];
23799
+ return Number.isSafeInteger(length) && length > 0 && isNonNegativeSafeInteger(sources) && sources < length;
23800
+ }
22631
23801
  function isNullableNonNegative(value) {
22632
23802
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
22633
23803
  }
@@ -22647,7 +23817,10 @@ function isRepairLifecycleEvent(value) {
22647
23817
  case "recovered":
22648
23818
  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"]);
22649
23819
  case "failed":
22650
- return hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]);
23820
+ return hasExactKeys(
23821
+ value,
23822
+ "span" in value ? ["version", "type", "block", "blockClass", "symbols", "span"] : ["version", "type", "block", "blockClass", "symbols"]
23823
+ ) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]) && (!("span" in value) || isSpanFailure(value["span"]));
22651
23824
  case "repair-preempted":
22652
23825
  case "repair-deferred":
22653
23826
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
@@ -22856,6 +24029,8 @@ var MulticastManager = class {
22856
24029
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
22857
24030
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
22858
24031
  #repairReleases = /* @__PURE__ */ new Map();
24032
+ /** Protected repair flows owned by each live repair-endpoint release. */
24033
+ #repairProvenanceFlows = /* @__PURE__ */ new Map();
22859
24034
  /** Each source's catalog keyframe overlay, from its `ok` binding. */
22860
24035
  #overlayBindings = /* @__PURE__ */ new Map();
22861
24036
  /** Installed overlay decoders (`setKeyframeOverlayDecoder`), by source. */
@@ -22913,7 +24088,7 @@ var MulticastManager = class {
22913
24088
  onPublisherRestart: (packetId, catalogTrackName) => {
22914
24089
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
22915
24090
  },
22916
- onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
24091
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass, span) => {
22917
24092
  const pathCount = this.#fec.blockPathCount(
22918
24093
  sbn,
22919
24094
  packetId,
@@ -22931,7 +24106,8 @@ var MulticastManager = class {
22931
24106
  symbols: {
22932
24107
  multicast: pathCount?.multicastSymbols ?? 0,
22933
24108
  moq: pathCount?.moqSymbols ?? 0
22934
- }
24109
+ },
24110
+ ...span === void 0 ? {} : { span }
22935
24111
  });
22936
24112
  },
22937
24113
  onFrameGap: (decision) => {
@@ -23019,6 +24195,11 @@ var MulticastManager = class {
23019
24195
  this.#fec.onBlockVanished = (_sbn, packetId, catalogTrackName) => {
23020
24196
  this.#statsFor(packetId, catalogTrackName).vanishedBlocks++;
23021
24197
  };
24198
+ this.#fec.keyframeOverlayTiming = (packetId, catalogTrackName) => {
24199
+ const binding = this.#overlayInstalls.has(packetId) ? this.#overlayBindings.get(packetId) : void 0;
24200
+ if (binding === void 0) return void 0;
24201
+ return catalogTrackName === void 0 || catalogTrackName === binding.sourceCatalogTrackName ? binding.geometry : void 0;
24202
+ };
23022
24203
  this.#fec.onDecoderUnavailable = (event) => {
23023
24204
  this.#emitRepairLifecycle({
23024
24205
  version: 2,
@@ -23521,6 +24702,9 @@ var MulticastManager = class {
23521
24702
  this.#transport.onFailback((reason) => {
23522
24703
  const joined = this.#provenanceJoin;
23523
24704
  if (joined !== null) this.#router.unprotectProvenanceFlow(joined.flow);
24705
+ for (const flows of this.#repairProvenanceFlows.values()) {
24706
+ for (const flow of flows) this.#router.unprotectProvenanceFlow(flow);
24707
+ }
23524
24708
  this.#onFailback?.(reason);
23525
24709
  });
23526
24710
  }
@@ -23555,6 +24739,12 @@ var MulticastManager = class {
23555
24739
  "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
23556
24740
  );
23557
24741
  }
24742
+ if (provenanceFlow !== void 0) {
24743
+ const flow = multicastProvenanceFlowKey(provenanceFlow);
24744
+ if ([...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
24745
+ throw new TypeError(`[MulticastManager] join: provenance flow already registered by a repair endpoint: ${flow}`);
24746
+ }
24747
+ }
23558
24748
  const staged = this.#renditionSwitch;
23559
24749
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
23560
24750
  this.configureFec(config);
@@ -23562,8 +24752,8 @@ var MulticastManager = class {
23562
24752
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
23563
24753
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
23564
24754
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
23565
- this.#releaseProvenanceJoin();
23566
24755
  const provenance = config.provenance;
24756
+ this.#releaseProvenanceJoin();
23567
24757
  const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
23568
24758
  const ingress = protectedTracks === void 0 ? void 0 : {
23569
24759
  tracks: Object.freeze(
@@ -23616,8 +24806,13 @@ var MulticastManager = class {
23616
24806
  * feeds the flow's receiver; media datagrams are held until one admits them.
23617
24807
  */
23618
24808
  #joinProvenance(provenance, ingress) {
24809
+ this.#router.registerProvenanceFlow(ingress, this.#provenanceReceiver(provenance));
24810
+ this.#hookFailback();
24811
+ this.#provenanceJoin = { flow: ingress.flow };
24812
+ }
24813
+ #provenanceReceiver(provenance) {
23619
24814
  const { flow, auth } = provenance;
23620
- const receiver = new BcProvenanceV2Receiver({
24815
+ return new BcProvenanceV2Receiver({
23621
24816
  ...provenance.receiver,
23622
24817
  // The caller's ctx when it passes one, else the catalog's: an explicit
23623
24818
  // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
@@ -23634,9 +24829,6 @@ var MulticastManager = class {
23634
24829
  maxAuthDelayMs: flow.maxAuthDelayMs,
23635
24830
  manifestTimerMs: flow.manifestTimerMs
23636
24831
  });
23637
- this.#router.registerProvenanceFlow(ingress, receiver);
23638
- this.#hookFailback();
23639
- this.#provenanceJoin = { flow: ingress.flow };
23640
24832
  }
23641
24833
  /** Un-protect: drop the flow's hold queues (no expiry counted). */
23642
24834
  #releaseProvenanceJoin() {
@@ -23667,8 +24859,25 @@ var MulticastManager = class {
23667
24859
  * callback delivers must come from a subscription opened on
23668
24860
  * `options.gateway`. A callback that also merges another source (a MoQ or
23669
24861
  * WebSocket repair feed) must not name a native provider here.
24862
+ *
24863
+ * An endpoint's `provenance` makes its group a protected flow of its own
24864
+ * (multicast-02 7.2.7), registered here and released with the group; its
24865
+ * records ride in band on the group's port. On the user-agent path a
24866
+ * flow-less repair group of a protected track is set aside, never read, so
24867
+ * a player joining a protected catalog's repair groups passes it.
23670
24868
  */
23671
24869
  joinRepairEndpoints(endpoints, provider, options) {
24870
+ for (const { provenance, flow, source, group, port } of endpoints) {
24871
+ if (provenance === void 0) continue;
24872
+ if (flow !== void 0) {
24873
+ throw new TypeError("[MulticastManager] joinRepairEndpoints: an endpoint names provenance or flow, never both");
24874
+ }
24875
+ if (!sameIpAddress(source, provenance.flow.source) || !sameIpAddress(group, provenance.flow.groupAddress) || port !== provenance.flow.port) {
24876
+ throw new RangeError(
24877
+ "[MulticastManager] joinRepairEndpoints: provenance flow (S, G, port) must match the endpoint's source, group and port"
24878
+ );
24879
+ }
24880
+ }
23672
24881
  const releases = [];
23673
24882
  let released = false;
23674
24883
  const safely = (each) => {
@@ -23678,17 +24887,36 @@ var MulticastManager = class {
23678
24887
  console.warn("[MulticastManager] repair group release failed", error);
23679
24888
  }
23680
24889
  };
24890
+ const usedFlows = new Set(endpoints.flatMap(({ flow }) => flow === void 0 ? [] : [flow]));
24891
+ const preparedProvenance = endpoints.map((endpoint) => {
24892
+ if (endpoint.provenance === void 0) return void 0;
24893
+ const flow = multicastProvenanceFlowKey(endpoint.provenance.flow);
24894
+ if (usedFlows.has(flow) || this.#provenanceJoin?.flow === flow || [...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
24895
+ throw new TypeError(`[MulticastManager] joinRepairEndpoints: provenance flow already registered: ${flow}`);
24896
+ }
24897
+ usedFlows.add(flow);
24898
+ return { flow, receiver: this.#provenanceReceiver(endpoint.provenance) };
24899
+ });
24900
+ const provenanceFlows = [];
23681
24901
  const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners.map((owner) => owner.instance !== "keyframe" ? owner : {
23682
24902
  ...owner,
23683
24903
  ownerTrackName: endpoint.tracks.find((t) => t.packetId === owner.ownerPacketId)?.name,
23684
24904
  repairTrackName: endpoint.tracks.find((t) => t.packetId === owner.packetId)?.name
23685
24905
  }));
23686
24906
  this.#applyRepairOwners(repairOwners);
23687
- for (const endpoint of endpoints) {
24907
+ for (const [index, endpoint] of endpoints.entries()) {
24908
+ const flow = endpoint.provenance === void 0 ? endpoint.flow : multicastProvenanceFlowKey(endpoint.provenance.flow);
23688
24909
  const ingress = {
23689
24910
  tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
23690
- ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
24911
+ ...flow === void 0 ? {} : { flow }
23691
24912
  };
24913
+ if (endpoint.provenance !== void 0) {
24914
+ const prepared = preparedProvenance[index];
24915
+ if (prepared === void 0) throw new Error("[MulticastManager] repair provenance preparation missing");
24916
+ this.#router.registerProvenanceFlow(ingress, prepared.receiver);
24917
+ provenanceFlows.push(prepared.flow);
24918
+ releases.push(() => this.#router.releaseProvenanceFlow(flow));
24919
+ }
23692
24920
  let sender;
23693
24921
  const feed = (packet, sourceAddress, ingressToFeed) => {
23694
24922
  if (released) return;
@@ -23714,10 +24942,11 @@ var MulticastManager = class {
23714
24942
  mode: endpoint.mode,
23715
24943
  amtRelay: endpoint.amtRelay,
23716
24944
  amtRelayPort: endpoint.amtRelayPort ?? (endpoint.amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : void 0),
24945
+ amtDiscovery: endpoint.amtDiscovery,
23717
24946
  packetIds: endpoint.packetIds,
23718
24947
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
23719
24948
  // A protected repair group's records ride in band on its port (7.2.3).
23720
- ...endpoint.flow === void 0 ? {} : { protected: true }
24949
+ ...flow === void 0 ? {} : { protected: true }
23721
24950
  }, ingress).then((joined) => {
23722
24951
  if (!joined && !released) fail(transport.lastJoinOutcome);
23723
24952
  });
@@ -23726,9 +24955,12 @@ var MulticastManager = class {
23726
24955
  if (released) return;
23727
24956
  released = true;
23728
24957
  this.#repairReleases.delete(release);
24958
+ this.#repairProvenanceFlows.delete(release);
23729
24959
  for (const each of releases.splice(0)) safely(each);
23730
24960
  };
23731
24961
  this.#repairReleases.set(release, repairOwners);
24962
+ this.#repairProvenanceFlows.set(release, provenanceFlows);
24963
+ if (provenanceFlows.length) this.#hookFailback();
23732
24964
  return release;
23733
24965
  }
23734
24966
  #applyRepairOwners(owners) {
@@ -24214,7 +25446,8 @@ var MulticastManager = class {
24214
25446
  blockProfile: parseFecBlockProfile(
24215
25447
  geometry2.blockProfile,
24216
25448
  `tracks[${JSON.stringify(track.name)}].fec keyframe overlay blockProfile`
24217
- )
25449
+ ),
25450
+ geometry: geometry2
24218
25451
  });
24219
25452
  }
24220
25453
  }
@@ -24253,7 +25486,7 @@ var MulticastManager = class {
24253
25486
  for (const [sourcePacketId, install] of [...this.#overlayInstalls]) {
24254
25487
  const before = this.#overlayBindings.get(sourcePacketId);
24255
25488
  const after = overlayBindings.get(sourcePacketId);
24256
- const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => after[key] === before[key]);
25489
+ const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => key === "geometry" || after[key] === before[key]);
24257
25490
  if (!same) install.dispose();
24258
25491
  else if (this.#router.hasKeyframeOverlay(after.repairPacketId)) this.#router.resetKeyframeOverlays(sourcePacketId);
24259
25492
  else install.reattach();
@@ -24310,10 +25543,12 @@ var MulticastManager = class {
24310
25543
  * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
24311
25544
  * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
24312
25545
  * pending hole and reported here, and `closeIsoHoles` must be called for it
24313
- * once its range FETCH ends (or none is sent).
25546
+ * once its range FETCH ends (or none is sent). `onExpired` is told of a
25547
+ * pending hole the stream runs past the locator's horizon: returning true,
25548
+ * the caller closes it (`closeIsoHoles`); otherwise it is discarded.
24314
25549
  */
24315
- onUndelimitedLoss(cb) {
24316
- this.#fec.setUndelimitedLossHandler(cb);
25550
+ onUndelimitedLoss(cb, onExpired) {
25551
+ this.#fec.setUndelimitedLossHandler(cb, onExpired ?? null);
24317
25552
  }
24318
25553
  /**
24319
25554
  * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
@@ -24549,7 +25784,8 @@ var MulticastManager = class {
24549
25784
  "stream" in event ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
24550
25785
  ...event,
24551
25786
  block: Object.freeze({ ...event.block }),
24552
- ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {}
25787
+ ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {},
25788
+ ..."span" in event && event.span !== void 0 ? { span: Object.freeze({ ...event.span }) } : {}
24553
25789
  }
24554
25790
  );
24555
25791
  if (this.#logRepairLifecycle) {