@blockcast/mmt-container 2.2.0-main.f480a7ede8b1 → 2.2.0-main.fde7aee36726

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 (137) hide show
  1. package/README.md +5 -2
  2. package/dist/block-policy.d.ts +88 -16
  3. package/dist/block-policy.d.ts.map +1 -1
  4. package/dist/block-policy.js +164 -56
  5. package/dist/block-policy.js.map +3 -3
  6. package/dist/browser-runtime.js +2163 -303
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +40 -1
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +163 -10
  11. package/dist/carp-catalog.js.map +4 -4
  12. package/dist/catalog-fec-params.d.ts +1 -1
  13. package/dist/catalog-fec-params.d.ts.map +1 -1
  14. package/dist/catalog-fec-params.js +48 -1
  15. package/dist/catalog-fec-params.js.map +3 -3
  16. package/dist/catalog-network-source.js +34 -0
  17. package/dist/catalog-network-source.js.map +3 -3
  18. package/dist/cmaf-block-assembler.js +92 -1
  19. package/dist/cmaf-block-assembler.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 +68 -0
  24. package/dist/delivery-catalog.js.map +4 -4
  25. package/dist/delta-fallback-config.js +39 -1
  26. package/dist/delta-fallback-config.js.map +4 -4
  27. package/dist/fec-manager.d.ts +222 -21
  28. package/dist/fec-manager.d.ts.map +1 -1
  29. package/dist/fec-manager.js +875 -131
  30. package/dist/fec-manager.js.map +4 -4
  31. package/dist/fec-state.d.ts +17 -5
  32. package/dist/fec-state.d.ts.map +1 -1
  33. package/dist/fec-state.js +41 -1
  34. package/dist/fec-state.js.map +3 -3
  35. package/dist/fec-worker-setup.js +34 -0
  36. package/dist/fec-worker-setup.js.map +3 -3
  37. package/dist/held-layer-admission.js +34 -0
  38. package/dist/held-layer-admission.js.map +3 -3
  39. package/dist/index.d.ts +6 -5
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +9 -1
  42. package/dist/index.js.map +2 -2
  43. package/dist/iso-block-locator.d.ts +55 -13
  44. package/dist/iso-block-locator.d.ts.map +1 -1
  45. package/dist/iso-block-locator.js +142 -25
  46. package/dist/iso-block-locator.js.map +3 -3
  47. package/dist/media-router.js.map +1 -1
  48. package/dist/mfu-reassembler.js +34 -0
  49. package/dist/mfu-reassembler.js.map +3 -3
  50. package/dist/mmtp-container-parser.d.ts +72 -10
  51. package/dist/mmtp-container-parser.d.ts.map +1 -1
  52. package/dist/mmtp-container-parser.js +260 -18
  53. package/dist/mmtp-container-parser.js.map +3 -3
  54. package/dist/mmtp-container-parser.no-modules.js +411 -34
  55. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  56. package/dist/mmtp-decode-pipeline.js +260 -18
  57. package/dist/mmtp-decode-pipeline.js.map +3 -3
  58. package/dist/mmtp-fec-session.js +34 -0
  59. package/dist/mmtp-fec-session.js.map +3 -3
  60. package/dist/mmtp-mode-selection.d.ts +48 -0
  61. package/dist/mmtp-mode-selection.d.ts.map +1 -0
  62. package/dist/mmtp-mode-selection.js +79 -0
  63. package/dist/mmtp-mode-selection.js.map +7 -0
  64. package/dist/mmtp-router.d.ts +94 -16
  65. package/dist/mmtp-router.d.ts.map +1 -1
  66. package/dist/mmtp-router.js +754 -78
  67. package/dist/mmtp-router.js.map +4 -4
  68. package/dist/multicast-auth-catalog.js +42 -2
  69. package/dist/multicast-auth-catalog.js.map +3 -3
  70. package/dist/multicast-input.js +42 -2
  71. package/dist/multicast-input.js.map +3 -3
  72. package/dist/multicast-manager.d.ts +121 -4
  73. package/dist/multicast-manager.d.ts.map +1 -1
  74. package/dist/multicast-manager.js +1774 -248
  75. package/dist/multicast-manager.js.map +4 -4
  76. package/dist/multicast-transport.js +70 -2
  77. package/dist/multicast-transport.js.map +4 -4
  78. package/dist/multicast-unwrap.js +34 -0
  79. package/dist/multicast-unwrap.js.map +3 -3
  80. package/dist/no-modules.d.ts +1 -0
  81. package/dist/no-modules.d.ts.map +1 -1
  82. package/dist/no-modules.js +415 -35
  83. package/dist/no-modules.js.map +4 -4
  84. package/dist/phase14-catalog-override.d.ts +2 -1
  85. package/dist/phase14-catalog-override.d.ts.map +1 -1
  86. package/dist/phase14-catalog-override.js +69 -2
  87. package/dist/phase14-catalog-override.js.map +3 -3
  88. package/dist/repair-fetch.d.ts +38 -8
  89. package/dist/repair-fetch.d.ts.map +1 -1
  90. package/dist/repair-fetch.js +336 -27
  91. package/dist/repair-fetch.js.map +3 -3
  92. package/dist/repair-layer-subscriptions.js +34 -0
  93. package/dist/repair-layer-subscriptions.js.map +3 -3
  94. package/dist/signaling.js +34 -0
  95. package/dist/signaling.js.map +3 -3
  96. package/dist/timestamp-codec.js +34 -0
  97. package/dist/timestamp-codec.js.map +3 -3
  98. package/dist/track-session.d.ts.map +1 -1
  99. package/dist/track-session.js +1 -0
  100. package/dist/track-session.js.map +2 -2
  101. package/dist/wasm-mfu-reassembler.js +34 -0
  102. package/dist/wasm-mfu-reassembler.js.map +3 -3
  103. package/dist/wasm-mmtp-container-parser.js +260 -18
  104. package/dist/wasm-mmtp-container-parser.js.map +3 -3
  105. package/package.json +5 -5
  106. package/schemas/catalog.schema.json +2 -2
  107. package/src/block-policy.ts +324 -83
  108. package/src/carp-catalog.ts +165 -5
  109. package/src/catalog-fec-params.ts +1 -0
  110. package/src/codec-utils.ts +121 -1
  111. package/src/fec-manager.ts +835 -66
  112. package/src/fec-state.ts +21 -5
  113. package/src/index.ts +25 -0
  114. package/src/iso-block-locator.ts +148 -31
  115. package/src/mmtp-container-parser.ts +259 -24
  116. package/src/mmtp-mode-selection.ts +80 -0
  117. package/src/mmtp-router.ts +774 -86
  118. package/src/multicast-manager.ts +262 -16
  119. package/src/no-modules.ts +3 -0
  120. package/src/phase14-catalog-override.ts +14 -3
  121. package/src/repair-fetch.ts +389 -50
  122. package/src/track-session.ts +3 -0
  123. package/test-vectors/catalog/README.md +36 -2
  124. package/test-vectors/catalog/mmtp-siblings/ambiguous-sibling.json +158 -0
  125. package/test-vectors/catalog/mmtp-siblings/ladder-bitrate-only.json +231 -0
  126. package/test-vectors/catalog/mmtp-siblings/ladder-four-rungs.json +405 -0
  127. package/test-vectors/catalog/mmtp-siblings/ladder-other-names.json +231 -0
  128. package/test-vectors/catalog/mmtp-siblings/mmtp-mode-unknown.json +143 -0
  129. package/test-vectors/catalog/mmtp-siblings/multicast-endpoint-lists-datagram-track.json +143 -0
  130. package/test-vectors/catalog/mmtp-siblings/no-sibling.json +79 -0
  131. package/test-vectors/catalog/mmtp-siblings/rendition-mismatch.json +143 -0
  132. package/test-vectors/catalog/mmtp-siblings/stream-delivery-mode.json +143 -0
  133. package/test-vectors/catalog/mmtp-siblings/timescale-mismatch.json +143 -0
  134. package/test-vectors/catalog/mmtp-siblings/valid-pair.json +142 -0
  135. package/test-vectors/catalog/section-codes.json +3 -3
  136. package/test-vectors/catalog-validation.json +266 -7
  137. package/test-vectors/moq/mmtp-mode-selection.json +259 -0
@@ -311,6 +311,40 @@ var RUNTIME_FEC_RECEIVER = Object.freeze({
311
311
  overlays: true
312
312
  });
313
313
 
314
+ // ../mmt-base/dist/mmtp-siblings.js
315
+ var MMTP_MODES = Object.freeze(["mfu", "mfu-datagram"]);
316
+ var MMTP_SIBLING_HARD_FIELDS = Object.freeze([
317
+ "namespace",
318
+ "timescale",
319
+ "presentationAnchorTicks",
320
+ "groupDuration"
321
+ ]);
322
+ var MMTP_SIBLING_RENDITION_FIELDS = Object.freeze([
323
+ "codec",
324
+ "width",
325
+ "height",
326
+ "framerate",
327
+ "bitrate",
328
+ "samplerate",
329
+ "channelConfig",
330
+ "lang"
331
+ ]);
332
+ var MMTP_SIBLING_SOFT_FIELDS = Object.freeze([
333
+ "initRef",
334
+ "keyframeIntervalMs",
335
+ "keyframeIntervalTicks",
336
+ "isLive",
337
+ "altGroup"
338
+ ]);
339
+
340
+ // ../mmt-base/dist/datagram-leg-size.js
341
+ var DATAGRAM_LEG_UDP_FLOOR = 1200;
342
+ var DATAGRAM_LEG_QUIC_WT_FRAMING = 48;
343
+ var DATAGRAM_LEG_OBJECT_HEADER = 13;
344
+ var DATAGRAM_LEG_RELAY_ROOM = 16;
345
+ var DATAGRAM_LEG_DATAGRAM_MAX = DATAGRAM_LEG_UDP_FLOOR - DATAGRAM_LEG_QUIC_WT_FRAMING;
346
+ var DATAGRAM_LEG_BODY_MAX = DATAGRAM_LEG_DATAGRAM_MAX - DATAGRAM_LEG_OBJECT_HEADER - DATAGRAM_LEG_RELAY_ROOM;
347
+
314
348
  // src/iso-block-locator.ts
315
349
  var IsoBlockLocator = class _IsoBlockLocator {
316
350
  /**
@@ -327,6 +361,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
327
361
  this.#heldEvicted = 0;
328
362
  /** Pending holes (see `deferIncompleteGaps`): unstated, sources still held. */
329
363
  this.#holes = [];
364
+ /** Holes the horizon passed while pending: sources held until closed. */
365
+ this.#expired = [];
366
+ /** Of `#expired`, those `takeExpiredHoles` has not handed out yet. */
367
+ this.#newlyExpired = [];
368
+ /**
369
+ * Spans closed from expired holes: behind the horizon, so kept only for
370
+ * `locate` while their sources are fed, until the next retirement.
371
+ */
372
+ this.#closedBehind = [];
330
373
  /**
331
374
  * Keep a gap that is missing a source as a pending hole rather than a span,
332
375
  * so a repair FETCHed for it (draft-ramadan-moq-fec §7.5) can still state
@@ -350,6 +393,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
350
393
  #newest;
351
394
  #newestSource;
352
395
  #holes;
396
+ #expired;
397
+ #newlyExpired;
398
+ #closedBehind;
353
399
  static #checkedRetention(retentionBlocks) {
354
400
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
355
401
  throw new Error(
@@ -419,17 +465,29 @@ var IsoBlockLocator = class _IsoBlockLocator {
419
465
  }
420
466
  /** The known block or span containing `ssId`, with its ESI. */
421
467
  locate(ssId) {
422
- for (let i = this.#blocks.length - 1; i >= 0; i--) {
423
- const block = this.#blocks[i];
424
- if (isoBlockContains(block.start, block.length, ssId)) {
425
- return { block, esi: serial32Distance(block.start, ssId) };
468
+ for (const blocks of [this.#blocks, this.#closedBehind]) {
469
+ for (let i = blocks.length - 1; i >= 0; i--) {
470
+ const block = blocks[i];
471
+ if (isoBlockContains(block.start, block.length, ssId)) {
472
+ return { block, esi: serial32Distance(block.start, ssId) };
473
+ }
426
474
  }
427
475
  }
428
476
  return null;
429
477
  }
430
- /** Number of pending holes. */
478
+ /** Number of holes not closed yet, pending or past the horizon. */
431
479
  get holeCount() {
432
- return this.#holes.length;
480
+ return this.#holes.length + this.#expired.length;
481
+ }
482
+ /**
483
+ * The pending holes the horizon has passed since the last call, in the
484
+ * order it passed them. Each is no longer pending: no repair states a block
485
+ * in it (that repair is `stale`, as for a span the horizon retired) and the
486
+ * release gate does not wait for it. Its owner must close it
487
+ * (`closeHolesWithin`), which turns it into a span that is not kept here.
488
+ */
489
+ takeExpiredHoles() {
490
+ return this.#newlyExpired.splice(0);
433
491
  }
434
492
  /** The stated block (never a span) ending exactly at `end`. */
435
493
  blockEndingAt(end) {
@@ -482,12 +540,42 @@ var IsoBlockLocator = class _IsoBlockLocator {
482
540
  isHeld(ssId) {
483
541
  return this.#held.has(ssId);
484
542
  }
543
+ /** The payload held unplaced for `ssId`, if any. */
544
+ heldSource(ssId) {
545
+ return this.#held.get(ssId);
546
+ }
547
+ /**
548
+ * The SS_IDs strictly between `a` and `b` that no repair has delimited a
549
+ * block of yet: those from the coverage end on, or all of them before the
550
+ * first repair. `missing` is the highest of them no source is held for;
551
+ * absent, every one of them arrived (C.5.2: SS_IDs are consecutive). Null
552
+ * when none lies past coverage. `flagged` is whether a source held among
553
+ * them satisfies `flag` (a RAP fragment, say): the held packets read as
554
+ * fec-multicast-00 Block Classification item 1 reads bounding packets.
555
+ */
556
+ undelimitedBetween(a, b, flag) {
557
+ if (!serial32Precedes(a, b) || serial32Distance(a, b) <= 1) return null;
558
+ const first = a + 1 >>> 0;
559
+ const end = this.#coverageEnd;
560
+ const start = end !== void 0 && serial32Precedes(first, end) ? end : first;
561
+ if (!serial32Precedes(start, b)) return null;
562
+ const length = serial32Distance(start, b);
563
+ const missing = this.#highestMissing(start, length);
564
+ let flagged = false;
565
+ for (let i = 0; flag !== void 0 && !flagged && i < length; i++) {
566
+ const payload = this.#held.get(serial32Add(start, i));
567
+ flagged = payload !== void 0 && flag(payload);
568
+ }
569
+ return missing === void 0 ? { start, flagged } : { start, missing, flagged };
570
+ }
485
571
  /**
486
572
  * Apply one repair symbol's `(SS_Start, SSB_length)`. The first repair of a
487
573
  * block states its range and places every held source in it; later repair
488
- * symbols of the same block change nothing. A range that contradicts a
489
- * known block (a different length, or an overlap with another block or a
490
- * span) fails closed: the repair symbol is dropped and no block changes.
574
+ * symbols of the same block change nothing. A repair whose range is exactly
575
+ * a repair-less span states that span's one block. A range that contradicts
576
+ * a known block (a different length, or an overlap with another block or
577
+ * with part of a span) fails closed: the repair symbol is dropped and no
578
+ * block changes.
491
579
  * A newly stated block retires behind its SS_Start (see the class note).
492
580
  * A block so far past `newest` that stating it would retire the position
493
581
  * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
@@ -506,7 +594,16 @@ var IsoBlockLocator = class _IsoBlockLocator {
506
594
  const known = this.blockAt(start);
507
595
  if (known !== void 0) {
508
596
  if (known.span) {
509
- return { status: "overlap", reason: `repair block ${start}+${length} falls inside a repair-less span` };
597
+ if (known.length === length) {
598
+ const block2 = { start, length, span: false };
599
+ this.#blocks[this.#blocks.indexOf(known)] = block2;
600
+ return { status: "placed", block: block2, placed: [] };
601
+ }
602
+ return length < known.length ? {
603
+ status: "overlap",
604
+ reason: `repair block ${start}+${length} is only the first block of repair-less span ${known.start}+${known.length}`,
605
+ ofSpan: known
606
+ } : { status: "overlap", reason: `repair block ${start}+${length} runs past repair-less span ${known.start}+${known.length}` };
510
607
  }
511
608
  if (known.length !== length) {
512
609
  return {
@@ -574,18 +671,28 @@ var IsoBlockLocator = class _IsoBlockLocator {
574
671
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
575
672
  }
576
673
  /**
577
- * Turn every pending hole inside `[start, start + length)` into a
578
- * repair-less span, claiming its held sources: its range FETCH ended, so
579
- * nothing more will state its blocks. Returns the spans, in SS_ID order.
674
+ * Turn every hole inside `[start, start + length)` into a repair-less span,
675
+ * claiming its held sources: its range FETCH ended, so nothing more will
676
+ * state its blocks. A hole the horizon passed (`takeExpiredHoles`) leaves a
677
+ * span that is not kept among the blocks, as the horizon would retire it at
678
+ * once; only `locate` finds it, until the next retirement, so its sources
679
+ * can be fed. Returns the spans, in SS_ID order.
580
680
  */
581
681
  closeHolesWithin(start, length) {
582
682
  const closed = [];
583
- for (const hole of [...this.#holes]) {
584
- if (!isoBlockContains(start, length, hole.start)) continue;
585
- this.#holes.splice(this.#holes.indexOf(hole), 1);
586
- const spanBlock = { start: hole.start, length: hole.length, span: true };
587
- closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
588
- this.#blocks.push(spanBlock);
683
+ for (const holes of [this.#holes, this.#expired]) {
684
+ for (const hole of [...holes]) {
685
+ if (!isoBlockContains(start, length, hole.start)) continue;
686
+ holes.splice(holes.indexOf(hole), 1);
687
+ const spanBlock = { start: hole.start, length: hole.length, span: true };
688
+ closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
689
+ if (holes === this.#holes) {
690
+ this.#blocks.push(spanBlock);
691
+ } else {
692
+ this.#closedBehind.push(spanBlock);
693
+ if (this.#newlyExpired.includes(hole)) this.#newlyExpired.splice(this.#newlyExpired.indexOf(hole), 1);
694
+ }
695
+ }
589
696
  }
590
697
  return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
591
698
  }
@@ -599,15 +706,17 @@ var IsoBlockLocator = class _IsoBlockLocator {
599
706
  return void 0;
600
707
  }
601
708
  /**
602
- * Retire every block and span whose last SS_ID, and every held source,
603
- * lies more than `retentionBlocks` blocks behind `position`, with the shared
604
- * lower-bound metric (`isoBlocksBehindLowerBound`) every ISO interleave
605
- * horizon uses. Returns the retired block starts.
709
+ * Retire every block and span whose last SS_ID, and every held source
710
+ * outside a hole, lies more than `retentionBlocks` blocks behind
711
+ * `position`, with the shared lower-bound metric (`isoBlocksBehindLowerBound`)
712
+ * every ISO interleave horizon uses; a pending hole so far behind expires
713
+ * (`takeExpiredHoles`). Returns the retired block starts.
606
714
  */
607
715
  retireBehind(position) {
608
716
  this.observe(position);
609
717
  const horizon = this.#retentionBlocks;
610
718
  const retired = [];
719
+ this.#closedBehind.length = 0;
611
720
  for (let i = this.#blocks.length - 1; i >= 0; i--) {
612
721
  const block = this.#blocks[i];
613
722
  const last = serial32Add(block.start, block.length - 1);
@@ -619,10 +728,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
619
728
  for (let i = this.#holes.length - 1; i >= 0; i--) {
620
729
  const hole = this.#holes[i];
621
730
  const last = serial32Add(hole.start, hole.length - 1);
622
- if (isoBlocksBehindLowerBound(last, position, this.#kMax) > horizon) this.#holes.splice(i, 1);
731
+ if (isoBlocksBehindLowerBound(last, position, this.#kMax) <= horizon) continue;
732
+ this.#holes.splice(i, 1);
733
+ this.#expired.push(hole);
734
+ this.#newlyExpired.push(hole);
623
735
  }
624
736
  for (const ssId of [...this.#held.keys()]) {
625
- if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon) this.#held.delete(ssId);
737
+ 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))) {
738
+ this.#held.delete(ssId);
739
+ }
626
740
  }
627
741
  return retired;
628
742
  }
@@ -630,6 +744,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
630
744
  reset() {
631
745
  this.#blocks.length = 0;
632
746
  this.#holes.length = 0;
747
+ this.#expired.length = 0;
748
+ this.#newlyExpired.length = 0;
749
+ this.#closedBehind.length = 0;
633
750
  this.#held.clear();
634
751
  this.#coverageEnd = void 0;
635
752
  this.#newest = void 0;
@@ -666,7 +783,7 @@ var INACTIVE = Object.freeze({
666
783
  // src/block-policy.ts
667
784
  import { deriveFecInterleaveDepth } from "@blockcast/mmt-fec";
668
785
  function keyframeIntervalMediaTicks(geometry, mediaTimescale) {
669
- if (geometry.trackKind !== "video" || geometry.mode !== "classifying") return null;
786
+ if (geometry.trackKind !== "video" || geometry.keyframeInterval === void 0) return null;
670
787
  if (!Number.isSafeInteger(mediaTimescale) || mediaTimescale <= 0) return null;
671
788
  const { ticks, timescale } = geometry.keyframeInterval;
672
789
  if (!Number.isSafeInteger(ticks) || !Number.isSafeInteger(timescale)) return null;
@@ -675,9 +792,15 @@ function keyframeIntervalMediaTicks(geometry, mediaTimescale) {
675
792
  if (scaled % divisor !== 0n) return null;
676
793
  return scaled / divisor;
677
794
  }
795
+ function keyframeInstantBetween(start, interval, from, to) {
796
+ const k = from >= start ? (from - start) / interval + 1n : 1n;
797
+ return start + k * interval <= to;
798
+ }
678
799
  function compareDataUnitStarts(a, b) {
679
- return a.movieFragment - b.movieFragment || a.idx - b.idx || a.offset - b.offset;
800
+ return a.movieFragment - b.movieFragment | 0 || a.idx - b.idx || a.offset - b.offset;
680
801
  }
802
+ var LATE_RAP_MAX_MPUS_BACK = 64;
803
+ var UNPLACED = { rapNotMpuStart: false };
681
804
  var BlockClassifier = class {
682
805
  #geometry;
683
806
  #mode;
@@ -700,8 +823,24 @@ var BlockClassifier = class {
700
823
  #mpuSbnSpans = /* @__PURE__ */ new Map();
701
824
  #dataUnitStarts = /* @__PURE__ */ new Map();
702
825
  #highestMpu = null;
703
- /** MPU → movie_fragment_sequence_number observed in it. */
704
- #mpuFragments = /* @__PURE__ */ new Map();
826
+ /**
827
+ * P3 layout, kept for the MPUs within the classification horizon and valid
828
+ * within one continuous SBN sequence (`noteSourceDiscontinuity`).
829
+ */
830
+ #mpus = /* @__PURE__ */ new Map();
831
+ /** An MPU of this sequence showed two movie fragments: each frame is one. */
832
+ #fragmentPerFrame = false;
833
+ /** A DU header of this sequence stated sample_number above 1. */
834
+ #multiSampleFragment = false;
835
+ /**
836
+ * The anchor received last, whether or not its MPU is still in the
837
+ * horizon. Each new anchor, and the anchor of every DU header's MPU, is
838
+ * checked against it.
839
+ */
840
+ #lastAnchor = null;
841
+ /** Two anchors were exactly G fragments per MPU apart. */
842
+ #fragmentsProven = false;
843
+ /** The first RAP released of the latest MPU a RAP was released in, recorded in every mode. */
705
844
  #lastRap = null;
706
845
  constructor(geometry) {
707
846
  this.#geometry = geometry;
@@ -731,7 +870,7 @@ var BlockClassifier = class {
731
870
  this.#geometry = geometry;
732
871
  this.#blocks.clear();
733
872
  this.#clearContiguityLedger();
734
- this.#mpuFragments.clear();
873
+ this.#clearMpuLayout();
735
874
  this.#lastRap = null;
736
875
  this.#mpuBoundsRaps = true;
737
876
  if (geometry.trackKind === "video" && geometry.mode === "all-protected") {
@@ -765,11 +904,14 @@ var BlockClassifier = class {
765
904
  /**
766
905
  * The stream's SBN sequence restarted (FECManager source discontinuity:
767
906
  * a publisher restart, or the SS_ID space wrapped). Authored order and SBN
768
- * order are comparable only within one continuous sequence, so the P1
769
- * ledger starts again.
907
+ * order are comparable only within one continuous sequence, and a
908
+ * restarted publisher numbers MPUs and movie fragments again, so the P1
909
+ * ledger and the P3 layout start again.
770
910
  */
771
911
  noteSourceDiscontinuity() {
772
912
  this.#clearContiguityLedger();
913
+ this.#clearMpuLayout();
914
+ this.#lastRap = null;
773
915
  }
774
916
  /** Register a block that exists without evidence (a vanished block). */
775
917
  touch(sbn) {
@@ -788,16 +930,16 @@ var BlockClassifier = class {
788
930
  if (this.#geometry.trackKind === "audio") return [];
789
931
  const changes = [];
790
932
  const block = this.#blockFor(sbn);
933
+ const placement = this.#place(evidence);
791
934
  if (evidence.rap) block.rapSeen = true;
792
935
  if (evidence.mpu !== void 0) block.mpus.add(evidence.mpu);
793
- if (evidence.idx !== void 0) {
794
- block.idxMin = block.idxMin === void 0 ? evidence.idx : Math.min(block.idxMin, evidence.idx);
795
- block.idxMax = block.idxMax === void 0 ? evidence.idx : Math.max(block.idxMax, evidence.idx);
796
- }
797
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
798
- this.#mpuBoundsRaps = false;
936
+ const { position } = placement;
937
+ if (position !== void 0) {
938
+ block.positionMin = block.positionMin === void 0 ? position : Math.min(block.positionMin, position);
939
+ block.positionMax = block.positionMax === void 0 ? position : Math.max(block.positionMax, position);
799
940
  }
800
- const violation = this.#checkInvariants(sbn, block, evidence);
941
+ if (placement.rapNotMpuStart) this.#mpuBoundsRaps = false;
942
+ const violation = this.#checkInvariants(sbn, block, evidence, placement);
801
943
  if (violation !== null) changes.push(...this.#disable(violation));
802
944
  const next = this.#classify(block);
803
945
  if (next !== block.cls && this.#allowed(block.cls, next)) {
@@ -822,18 +964,35 @@ var BlockClassifier = class {
822
964
  * RAP-bearing block is the one a wrong G calls delta), because the next
823
965
  * released RAP then belongs to m+2. Every MPU is one interval long, so the
824
966
  * span to any later released RAP proves or refutes all MPUs in between.
967
+ *
968
+ * In every mode it keeps each MPU's first released RAP, with its decode
969
+ * time, as the start keyframeFreeBetween measures the catalog interval
970
+ * from, and a second RAP released inside one MPU refutes `mpuBoundsRaps`
971
+ * when it lies off the catalog lattice (not a whole number of intervals
972
+ * after the first; draft-ramadan-moq-mmt-02 4.4.3 binds every keyframe to
973
+ * it): with no repair, released RAPs are the only evidence of where they
974
+ * lie. Without a usable interval, or a decode time on either, any second
975
+ * RAP with another presentation time refutes.
825
976
  */
826
- noteReleasedRap(mpu, presentationTime, mediaTimescale) {
827
- if (this.#geometry.trackKind === "audio" || this.#mode === "all-protected") {
828
- return [];
829
- }
830
- const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
831
- if (interval === null) return this.#disable("keyframe-interval-not-media-integral");
977
+ noteReleasedRap(mpu, presentationTime, mediaTimescale, decodeTime) {
978
+ if (this.#geometry.trackKind === "audio") return [];
832
979
  const previous = this.#lastRap;
833
980
  if (previous !== null && previous.mpu === mpu && previous.mediaTimescale === mediaTimescale) {
981
+ if (presentationTime === previous.presentationTime) return [];
982
+ const interval2 = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
983
+ if (interval2 === null || decodeTime === void 0 || previous.decodeTime === void 0 || (decodeTime - previous.decodeTime) % interval2 !== 0n) {
984
+ this.#mpuBoundsRaps = false;
985
+ }
834
986
  return [];
835
987
  }
836
- this.#lastRap = { mpu, presentationTime, mediaTimescale };
988
+ if (previous !== null && previous.mediaTimescale === mediaTimescale) {
989
+ const back = previous.mpu - mpu >>> 0;
990
+ if (back !== 0 && back <= LATE_RAP_MAX_MPUS_BACK && presentationTime < previous.presentationTime) return [];
991
+ }
992
+ this.#lastRap = { mpu, presentationTime, mediaTimescale, ...decodeTime === void 0 ? {} : { decodeTime } };
993
+ if (this.#mode === "all-protected") return [];
994
+ const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
995
+ if (interval === null) return this.#disable("keyframe-interval-not-media-integral");
837
996
  if (previous === null || mpu < previous.mpu || previous.mediaTimescale !== mediaTimescale) {
838
997
  return [];
839
998
  }
@@ -842,6 +1001,22 @@ var BlockClassifier = class {
842
1001
  }
843
1002
  return this.#disable("rap-spacing-mismatch");
844
1003
  }
1004
+ /**
1005
+ * Whether a gap inside MPU `mpu`, between the decode times `from` and `to`
1006
+ * of the frames on either side, holds no keyframe: MPU boundaries still
1007
+ * bound RAPs, the catalog states an interval exact in this timescale, and
1008
+ * none of its instants after the MPU's first released RAP lies in
1009
+ * `(from, to]` (fec-multicast-00 Block Classification item 3). Anything
1010
+ * unknown counts as a keyframe.
1011
+ */
1012
+ keyframeFreeBetween(mpu, from, to, mediaTimescale) {
1013
+ const rap = this.#lastRap;
1014
+ if (!this.#mpuBoundsRaps || rap?.mpu !== mpu || rap.mediaTimescale !== mediaTimescale || rap.decodeTime === void 0) {
1015
+ return false;
1016
+ }
1017
+ const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
1018
+ return interval !== null && !keyframeInstantBetween(rap.decodeTime, interval, from, to);
1019
+ }
845
1020
  #blockFor(sbn) {
846
1021
  let block = this.#blocks.get(sbn);
847
1022
  if (!block) {
@@ -850,35 +1025,89 @@ var BlockClassifier = class {
850
1025
  }
851
1026
  return block;
852
1027
  }
853
- #checkInvariants(sbn, block, evidence) {
1028
+ #checkInvariants(sbn, block, evidence, placement) {
854
1029
  if (this.#mode === "all-protected" || this.#geometry.trackKind !== "video") return null;
855
1030
  const geometry = this.#geometry;
856
1031
  if (geometry.mode !== "classifying") return null;
857
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
858
- return "rap-not-mpu-start";
859
- }
860
- if (evidence.idx !== void 0 && evidence.idx >= geometry.gopFrames) {
1032
+ if (placement.rapNotMpuStart) return "rap-not-mpu-start";
1033
+ if (placement.position !== void 0 && placement.position >= geometry.gopFrames) {
861
1034
  return "mpu-longer-than-gop";
862
1035
  }
863
- if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0 && block.idxMax - block.idxMin >= geometry.interleaveUnits) {
1036
+ if (block.mpus.size === 1 && block.positionMin !== void 0 && block.positionMax !== void 0 && block.positionMax - block.positionMin >= geometry.interleaveUnits) {
864
1037
  return "block-wider-than-interleave";
865
1038
  }
866
- if (evidence.mpu !== void 0 && evidence.movieFragment !== void 0) {
867
- const fragment = this.#mpuFragments.get(evidence.mpu);
868
- if (fragment === void 0) {
869
- this.#mpuFragments.set(evidence.mpu, evidence.movieFragment);
870
- for (const mpu of this.#mpuFragments.keys()) {
871
- if (mpu + 1 < evidence.mpu) this.#mpuFragments.delete(mpu);
872
- }
873
- } else if (fragment !== evidence.movieFragment) {
874
- return "mpu-multiple-fragments";
875
- }
876
- }
1039
+ if (placement.violation !== void 0) return placement.violation;
877
1040
  if (evidence.mpu !== void 0 && this.#contradictsAuthoredOrder(sbn, evidence.mpu, evidence)) {
878
1041
  return "block-not-contiguous";
879
1042
  }
880
1043
  return null;
881
1044
  }
1045
+ /**
1046
+ * The MPU position a source symbol's DU header proves (P3), and what it
1047
+ * refutes. Runs in every mode: mpuBoundsRaps needs its RAP verdict.
1048
+ */
1049
+ #place(evidence) {
1050
+ const { mpu, idx, movieFragment: fragment } = evidence;
1051
+ if (idx === void 0) return UNPLACED;
1052
+ const bySample = { position: idx, rapNotMpuStart: evidence.rap && idx !== 0 };
1053
+ if (mpu === void 0 || fragment === void 0) {
1054
+ return this.#fragmentPerFrame && !this.#multiSampleFragment ? { rapNotMpuStart: bySample.rapNotMpuStart } : bySample;
1055
+ }
1056
+ let layout = this.#mpus.get(mpu);
1057
+ if (layout === void 0) {
1058
+ layout = { low: fragment };
1059
+ this.#mpus.set(mpu, layout);
1060
+ for (const other of this.#mpus.keys()) {
1061
+ if (other + 1 < mpu) this.#mpus.delete(other);
1062
+ }
1063
+ } else if (fragment !== layout.low) {
1064
+ this.#fragmentPerFrame = true;
1065
+ if ((fragment - layout.low | 0) < 0) layout.low = fragment;
1066
+ }
1067
+ if (idx !== 0) this.#multiSampleFragment = true;
1068
+ let arrival;
1069
+ if (evidence.rap && layout.anchor === void 0) {
1070
+ layout.anchor = fragment;
1071
+ arrival = this.#anchorDrift(mpu, fragment);
1072
+ if (arrival === 0 && this.#lastAnchor?.mpu !== mpu) this.#fragmentsProven = true;
1073
+ this.#lastAnchor = { mpu, fragment };
1074
+ }
1075
+ if (!this.#fragmentPerFrame) return bySample;
1076
+ if (this.#multiSampleFragment) return { ...bySample, violation: "mpu-multiple-fragments" };
1077
+ const { anchor } = layout;
1078
+ if (anchor === void 0) return UNPLACED;
1079
+ const drift = arrival ?? this.#anchorDrift(mpu, anchor);
1080
+ const offset = fragment - anchor | 0;
1081
+ return {
1082
+ ...offset === 0 || offset > 0 && this.#fragmentsProven ? { position: offset } : {},
1083
+ rapNotMpuStart: evidence.rap && offset !== 0 || (layout.low - anchor | 0) < 0 || // Fragments count frames: an anchor arriving past the spacing is a
1084
+ // RAP inside its MPU, or an earlier MPU outran G.
1085
+ arrival !== void 0 && arrival > 0 && this.#fragmentsProven,
1086
+ ...drift === void 0 || drift === 0 ? {} : { violation: "rap-spacing-mismatch" }
1087
+ };
1088
+ }
1089
+ /**
1090
+ * How many fragments MPU m's anchor `fragment` lies past the start that
1091
+ * the anchor received last predicts for MPU m: one frame per fragment and
1092
+ * G frames per MPU put the anchors of MPUs m and m' exactly G * (m - m')
1093
+ * fragments apart, modulo 2^32. Undefined without a last anchor, a
1094
+ * cadence, or this layout.
1095
+ */
1096
+ #anchorDrift(mpu, fragment) {
1097
+ const geometry = this.#geometry;
1098
+ const last = this.#lastAnchor;
1099
+ if (last === null || !this.#fragmentPerFrame || this.#multiSampleFragment || geometry.trackKind !== "video" || geometry.mode !== "classifying") {
1100
+ return void 0;
1101
+ }
1102
+ return fragment - last.fragment - geometry.gopFrames * (mpu - last.mpu) | 0;
1103
+ }
1104
+ #clearMpuLayout() {
1105
+ this.#mpus.clear();
1106
+ this.#fragmentPerFrame = false;
1107
+ this.#multiSampleFragment = false;
1108
+ this.#lastAnchor = null;
1109
+ this.#fragmentsProven = false;
1110
+ }
882
1111
  #clearContiguityLedger() {
883
1112
  this.#mpuSbnSpans.clear();
884
1113
  this.#dataUnitStarts.clear();
@@ -978,9 +1207,9 @@ var BlockClassifier = class {
978
1207
  if (this.#mode === "all-protected") return "unknown";
979
1208
  const geometry = this.#geometry;
980
1209
  if (geometry.trackKind !== "video" || geometry.mode !== "classifying") return "unknown";
981
- if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0) {
1210
+ if (block.mpus.size === 1 && block.positionMin !== void 0 && block.positionMax !== void 0) {
982
1211
  const span = geometry.interleaveUnits - 1;
983
- if (block.idxMax - span >= 1 && block.idxMin + span <= geometry.gopFrames - 1) {
1212
+ if (block.positionMax - span >= 1 && block.positionMin + span <= geometry.gopFrames - 1) {
984
1213
  return "delta";
985
1214
  }
986
1215
  }
@@ -1098,6 +1327,7 @@ var WORKER_ERROR_LOG_CAP = 5;
1098
1327
  var WORKER_ERROR_KIND_CAP = 32;
1099
1328
  var WORKER_ERROR_OVERFLOW_KIND = "other";
1100
1329
  var STARTUP_REPAIR_WAIT_SOURCE_BOUNDARIES = 2;
1330
+ var NOT_TAKEN = Object.freeze({ taken: false, recovered: null });
1101
1331
  function isMulticastSymbolDelivery(value) {
1102
1332
  return value === "datagram" || value === "ordered-relay";
1103
1333
  }
@@ -1179,7 +1409,12 @@ var FECManager = class _FECManager {
1179
1409
  this.#repairHoldUntilMs = /* @__PURE__ */ new Map();
1180
1410
  // Receiver-measured multicast delivery gap: the late-symbol wait's jitter
1181
1411
  // term (see DeliveryGapEstimator for the statistic and why).
1182
- this.#deliveryGaps = new DeliveryGapEstimator();
1412
+ // One estimator per lossy path, so a hybrid session never lets one leg's
1413
+ // stall widen the other's wait; the wait reads the larger peak.
1414
+ this.#deliveryGaps = {
1415
+ multicast: new DeliveryGapEstimator(),
1416
+ "moq-datagram": new DeliveryGapEstimator()
1417
+ };
1183
1418
  this.#lifecycleTrace = [];
1184
1419
  // Worker-backed timeouts enqueue cleanup behind all prior symbol messages.
1185
1420
  // Failure remains pending until cleanupComplete acknowledges that queue drain.
@@ -1191,10 +1426,18 @@ var FECManager = class _FECManager {
1191
1426
  // 'pending' forever, which would park every later frame of its stream in
1192
1427
  // the in-order release gate. Each entry owns its handle; the callback
1193
1428
  // checks it still owns the key, so a settled or reset key is never touched.
1429
+ /**
1430
+ * Per owed Worker cleanup: the bound on its acknowledgement, when its block
1431
+ * was due, and when its cleanup was asked for (see `onCleanupComplete`).
1432
+ */
1194
1433
  this.#pendingWorkerCleanupBounds = /* @__PURE__ */ new Map();
1195
1434
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
1196
1435
  this.#blockSourceCounts = /* @__PURE__ */ new Map();
1197
1436
  this.#blockSourceEsis = /* @__PURE__ */ new Map();
1437
+ // Source ESIs per block that another FEC instance rebuilt and fed in
1438
+ // (feedRebuiltSourceSymbol). Kept apart from #blockSourceEsis: they are
1439
+ // not network arrivals and never make a block clean.
1440
+ this.#blockRebuiltEsis = /* @__PURE__ */ new Map();
1198
1441
  // Authored SSB_length per block (ISO/IEC 23008-1 §C.5.3), learned from the
1199
1442
  // first repair symbol. The FFmpeg moq_mmt publisher closes a block every D
1200
1443
  // media units, usually before it holds K symbols; under iso-ssbg1-v1
@@ -1203,10 +1446,14 @@ var FECManager = class _FECManager {
1203
1446
  // SSB_length source arrivals and recoverable from SSB_length received
1204
1447
  // symbols; waiting for K fails every one of them.
1205
1448
  this.#blockAuthoredLengths = /* @__PURE__ */ new Map();
1449
+ // Keys whose authored length is a repair-less span's (#openIsoSpan), until
1450
+ // a repair states the block there or the span resolves.
1451
+ this.#isoSpanKeys = /* @__PURE__ */ new Set();
1206
1452
  this.#ssbLengthConflictCount = 0;
1207
1453
  this.#blockRepairRsIds = /* @__PURE__ */ new Map();
1208
1454
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
1209
- // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
1455
+ // symbols its repair group carries; 0 for a repair-less span no repair can
1456
+ // state (#openIsoSpan). Same lifecycle as #blockRepairRsIds.
1210
1457
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
1211
1458
  /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
1212
1459
  this.#heldLayerStates = /* @__PURE__ */ new Map();
@@ -1359,6 +1606,14 @@ var FECManager = class _FECManager {
1359
1606
  // iso-ssbg1-v1 block location per stream (streamKey). A source belongs to a
1360
1607
  // block only once a repair symbol stated the block's (SS_Start, SSB_length).
1361
1608
  this.#isoLocators = /* @__PURE__ */ new Map();
1609
+ // The ts of the run behind the gap the release gate last asked about, per
1610
+ // stream (isoRepairlessWaitMs), keyed on the frame before the gap: kept, as
1611
+ // the source it came from may retire before the run's deadline, and the
1612
+ // earliest found wins, so a late frame that becomes the head restarts
1613
+ // nothing. It stays until the next run gap: a source discontinuity drops
1614
+ // it, and one older than twice the hold ceiling is not this gap's.
1615
+ // `counted` once the deadline passed (onUndelimitedRunGap).
1616
+ this.#runAnchors = /* @__PURE__ */ new Map();
1362
1617
  this.#deferIsoGaps = false;
1363
1618
  this.#isoRepairRefusedCount = 0;
1364
1619
  this.#isoSourceOversizeCount = 0;
@@ -1394,13 +1649,18 @@ var FECManager = class _FECManager {
1394
1649
  this.#workerErrorCounts = /* @__PURE__ */ new Map();
1395
1650
  this.#decoderUnavailableEvents = 0;
1396
1651
  this.#repairSymbolSizeMismatchCount = 0;
1652
+ this.#unlistedRepairTrackRefusals = 0;
1653
+ this.#unresolvedRepairOwnerDrops = { unregistered: 0, ownerAbsent: 0, ownerAmbiguous: 0 };
1397
1654
  // Event callbacks — block lifecycle notifications for MmtpRouter wiring.
1398
1655
  // NOTE: For sync WASM path, recovery routing is handled by MmtpRouter from
1399
1656
  // feedSourceSymbol/feedRepairSymbol return values. For Worker path, recovery
1400
1657
  // arrives via onBlockRecovered callback.
1401
1658
  this.onBlockStarted = null;
1402
1659
  this.onBlockComplete = null;
1403
- /** A block reached its fail bound. `blockClass` is its class at failure. */
1660
+ /**
1661
+ * A block reached its fail bound. `blockClass` is its class at failure.
1662
+ * `span` is set when what failed is a repair-less span starting at `sbn`.
1663
+ */
1404
1664
  this.onBlockFailed = null;
1405
1665
  /**
1406
1666
  * Fired once per stream when its Worker decoder stops being routable.
@@ -1442,12 +1702,26 @@ var FECManager = class _FECManager {
1442
1702
  * for it, which it must be.
1443
1703
  */
1444
1704
  this.#onUndelimitedLoss = null;
1705
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
1706
+ this.#onIsoHoleExpired = null;
1445
1707
  /** A block every symbol of which vanished was created by SBN evidence. */
1446
1708
  this.onBlockVanished = null;
1447
1709
  /** A block reached a terminal state (completed, recovered, or failed). */
1448
1710
  this.onBlockResolved = null;
1449
1711
  /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
1450
1712
  this.onSourceDiscontinuity = null;
1713
+ /** The FEC deadline of a run no repair delimited passed, releasing the gap behind it (once per gap). */
1714
+ this.onUndelimitedRunGap = null;
1715
+ /**
1716
+ * The span and tolerance the catalog states for a keyframe overlay
1717
+ * installed over a source track (draft-ramadan-moq-mmt-02 7.4.1: the
1718
+ * overlay instance's own interleaveDepthMs and reorderToleranceMs), or
1719
+ * undefined while none is installed. A stated block only a late source
1720
+ * can complete, and a frame whose gap may hide a RAP behind a span only a
1721
+ * late source can fill, also wait for that overlay's repair
1722
+ * (#overlayLateWaitMs).
1723
+ */
1724
+ this.keyframeOverlayTiming = null;
1451
1725
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
1452
1726
  /**
1453
1727
  * A recovered source symbol. Return false when admission refused the
@@ -1484,7 +1758,9 @@ var FECManager = class _FECManager {
1484
1758
  #pendingWorkerCleanupBounds;
1485
1759
  #blockSourceCounts;
1486
1760
  #blockSourceEsis;
1761
+ #blockRebuiltEsis;
1487
1762
  #blockAuthoredLengths;
1763
+ #isoSpanKeys;
1488
1764
  #ssbLengthConflictCount;
1489
1765
  #blockRepairRsIds;
1490
1766
  #blockRsbLengths;
@@ -1536,6 +1812,7 @@ var FECManager = class _FECManager {
1536
1812
  #highestSbn;
1537
1813
  #sourceFrontiers;
1538
1814
  #isoLocators;
1815
+ #runAnchors;
1539
1816
  #deferIsoGaps;
1540
1817
  #isoRepairRefusedCount;
1541
1818
  #isoSourceOversizeCount;
@@ -1550,7 +1827,10 @@ var FECManager = class _FECManager {
1550
1827
  #workerErrorCounts;
1551
1828
  #decoderUnavailableEvents;
1552
1829
  #repairSymbolSizeMismatchCount;
1830
+ #unlistedRepairTrackRefusals;
1831
+ #unresolvedRepairOwnerDrops;
1553
1832
  #onUndelimitedLoss;
1833
+ #onIsoHoleExpired;
1554
1834
  #encodeTrackName(catalogTrackName) {
1555
1835
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
1556
1836
  if (encoded === void 0) {
@@ -2022,7 +2302,10 @@ var FECManager = class _FECManager {
2022
2302
  timer.handle = null;
2023
2303
  this.#requestRepair(sbn, packetId, catalogTrackName);
2024
2304
  };
2025
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
2305
+ timer.handle = setTimeout(
2306
+ onFire,
2307
+ this.#receiptAtMs === void 0 ? Math.max(0, deadlineMs - performance.now()) : this.#receiptTimerDelayMs(deadlineMs, 0)
2308
+ );
2026
2309
  this.#repairDeadlines.set(key, timer);
2027
2310
  }
2028
2311
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -2166,8 +2449,14 @@ var FECManager = class _FECManager {
2166
2449
  * Vanished blocks are not enumerated here: their starts are unknown until a
2167
2450
  * repair states them. The SS_IDs between two stated blocks become one
2168
2451
  * repair-less span when the later block's repair arrives (placeIsoRepair).
2452
+ *
2453
+ * A `held` source arrived before its block was known and is fed only now
2454
+ * that a repair, a span or a closed hole placed it: how far its block start
2455
+ * then lies behind the frontier measures how long the receiver held it, not
2456
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
2457
+ * it (BLO-52085).
2169
2458
  */
2170
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
2459
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn, held = false) {
2171
2460
  const streamKey = this.#streamKey(packetId, catalogTrackName);
2172
2461
  const now = performance.now();
2173
2462
  const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
@@ -2189,6 +2478,7 @@ var FECManager = class _FECManager {
2189
2478
  const discontinuity = () => {
2190
2479
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity();
2191
2480
  this.#noSpanRaps.delete(streamKey);
2481
+ this.#runAnchors.delete(streamKey);
2192
2482
  this.#highestSbn.set(streamKey, { sbn, atMs: now });
2193
2483
  this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
2194
2484
  if (psn === void 0) this.#sourceAnchors.delete(streamKey);
@@ -2206,7 +2496,7 @@ var FECManager = class _FECManager {
2206
2496
  return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
2207
2497
  };
2208
2498
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
2209
- if (symbol === "source" && window !== 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))) {
2499
+ if (symbol === "source" && window !== 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))) {
2210
2500
  discontinuity();
2211
2501
  return;
2212
2502
  }
@@ -2359,7 +2649,7 @@ var FECManager = class _FECManager {
2359
2649
  consider(geometry, this.#parseStreamKey(streamKey).packetId);
2360
2650
  }
2361
2651
  for (const [packetId, config] of this.#trackConfigs) consider(config.geometry, packetId);
2362
- this.#deliveryGaps.setWindowMs(windowMs);
2652
+ for (const estimator of Object.values(this.#deliveryGaps)) estimator.setWindowMs(windowMs);
2363
2653
  }
2364
2654
  /**
2365
2655
  * The multicast late-symbol wait: the block span plus the larger of the
@@ -2372,14 +2662,14 @@ var FECManager = class _FECManager {
2372
2662
  * stream order and never feeds the estimator.
2373
2663
  */
2374
2664
  #multicastWaitMs(config) {
2375
- return this.#waitForGapMs(config, this.#deliveryGaps.peakGapMs(performance.now()));
2665
+ return this.#waitForGapMs(config, this.#peakDeliveryGapMs());
2376
2666
  }
2377
2667
  /**
2378
2668
  * The widest #multicastWaitMs can become: the estimator reports at most its
2379
2669
  * catalog window, so this is a catalog quantity that no measurement moves.
2380
2670
  */
2381
2671
  #maxMulticastWaitMs(config) {
2382
- return this.#waitForGapMs(config, this.#deliveryGaps.windowMs ?? 0);
2672
+ return this.#waitForGapMs(config, this.#deliveryGaps.multicast.windowMs ?? 0);
2383
2673
  }
2384
2674
  #waitForGapMs(config, gapMs) {
2385
2675
  if (!(gapMs > 0) || !(config.interleaveDepthMs > 0)) return config.timeoutMs;
@@ -2468,17 +2758,21 @@ var FECManager = class _FECManager {
2468
2758
  this.#blockWaitDeadlinesMs.delete(key);
2469
2759
  this.#repairHoldUntilMs.delete(key);
2470
2760
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
2471
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName);
2761
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs);
2472
2762
  };
2473
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)));
2763
+ timer.handle = setTimeout(
2764
+ onFire,
2765
+ this.#receiptAtMs === void 0 ? Math.max(1, Math.ceil(deadlineMs - nowMs)) : this.#receiptTimerDelayMs(deadlineMs, 1)
2766
+ );
2474
2767
  this.#activeBlocks.set(key, timer);
2475
2768
  this.#indexBlockKey(key, sbn, packetId);
2476
2769
  }
2477
2770
  /**
2478
2771
  * Hand a block whose delivery is over to its decoder for finalization: the
2479
- * datagram deadline fired, or the ordered relay moved past it.
2772
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
2773
+ * is when it was due: its deadline, or now.
2480
2774
  */
2481
- #finalizeExpiredBlock(sbn, packetId, catalogTrackName) {
2775
+ #finalizeExpiredBlock(sbn, packetId, catalogTrackName, dueAtMs = performance.now()) {
2482
2776
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
2483
2777
  if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
2484
2778
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -2494,7 +2788,7 @@ var FECManager = class _FECManager {
2494
2788
  if (workerClient) {
2495
2789
  this.#pendingWorkerCleanups.add(key);
2496
2790
  this.#pendingWorkerCleanupClients.set(key, workerClient);
2497
- this.#boundOwedCleanup(key, packetId, workerClient);
2791
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs);
2498
2792
  workerClient.cleanup(sbn);
2499
2793
  } else {
2500
2794
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
@@ -2559,6 +2853,7 @@ var FECManager = class _FECManager {
2559
2853
  ...(config.trackKind ?? previous.trackKind) === void 0 ? {} : { trackKind: config.trackKind ?? previous.trackKind },
2560
2854
  ...(config.codec ?? previous.codec) === void 0 ? {} : { codec: config.codec ?? previous.codec },
2561
2855
  ...(config.geometry ?? previous.geometry) === void 0 ? {} : { geometry: config.geometry ?? previous.geometry },
2856
+ ...(config.groupDurationMs ?? previous.groupDurationMs) === void 0 ? {} : { groupDurationMs: config.groupDurationMs ?? previous.groupDurationMs },
2562
2857
  ...(config.repairLayers ?? previous.repairLayers) === void 0 ? {} : { repairLayers: config.repairLayers ?? previous.repairLayers },
2563
2858
  ...(config.heldLayers ?? previous.heldLayers) === void 0 ? {} : { heldLayers: config.heldLayers ?? previous.heldLayers }
2564
2859
  };
@@ -2665,6 +2960,10 @@ var FECManager = class _FECManager {
2665
2960
  lifecycleTrace: this.#lifecycleTrace.map((entry) => ({ ...entry }))
2666
2961
  };
2667
2962
  }
2963
+ /** Count a repair packet the router dropped for want of an owning track (BLO-55759). */
2964
+ countUnresolvedRepairOwner(reason) {
2965
+ this.#unresolvedRepairOwnerDrops[reason]++;
2966
+ }
2668
2967
  get fecStats() {
2669
2968
  const s = this.#fecStats;
2670
2969
  const affected = s.blocksRecovered + s.blocksFailed;
@@ -2704,6 +3003,8 @@ var FECManager = class _FECManager {
2704
3003
  packetId
2705
3004
  })),
2706
3005
  repairSymbolSizeMismatches: this.#repairSymbolSizeMismatchCount,
3006
+ unlistedRepairTrackRefusals: this.#unlistedRepairTrackRefusals,
3007
+ unresolvedRepairOwnerDrops: { ...this.#unresolvedRepairOwnerDrops },
2707
3008
  repairObjectRejects: [...this.#repairObjectRejects.values()].map((r) => ({ ...r })),
2708
3009
  workerErrors: Object.fromEntries(this.#workerErrorCounts)
2709
3010
  };
@@ -2728,6 +3029,16 @@ var FECManager = class _FECManager {
2728
3029
  this.#startupRepairBoundaryCounts.clear();
2729
3030
  this.#startupRepairFailOpenPackets.clear();
2730
3031
  }
3032
+ /**
3033
+ * Start a new "mfu-datagram" leg (mmt-02 4.3.1) without discarding
3034
+ * track/decoder state: the same join-boundary rules as a multicast join,
3035
+ * since the leg starts at an arbitrary datagram too. It resets the whole
3036
+ * join boundary of this manager, a multicast ordered-relay frontier
3037
+ * included, so a host gives the leg a manager of its own.
3038
+ */
3039
+ beginLegJoin() {
3040
+ this.beginMulticastJoin();
3041
+ }
2731
3042
  /** How the multicast leg currently delivers symbols. */
2732
3043
  get multicastSymbolDelivery() {
2733
3044
  return this.#multicastSymbolDelivery;
@@ -2750,7 +3061,8 @@ var FECManager = class _FECManager {
2750
3061
  );
2751
3062
  }
2752
3063
  if (delivery === this.#multicastSymbolDelivery) return;
2753
- this.#deliveryGaps.reset();
3064
+ this.#deliveryGaps.multicast.reset();
3065
+ this.#runAnchors.clear();
2754
3066
  if (delivery === "ordered-relay") {
2755
3067
  for (const [packetId, config] of this.#trackConfigs) {
2756
3068
  this.#orderedHorizonBlocksFor(packetId, config);
@@ -2806,7 +3118,9 @@ var FECManager = class _FECManager {
2806
3118
  }
2807
3119
  resetMap(this.#blockSourceCounts);
2808
3120
  resetMap(this.#blockSourceEsis);
3121
+ resetMap(this.#blockRebuiltEsis);
2809
3122
  resetMap(this.#blockAuthoredLengths);
3123
+ resetSet(this.#isoSpanKeys);
2810
3124
  resetMap(this.#blockRepairRsIds);
2811
3125
  resetMap(this.#blockRsbLengths);
2812
3126
  resetMap(this.#heldLayerStates);
@@ -2837,6 +3151,7 @@ var FECManager = class _FECManager {
2837
3151
  resetMap(this.#highestSbn);
2838
3152
  resetMap(this.#sourceFrontiers);
2839
3153
  resetMap(this.#isoLocators);
3154
+ resetMap(this.#runAnchors);
2840
3155
  resetMap(this.#sourceAnchors);
2841
3156
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName));
2842
3157
  this.#noSpanRaps.delete(this.#streamKey(packetId, catalogTrackName));
@@ -2930,7 +3245,9 @@ var FECManager = class _FECManager {
2930
3245
  dropMap(this.#pendingWorkerCleanupClients);
2931
3246
  dropMap(this.#blockSourceCounts);
2932
3247
  dropMap(this.#blockSourceEsis);
3248
+ dropMap(this.#blockRebuiltEsis);
2933
3249
  dropMap(this.#blockAuthoredLengths);
3250
+ dropSet(this.#isoSpanKeys);
2934
3251
  dropMap(this.#blockRepairRsIds);
2935
3252
  dropMap(this.#blockRsbLengths);
2936
3253
  dropMap(this.#blockPathCounts);
@@ -2944,6 +3261,7 @@ var FECManager = class _FECManager {
2944
3261
  dropMap(this.#highestSbn);
2945
3262
  dropMap(this.#sourceFrontiers);
2946
3263
  dropMap(this.#isoLocators);
3264
+ dropMap(this.#runAnchors);
2947
3265
  dropMap(this.#sourceAnchors);
2948
3266
  dropMap(this.#classifiers);
2949
3267
  dropMap(this.#noSpanRaps);
@@ -3011,8 +3329,8 @@ var FECManager = class _FECManager {
3011
3329
  const sourceSymbols = this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? this.#trackConfig(packetId).k;
3012
3330
  const isSourceSymbol = esi >= 0 && esi < sourceSymbols;
3013
3331
  const isStartupPartial = this.#startupPartialBlocks.has(blockKey);
3014
- const isReadyMulticastRepair = this.#startupRequireRepairReady && source === "multicast" && !isSourceSymbol && this.#startupRepairReadyPackets.has(streamKey);
3015
- const awaitingMulticastRepair = this.#startupRequireRepairReady && source === "multicast" && !this.#startupRepairReadyPackets.has(streamKey) && !this.#startupRepairFailOpenPackets.has(streamKey);
3332
+ const isReadyMulticastRepair = this.#startupRequireRepairReady && source !== "moq" && !isSourceSymbol && this.#startupRepairReadyPackets.has(streamKey);
3333
+ const awaitingMulticastRepair = this.#startupRequireRepairReady && source !== "moq" && !this.#startupRepairReadyPackets.has(streamKey) && !this.#startupRepairFailOpenPackets.has(streamKey);
3016
3334
  if (awaitingMulticastRepair) {
3017
3335
  if (!isSourceSymbol) {
3018
3336
  this.#startupRepairReadyPackets.add(streamKey);
@@ -3066,12 +3384,14 @@ var FECManager = class _FECManager {
3066
3384
  ...catalogTrackName === void 0 ? {} : { catalogTrackName },
3067
3385
  multicastSymbols: 0,
3068
3386
  moqSymbols: 0,
3387
+ datagramSymbols: 0,
3069
3388
  complete: false
3070
3389
  };
3071
3390
  const receivedAtMs = this.#receiptNow();
3072
3391
  const anchorMs = this.#blockAnchorsMs.get(blockKey);
3073
3392
  if (anchorMs === void 0 || receivedAtMs < anchorMs) this.#blockAnchorsMs.set(blockKey, receivedAtMs);
3074
3393
  if (source === "multicast") counts.multicastSymbols++;
3394
+ else if (source === "moq-datagram") counts.datagramSymbols++;
3075
3395
  else counts.moqSymbols++;
3076
3396
  this.#blockPathCounts.set(blockKey, counts);
3077
3397
  this.#observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName);
@@ -3092,7 +3412,7 @@ var FECManager = class _FECManager {
3092
3412
  this.#unindexBlockKey(key);
3093
3413
  }
3094
3414
  }
3095
- if (isSourceSymbol && source === "multicast") {
3415
+ if (isSourceSymbol && source !== "moq") {
3096
3416
  this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), sbn + esi >>> 0, packetId, catalogTrackName);
3097
3417
  }
3098
3418
  return true;
@@ -3181,8 +3501,22 @@ var FECManager = class _FECManager {
3181
3501
  * DeliveryGapEstimator). Datagram delivery only.
3182
3502
  */
3183
3503
  noteMulticastArrival(packetId, packetSequenceNumber) {
3184
- if (this.#multicastSymbolDelivery !== "datagram") return;
3185
- this.#deliveryGaps.noteArrival(performance.now(), packetId, packetSequenceNumber);
3504
+ this.noteArrival("multicast", packetId, packetSequenceNumber);
3505
+ }
3506
+ /**
3507
+ * Record one MMTP packet arrival on a lossy path for that path's
3508
+ * delivery-gap measurement: the multicast leg (datagram delivery only; an
3509
+ * ordered relay settles by stream order) or an "mfu-datagram" leg, whose
3510
+ * datagrams are always a lossy path (#lossyDatagramPath).
3511
+ */
3512
+ noteArrival(path, packetId, packetSequenceNumber) {
3513
+ if (!this.#lossyDatagramPath(path)) return;
3514
+ this.#deliveryGaps[path].noteArrival(performance.now(), packetId, packetSequenceNumber);
3515
+ }
3516
+ /** The largest delivery gap any lossy path measured over its window. */
3517
+ #peakDeliveryGapMs() {
3518
+ const now = performance.now();
3519
+ return Math.max(...Object.values(this.#deliveryGaps).map((estimator) => estimator.peakGapMs(now)));
3186
3520
  }
3187
3521
  /**
3188
3522
  * Resolved per-track multicast late-symbol wait in milliseconds: the span
@@ -3196,16 +3530,18 @@ var FECManager = class _FECManager {
3196
3530
  * Largest multicast delivery gap measured over the current window (ms), and
3197
3531
  * that window (undefined: held since the last reset). Diagnostics.
3198
3532
  */
3199
- multicastDeliveryGap() {
3533
+ multicastDeliveryGap(path = "multicast") {
3200
3534
  return {
3201
- peakGapMs: this.#deliveryGaps.peakGapMs(performance.now()),
3202
- windowMs: this.#deliveryGaps.windowMs
3535
+ peakGapMs: this.#deliveryGaps[path].peakGapMs(performance.now()),
3536
+ windowMs: this.#deliveryGaps[path].windowMs
3203
3537
  };
3204
3538
  }
3205
3539
  /**
3206
3540
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
3207
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
3208
- * Undefined for a block that is not open.
3541
+ * (SSB_length) and RSB_length (each undefined until a repair stated it; a
3542
+ * repair-less span states its length, and RSB_length 0 when it is longer
3543
+ * than K, since no repair can reach it). Undefined for a block that is not
3544
+ * open.
3209
3545
  */
3210
3546
  blockSymbolCounts(sbn, packetId, catalogTrackName) {
3211
3547
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -3273,8 +3609,9 @@ var FECManager = class _FECManager {
3273
3609
  return true;
3274
3610
  }
3275
3611
  /**
3276
- * Drop a block's repair hold: its FETCH ended without delivering. The block
3277
- * falls back to its multicast wait, which may already have passed.
3612
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
3613
+ * back only a repair that cannot complete it. The block falls back to its
3614
+ * multicast wait, which may already have passed.
3278
3615
  */
3279
3616
  releaseRepairHold(sbn, packetId, catalogTrackName) {
3280
3617
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -3294,6 +3631,23 @@ var FECManager = class _FECManager {
3294
3631
  const config = this.#trackConfigs.get(packetId);
3295
3632
  return config === void 0 ? void 0 : this.#blockLifetimeMs(config);
3296
3633
  }
3634
+ /**
3635
+ * How long an "mfu-datagram" leg's duplicate ledgers must remember a packet
3636
+ * so a legal reorder never reads as a publisher restart: one block span,
3637
+ * the reorder tolerance (`timeoutMs` is span + tolerance) and one group,
3638
+ * since a datagram may trail the stream by a whole group behind a joining
3639
+ * FETCH (mmt-02 6.1 step 3). The group is the catalog group duration
3640
+ * (`groupDurationMs`), whatever the track kind; a video track configured
3641
+ * without one falls back to its keyframe interval (one GOP per group).
3642
+ * Undefined for an unconfigured packet id.
3643
+ */
3644
+ datagramLegLedgerRetentionMsForPacket(packetId) {
3645
+ const config = this.#trackConfigs.get(packetId);
3646
+ if (config === void 0) return void 0;
3647
+ const geometry = config.geometry;
3648
+ const groupMs = config.groupDurationMs ?? (geometry?.trackKind === "video" && geometry.mode === "classifying" ? geometry.keyframeInterval.ticks / geometry.keyframeInterval.timescale * 1e3 : 0);
3649
+ return config.timeoutMs + (Number.isFinite(groupMs) ? groupMs : 0);
3650
+ }
3297
3651
  /**
3298
3652
  * How long a terminal (clean, recovered or failed) block stays authoritative,
3299
3653
  * for late symbols and for the in-order release gate. It is also the gate's
@@ -3320,7 +3674,7 @@ var FECManager = class _FECManager {
3320
3674
  }
3321
3675
  const trackConfig = this.#trackConfigs.get(packetId);
3322
3676
  if (trackConfig === void 0) return void 0;
3323
- return Math.max(1, trackConfig.timeoutMs - this.#repairDeadlineMs(trackConfig));
3677
+ return Math.max(1, this.#repairGraceMs(trackConfig, this.#multicastWaitMs(trackConfig)));
3324
3678
  }
3325
3679
  /** True once configureTrack/setFecDecoder/setFecWorker configured this packetId. */
3326
3680
  // -----------------------------------------------------------------------
@@ -3362,6 +3716,9 @@ var FECManager = class _FECManager {
3362
3716
  for (const key of [...this.#isoLocators.keys()]) {
3363
3717
  if (this.#belongsToPacket(key, packetId)) this.#isoLocators.delete(key);
3364
3718
  }
3719
+ for (const key of [...this.#runAnchors.keys()]) {
3720
+ if (this.#belongsToPacket(key, packetId)) this.#runAnchors.delete(key);
3721
+ }
3365
3722
  }
3366
3723
  /**
3367
3724
  * The iso-ssbg1-v1 locator horizon in blocks: every block the manager can
@@ -3411,8 +3768,9 @@ var FECManager = class _FECManager {
3411
3768
  holdIsoSource(packetId, catalogTrackName, ssId, source) {
3412
3769
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
3413
3770
  const evictedBefore = locator.heldEvicted;
3414
- const held = locator.hold(ssId, source);
3415
- if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
3771
+ const held = locator.hold(ssId, source.arrivedAtMs === void 0 ? { ...source, arrivedAtMs: this.#receiptNow() } : source);
3772
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
3773
+ if (held && source.source !== "moq") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
3416
3774
  const evicted = locator.heldEvicted - evictedBefore;
3417
3775
  if (evicted > 0) {
3418
3776
  const before = this.#isoHeldEvictedCount;
@@ -3433,17 +3791,20 @@ var FECManager = class _FECManager {
3433
3791
  * contradicts a known block is refused (counted) and must be dropped.
3434
3792
  */
3435
3793
  placeIsoRepair(packetId, catalogTrackName, ssStart, ssbLength) {
3436
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength);
3794
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
3795
+ const placement = locator.placeRepair(ssStart, ssbLength);
3796
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
3437
3797
  if (placement.status !== "placed") {
3438
3798
  this.#isoRepairRefusedCount++;
3439
3799
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
3440
3800
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`);
3441
3801
  }
3802
+ if (placement.ofSpan !== void 0) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName);
3442
3803
  return placement;
3443
3804
  }
3805
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName));
3444
3806
  if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
3445
3807
  if (placement.hole !== void 0) {
3446
- const locator = this.#isoLocatorFor(packetId, catalogTrackName);
3447
3808
  const hole = placement.hole.block;
3448
3809
  const previous = locator.blockEndingAt(hole.start);
3449
3810
  const loss = {
@@ -3464,17 +3825,29 @@ var FECManager = class _FECManager {
3464
3825
  * `handler`, instead of a repair-less span; null restores spans. Set by the
3465
3826
  * range repair scheduler; applies to every stream from its next gap. The
3466
3827
  * handler and the deferral are one setting, so no hole is ever created with
3467
- * nobody to close it.
3828
+ * nobody to close it. `onExpired` is told of each pending hole the stream
3829
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
3830
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
3831
+ * reported; otherwise the hole is discarded with its sources.
3468
3832
  */
3469
- setUndelimitedLossHandler(handler) {
3833
+ setUndelimitedLossHandler(handler, onExpired = null) {
3470
3834
  this.#onUndelimitedLoss = handler;
3835
+ this.#onIsoHoleExpired = handler === null ? null : onExpired;
3471
3836
  this.#deferIsoGaps = handler !== null;
3472
3837
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
3473
3838
  }
3839
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
3840
+ #settleExpiredIsoHoles(locator, packetId, catalogTrackName) {
3841
+ for (const hole of locator.takeExpiredHoles()) {
3842
+ const expired = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length };
3843
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length);
3844
+ }
3845
+ }
3474
3846
  /**
3475
- * The range repair for a hole ended: every hole still pending inside
3476
- * `[start, start + length)` becomes a repair-less span. Returns those spans
3477
- * with the held sources they placed, for the caller to feed (MmtpRouter).
3847
+ * The range repair for a hole ended: every hole inside `[start, start +
3848
+ * length)`, pending or expired, becomes a repair-less span. Returns those
3849
+ * spans with the held sources they placed, for the caller to feed
3850
+ * (MmtpRouter).
3478
3851
  */
3479
3852
  closeIsoHoles(packetId, catalogTrackName, start, length) {
3480
3853
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
@@ -3490,17 +3863,37 @@ var FECManager = class _FECManager {
3490
3863
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
3491
3864
  * SS_ID of which vanished resolves through its deadline like any vanished
3492
3865
  * block.
3866
+ *
3867
+ * A span longer than K holds more than one block (SSB_length <= K), and the
3868
+ * locator states no block inside a span, only one exactly its range
3869
+ * (IsoBlockLocator.placeRepair): no repair, multicast or FETCHed, can ever
3870
+ * reach it. Its repair group is empty, so the repair scheduler FETCHes no
3871
+ * Group of it (group-cannot-complete). Every span still keeps its whole
3872
+ * wait (#lateSourceWaitMs): failing it early released the frames behind it
3873
+ * past a keyframe the overlay was still rebuilding (BLO-52085). The release
3874
+ * gate lets those frames go once only a late source can fill the gap
3875
+ * before them, as long after they arrived as the gap's decision allows
3876
+ * (isoRepairlessWaitMs).
3493
3877
  */
3494
3878
  #openIsoSpan(span, packetId, catalogTrackName) {
3495
3879
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
3496
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
3880
+ if (!this.#blockAuthoredLengths.has(key)) {
3881
+ this.#blockAuthoredLengths.set(key, span.block.length);
3882
+ this.#isoSpanKeys.add(key);
3883
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0);
3884
+ }
3497
3885
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
3498
3886
  }
3499
3887
  /**
3500
3888
  * Resolution of the SS_IDs strictly between two released frames' SS_IDs on
3501
3889
  * an iso-ssbg1-v1 stream, for in-order frame release: null while a block
3502
3890
  * that could hold them is pending or not yet stated by a repair, else the
3503
- * starts of the blocks that failed or vanished.
3891
+ * starts of the blocks that failed or vanished. SS_IDs no repair has
3892
+ * delimited yet that all arrived lost nothing and wait for no repair, only
3893
+ * the late-source allowance after the datagram of a lossy path that clocks
3894
+ * them arrived (#lossFreeRunReadyAtMs), and not even that when none of them
3895
+ * came as one; one missing makes a run that waits as one block
3896
+ * (isoRepairlessWaitMs).
3504
3897
  *
3505
3898
  * `untracked` reads as the release gate reads it (MmtpRouter
3506
3899
  * #createFecReleaseGate): a block holding either released frame's SS_ID
@@ -3513,7 +3906,16 @@ var FECManager = class _FECManager {
3513
3906
  isoSpanResolution(packetId, catalogTrackName, fromSsId, toSsId) {
3514
3907
  if (!serial32Precedes(fromSsId, toSsId) || serial32Distance(fromSsId, toSsId) <= 1) return [];
3515
3908
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
3516
- if (!locator || !locator.coversBetween(fromSsId, toSsId)) return null;
3909
+ if (!locator) return null;
3910
+ const run = locator.undelimitedBetween(fromSsId, toSsId);
3911
+ if (run?.missing !== void 0) return null;
3912
+ if (run !== null) {
3913
+ const config = this.#trackConfigs.get(packetId);
3914
+ const readyAtMs = config === void 0 ? void 0 : this.#lossFreeRunReadyAtMs(config, locator, run.start, toSsId);
3915
+ if (readyAtMs !== void 0 && this.#receiptNow() < readyAtMs) return null;
3916
+ }
3917
+ if (locator.coverageEnd === void 0) return [];
3918
+ if (!locator.coversBetween(fromSsId, run?.start ?? toSsId)) return null;
3517
3919
  const highest = this.highestSbn(packetId, catalogTrackName);
3518
3920
  const lost = [];
3519
3921
  for (const block of locator.blocksBetween(fromSsId, toSsId)) {
@@ -3531,6 +3933,162 @@ var FECManager = class _FECManager {
3531
3933
  }
3532
3934
  return lost;
3533
3935
  }
3936
+ /**
3937
+ * When undelimited SS_IDs from `runStart` up to `toSsId` that all arrived
3938
+ * stop holding its frame: the late-source allowance after the receipt of
3939
+ * a datagram of a lossy path (#lossyDatagramPath: a multicast datagram, or
3940
+ * one of an "mfu-datagram" leg). Until then a frame between them may still
3941
+ * complete from a packet with no SS_ID (an untagged FT=0/FT=1 reordered
3942
+ * behind the next frame), and a repair may delimit them. The receipt is
3943
+ * `toSsId`'s own when it is held from such a datagram. Otherwise (its
3944
+ * packet came only as an overlap copy or from a MoQ stream, or was evicted
3945
+ * or retired) it is the newest among those SS_IDs, every one of which is
3946
+ * held and states its path. So the time moves at most once, when the
3947
+ * head's own datagram copy arrives while its frame waits or its held
3948
+ * source is dropped, and never on a later ask.
3949
+ *
3950
+ * Undefined, so the range releases at once, when no SS_ID of it came as
3951
+ * such a datagram: a MoQ arrival, an ordered relay's and the frame's own
3952
+ * are no clock for datagram reordering (#lossyReceiptMs). Undefined too
3953
+ * on a track with no catalog span, which states no allowance: the local
3954
+ * timeout is a cleanup bound, and isoRepairlessWaitMs arms no wake there,
3955
+ * so a wait would hold the frame until the next packet. The cost, on
3956
+ * multicast and on the leg too: an untagged FT=0/FT=1 reordered behind
3957
+ * the next frame of such a track is dropped stale.
3958
+ */
3959
+ #lossFreeRunReadyAtMs(config, locator, runStart, toSsId) {
3960
+ if (!_FECManager.#hasCatalogTiming(config)) return void 0;
3961
+ let clockMs = this.#lossyReceiptMs(locator.heldSource(toSsId));
3962
+ if (clockMs === void 0) {
3963
+ for (let ssId = runStart; ssId !== toSsId; ssId = ssId + 1 >>> 0) {
3964
+ const atMs = this.#lossyReceiptMs(locator.heldSource(ssId));
3965
+ if (atMs !== void 0 && (clockMs === void 0 || atMs > clockMs)) clockMs = atMs;
3966
+ }
3967
+ }
3968
+ if (clockMs === void 0) return void 0;
3969
+ return clockMs + Math.max(0, this.#multicastWaitMs(config) - config.interleaveDepthMs);
3970
+ }
3971
+ /**
3972
+ * Receipt time of a held source that came as a datagram of a lossy path
3973
+ * (#lossyDatagramPath), else undefined: a MoQ stream and an ordered relay
3974
+ * deliver in order, so their arrivals clock no reorder allowance and no
3975
+ * FEC deadline. The path is the one the feed stated (IsoHeldSource.source,
3976
+ * and MulticastSymbolDelivery for a multicast source), never a guess.
3977
+ */
3978
+ #lossyReceiptMs(held) {
3979
+ return held !== void 0 && this.#lossyDatagramPath(held.source) ? held.arrivedAtMs : void 0;
3980
+ }
3981
+ /**
3982
+ * The one path predicate of the loss gates: whether a symbol fed as
3983
+ * `source` reached this manager as a datagram of its own, on a path that
3984
+ * loses and reorders (mmt-02 Section 2, a datagram leg). A multicast
3985
+ * symbol does unless its provider declared an ordered relay. An
3986
+ * "mfu-datagram" object always does (4.3.1): MulticastSymbolDelivery is
3987
+ * the multicast provider's statement and is never read for the leg. A MoQ
3988
+ * stream object never does, a stream copy of the leg included.
3989
+ */
3990
+ #lossyDatagramPath(source) {
3991
+ return source === "moq-datagram" || source === "multicast" && this.#multicastSymbolDelivery === "datagram";
3992
+ }
3993
+ /**
3994
+ * The release gate's wait, from a frame's arrival, for the SS_IDs strictly
3995
+ * between two released frames' SS_IDs once only a late source can still
3996
+ * fill them, else undefined. That is when every one missing (neither
3997
+ * arrived nor held) lies in a repair-less span longer than K, which no
3998
+ * repair can state a block of (#openIsoSpan), or in a stated block its
3999
+ * own repair group cannot complete every SS_ID of which it misses lies
4000
+ * between them (so the gap's decision covers all it lost), and a source of
4001
+ * a lossy leg (multicast, or an "mfu-datagram" leg's datagram) at or past
4002
+ * `toSsId` arrived, so each is lost or reordered behind it (a MoQ source
4003
+ * shows nothing: MoQ streams overtake one another). The span or block
4004
+ * itself keeps its own wait.
4005
+ *
4006
+ * The wait is the late-symbol allowance, unless `rapMayHide`: the gap may
4007
+ * hold a RAP packet an installed keyframe overlay can still rebuild (its
4008
+ * decision stalls, or it ends at a RAP that may lie past a whole MPU).
4009
+ * Then the frame waits as a stated block its group cannot complete does
4010
+ * (#overlayLateWaitMs): the allowance alone with no overlay installed, the
4011
+ * overlay's span plus the larger of the allowance and its tolerance, or,
4012
+ * for an overlay that states no span, the span's whole wait (undefined).
4013
+ * So does `rapNext` (the gap ends at the RAP that opens the next MPU) when
4014
+ * the gap holds a stated block's loss.
4015
+ *
4016
+ * A run of SS_IDs no repair has delimited yet, one of which never arrived,
4017
+ * is one block of its own instead (draft-ramadan-moq-fec-multicast-00,
4018
+ * Receiver Repair Policy; on an "mfu-datagram" leg fec-core-00 9.3 and
4019
+ * mmt-02 5.3.3): the frame then waits for that block's FEC deadline,
4020
+ * whatever the flags: ts plus the whole multicast wait (fec-core-00 9.3),
4021
+ * ts the receipt of the lowest held source above the run that came as a
4022
+ * datagram of a lossy path (#lossyDatagramPath), up to the newest
4023
+ * (fec-multicast-00, Deadline Anchoring; under reordering at or after the
4024
+ * draft's first signal, never before). The wait returned counts from
4025
+ * `arrivedAtMs`, the frame's arrival; without it, it is the whole wait.
4026
+ * With no such source held (never arrived, retired, or evicted, or every
4027
+ * one from a MoQ stream or an ordered relay) the frame keeps the hold
4028
+ * ceiling: a stream arrival is no clock for a datagram deadline.
4029
+ */
4030
+ isoRepairlessWaitMs(packetId, catalogTrackName, fromSsId, toSsId, rapMayHide = false, rapNext = false, arrivedAtMs) {
4031
+ const config = this.#trackConfigs.get(packetId);
4032
+ if (config === void 0 || !_FECManager.#hasCatalogTiming(config)) return void 0;
4033
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
4034
+ const locator = this.#isoLocators.get(streamKey);
4035
+ if (locator === void 0) return void 0;
4036
+ const run = locator.undelimitedBetween(fromSsId, toSsId);
4037
+ const readyAtMs = run === null || run.missing !== void 0 ? void 0 : this.#lossFreeRunReadyAtMs(config, locator, run.start, toSsId);
4038
+ if (readyAtMs !== void 0 && this.#receiptNow() < readyAtMs) {
4039
+ return Math.max(0, readyAtMs - (arrivedAtMs ?? this.#receiptNow()));
4040
+ }
4041
+ const newestSource = locator.newestSource;
4042
+ if (newestSource === void 0 || serial32Precedes(newestSource, toSsId)) return void 0;
4043
+ if (run?.missing !== void 0) {
4044
+ if (this.isoSpanResolution(packetId, catalogTrackName, fromSsId, run.start) === null) return void 0;
4045
+ const kept = this.#runAnchors.get(streamKey);
4046
+ const anchor = kept?.fromSsId === fromSsId && this.#receiptNow() - kept.tsMs <= 2 * (config.interleaveDepthMs + 2 * this.#blockLifetimeMs(config)) ? kept : void 0;
4047
+ let tsMs = anchor?.tsMs;
4048
+ for (let ssId = run.missing + 1 >>> 0; !serial32Precedes(newestSource, ssId); ssId = ssId + 1 >>> 0) {
4049
+ const atMs = this.#lossyReceiptMs(locator.heldSource(ssId));
4050
+ if (atMs === void 0) continue;
4051
+ if (tsMs === void 0 || atMs < tsMs) tsMs = atMs;
4052
+ break;
4053
+ }
4054
+ if (tsMs === void 0) return void 0;
4055
+ const waitMs2 = this.#multicastWaitMs(config);
4056
+ let counted = anchor?.counted === true;
4057
+ if (!counted && tsMs + waitMs2 <= this.#receiptNow()) {
4058
+ counted = true;
4059
+ this.onUndelimitedRunGap?.(packetId, catalogTrackName);
4060
+ }
4061
+ this.#runAnchors.set(streamKey, { fromSsId, tsMs, counted });
4062
+ return arrivedAtMs === void 0 ? waitMs2 : Math.max(0, tsMs + waitMs2 - arrivedAtMs);
4063
+ }
4064
+ if (!locator.coversBetween(fromSsId, run?.start ?? toSsId)) return void 0;
4065
+ let repairless = false;
4066
+ let stated = false;
4067
+ for (const block of locator.blocksBetween(fromSsId, toSsId)) {
4068
+ const key = this.#blockKey(block.start, packetId, catalogTrackName);
4069
+ if (this.#completedBlocks.has(key)) continue;
4070
+ if (block.span && block.length > locator.kMax) {
4071
+ repairless = true;
4072
+ continue;
4073
+ }
4074
+ const received = this.#blockSourceEsis.get(key);
4075
+ const rebuilt = this.#blockRebuiltEsis.get(key);
4076
+ let missesInGap = false;
4077
+ let missesOutside = false;
4078
+ for (let esi = 0; esi < block.length; esi++) {
4079
+ const ssId = serial32Add(block.start, esi);
4080
+ if (received?.has(esi) || locator.isHeld(ssId)) continue;
4081
+ if (serial32Precedes(fromSsId, ssId) && serial32Precedes(ssId, toSsId)) missesInGap = true;
4082
+ else if (!rebuilt?.has(esi)) missesOutside = true;
4083
+ }
4084
+ if (!missesInGap) continue;
4085
+ if (missesOutside || block.span || !this.#groupCannotComplete(key)) return void 0;
4086
+ repairless = stated = true;
4087
+ }
4088
+ if (!repairless) return void 0;
4089
+ const waitMs = rapMayHide || stated && rapNext ? this.#overlayLateWaitMs(packetId, catalogTrackName, config) : this.#multicastWaitMs(config) - config.interleaveDepthMs;
4090
+ return waitMs === void 0 ? void 0 : Math.max(0, waitMs);
4091
+ }
3534
4092
  /**
3535
4093
  * iso-ssbg1-v1 block location: repair symbols it refused, oversize sources,
3536
4094
  * the sources held now for a block no repair has stated yet, and the held
@@ -3584,11 +4142,31 @@ var FECManager = class _FECManager {
3584
4142
  * it does not. A stream with no classifier yet has shown nothing against it,
3585
4143
  * and neither has a stream without catalog timing until it releases two
3586
4144
  * RAPs inside one MPU.
4145
+ *
4146
+ * With catalog timing and a `gap` inside one MPU, between the authored
4147
+ * timing of the frames on either side, it also takes the catalog keyframe
4148
+ * interval to rule a keyframe out of the gap
4149
+ * (`BlockClassifier.keyframeFreeBetween`, fec-multicast-00 Block
4150
+ * Classification item 3), and no source held between the frames' SS_IDs
4151
+ * may carry the RAP flag or another MPU's number (item 1 read on the held
4152
+ * packets: a RAP the loss cut in two is never released, so the frames
4153
+ * alone cannot show it); anything unknown counts as a keyframe.
3587
4154
  */
3588
- mpuBoundsRapsFor(packetId, catalogTrackName) {
4155
+ mpuBoundsRapsFor(packetId, catalogTrackName, gap) {
3589
4156
  const streamKey = this.#streamKey(packetId, catalogTrackName);
3590
4157
  if (!this.#hasCatalogTimingForPacket(packetId)) return this.#noSpanRaps.get(streamKey)?.inside !== true;
3591
- return this.#classifiers.get(streamKey)?.mpuBoundsRaps ?? true;
4158
+ const classifier = this.#classifiers.get(streamKey);
4159
+ if (gap === void 0) return classifier?.mpuBoundsRaps ?? true;
4160
+ const { mpu, from, to, fromSsId, toSsId } = gap;
4161
+ if (fromSsId !== void 0 && toSsId !== void 0) {
4162
+ const run = this.#isoLocators.get(streamKey)?.undelimitedBetween(
4163
+ fromSsId,
4164
+ toSsId,
4165
+ ({ evidence }) => evidence.rap || evidence.mpu !== void 0 && evidence.mpu !== mpu
4166
+ );
4167
+ if (run?.flagged) return false;
4168
+ }
4169
+ return classifier !== void 0 && from !== void 0 && to !== void 0 && from.mediaTimescale === to.mediaTimescale && classifier.keyframeFreeBetween(mpu, from.decodeTime, to.decodeTime, from.mediaTimescale);
3592
4170
  }
3593
4171
  /** A block's class now, or frozen at its resolution. */
3594
4172
  blockClassFor(sbn, packetId, catalogTrackName) {
@@ -3611,9 +4189,11 @@ var FECManager = class _FECManager {
3611
4189
  }
3612
4190
  /**
3613
4191
  * Record a RAP frame released in order, for the classifier's RAP-spacing
3614
- * invariant (consecutive MPUs exactly one keyframe interval apart).
4192
+ * invariant (consecutive MPUs exactly one keyframe interval apart) and,
4193
+ * with its decode time, as the MPU start gap decisions measure the catalog
4194
+ * keyframe interval from (mpuBoundsRapsFor).
3615
4195
  */
3616
- noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale) {
4196
+ noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale, decodeTime) {
3617
4197
  if (!this.#trackConfigs.has(packetId)) return;
3618
4198
  if (!this.#hasCatalogTimingForPacket(packetId)) {
3619
4199
  const streamKey = this.#streamKey(packetId, catalogTrackName);
@@ -3628,7 +4208,8 @@ var FECManager = class _FECManager {
3628
4208
  this.#classifierFor(packetId, catalogTrackName).noteReleasedRap(
3629
4209
  mpu,
3630
4210
  presentationTime,
3631
- mediaTimescale
4211
+ mediaTimescale,
4212
+ decodeTime
3632
4213
  )
3633
4214
  );
3634
4215
  }
@@ -3834,11 +4415,14 @@ var FECManager = class _FECManager {
3834
4415
  });
3835
4416
  client.onCleanupComplete((sbn) => {
3836
4417
  if (this.#releasedWorkerClients.has(client)) return;
3837
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
4418
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
4419
+ const cleanupKeys = owed.filter((key) => {
3838
4420
  const block = this.#parseBlockKey(key);
3839
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
4421
+ return block.packetId === packetId && block.sbn === sbn;
3840
4422
  });
3841
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
4423
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
4424
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
4425
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
3842
4426
  });
3843
4427
  client.onError((msg, code) => {
3844
4428
  const requestedKind = code ?? msg;
@@ -3908,9 +4492,11 @@ var FECManager = class _FECManager {
3908
4492
  * fail deadline already passed, so failing it is the decision that deadline
3909
4493
  * made. A late ack then finds nothing owed and is a no-op.
3910
4494
  */
3911
- #boundOwedCleanup(key, packetId, client) {
4495
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
3912
4496
  this.#clearOwedCleanupBound(key);
3913
4497
  const bound = {
4498
+ dueAtMs,
4499
+ askedAtMs: performance.now(),
3914
4500
  handle: setTimeout(() => {
3915
4501
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
3916
4502
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -4008,7 +4594,15 @@ var FECManager = class _FECManager {
4008
4594
  this.#isoSourceOversizeCount++;
4009
4595
  return null;
4010
4596
  }
4011
- const sbn = located.block.start;
4597
+ return this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, located.block.start);
4598
+ }
4599
+ /**
4600
+ * Hand one placed source symbol to the stream's decoder: its Worker, which
4601
+ * answers through onFrame (null here), or its synchronous decoder, whose
4602
+ * recovered block is returned. `sbn` is the SS_Start of the block a repair
4603
+ * stated for `ssId`.
4604
+ */
4605
+ #feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn) {
4012
4606
  const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
4013
4607
  const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey);
4014
4608
  const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
@@ -4037,6 +4631,74 @@ var FECManager = class _FECManager {
4037
4631
  }
4038
4632
  return recovered;
4039
4633
  }
4634
+ /**
4635
+ * Feed a source symbol of this stream that another FEC instance over the
4636
+ * same packets rebuilt: a keyframe overlay recovery whose base SS_ID the
4637
+ * caller determined (draft-ramadan-moq-mmt-02 7.1, 7.4.4; joint decoding,
4638
+ * BLO-52085). It joins its block's decoder as a received source would, so
4639
+ * it reduces the erasures the block still has to solve, but it is not a
4640
+ * network arrival: no transport accounting, no classification evidence,
4641
+ * no deadline refresh, and it never makes a block clean.
4642
+ *
4643
+ * Only a block a repair stated takes one (a repair-less span has no
4644
+ * decoder block). A block that is terminal, or already holds that source,
4645
+ * does not. The symbol is the exact protected packet, unpadded, as
4646
+ * feedSourceSymbol takes it.
4647
+ *
4648
+ * `recovered` is the block the synchronous decoder completed with it; the
4649
+ * caller routes it and completes the block, as for any recovery. When
4650
+ * every source of the block is then present, received or rebuilt, and no
4651
+ * decoder returned it (a Worker answers asynchronously, and reports such a
4652
+ * block as clean on its own side), the block is completed here as
4653
+ * recovered, with nothing left to route.
4654
+ */
4655
+ feedRebuiltSourceSymbol(packetId, ssId, symbolData, catalogTrackName) {
4656
+ if (!this.#hasBlockProfile(packetId)) return NOT_TAKEN;
4657
+ const located = this.#isoLocatorFor(packetId, catalogTrackName).locate(ssId);
4658
+ if (located === null || located.block.span) return NOT_TAKEN;
4659
+ if (!ssbg1FitsSymbol(symbolData.byteLength, this.#trackConfig(packetId).symbolSize)) return NOT_TAKEN;
4660
+ const sbn = located.block.start;
4661
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
4662
+ if (this.#completedBlocks.has(key) || this.#blockSourceEsis.get(key)?.has(located.esi)) return NOT_TAKEN;
4663
+ let rebuilt = this.#blockRebuiltEsis.get(key);
4664
+ if (rebuilt?.has(located.esi)) return NOT_TAKEN;
4665
+ if (rebuilt === void 0) {
4666
+ rebuilt = /* @__PURE__ */ new Set();
4667
+ this.#blockRebuiltEsis.set(key, rebuilt);
4668
+ }
4669
+ const config = this.#trackConfigs.get(packetId);
4670
+ const wasShort = config !== void 0 && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) !== void 0;
4671
+ rebuilt.add(located.esi);
4672
+ const recovered = this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn);
4673
+ if (recovered === null && !this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName)) {
4674
+ if (wasShort && this.#activeBlocks.has(key) && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) === void 0) {
4675
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, this.#multicastWaitMs(config));
4676
+ }
4677
+ }
4678
+ return { taken: true, recovered };
4679
+ }
4680
+ /**
4681
+ * A block that holds every one of its `length` sources, received or
4682
+ * rebuilt by another instance, with at least one rebuilt, is recovered:
4683
+ * every packet of it was delivered, by its own arrival or by the instance
4684
+ * that rebuilt it, so nothing is routed. Returns whether it completed it.
4685
+ */
4686
+ #completeWhenSourcesPresent(key, sbn, length, packetId, catalogTrackName) {
4687
+ const rebuilt = this.#blockRebuiltEsis.get(key);
4688
+ if (rebuilt === void 0 || this.#completedBlocks.has(key)) return false;
4689
+ let present = rebuilt.size;
4690
+ for (const esi of this.#blockSourceEsis.get(key) ?? []) if (!rebuilt.has(esi)) present++;
4691
+ if (present < length) return false;
4692
+ this.#traceLifecycle("recovered", sbn, packetId, catalogTrackName);
4693
+ this.countRecovery(packetId, sbn, catalogTrackName);
4694
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
4695
+ if (catalogTrackName === void 0) {
4696
+ this.onBlockComplete?.(sbn, packetId);
4697
+ } else {
4698
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName);
4699
+ }
4700
+ return true;
4701
+ }
4040
4702
  /**
4041
4703
  * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
4042
4704
  * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
@@ -4098,7 +4760,10 @@ var FECManager = class _FECManager {
4098
4760
  this.#layerAnchorHorizon(packetId),
4099
4761
  this.#sourceFrontiers.get(streamKey)?.sbn
4100
4762
  );
4101
- if (verdict === "discard") return false;
4763
+ if (verdict === "discard") {
4764
+ this.#unlistedRepairTrackRefusals++;
4765
+ return false;
4766
+ }
4102
4767
  if (verdict !== void 0) {
4103
4768
  this.#failClosed(streamKey, verdict, packetId, catalogTrackName);
4104
4769
  return false;
@@ -4247,15 +4912,17 @@ var FECManager = class _FECManager {
4247
4912
  * its sources in send order, so one that moves the stream's newest source
4248
4913
  * position past a block leaves the sources that block still misses
4249
4914
  * reordered behind it at best: it shortens the wait of every block it
4250
- * passed that only a late source can complete. MoQ is left out: its streams
4251
- * can overtake one another, so a MoQ source shows nothing about the sources
4252
- * sent before it.
4915
+ * passed that only a late source can complete. Reliable MoQ is left out:
4916
+ * its streams can overtake one another, so a MoQ source shows nothing
4917
+ * about the sources sent before it. An "mfu-datagram" leg is in: its
4918
+ * datagrams leave the publisher in send order and reorder only within the
4919
+ * path's tolerance, as multicast does.
4253
4920
  */
4254
4921
  #noteMulticastSource(locator, ssId, packetId, catalogTrackName) {
4255
4922
  const previous = locator.newestSource;
4256
4923
  if (!locator.noteSource(ssId) || previous === void 0) return;
4257
4924
  for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
4258
- if (block.span || !serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
4925
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
4259
4926
  this.#shortenUnrecoverableWait(
4260
4927
  this.#blockKey(block.start, packetId, catalogTrackName),
4261
4928
  block.start,
@@ -4273,18 +4940,61 @@ var FECManager = class _FECManager {
4273
4940
  * covers repair symbols paced after its sources, buys it nothing: it waits
4274
4941
  * the late-symbol allowance alone, the multicast wait less the span (the
4275
4942
  * catalog tolerance or the measured delivery gap). Undefined for any other
4276
- * block.
4943
+ * block. While a keyframe overlay is installed, the block waits for its
4944
+ * repair too (#overlayLateWaitMs). A repair-less span keeps its whole
4945
+ * wait, even one longer than K whose group is empty (#openIsoSpan): its
4946
+ * resolution is what releases the frames behind it, and failing it early
4947
+ * released them past a keyframe the overlay was still rebuilding, which
4948
+ * then arrived stale. The release gate lets them go instead
4949
+ * (isoRepairlessWaitMs).
4277
4950
  */
4278
4951
  #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
4952
+ if (this.#isoSpanKeys.has(key) || !this.#groupCannotComplete(key)) return void 0;
4279
4953
  const authoredLength = this.#blockAuthoredLengths.get(key);
4280
- const rsbLength = this.#blockRsbLengths.get(key);
4281
- if (authoredLength === void 0 || rsbLength === void 0) return void 0;
4282
- if ((this.#blockSourceCounts.get(key) ?? 0) + rsbLength >= authoredLength) return void 0;
4283
4954
  const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
4284
4955
  if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
4285
4956
  return void 0;
4286
4957
  }
4287
- return this.#multicastWaitMs(config) - config.interleaveDepthMs;
4958
+ return this.#overlayLateWaitMs(packetId, catalogTrackName, config);
4959
+ }
4960
+ /**
4961
+ * A repair stated the block, and its sources plus every symbol its repair
4962
+ * group carries (RSB_length) are short of its SSB_length.
4963
+ */
4964
+ #groupCannotComplete(key) {
4965
+ const authoredLength = this.#blockAuthoredLengths.get(key);
4966
+ const rsbLength = this.#blockRsbLengths.get(key);
4967
+ if (authoredLength === void 0 || rsbLength === void 0) return false;
4968
+ let present = this.#blockSourceCounts.get(key) ?? 0;
4969
+ const received = this.#blockSourceEsis.get(key);
4970
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
4971
+ return present + rsbLength < authoredLength;
4972
+ }
4973
+ /**
4974
+ * How long a loss only a late source or an installed keyframe overlay can
4975
+ * still fill waits once a later source passed it: the late-symbol
4976
+ * allowance alone (the multicast wait less the span) while no overlay is
4977
+ * installed. An installed one (keyframeOverlayTiming) may still rebuild a
4978
+ * RAP packet the loss took: a second FEC instance over the same packets
4979
+ * (draft-ramadan-moq-mmt-02 7.4), whose repair is paced across its own
4980
+ * span, unrelated to the base's. That packet can complete a stated block
4981
+ * (feedRebuiltSourceSymbol), or play behind a span; giving the loss up
4982
+ * first lets the release gate pass the keyframe, whose rebuild then lands
4983
+ * stale. The overlay repair of a packet the loss took goes out within the
4984
+ * overlay's span of that packet (fec-core-00 9.3), and the later source was
4985
+ * sent after it, so the loss waits that span plus the larger of the
4986
+ * allowance and the overlay's own tolerance. An overlay that states no
4987
+ * span (its block may then span keyframes), or one whose wait is not
4988
+ * shorter than the whole multicast wait, leaves the whole wait: undefined.
4989
+ */
4990
+ #overlayLateWaitMs(packetId, catalogTrackName, config) {
4991
+ const waitMs = this.#multicastWaitMs(config);
4992
+ const allowanceMs = waitMs - config.interleaveDepthMs;
4993
+ const overlay = this.keyframeOverlayTiming?.(packetId, catalogTrackName);
4994
+ if (overlay === void 0) return allowanceMs;
4995
+ const overlaySpanMs = overlay.interleaveDepthMs ?? 0;
4996
+ const overlayWaitMs = overlaySpanMs + Math.max(allowanceMs, overlay.reorderToleranceMs ?? 0);
4997
+ return overlaySpanMs > 0 && overlayWaitMs < waitMs ? overlayWaitMs : void 0;
4288
4998
  }
4289
4999
  /**
4290
5000
  * Bring an open block's wait in to its late-source wait, when it has one.
@@ -4402,12 +5112,13 @@ var FECManager = class _FECManager {
4402
5112
  * the inactivity deadline on each symbol, records the symbol's in-band
4403
5113
  * classification evidence, and marks the block clean when all of its
4404
5114
  * authored source symbols arrived: the SSB_length a repair symbol declared,
4405
- * otherwise K.
5115
+ * otherwise K. `held` marks a source held unplaced since it arrived and
5116
+ * placed only now (see #noteSbnSeen).
4406
5117
  *
4407
5118
  * Throws for a packetId that was never configured, so a classified block
4408
5119
  * never reads the manager-global K or timeout.
4409
5120
  */
4410
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
5121
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
4411
5122
  const trackConfig = this.#trackConfigs.get(packetId);
4412
5123
  if (trackConfig === void 0) {
4413
5124
  throw new Error(
@@ -4423,7 +5134,8 @@ var FECManager = class _FECManager {
4423
5134
  catalogTrackName,
4424
5135
  "source",
4425
5136
  evidence.packetSequenceNumber,
4426
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
5137
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
5138
+ held
4427
5139
  );
4428
5140
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
4429
5141
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -4459,6 +5171,15 @@ var FECManager = class _FECManager {
4459
5171
  this.#completeCleanBlock(key, sbn, packetId, catalogTrackName);
4460
5172
  return;
4461
5173
  }
5174
+ if (this.#blockRebuiltEsis.has(key) && this.#completeWhenSourcesPresent(
5175
+ key,
5176
+ sbn,
5177
+ this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? authoredLength,
5178
+ packetId,
5179
+ catalogTrackName
5180
+ )) {
5181
+ return;
5182
+ }
4462
5183
  this.noteBlockActivity(sbn, packetId, catalogTrackName, true);
4463
5184
  }
4464
5185
  #completeCleanBlock(key, sbn, packetId, catalogTrackName) {
@@ -4467,7 +5188,9 @@ var FECManager = class _FECManager {
4467
5188
  this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
4468
5189
  this.#blockSourceCounts.delete(key);
4469
5190
  this.#blockSourceEsis.delete(key);
5191
+ this.#blockRebuiltEsis.delete(key);
4470
5192
  this.#blockAuthoredLengths.delete(key);
5193
+ this.#isoSpanKeys.delete(key);
4471
5194
  this.#blockRepairRsIds.delete(key);
4472
5195
  this.#blockRsbLengths.delete(key);
4473
5196
  this.#markTerminal(key, sbn, packetId, true);
@@ -4498,6 +5221,19 @@ var FECManager = class _FECManager {
4498
5221
  #receiptNow() {
4499
5222
  return this.#receiptAtMs ?? performance.now();
4500
5223
  }
5224
+ /**
5225
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
5226
+ * scope: counted from the receipt time, as the timer of a symbol fed when
5227
+ * it was received was, less the whole ms since. So it fires on the tick
5228
+ * that timer would have, never later than a delay counted from now, and
5229
+ * its handler still re-arms a timer that fires before its deadline.
5230
+ * Counted from now, a deadline set from the receipt time is rounded up
5231
+ * from another fraction of a ms (BLO-52085).
5232
+ */
5233
+ #receiptTimerDelayMs(deadlineMs, minMs) {
5234
+ const receivedAtMs = this.#receiptAtMs;
5235
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
5236
+ }
4501
5237
  /**
4502
5238
  * A held packet admitted late arms from its (earlier) receipt time; that
4503
5239
  * never pulls in a deadline later activity already armed. Outside a
@@ -4546,6 +5282,7 @@ var FECManager = class _FECManager {
4546
5282
  }
4547
5283
  #failBlock(sbn, packetId, catalogTrackName) {
4548
5284
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
5285
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
4549
5286
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
4550
5287
  this.#clearRepairDeadline(key);
4551
5288
  this.#clearBlockTimer(key);
@@ -4555,6 +5292,7 @@ var FECManager = class _FECManager {
4555
5292
  }
4556
5293
  this.#blockSourceCounts.delete(key);
4557
5294
  this.#blockSourceEsis.delete(key);
5295
+ this.#blockRebuiltEsis.delete(key);
4558
5296
  this.#blockAuthoredLengths.delete(key);
4559
5297
  this.#blockRepairRsIds.delete(key);
4560
5298
  this.#blockRsbLengths.delete(key);
@@ -4564,7 +5302,8 @@ var FECManager = class _FECManager {
4564
5302
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
4565
5303
  this.#fecStats.blocksFailed++;
4566
5304
  this.#statsForPacket(packetId).blocksFailed++;
4567
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5305
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
5306
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
4568
5307
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
4569
5308
  }
4570
5309
  /**
@@ -4593,7 +5332,9 @@ var FECManager = class _FECManager {
4593
5332
  this.#retireBlockClass(key, block.sbn, block.packetId, block.catalogTrackName);
4594
5333
  this.#blockSourceCounts.delete(key);
4595
5334
  this.#blockSourceEsis.delete(key);
5335
+ this.#blockRebuiltEsis.delete(key);
4596
5336
  this.#blockAuthoredLengths.delete(key);
5337
+ this.#isoSpanKeys.delete(key);
4597
5338
  this.#blockRepairRsIds.delete(key);
4598
5339
  this.#blockRsbLengths.delete(key);
4599
5340
  this.#clearBlockTimer(key);
@@ -4642,7 +5383,7 @@ var FECManager = class _FECManager {
4642
5383
  blockDeliveryProvenance(sbn, packetId, catalogTrackName) {
4643
5384
  const counts = this.blockPathCount(sbn, packetId, catalogTrackName);
4644
5385
  if (!counts) return "unknown";
4645
- if (counts.moqSymbols > 0) return "mixed";
5386
+ if (counts.moqSymbols > 0 || counts.datagramSymbols > 0) return "mixed";
4646
5387
  if (counts.multicastSymbols > 0) return "multicast";
4647
5388
  return "unknown";
4648
5389
  }
@@ -4669,7 +5410,7 @@ var FECManager = class _FECManager {
4669
5410
  this.#activeBlockDeadlinesMs.clear();
4670
5411
  this.#blockWaitDeadlinesMs.clear();
4671
5412
  this.#repairHoldUntilMs.clear();
4672
- this.#deliveryGaps.reset();
5413
+ for (const estimator of Object.values(this.#deliveryGaps)) estimator.reset();
4673
5414
  this.#pendingWorkerCleanups.clear();
4674
5415
  this.#pendingWorkerCleanupClients.clear();
4675
5416
  for (const bound of this.#pendingWorkerCleanupBounds.values()) clearTimeout(bound.handle);
@@ -4684,7 +5425,9 @@ var FECManager = class _FECManager {
4684
5425
  this.#blockKeysBySbn.clear();
4685
5426
  this.#blockSourceCounts.clear();
4686
5427
  this.#blockSourceEsis.clear();
5428
+ this.#blockRebuiltEsis.clear();
4687
5429
  this.#blockAuthoredLengths.clear();
5430
+ this.#isoSpanKeys.clear();
4688
5431
  this.#blockRepairRsIds.clear();
4689
5432
  this.#blockRsbLengths.clear();
4690
5433
  this.#heldLayerStates.clear();
@@ -4718,6 +5461,7 @@ var FECManager = class _FECManager {
4718
5461
  this.#highestSbn.clear();
4719
5462
  this.#sourceFrontiers.clear();
4720
5463
  this.#isoLocators.clear();
5464
+ this.#runAnchors.clear();
4721
5465
  this.#sourceAnchors.clear();
4722
5466
  this.#trackConfigs.clear();
4723
5467
  this.#fecDecoders.clear();