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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +34 -19
  2. package/dist/block-policy.d.ts +55 -13
  3. package/dist/block-policy.d.ts.map +1 -1
  4. package/dist/block-policy.js +104 -32
  5. package/dist/block-policy.js.map +2 -2
  6. package/dist/browser-runtime.js +2094 -385
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.js.map +2 -2
  9. package/dist/catalog-fec-params.d.ts +18 -2
  10. package/dist/catalog-fec-params.d.ts.map +1 -1
  11. package/dist/catalog-fec-params.js +29 -1
  12. package/dist/catalog-fec-params.js.map +2 -2
  13. package/dist/catalog-network-source.js.map +2 -2
  14. package/dist/cmaf-block-assembler.js +92 -1
  15. package/dist/cmaf-block-assembler.js.map +2 -2
  16. package/dist/cmcd-producer.d.ts +60 -47
  17. package/dist/cmcd-producer.d.ts.map +1 -1
  18. package/dist/cmcd-producer.js +138 -109
  19. package/dist/cmcd-producer.js.map +2 -2
  20. package/dist/codec-utils.d.ts.map +1 -1
  21. package/dist/codec-utils.js +92 -1
  22. package/dist/codec-utils.js.map +2 -2
  23. package/dist/delivery-catalog.js +26 -16
  24. package/dist/delivery-catalog.js.map +2 -2
  25. package/dist/delta-fallback-config.js +5 -1
  26. package/dist/delta-fallback-config.js.map +3 -3
  27. package/dist/fec-manager.d.ts +114 -15
  28. package/dist/fec-manager.d.ts.map +1 -1
  29. package/dist/fec-manager.js +639 -95
  30. package/dist/fec-manager.js.map +2 -2
  31. package/dist/fec-state.js +5 -1
  32. package/dist/fec-state.js.map +2 -2
  33. package/dist/fec-worker-setup.d.ts +1 -1
  34. package/dist/fec-worker-setup.js +1 -1
  35. package/dist/fec-worker-setup.js.map +2 -2
  36. package/dist/held-layer-admission.js.map +2 -2
  37. package/dist/index.d.ts +6 -5
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +12 -2
  40. package/dist/index.js.map +2 -2
  41. package/dist/iso-block-locator.d.ts +48 -13
  42. package/dist/iso-block-locator.d.ts.map +1 -1
  43. package/dist/iso-block-locator.js +97 -25
  44. package/dist/iso-block-locator.js.map +2 -2
  45. package/dist/iso-bmff-timing.d.ts +10 -1
  46. package/dist/iso-bmff-timing.d.ts.map +1 -1
  47. package/dist/iso-bmff-timing.js +36 -2
  48. package/dist/iso-bmff-timing.js.map +2 -2
  49. package/dist/media-router.js.map +1 -1
  50. package/dist/mfu-reassembler.js +12 -19
  51. package/dist/mfu-reassembler.js.map +2 -2
  52. package/dist/mmtp-container-parser.d.ts +106 -12
  53. package/dist/mmtp-container-parser.d.ts.map +1 -1
  54. package/dist/mmtp-container-parser.js +324 -46
  55. package/dist/mmtp-container-parser.js.map +2 -2
  56. package/dist/mmtp-container-parser.no-modules.js +466 -66
  57. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  58. package/dist/mmtp-decode-pipeline.js +323 -46
  59. package/dist/mmtp-decode-pipeline.js.map +2 -2
  60. package/dist/mmtp-fec-session.d.ts +41 -3
  61. package/dist/mmtp-fec-session.d.ts.map +1 -1
  62. package/dist/mmtp-fec-session.js +118 -13
  63. package/dist/mmtp-fec-session.js.map +3 -3
  64. package/dist/mmtp-router.d.ts +36 -8
  65. package/dist/mmtp-router.d.ts.map +1 -1
  66. package/dist/mmtp-router.js +716 -100
  67. package/dist/mmtp-router.js.map +3 -3
  68. package/dist/multicast-auth-catalog.js.map +2 -2
  69. package/dist/multicast-input.js.map +2 -2
  70. package/dist/multicast-manager.d.ts +28 -3
  71. package/dist/multicast-manager.d.ts.map +1 -1
  72. package/dist/multicast-manager.js +1451 -215
  73. package/dist/multicast-manager.js.map +3 -3
  74. package/dist/multicast-transport.js +28 -18
  75. package/dist/multicast-transport.js.map +2 -2
  76. package/dist/multicast-unwrap.js +12 -19
  77. package/dist/multicast-unwrap.js.map +2 -2
  78. package/dist/no-modules.d.ts +1 -0
  79. package/dist/no-modules.d.ts.map +1 -1
  80. package/dist/no-modules.js +463 -64
  81. package/dist/no-modules.js.map +4 -4
  82. package/dist/repair-fetch.d.ts +38 -8
  83. package/dist/repair-fetch.d.ts.map +1 -1
  84. package/dist/repair-fetch.js +286 -27
  85. package/dist/repair-fetch.js.map +3 -3
  86. package/dist/repair-layer-subscriptions.d.ts +82 -0
  87. package/dist/repair-layer-subscriptions.d.ts.map +1 -0
  88. package/dist/repair-layer-subscriptions.js +192 -0
  89. package/dist/repair-layer-subscriptions.js.map +7 -0
  90. package/dist/signaling.js.map +2 -2
  91. package/dist/timestamp-codec.js +12 -19
  92. package/dist/timestamp-codec.js.map +2 -2
  93. package/dist/track-session.d.ts +1 -1
  94. package/dist/track-session.d.ts.map +1 -1
  95. package/dist/track-session.js +1 -0
  96. package/dist/track-session.js.map +2 -2
  97. package/dist/wasm-mfu-reassembler.js.map +2 -2
  98. package/dist/wasm-mmtp-container-parser.js +323 -46
  99. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  100. package/package.json +8 -5
  101. package/schemas/catalog.schema.json +4 -0
  102. package/src/block-policy.ts +216 -52
  103. package/src/catalog-fec-params.ts +37 -1
  104. package/src/cmcd-producer.ts +189 -179
  105. package/src/codec-utils.ts +121 -1
  106. package/src/fec-manager.ts +619 -37
  107. package/src/fec-worker-setup.ts +2 -2
  108. package/src/index.ts +22 -2
  109. package/src/iso-block-locator.ts +133 -31
  110. package/src/iso-bmff-timing.ts +40 -1
  111. package/src/mmtp-container-parser.ts +353 -32
  112. package/src/mmtp-fec-session.ts +115 -15
  113. package/src/mmtp-router.ts +618 -44
  114. package/src/multicast-manager.ts +139 -16
  115. package/src/no-modules.ts +3 -0
  116. package/src/repair-fetch.ts +366 -50
  117. package/src/repair-layer-subscriptions.ts +261 -0
  118. package/src/track-session.ts +4 -1
@@ -327,6 +327,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
327
327
  this.#heldEvicted = 0;
328
328
  /** Pending holes (see `deferIncompleteGaps`): unstated, sources still held. */
329
329
  this.#holes = [];
330
+ /** Holes the horizon passed while pending: sources held until closed. */
331
+ this.#expired = [];
332
+ /** Of `#expired`, those `takeExpiredHoles` has not handed out yet. */
333
+ this.#newlyExpired = [];
334
+ /**
335
+ * Spans closed from expired holes: behind the horizon, so kept only for
336
+ * `locate` while their sources are fed, until the next retirement.
337
+ */
338
+ this.#closedBehind = [];
330
339
  /**
331
340
  * Keep a gap that is missing a source as a pending hole rather than a span,
332
341
  * so a repair FETCHed for it (draft-ramadan-moq-fec §7.5) can still state
@@ -348,7 +357,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
348
357
  #retentionBlocks;
349
358
  #heldEvicted;
350
359
  #newest;
360
+ #newestSource;
351
361
  #holes;
362
+ #expired;
363
+ #newlyExpired;
364
+ #closedBehind;
352
365
  static #checkedRetention(retentionBlocks) {
353
366
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
354
367
  throw new Error(
@@ -385,6 +398,21 @@ var IsoBlockLocator = class _IsoBlockLocator {
385
398
  observe(position) {
386
399
  if (this.#newest === void 0 || serial32Precedes(this.#newest, position)) this.#newest = position;
387
400
  }
401
+ /**
402
+ * The newest source SS_ID noted with `noteSource` (RFC 1982 order). Unlike
403
+ * `newest`, a repair never moves it: a repair can run ahead of its sources,
404
+ * a source cannot run ahead of the sources sent before it except by
405
+ * reordering.
406
+ */
407
+ get newestSource() {
408
+ return this.#newestSource;
409
+ }
410
+ /** Note a received source's SS_ID; true when it is the newest one yet. */
411
+ noteSource(ssId) {
412
+ if (this.#newestSource !== void 0 && !serial32Precedes(this.#newestSource, ssId)) return false;
413
+ this.#newestSource = ssId;
414
+ return true;
415
+ }
388
416
  /** Held sources evicted by `heldCapacity` (never by the horizon itself). */
389
417
  get heldEvicted() {
390
418
  return this.#heldEvicted;
@@ -403,17 +431,29 @@ var IsoBlockLocator = class _IsoBlockLocator {
403
431
  }
404
432
  /** The known block or span containing `ssId`, with its ESI. */
405
433
  locate(ssId) {
406
- for (let i = this.#blocks.length - 1; i >= 0; i--) {
407
- const block = this.#blocks[i];
408
- if (isoBlockContains(block.start, block.length, ssId)) {
409
- return { block, esi: serial32Distance(block.start, ssId) };
434
+ for (const blocks of [this.#blocks, this.#closedBehind]) {
435
+ for (let i = blocks.length - 1; i >= 0; i--) {
436
+ const block = blocks[i];
437
+ if (isoBlockContains(block.start, block.length, ssId)) {
438
+ return { block, esi: serial32Distance(block.start, ssId) };
439
+ }
410
440
  }
411
441
  }
412
442
  return null;
413
443
  }
414
- /** Number of pending holes. */
444
+ /** Number of holes not closed yet, pending or past the horizon. */
415
445
  get holeCount() {
416
- return this.#holes.length;
446
+ return this.#holes.length + this.#expired.length;
447
+ }
448
+ /**
449
+ * The pending holes the horizon has passed since the last call, in the
450
+ * order it passed them. Each is no longer pending: no repair states a block
451
+ * in it (that repair is `stale`, as for a span the horizon retired) and the
452
+ * release gate does not wait for it. Its owner must close it
453
+ * (`closeHolesWithin`), which turns it into a span that is not kept here.
454
+ */
455
+ takeExpiredHoles() {
456
+ return this.#newlyExpired.splice(0);
417
457
  }
418
458
  /** The stated block (never a span) ending exactly at `end`. */
419
459
  blockEndingAt(end) {
@@ -469,9 +509,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
469
509
  /**
470
510
  * Apply one repair symbol's `(SS_Start, SSB_length)`. The first repair of a
471
511
  * block states its range and places every held source in it; later repair
472
- * symbols of the same block change nothing. A range that contradicts a
473
- * known block (a different length, or an overlap with another block or a
474
- * span) fails closed: the repair symbol is dropped and no block changes.
512
+ * symbols of the same block change nothing. A repair whose range is exactly
513
+ * a repair-less span states that span's one block. A range that contradicts
514
+ * a known block (a different length, or an overlap with another block or
515
+ * with part of a span) fails closed: the repair symbol is dropped and no
516
+ * block changes.
475
517
  * A newly stated block retires behind its SS_Start (see the class note).
476
518
  * A block so far past `newest` that stating it would retire the position
477
519
  * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
@@ -490,7 +532,16 @@ var IsoBlockLocator = class _IsoBlockLocator {
490
532
  const known = this.blockAt(start);
491
533
  if (known !== void 0) {
492
534
  if (known.span) {
493
- return { status: "overlap", reason: `repair block ${start}+${length} falls inside a repair-less span` };
535
+ if (known.length === length) {
536
+ const block2 = { start, length, span: false };
537
+ this.#blocks[this.#blocks.indexOf(known)] = block2;
538
+ return { status: "placed", block: block2, placed: [] };
539
+ }
540
+ return length < known.length ? {
541
+ status: "overlap",
542
+ reason: `repair block ${start}+${length} is only the first block of repair-less span ${known.start}+${known.length}`,
543
+ ofSpan: known
544
+ } : { status: "overlap", reason: `repair block ${start}+${length} runs past repair-less span ${known.start}+${known.length}` };
494
545
  }
495
546
  if (known.length !== length) {
496
547
  return {
@@ -558,18 +609,28 @@ var IsoBlockLocator = class _IsoBlockLocator {
558
609
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
559
610
  }
560
611
  /**
561
- * Turn every pending hole inside `[start, start + length)` into a
562
- * repair-less span, claiming its held sources: its range FETCH ended, so
563
- * nothing more will state its blocks. Returns the spans, in SS_ID order.
612
+ * Turn every hole inside `[start, start + length)` into a repair-less span,
613
+ * claiming its held sources: its range FETCH ended, so nothing more will
614
+ * state its blocks. A hole the horizon passed (`takeExpiredHoles`) leaves a
615
+ * span that is not kept among the blocks, as the horizon would retire it at
616
+ * once; only `locate` finds it, until the next retirement, so its sources
617
+ * can be fed. Returns the spans, in SS_ID order.
564
618
  */
565
619
  closeHolesWithin(start, length) {
566
620
  const closed = [];
567
- for (const hole of [...this.#holes]) {
568
- if (!isoBlockContains(start, length, hole.start)) continue;
569
- this.#holes.splice(this.#holes.indexOf(hole), 1);
570
- const spanBlock = { start: hole.start, length: hole.length, span: true };
571
- closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
572
- this.#blocks.push(spanBlock);
621
+ for (const holes of [this.#holes, this.#expired]) {
622
+ for (const hole of [...holes]) {
623
+ if (!isoBlockContains(start, length, hole.start)) continue;
624
+ holes.splice(holes.indexOf(hole), 1);
625
+ const spanBlock = { start: hole.start, length: hole.length, span: true };
626
+ closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
627
+ if (holes === this.#holes) {
628
+ this.#blocks.push(spanBlock);
629
+ } else {
630
+ this.#closedBehind.push(spanBlock);
631
+ if (this.#newlyExpired.includes(hole)) this.#newlyExpired.splice(this.#newlyExpired.indexOf(hole), 1);
632
+ }
633
+ }
573
634
  }
574
635
  return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
575
636
  }
@@ -583,15 +644,17 @@ var IsoBlockLocator = class _IsoBlockLocator {
583
644
  return void 0;
584
645
  }
585
646
  /**
586
- * Retire every block and span whose last SS_ID, and every held source,
587
- * lies more than `retentionBlocks` blocks behind `position`, with the shared
588
- * lower-bound metric (`isoBlocksBehindLowerBound`) every ISO interleave
589
- * horizon uses. Returns the retired block starts.
647
+ * Retire every block and span whose last SS_ID, and every held source
648
+ * outside a hole, lies more than `retentionBlocks` blocks behind
649
+ * `position`, with the shared lower-bound metric (`isoBlocksBehindLowerBound`)
650
+ * every ISO interleave horizon uses; a pending hole so far behind expires
651
+ * (`takeExpiredHoles`). Returns the retired block starts.
590
652
  */
591
653
  retireBehind(position) {
592
654
  this.observe(position);
593
655
  const horizon = this.#retentionBlocks;
594
656
  const retired = [];
657
+ this.#closedBehind.length = 0;
595
658
  for (let i = this.#blocks.length - 1; i >= 0; i--) {
596
659
  const block = this.#blocks[i];
597
660
  const last = serial32Add(block.start, block.length - 1);
@@ -603,10 +666,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
603
666
  for (let i = this.#holes.length - 1; i >= 0; i--) {
604
667
  const hole = this.#holes[i];
605
668
  const last = serial32Add(hole.start, hole.length - 1);
606
- if (isoBlocksBehindLowerBound(last, position, this.#kMax) > horizon) this.#holes.splice(i, 1);
669
+ if (isoBlocksBehindLowerBound(last, position, this.#kMax) <= horizon) continue;
670
+ this.#holes.splice(i, 1);
671
+ this.#expired.push(hole);
672
+ this.#newlyExpired.push(hole);
607
673
  }
608
674
  for (const ssId of [...this.#held.keys()]) {
609
- if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon) this.#held.delete(ssId);
675
+ 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))) {
676
+ this.#held.delete(ssId);
677
+ }
610
678
  }
611
679
  return retired;
612
680
  }
@@ -614,9 +682,13 @@ var IsoBlockLocator = class _IsoBlockLocator {
614
682
  reset() {
615
683
  this.#blocks.length = 0;
616
684
  this.#holes.length = 0;
685
+ this.#expired.length = 0;
686
+ this.#newlyExpired.length = 0;
687
+ this.#closedBehind.length = 0;
617
688
  this.#held.clear();
618
689
  this.#coverageEnd = void 0;
619
690
  this.#newest = void 0;
691
+ this.#newestSource = void 0;
620
692
  }
621
693
  #claim(block) {
622
694
  const placed = [];
@@ -659,8 +731,9 @@ function keyframeIntervalMediaTicks(geometry, mediaTimescale) {
659
731
  return scaled / divisor;
660
732
  }
661
733
  function compareDataUnitStarts(a, b) {
662
- return a.movieFragment - b.movieFragment || a.idx - b.idx || a.offset - b.offset;
734
+ return a.movieFragment - b.movieFragment | 0 || a.idx - b.idx || a.offset - b.offset;
663
735
  }
736
+ var UNPLACED = { rapNotMpuStart: false };
664
737
  var BlockClassifier = class {
665
738
  #geometry;
666
739
  #mode;
@@ -683,8 +756,23 @@ var BlockClassifier = class {
683
756
  #mpuSbnSpans = /* @__PURE__ */ new Map();
684
757
  #dataUnitStarts = /* @__PURE__ */ new Map();
685
758
  #highestMpu = null;
686
- /** MPU → movie_fragment_sequence_number observed in it. */
687
- #mpuFragments = /* @__PURE__ */ new Map();
759
+ /**
760
+ * P3 layout, kept for the MPUs within the classification horizon and valid
761
+ * within one continuous SBN sequence (`noteSourceDiscontinuity`).
762
+ */
763
+ #mpus = /* @__PURE__ */ new Map();
764
+ /** An MPU of this sequence showed two movie fragments: each frame is one. */
765
+ #fragmentPerFrame = false;
766
+ /** A DU header of this sequence stated sample_number above 1. */
767
+ #multiSampleFragment = false;
768
+ /**
769
+ * The anchor received last, whether or not its MPU is still in the
770
+ * horizon. Each new anchor, and the anchor of every DU header's MPU, is
771
+ * checked against it.
772
+ */
773
+ #lastAnchor = null;
774
+ /** Two anchors were exactly G fragments per MPU apart. */
775
+ #fragmentsProven = false;
688
776
  #lastRap = null;
689
777
  constructor(geometry) {
690
778
  this.#geometry = geometry;
@@ -714,7 +802,7 @@ var BlockClassifier = class {
714
802
  this.#geometry = geometry;
715
803
  this.#blocks.clear();
716
804
  this.#clearContiguityLedger();
717
- this.#mpuFragments.clear();
805
+ this.#clearMpuLayout();
718
806
  this.#lastRap = null;
719
807
  this.#mpuBoundsRaps = true;
720
808
  if (geometry.trackKind === "video" && geometry.mode === "all-protected") {
@@ -748,11 +836,13 @@ var BlockClassifier = class {
748
836
  /**
749
837
  * The stream's SBN sequence restarted (FECManager source discontinuity:
750
838
  * a publisher restart, or the SS_ID space wrapped). Authored order and SBN
751
- * order are comparable only within one continuous sequence, so the P1
752
- * ledger starts again.
839
+ * order are comparable only within one continuous sequence, and a
840
+ * restarted publisher numbers MPUs and movie fragments again, so the P1
841
+ * ledger and the P3 layout start again.
753
842
  */
754
843
  noteSourceDiscontinuity() {
755
844
  this.#clearContiguityLedger();
845
+ this.#clearMpuLayout();
756
846
  }
757
847
  /** Register a block that exists without evidence (a vanished block). */
758
848
  touch(sbn) {
@@ -771,16 +861,16 @@ var BlockClassifier = class {
771
861
  if (this.#geometry.trackKind === "audio") return [];
772
862
  const changes = [];
773
863
  const block = this.#blockFor(sbn);
864
+ const placement = this.#place(evidence);
774
865
  if (evidence.rap) block.rapSeen = true;
775
866
  if (evidence.mpu !== void 0) block.mpus.add(evidence.mpu);
776
- if (evidence.idx !== void 0) {
777
- block.idxMin = block.idxMin === void 0 ? evidence.idx : Math.min(block.idxMin, evidence.idx);
778
- block.idxMax = block.idxMax === void 0 ? evidence.idx : Math.max(block.idxMax, evidence.idx);
867
+ const { position } = placement;
868
+ if (position !== void 0) {
869
+ block.positionMin = block.positionMin === void 0 ? position : Math.min(block.positionMin, position);
870
+ block.positionMax = block.positionMax === void 0 ? position : Math.max(block.positionMax, position);
779
871
  }
780
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
781
- this.#mpuBoundsRaps = false;
782
- }
783
- const violation = this.#checkInvariants(sbn, block, evidence);
872
+ if (placement.rapNotMpuStart) this.#mpuBoundsRaps = false;
873
+ const violation = this.#checkInvariants(sbn, block, evidence, placement);
784
874
  if (violation !== null) changes.push(...this.#disable(violation));
785
875
  const next = this.#classify(block);
786
876
  if (next !== block.cls && this.#allowed(block.cls, next)) {
@@ -833,35 +923,89 @@ var BlockClassifier = class {
833
923
  }
834
924
  return block;
835
925
  }
836
- #checkInvariants(sbn, block, evidence) {
926
+ #checkInvariants(sbn, block, evidence, placement) {
837
927
  if (this.#mode === "all-protected" || this.#geometry.trackKind !== "video") return null;
838
928
  const geometry = this.#geometry;
839
929
  if (geometry.mode !== "classifying") return null;
840
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
841
- return "rap-not-mpu-start";
842
- }
843
- if (evidence.idx !== void 0 && evidence.idx >= geometry.gopFrames) {
930
+ if (placement.rapNotMpuStart) return "rap-not-mpu-start";
931
+ if (placement.position !== void 0 && placement.position >= geometry.gopFrames) {
844
932
  return "mpu-longer-than-gop";
845
933
  }
846
- if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0 && block.idxMax - block.idxMin >= geometry.interleaveUnits) {
934
+ if (block.mpus.size === 1 && block.positionMin !== void 0 && block.positionMax !== void 0 && block.positionMax - block.positionMin >= geometry.interleaveUnits) {
847
935
  return "block-wider-than-interleave";
848
936
  }
849
- if (evidence.mpu !== void 0 && evidence.movieFragment !== void 0) {
850
- const fragment = this.#mpuFragments.get(evidence.mpu);
851
- if (fragment === void 0) {
852
- this.#mpuFragments.set(evidence.mpu, evidence.movieFragment);
853
- for (const mpu of this.#mpuFragments.keys()) {
854
- if (mpu + 1 < evidence.mpu) this.#mpuFragments.delete(mpu);
855
- }
856
- } else if (fragment !== evidence.movieFragment) {
857
- return "mpu-multiple-fragments";
858
- }
859
- }
937
+ if (placement.violation !== void 0) return placement.violation;
860
938
  if (evidence.mpu !== void 0 && this.#contradictsAuthoredOrder(sbn, evidence.mpu, evidence)) {
861
939
  return "block-not-contiguous";
862
940
  }
863
941
  return null;
864
942
  }
943
+ /**
944
+ * The MPU position a source symbol's DU header proves (P3), and what it
945
+ * refutes. Runs in every mode: mpuBoundsRaps needs its RAP verdict.
946
+ */
947
+ #place(evidence) {
948
+ const { mpu, idx, movieFragment: fragment } = evidence;
949
+ if (idx === void 0) return UNPLACED;
950
+ const bySample = { position: idx, rapNotMpuStart: evidence.rap && idx !== 0 };
951
+ if (mpu === void 0 || fragment === void 0) {
952
+ return this.#fragmentPerFrame && !this.#multiSampleFragment ? { rapNotMpuStart: bySample.rapNotMpuStart } : bySample;
953
+ }
954
+ let layout = this.#mpus.get(mpu);
955
+ if (layout === void 0) {
956
+ layout = { low: fragment };
957
+ this.#mpus.set(mpu, layout);
958
+ for (const other of this.#mpus.keys()) {
959
+ if (other + 1 < mpu) this.#mpus.delete(other);
960
+ }
961
+ } else if (fragment !== layout.low) {
962
+ this.#fragmentPerFrame = true;
963
+ if ((fragment - layout.low | 0) < 0) layout.low = fragment;
964
+ }
965
+ if (idx !== 0) this.#multiSampleFragment = true;
966
+ let arrival;
967
+ if (evidence.rap && layout.anchor === void 0) {
968
+ layout.anchor = fragment;
969
+ arrival = this.#anchorDrift(mpu, fragment);
970
+ if (arrival === 0 && this.#lastAnchor?.mpu !== mpu) this.#fragmentsProven = true;
971
+ this.#lastAnchor = { mpu, fragment };
972
+ }
973
+ if (!this.#fragmentPerFrame) return bySample;
974
+ if (this.#multiSampleFragment) return { ...bySample, violation: "mpu-multiple-fragments" };
975
+ const { anchor } = layout;
976
+ if (anchor === void 0) return UNPLACED;
977
+ const drift = arrival ?? this.#anchorDrift(mpu, anchor);
978
+ const offset = fragment - anchor | 0;
979
+ return {
980
+ ...offset === 0 || offset > 0 && this.#fragmentsProven ? { position: offset } : {},
981
+ rapNotMpuStart: evidence.rap && offset !== 0 || (layout.low - anchor | 0) < 0 || // Fragments count frames: an anchor arriving past the spacing is a
982
+ // RAP inside its MPU, or an earlier MPU outran G.
983
+ arrival !== void 0 && arrival > 0 && this.#fragmentsProven,
984
+ ...drift === void 0 || drift === 0 ? {} : { violation: "rap-spacing-mismatch" }
985
+ };
986
+ }
987
+ /**
988
+ * How many fragments MPU m's anchor `fragment` lies past the start that
989
+ * the anchor received last predicts for MPU m: one frame per fragment and
990
+ * G frames per MPU put the anchors of MPUs m and m' exactly G * (m - m')
991
+ * fragments apart, modulo 2^32. Undefined without a last anchor, a
992
+ * cadence, or this layout.
993
+ */
994
+ #anchorDrift(mpu, fragment) {
995
+ const geometry = this.#geometry;
996
+ const last = this.#lastAnchor;
997
+ if (last === null || !this.#fragmentPerFrame || this.#multiSampleFragment || geometry.trackKind !== "video" || geometry.mode !== "classifying") {
998
+ return void 0;
999
+ }
1000
+ return fragment - last.fragment - geometry.gopFrames * (mpu - last.mpu) | 0;
1001
+ }
1002
+ #clearMpuLayout() {
1003
+ this.#mpus.clear();
1004
+ this.#fragmentPerFrame = false;
1005
+ this.#multiSampleFragment = false;
1006
+ this.#lastAnchor = null;
1007
+ this.#fragmentsProven = false;
1008
+ }
865
1009
  #clearContiguityLedger() {
866
1010
  this.#mpuSbnSpans.clear();
867
1011
  this.#dataUnitStarts.clear();
@@ -961,9 +1105,9 @@ var BlockClassifier = class {
961
1105
  if (this.#mode === "all-protected") return "unknown";
962
1106
  const geometry = this.#geometry;
963
1107
  if (geometry.trackKind !== "video" || geometry.mode !== "classifying") return "unknown";
964
- if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0) {
1108
+ if (block.mpus.size === 1 && block.positionMin !== void 0 && block.positionMax !== void 0) {
965
1109
  const span = geometry.interleaveUnits - 1;
966
- if (block.idxMax - span >= 1 && block.idxMin + span <= geometry.gopFrames - 1) {
1110
+ if (block.positionMax - span >= 1 && block.positionMin + span <= geometry.gopFrames - 1) {
967
1111
  return "delta";
968
1112
  }
969
1113
  }
@@ -1081,6 +1225,7 @@ var WORKER_ERROR_LOG_CAP = 5;
1081
1225
  var WORKER_ERROR_KIND_CAP = 32;
1082
1226
  var WORKER_ERROR_OVERFLOW_KIND = "other";
1083
1227
  var STARTUP_REPAIR_WAIT_SOURCE_BOUNDARIES = 2;
1228
+ var NOT_TAKEN = Object.freeze({ taken: false, recovered: null });
1084
1229
  function isMulticastSymbolDelivery(value) {
1085
1230
  return value === "datagram" || value === "ordered-relay";
1086
1231
  }
@@ -1174,10 +1319,18 @@ var FECManager = class _FECManager {
1174
1319
  // 'pending' forever, which would park every later frame of its stream in
1175
1320
  // the in-order release gate. Each entry owns its handle; the callback
1176
1321
  // checks it still owns the key, so a settled or reset key is never touched.
1322
+ /**
1323
+ * Per owed Worker cleanup: the bound on its acknowledgement, when its block
1324
+ * was due, and when its cleanup was asked for (see `onCleanupComplete`).
1325
+ */
1177
1326
  this.#pendingWorkerCleanupBounds = /* @__PURE__ */ new Map();
1178
1327
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
1179
1328
  this.#blockSourceCounts = /* @__PURE__ */ new Map();
1180
1329
  this.#blockSourceEsis = /* @__PURE__ */ new Map();
1330
+ // Source ESIs per block that another FEC instance rebuilt and fed in
1331
+ // (feedRebuiltSourceSymbol). Kept apart from #blockSourceEsis: they are
1332
+ // not network arrivals and never make a block clean.
1333
+ this.#blockRebuiltEsis = /* @__PURE__ */ new Map();
1181
1334
  // Authored SSB_length per block (ISO/IEC 23008-1 §C.5.3), learned from the
1182
1335
  // first repair symbol. The FFmpeg moq_mmt publisher closes a block every D
1183
1336
  // media units, usually before it holds K symbols; under iso-ssbg1-v1
@@ -1186,10 +1339,14 @@ var FECManager = class _FECManager {
1186
1339
  // SSB_length source arrivals and recoverable from SSB_length received
1187
1340
  // symbols; waiting for K fails every one of them.
1188
1341
  this.#blockAuthoredLengths = /* @__PURE__ */ new Map();
1342
+ // Keys whose authored length is a repair-less span's (#openIsoSpan), until
1343
+ // a repair states the block there or the span resolves.
1344
+ this.#isoSpanKeys = /* @__PURE__ */ new Set();
1189
1345
  this.#ssbLengthConflictCount = 0;
1190
1346
  this.#blockRepairRsIds = /* @__PURE__ */ new Map();
1191
1347
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
1192
- // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
1348
+ // symbols its repair group carries; 0 for a repair-less span no repair can
1349
+ // state (#openIsoSpan). Same lifecycle as #blockRepairRsIds.
1193
1350
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
1194
1351
  /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
1195
1352
  this.#heldLayerStates = /* @__PURE__ */ new Map();
@@ -1306,6 +1463,10 @@ var FECManager = class _FECManager {
1306
1463
  // ── Keyframe-protected repair policy (block-policy.ts) ──
1307
1464
  // One classifier per physical stream, built from that stream's geometry.
1308
1465
  this.#classifiers = /* @__PURE__ */ new Map();
1466
+ // A stream without catalog timing has no classifier, so the last RAP it
1467
+ // released stands in for one: "an MPU boundary bounds its RAPs" holds until
1468
+ // a second RAP is released inside one MPU (BLO-52085).
1469
+ this.#noSpanRaps = /* @__PURE__ */ new Map();
1309
1470
  // Geometry a stream-scoped configuration gave one stream (streamKey). ABR
1310
1471
  // rungs can share a packetId with a different framerate or GOP, so the
1311
1472
  // packet-level geometry is only the geometry of a packet whose streams
@@ -1373,13 +1534,17 @@ var FECManager = class _FECManager {
1373
1534
  this.#workerErrorCounts = /* @__PURE__ */ new Map();
1374
1535
  this.#decoderUnavailableEvents = 0;
1375
1536
  this.#repairSymbolSizeMismatchCount = 0;
1537
+ this.#unlistedRepairTrackRefusals = 0;
1376
1538
  // Event callbacks — block lifecycle notifications for MmtpRouter wiring.
1377
1539
  // NOTE: For sync WASM path, recovery routing is handled by MmtpRouter from
1378
1540
  // feedSourceSymbol/feedRepairSymbol return values. For Worker path, recovery
1379
1541
  // arrives via onBlockRecovered callback.
1380
1542
  this.onBlockStarted = null;
1381
1543
  this.onBlockComplete = null;
1382
- /** A block reached its fail bound. `blockClass` is its class at failure. */
1544
+ /**
1545
+ * A block reached its fail bound. `blockClass` is its class at failure.
1546
+ * `span` is set when what failed is a repair-less span starting at `sbn`.
1547
+ */
1383
1548
  this.onBlockFailed = null;
1384
1549
  /**
1385
1550
  * Fired once per stream when its Worker decoder stops being routable.
@@ -1421,12 +1586,24 @@ var FECManager = class _FECManager {
1421
1586
  * for it, which it must be.
1422
1587
  */
1423
1588
  this.#onUndelimitedLoss = null;
1589
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
1590
+ this.#onIsoHoleExpired = null;
1424
1591
  /** A block every symbol of which vanished was created by SBN evidence. */
1425
1592
  this.onBlockVanished = null;
1426
1593
  /** A block reached a terminal state (completed, recovered, or failed). */
1427
1594
  this.onBlockResolved = null;
1428
1595
  /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
1429
1596
  this.onSourceDiscontinuity = null;
1597
+ /**
1598
+ * The span and tolerance the catalog states for a keyframe overlay
1599
+ * installed over a source track (draft-ramadan-moq-mmt-02 7.4.1: the
1600
+ * overlay instance's own interleaveDepthMs and reorderToleranceMs), or
1601
+ * undefined while none is installed. A stated block only a late source
1602
+ * can complete, and a frame whose gap may hide a RAP behind a span only a
1603
+ * late source can fill, also wait for that overlay's repair
1604
+ * (#overlayLateWaitMs).
1605
+ */
1606
+ this.keyframeOverlayTiming = null;
1430
1607
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
1431
1608
  /**
1432
1609
  * A recovered source symbol. Return false when admission refused the
@@ -1463,7 +1640,9 @@ var FECManager = class _FECManager {
1463
1640
  #pendingWorkerCleanupBounds;
1464
1641
  #blockSourceCounts;
1465
1642
  #blockSourceEsis;
1643
+ #blockRebuiltEsis;
1466
1644
  #blockAuthoredLengths;
1645
+ #isoSpanKeys;
1467
1646
  #ssbLengthConflictCount;
1468
1647
  #blockRepairRsIds;
1469
1648
  #blockRsbLengths;
@@ -1505,6 +1684,7 @@ var FECManager = class _FECManager {
1505
1684
  #orderedFrontiers;
1506
1685
  #orderedPendingBlocks;
1507
1686
  #classifiers;
1687
+ #noSpanRaps;
1508
1688
  #streamGeometries;
1509
1689
  #failedBlocks;
1510
1690
  #resolvedBlockClasses;
@@ -1528,7 +1708,9 @@ var FECManager = class _FECManager {
1528
1708
  #workerErrorCounts;
1529
1709
  #decoderUnavailableEvents;
1530
1710
  #repairSymbolSizeMismatchCount;
1711
+ #unlistedRepairTrackRefusals;
1531
1712
  #onUndelimitedLoss;
1713
+ #onIsoHoleExpired;
1532
1714
  #encodeTrackName(catalogTrackName) {
1533
1715
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
1534
1716
  if (encoded === void 0) {
@@ -2000,7 +2182,10 @@ var FECManager = class _FECManager {
2000
2182
  timer.handle = null;
2001
2183
  this.#requestRepair(sbn, packetId, catalogTrackName);
2002
2184
  };
2003
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
2185
+ timer.handle = setTimeout(
2186
+ onFire,
2187
+ this.#receiptAtMs === void 0 ? Math.max(0, deadlineMs - performance.now()) : this.#receiptTimerDelayMs(deadlineMs, 0)
2188
+ );
2004
2189
  this.#repairDeadlines.set(key, timer);
2005
2190
  }
2006
2191
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -2144,8 +2329,14 @@ var FECManager = class _FECManager {
2144
2329
  * Vanished blocks are not enumerated here: their starts are unknown until a
2145
2330
  * repair states them. The SS_IDs between two stated blocks become one
2146
2331
  * repair-less span when the later block's repair arrives (placeIsoRepair).
2332
+ *
2333
+ * A `held` source arrived before its block was known and is fed only now
2334
+ * that a repair, a span or a closed hole placed it: how far its block start
2335
+ * then lies behind the frontier measures how long the receiver held it, not
2336
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
2337
+ * it (BLO-52085).
2147
2338
  */
2148
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
2339
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn, held = false) {
2149
2340
  const streamKey = this.#streamKey(packetId, catalogTrackName);
2150
2341
  const now = performance.now();
2151
2342
  const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
@@ -2166,6 +2357,7 @@ var FECManager = class _FECManager {
2166
2357
  };
2167
2358
  const discontinuity = () => {
2168
2359
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity();
2360
+ this.#noSpanRaps.delete(streamKey);
2169
2361
  this.#highestSbn.set(streamKey, { sbn, atMs: now });
2170
2362
  this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
2171
2363
  if (psn === void 0) this.#sourceAnchors.delete(streamKey);
@@ -2183,7 +2375,7 @@ var FECManager = class _FECManager {
2183
2375
  return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
2184
2376
  };
2185
2377
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
2186
- 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))) {
2378
+ 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))) {
2187
2379
  discontinuity();
2188
2380
  return;
2189
2381
  }
@@ -2445,17 +2637,21 @@ var FECManager = class _FECManager {
2445
2637
  this.#blockWaitDeadlinesMs.delete(key);
2446
2638
  this.#repairHoldUntilMs.delete(key);
2447
2639
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
2448
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName);
2640
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs);
2449
2641
  };
2450
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)));
2642
+ timer.handle = setTimeout(
2643
+ onFire,
2644
+ this.#receiptAtMs === void 0 ? Math.max(1, Math.ceil(deadlineMs - nowMs)) : this.#receiptTimerDelayMs(deadlineMs, 1)
2645
+ );
2451
2646
  this.#activeBlocks.set(key, timer);
2452
2647
  this.#indexBlockKey(key, sbn, packetId);
2453
2648
  }
2454
2649
  /**
2455
2650
  * Hand a block whose delivery is over to its decoder for finalization: the
2456
- * datagram deadline fired, or the ordered relay moved past it.
2651
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
2652
+ * is when it was due: its deadline, or now.
2457
2653
  */
2458
- #finalizeExpiredBlock(sbn, packetId, catalogTrackName) {
2654
+ #finalizeExpiredBlock(sbn, packetId, catalogTrackName, dueAtMs = performance.now()) {
2459
2655
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
2460
2656
  if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
2461
2657
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -2471,7 +2667,7 @@ var FECManager = class _FECManager {
2471
2667
  if (workerClient) {
2472
2668
  this.#pendingWorkerCleanups.add(key);
2473
2669
  this.#pendingWorkerCleanupClients.set(key, workerClient);
2474
- this.#boundOwedCleanup(key, packetId, workerClient);
2670
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs);
2475
2671
  workerClient.cleanup(sbn);
2476
2672
  } else {
2477
2673
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
@@ -2578,6 +2774,9 @@ var FECManager = class _FECManager {
2578
2774
  }
2579
2775
  if (policyChanged) {
2580
2776
  this.#bumpEpoch(packetId);
2777
+ for (const key of [...this.#noSpanRaps.keys()]) {
2778
+ if (this.#belongsToPacket(key, packetId)) this.#noSpanRaps.delete(key);
2779
+ }
2581
2780
  for (const [key, classifier] of [...this.#classifiers]) {
2582
2781
  if (!this.#belongsToPacket(key, packetId)) continue;
2583
2782
  const stream = this.#parseStreamKey(key);
@@ -2678,6 +2877,7 @@ var FECManager = class _FECManager {
2678
2877
  packetId
2679
2878
  })),
2680
2879
  repairSymbolSizeMismatches: this.#repairSymbolSizeMismatchCount,
2880
+ unlistedRepairTrackRefusals: this.#unlistedRepairTrackRefusals,
2681
2881
  repairObjectRejects: [...this.#repairObjectRejects.values()].map((r) => ({ ...r })),
2682
2882
  workerErrors: Object.fromEntries(this.#workerErrorCounts)
2683
2883
  };
@@ -2780,7 +2980,9 @@ var FECManager = class _FECManager {
2780
2980
  }
2781
2981
  resetMap(this.#blockSourceCounts);
2782
2982
  resetMap(this.#blockSourceEsis);
2983
+ resetMap(this.#blockRebuiltEsis);
2783
2984
  resetMap(this.#blockAuthoredLengths);
2985
+ resetSet(this.#isoSpanKeys);
2784
2986
  resetMap(this.#blockRepairRsIds);
2785
2987
  resetMap(this.#blockRsbLengths);
2786
2988
  resetMap(this.#heldLayerStates);
@@ -2813,6 +3015,7 @@ var FECManager = class _FECManager {
2813
3015
  resetMap(this.#isoLocators);
2814
3016
  resetMap(this.#sourceAnchors);
2815
3017
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName));
3018
+ this.#noSpanRaps.delete(this.#streamKey(packetId, catalogTrackName));
2816
3019
  this.#bumpEpoch(packetId);
2817
3020
  for (const [sbn, keys] of this.#blockKeysBySbn) {
2818
3021
  for (const key of keys.keys()) {
@@ -2903,7 +3106,9 @@ var FECManager = class _FECManager {
2903
3106
  dropMap(this.#pendingWorkerCleanupClients);
2904
3107
  dropMap(this.#blockSourceCounts);
2905
3108
  dropMap(this.#blockSourceEsis);
3109
+ dropMap(this.#blockRebuiltEsis);
2906
3110
  dropMap(this.#blockAuthoredLengths);
3111
+ dropSet(this.#isoSpanKeys);
2907
3112
  dropMap(this.#blockRepairRsIds);
2908
3113
  dropMap(this.#blockRsbLengths);
2909
3114
  dropMap(this.#blockPathCounts);
@@ -2919,6 +3124,7 @@ var FECManager = class _FECManager {
2919
3124
  dropMap(this.#isoLocators);
2920
3125
  dropMap(this.#sourceAnchors);
2921
3126
  dropMap(this.#classifiers);
3127
+ dropMap(this.#noSpanRaps);
2922
3128
  dropMap(this.#streamGeometries);
2923
3129
  dropSet(this.#pendingWorkerCleanups);
2924
3130
  dropSet(this.#completedBlocks);
@@ -3064,6 +3270,9 @@ var FECManager = class _FECManager {
3064
3270
  this.#unindexBlockKey(key);
3065
3271
  }
3066
3272
  }
3273
+ if (isSourceSymbol && source === "multicast") {
3274
+ this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), sbn + esi >>> 0, packetId, catalogTrackName);
3275
+ }
3067
3276
  return true;
3068
3277
  }
3069
3278
  #observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName) {
@@ -3173,8 +3382,10 @@ var FECManager = class _FECManager {
3173
3382
  }
3174
3383
  /**
3175
3384
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
3176
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
3177
- * Undefined for a block that is not open.
3385
+ * (SSB_length) and RSB_length (each undefined until a repair stated it; a
3386
+ * repair-less span states its length, and RSB_length 0 when it is longer
3387
+ * than K, since no repair can reach it). Undefined for a block that is not
3388
+ * open.
3178
3389
  */
3179
3390
  blockSymbolCounts(sbn, packetId, catalogTrackName) {
3180
3391
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -3242,8 +3453,9 @@ var FECManager = class _FECManager {
3242
3453
  return true;
3243
3454
  }
3244
3455
  /**
3245
- * Drop a block's repair hold: its FETCH ended without delivering. The block
3246
- * falls back to its multicast wait, which may already have passed.
3456
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
3457
+ * back only a repair that cannot complete it. The block falls back to its
3458
+ * multicast wait, which may already have passed.
3247
3459
  */
3248
3460
  releaseRepairHold(sbn, packetId, catalogTrackName) {
3249
3461
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -3289,7 +3501,7 @@ var FECManager = class _FECManager {
3289
3501
  }
3290
3502
  const trackConfig = this.#trackConfigs.get(packetId);
3291
3503
  if (trackConfig === void 0) return void 0;
3292
- return Math.max(1, trackConfig.timeoutMs - this.#repairDeadlineMs(trackConfig));
3504
+ return Math.max(1, this.#repairGraceMs(trackConfig, this.#multicastWaitMs(trackConfig)));
3293
3505
  }
3294
3506
  /** True once configureTrack/setFecDecoder/setFecWorker configured this packetId. */
3295
3507
  // -----------------------------------------------------------------------
@@ -3381,6 +3593,8 @@ var FECManager = class _FECManager {
3381
3593
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
3382
3594
  const evictedBefore = locator.heldEvicted;
3383
3595
  const held = locator.hold(ssId, source);
3596
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
3597
+ if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
3384
3598
  const evicted = locator.heldEvicted - evictedBefore;
3385
3599
  if (evicted > 0) {
3386
3600
  const before = this.#isoHeldEvictedCount;
@@ -3401,17 +3615,20 @@ var FECManager = class _FECManager {
3401
3615
  * contradicts a known block is refused (counted) and must be dropped.
3402
3616
  */
3403
3617
  placeIsoRepair(packetId, catalogTrackName, ssStart, ssbLength) {
3404
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength);
3618
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
3619
+ const placement = locator.placeRepair(ssStart, ssbLength);
3620
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
3405
3621
  if (placement.status !== "placed") {
3406
3622
  this.#isoRepairRefusedCount++;
3407
3623
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
3408
3624
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`);
3409
3625
  }
3626
+ if (placement.ofSpan !== void 0) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName);
3410
3627
  return placement;
3411
3628
  }
3629
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName));
3412
3630
  if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
3413
3631
  if (placement.hole !== void 0) {
3414
- const locator = this.#isoLocatorFor(packetId, catalogTrackName);
3415
3632
  const hole = placement.hole.block;
3416
3633
  const previous = locator.blockEndingAt(hole.start);
3417
3634
  const loss = {
@@ -3432,17 +3649,29 @@ var FECManager = class _FECManager {
3432
3649
  * `handler`, instead of a repair-less span; null restores spans. Set by the
3433
3650
  * range repair scheduler; applies to every stream from its next gap. The
3434
3651
  * handler and the deferral are one setting, so no hole is ever created with
3435
- * nobody to close it.
3652
+ * nobody to close it. `onExpired` is told of each pending hole the stream
3653
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
3654
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
3655
+ * reported; otherwise the hole is discarded with its sources.
3436
3656
  */
3437
- setUndelimitedLossHandler(handler) {
3657
+ setUndelimitedLossHandler(handler, onExpired = null) {
3438
3658
  this.#onUndelimitedLoss = handler;
3659
+ this.#onIsoHoleExpired = handler === null ? null : onExpired;
3439
3660
  this.#deferIsoGaps = handler !== null;
3440
3661
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
3441
3662
  }
3663
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
3664
+ #settleExpiredIsoHoles(locator, packetId, catalogTrackName) {
3665
+ for (const hole of locator.takeExpiredHoles()) {
3666
+ const expired = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length };
3667
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length);
3668
+ }
3669
+ }
3442
3670
  /**
3443
- * The range repair for a hole ended: every hole still pending inside
3444
- * `[start, start + length)` becomes a repair-less span. Returns those spans
3445
- * with the held sources they placed, for the caller to feed (MmtpRouter).
3671
+ * The range repair for a hole ended: every hole inside `[start, start +
3672
+ * length)`, pending or expired, becomes a repair-less span. Returns those
3673
+ * spans with the held sources they placed, for the caller to feed
3674
+ * (MmtpRouter).
3446
3675
  */
3447
3676
  closeIsoHoles(packetId, catalogTrackName, start, length) {
3448
3677
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
@@ -3458,10 +3687,25 @@ var FECManager = class _FECManager {
3458
3687
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
3459
3688
  * SS_ID of which vanished resolves through its deadline like any vanished
3460
3689
  * block.
3690
+ *
3691
+ * A span longer than K holds more than one block (SSB_length <= K), and the
3692
+ * locator states no block inside a span, only one exactly its range
3693
+ * (IsoBlockLocator.placeRepair): no repair, multicast or FETCHed, can ever
3694
+ * reach it. Its repair group is empty, so the repair scheduler FETCHes no
3695
+ * Group of it (group-cannot-complete). Every span still keeps its whole
3696
+ * wait (#lateSourceWaitMs): failing it early released the frames behind it
3697
+ * past a keyframe the overlay was still rebuilding (BLO-52085). The release
3698
+ * gate lets those frames go once only a late source can fill the gap
3699
+ * before them, as long after they arrived as the gap's decision allows
3700
+ * (isoRepairlessWaitMs).
3461
3701
  */
3462
3702
  #openIsoSpan(span, packetId, catalogTrackName) {
3463
3703
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
3464
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
3704
+ if (!this.#blockAuthoredLengths.has(key)) {
3705
+ this.#blockAuthoredLengths.set(key, span.block.length);
3706
+ this.#isoSpanKeys.add(key);
3707
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0);
3708
+ }
3465
3709
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
3466
3710
  }
3467
3711
  /**
@@ -3499,6 +3743,62 @@ var FECManager = class _FECManager {
3499
3743
  }
3500
3744
  return lost;
3501
3745
  }
3746
+ /**
3747
+ * The release gate's wait, from a frame's arrival, for the SS_IDs strictly
3748
+ * between two released frames' SS_IDs once only a late source can still
3749
+ * fill them, else undefined. That is when every one missing (neither
3750
+ * arrived nor held) lies in a repair-less span longer than K, which no
3751
+ * repair can state a block of (#openIsoSpan), or in a stated block its
3752
+ * own repair group cannot complete every SS_ID of which it misses lies
3753
+ * between them (so the gap's decision covers all it lost), and a multicast
3754
+ * source at or past `toSsId` arrived, so each is lost or reordered behind
3755
+ * it (a MoQ source shows nothing: MoQ streams overtake one another). The
3756
+ * span or block itself keeps its own wait.
3757
+ *
3758
+ * The wait is the late-symbol allowance, unless `rapMayHide`: the gap may
3759
+ * hold a RAP packet an installed keyframe overlay can still rebuild (its
3760
+ * decision stalls, or it ends at a RAP that may lie past a whole MPU).
3761
+ * Then the frame waits as a stated block its group cannot complete does
3762
+ * (#overlayLateWaitMs): the allowance alone with no overlay installed, the
3763
+ * overlay's span plus the larger of the allowance and its tolerance, or,
3764
+ * for an overlay that states no span, the span's whole wait (undefined).
3765
+ * So does `rapNext` (the gap ends at the RAP that opens the next MPU) when
3766
+ * the gap holds a stated block's loss.
3767
+ */
3768
+ isoRepairlessWaitMs(packetId, catalogTrackName, fromSsId, toSsId, rapMayHide = false, rapNext = false) {
3769
+ const config = this.#trackConfigs.get(packetId);
3770
+ if (config === void 0 || !_FECManager.#hasCatalogTiming(config)) return void 0;
3771
+ const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
3772
+ if (locator === void 0 || !locator.coversBetween(fromSsId, toSsId)) return void 0;
3773
+ const newestSource = locator.newestSource;
3774
+ if (newestSource === void 0 || serial32Precedes(newestSource, toSsId)) return void 0;
3775
+ let repairless = false;
3776
+ let stated = false;
3777
+ for (const block of locator.blocksBetween(fromSsId, toSsId)) {
3778
+ const key = this.#blockKey(block.start, packetId, catalogTrackName);
3779
+ if (this.#completedBlocks.has(key)) continue;
3780
+ if (block.span && block.length > locator.kMax) {
3781
+ repairless = true;
3782
+ continue;
3783
+ }
3784
+ const received = this.#blockSourceEsis.get(key);
3785
+ const rebuilt = this.#blockRebuiltEsis.get(key);
3786
+ let missesInGap = false;
3787
+ let missesOutside = false;
3788
+ for (let esi = 0; esi < block.length; esi++) {
3789
+ const ssId = serial32Add(block.start, esi);
3790
+ if (received?.has(esi) || locator.isHeld(ssId)) continue;
3791
+ if (serial32Precedes(fromSsId, ssId) && serial32Precedes(ssId, toSsId)) missesInGap = true;
3792
+ else if (!rebuilt?.has(esi)) missesOutside = true;
3793
+ }
3794
+ if (!missesInGap) continue;
3795
+ if (missesOutside || block.span || !this.#groupCannotComplete(key)) return void 0;
3796
+ repairless = stated = true;
3797
+ }
3798
+ if (!repairless) return void 0;
3799
+ const waitMs = rapMayHide || stated && rapNext ? this.#overlayLateWaitMs(packetId, catalogTrackName, config) : this.#multicastWaitMs(config) - config.interleaveDepthMs;
3800
+ return waitMs === void 0 ? void 0 : Math.max(0, waitMs);
3801
+ }
3502
3802
  /**
3503
3803
  * iso-ssbg1-v1 block location: repair symbols it refused, oversize sources,
3504
3804
  * the sources held now for a block no repair has stated yet, and the held
@@ -3549,11 +3849,14 @@ var FECManager = class _FECManager {
3549
3849
  /**
3550
3850
  * Whether an MPU boundary still bounds this stream's RAPs (see
3551
3851
  * `BlockClassifier.mpuBoundsRaps`). Gap decisions drop MPU evidence once
3552
- * it does not. A stream with no classifier yet has shown nothing against it.
3852
+ * it does not. A stream with no classifier yet has shown nothing against it,
3853
+ * and neither has a stream without catalog timing until it releases two
3854
+ * RAPs inside one MPU.
3553
3855
  */
3554
3856
  mpuBoundsRapsFor(packetId, catalogTrackName) {
3555
- if (!this.#hasCatalogTimingForPacket(packetId)) return false;
3556
- return this.#classifiers.get(this.#streamKey(packetId, catalogTrackName))?.mpuBoundsRaps ?? true;
3857
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
3858
+ if (!this.#hasCatalogTimingForPacket(packetId)) return this.#noSpanRaps.get(streamKey)?.inside !== true;
3859
+ return this.#classifiers.get(streamKey)?.mpuBoundsRaps ?? true;
3557
3860
  }
3558
3861
  /** A block's class now, or frozen at its resolution. */
3559
3862
  blockClassFor(sbn, packetId, catalogTrackName) {
@@ -3579,7 +3882,14 @@ var FECManager = class _FECManager {
3579
3882
  * invariant (consecutive MPUs exactly one keyframe interval apart).
3580
3883
  */
3581
3884
  noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale) {
3582
- if (!this.#trackConfigs.has(packetId) || !this.#hasCatalogTimingForPacket(packetId)) return;
3885
+ if (!this.#trackConfigs.has(packetId)) return;
3886
+ if (!this.#hasCatalogTimingForPacket(packetId)) {
3887
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
3888
+ const last = this.#noSpanRaps.get(streamKey);
3889
+ const inside = last?.inside === true || last?.mpu === mpu && last.presentationTime !== presentationTime;
3890
+ this.#noSpanRaps.set(streamKey, { mpu, presentationTime, inside });
3891
+ return;
3892
+ }
3583
3893
  this.#applyClassifierChanges(
3584
3894
  packetId,
3585
3895
  catalogTrackName,
@@ -3792,11 +4102,14 @@ var FECManager = class _FECManager {
3792
4102
  });
3793
4103
  client.onCleanupComplete((sbn) => {
3794
4104
  if (this.#releasedWorkerClients.has(client)) return;
3795
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
4105
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
4106
+ const cleanupKeys = owed.filter((key) => {
3796
4107
  const block = this.#parseBlockKey(key);
3797
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
4108
+ return block.packetId === packetId && block.sbn === sbn;
3798
4109
  });
3799
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
4110
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
4111
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
4112
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
3800
4113
  });
3801
4114
  client.onError((msg, code) => {
3802
4115
  const requestedKind = code ?? msg;
@@ -3866,9 +4179,11 @@ var FECManager = class _FECManager {
3866
4179
  * fail deadline already passed, so failing it is the decision that deadline
3867
4180
  * made. A late ack then finds nothing owed and is a no-op.
3868
4181
  */
3869
- #boundOwedCleanup(key, packetId, client) {
4182
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
3870
4183
  this.#clearOwedCleanupBound(key);
3871
4184
  const bound = {
4185
+ dueAtMs,
4186
+ askedAtMs: performance.now(),
3872
4187
  handle: setTimeout(() => {
3873
4188
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
3874
4189
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -3966,7 +4281,15 @@ var FECManager = class _FECManager {
3966
4281
  this.#isoSourceOversizeCount++;
3967
4282
  return null;
3968
4283
  }
3969
- const sbn = located.block.start;
4284
+ return this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, located.block.start);
4285
+ }
4286
+ /**
4287
+ * Hand one placed source symbol to the stream's decoder: its Worker, which
4288
+ * answers through onFrame (null here), or its synchronous decoder, whose
4289
+ * recovered block is returned. `sbn` is the SS_Start of the block a repair
4290
+ * stated for `ssId`.
4291
+ */
4292
+ #feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn) {
3970
4293
  const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
3971
4294
  const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey);
3972
4295
  const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
@@ -3995,6 +4318,74 @@ var FECManager = class _FECManager {
3995
4318
  }
3996
4319
  return recovered;
3997
4320
  }
4321
+ /**
4322
+ * Feed a source symbol of this stream that another FEC instance over the
4323
+ * same packets rebuilt: a keyframe overlay recovery whose base SS_ID the
4324
+ * caller determined (draft-ramadan-moq-mmt-02 7.1, 7.4.4; joint decoding,
4325
+ * BLO-52085). It joins its block's decoder as a received source would, so
4326
+ * it reduces the erasures the block still has to solve, but it is not a
4327
+ * network arrival: no transport accounting, no classification evidence,
4328
+ * no deadline refresh, and it never makes a block clean.
4329
+ *
4330
+ * Only a block a repair stated takes one (a repair-less span has no
4331
+ * decoder block). A block that is terminal, or already holds that source,
4332
+ * does not. The symbol is the exact protected packet, unpadded, as
4333
+ * feedSourceSymbol takes it.
4334
+ *
4335
+ * `recovered` is the block the synchronous decoder completed with it; the
4336
+ * caller routes it and completes the block, as for any recovery. When
4337
+ * every source of the block is then present, received or rebuilt, and no
4338
+ * decoder returned it (a Worker answers asynchronously, and reports such a
4339
+ * block as clean on its own side), the block is completed here as
4340
+ * recovered, with nothing left to route.
4341
+ */
4342
+ feedRebuiltSourceSymbol(packetId, ssId, symbolData, catalogTrackName) {
4343
+ if (!this.#hasBlockProfile(packetId)) return NOT_TAKEN;
4344
+ const located = this.#isoLocatorFor(packetId, catalogTrackName).locate(ssId);
4345
+ if (located === null || located.block.span) return NOT_TAKEN;
4346
+ if (!ssbg1FitsSymbol(symbolData.byteLength, this.#trackConfig(packetId).symbolSize)) return NOT_TAKEN;
4347
+ const sbn = located.block.start;
4348
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
4349
+ if (this.#completedBlocks.has(key) || this.#blockSourceEsis.get(key)?.has(located.esi)) return NOT_TAKEN;
4350
+ let rebuilt = this.#blockRebuiltEsis.get(key);
4351
+ if (rebuilt?.has(located.esi)) return NOT_TAKEN;
4352
+ if (rebuilt === void 0) {
4353
+ rebuilt = /* @__PURE__ */ new Set();
4354
+ this.#blockRebuiltEsis.set(key, rebuilt);
4355
+ }
4356
+ const config = this.#trackConfigs.get(packetId);
4357
+ const wasShort = config !== void 0 && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) !== void 0;
4358
+ rebuilt.add(located.esi);
4359
+ const recovered = this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn);
4360
+ if (recovered === null && !this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName)) {
4361
+ if (wasShort && this.#activeBlocks.has(key) && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) === void 0) {
4362
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, this.#multicastWaitMs(config));
4363
+ }
4364
+ }
4365
+ return { taken: true, recovered };
4366
+ }
4367
+ /**
4368
+ * A block that holds every one of its `length` sources, received or
4369
+ * rebuilt by another instance, with at least one rebuilt, is recovered:
4370
+ * every packet of it was delivered, by its own arrival or by the instance
4371
+ * that rebuilt it, so nothing is routed. Returns whether it completed it.
4372
+ */
4373
+ #completeWhenSourcesPresent(key, sbn, length, packetId, catalogTrackName) {
4374
+ const rebuilt = this.#blockRebuiltEsis.get(key);
4375
+ if (rebuilt === void 0 || this.#completedBlocks.has(key)) return false;
4376
+ let present = rebuilt.size;
4377
+ for (const esi of this.#blockSourceEsis.get(key) ?? []) if (!rebuilt.has(esi)) present++;
4378
+ if (present < length) return false;
4379
+ this.#traceLifecycle("recovered", sbn, packetId, catalogTrackName);
4380
+ this.countRecovery(packetId, sbn, catalogTrackName);
4381
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
4382
+ if (catalogTrackName === void 0) {
4383
+ this.onBlockComplete?.(sbn, packetId);
4384
+ } else {
4385
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName);
4386
+ }
4387
+ return true;
4388
+ }
3998
4389
  /**
3999
4390
  * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
4000
4391
  * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
@@ -4056,7 +4447,10 @@ var FECManager = class _FECManager {
4056
4447
  this.#layerAnchorHorizon(packetId),
4057
4448
  this.#sourceFrontiers.get(streamKey)?.sbn
4058
4449
  );
4059
- if (verdict === "discard") return false;
4450
+ if (verdict === "discard") {
4451
+ this.#unlistedRepairTrackRefusals++;
4452
+ return false;
4453
+ }
4060
4454
  if (verdict !== void 0) {
4061
4455
  this.#failClosed(streamKey, verdict, packetId, catalogTrackName);
4062
4456
  return false;
@@ -4197,8 +4591,115 @@ var FECManager = class _FECManager {
4197
4591
  this.#completeCleanBlock(blockKey, sbn, packetId, catalogTrackName);
4198
4592
  return null;
4199
4593
  }
4594
+ if (recovered === null) this.#shortenUnrecoverableWait(blockKey, sbn, packetId, catalogTrackName);
4200
4595
  return recovered;
4201
4596
  }
4597
+ /**
4598
+ * A first-arrival multicast source, held or placed. A datagram flow keeps
4599
+ * its sources in send order, so one that moves the stream's newest source
4600
+ * position past a block leaves the sources that block still misses
4601
+ * reordered behind it at best: it shortens the wait of every block it
4602
+ * passed that only a late source can complete. MoQ is left out: its streams
4603
+ * can overtake one another, so a MoQ source shows nothing about the sources
4604
+ * sent before it.
4605
+ */
4606
+ #noteMulticastSource(locator, ssId, packetId, catalogTrackName) {
4607
+ const previous = locator.newestSource;
4608
+ if (!locator.noteSource(ssId) || previous === void 0) return;
4609
+ for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
4610
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
4611
+ this.#shortenUnrecoverableWait(
4612
+ this.#blockKey(block.start, packetId, catalogTrackName),
4613
+ block.start,
4614
+ packetId,
4615
+ catalogTrackName
4616
+ );
4617
+ }
4618
+ }
4619
+ /**
4620
+ * The wait of a block that only a late source can complete (BLO-52085): a
4621
+ * repair stated it, its received sources plus every symbol its repair group
4622
+ * carries (RSB_length) are short of K' (the repair scheduler's
4623
+ * group-cannot-complete), and a later source of the stream has arrived, so
4624
+ * a source it misses is lost or reordered behind that one. The span, which
4625
+ * covers repair symbols paced after its sources, buys it nothing: it waits
4626
+ * the late-symbol allowance alone, the multicast wait less the span (the
4627
+ * catalog tolerance or the measured delivery gap). Undefined for any other
4628
+ * block. While a keyframe overlay is installed, the block waits for its
4629
+ * repair too (#overlayLateWaitMs). A repair-less span keeps its whole
4630
+ * wait, even one longer than K whose group is empty (#openIsoSpan): its
4631
+ * resolution is what releases the frames behind it, and failing it early
4632
+ * released them past a keyframe the overlay was still rebuilding, which
4633
+ * then arrived stale. The release gate lets them go instead
4634
+ * (isoRepairlessWaitMs).
4635
+ */
4636
+ #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
4637
+ if (this.#isoSpanKeys.has(key) || !this.#groupCannotComplete(key)) return void 0;
4638
+ const authoredLength = this.#blockAuthoredLengths.get(key);
4639
+ const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
4640
+ if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
4641
+ return void 0;
4642
+ }
4643
+ return this.#overlayLateWaitMs(packetId, catalogTrackName, config);
4644
+ }
4645
+ /**
4646
+ * A repair stated the block, and its sources plus every symbol its repair
4647
+ * group carries (RSB_length) are short of its SSB_length.
4648
+ */
4649
+ #groupCannotComplete(key) {
4650
+ const authoredLength = this.#blockAuthoredLengths.get(key);
4651
+ const rsbLength = this.#blockRsbLengths.get(key);
4652
+ if (authoredLength === void 0 || rsbLength === void 0) return false;
4653
+ let present = this.#blockSourceCounts.get(key) ?? 0;
4654
+ const received = this.#blockSourceEsis.get(key);
4655
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
4656
+ return present + rsbLength < authoredLength;
4657
+ }
4658
+ /**
4659
+ * How long a loss only a late source or an installed keyframe overlay can
4660
+ * still fill waits once a later source passed it: the late-symbol
4661
+ * allowance alone (the multicast wait less the span) while no overlay is
4662
+ * installed. An installed one (keyframeOverlayTiming) may still rebuild a
4663
+ * RAP packet the loss took: a second FEC instance over the same packets
4664
+ * (draft-ramadan-moq-mmt-02 7.4), whose repair is paced across its own
4665
+ * span, unrelated to the base's. That packet can complete a stated block
4666
+ * (feedRebuiltSourceSymbol), or play behind a span; giving the loss up
4667
+ * first lets the release gate pass the keyframe, whose rebuild then lands
4668
+ * stale. The overlay repair of a packet the loss took goes out within the
4669
+ * overlay's span of that packet (fec-core-00 9.3), and the later source was
4670
+ * sent after it, so the loss waits that span plus the larger of the
4671
+ * allowance and the overlay's own tolerance. An overlay that states no
4672
+ * span (its block may then span keyframes), or one whose wait is not
4673
+ * shorter than the whole multicast wait, leaves the whole wait: undefined.
4674
+ */
4675
+ #overlayLateWaitMs(packetId, catalogTrackName, config) {
4676
+ const waitMs = this.#multicastWaitMs(config);
4677
+ const allowanceMs = waitMs - config.interleaveDepthMs;
4678
+ const overlay = this.keyframeOverlayTiming?.(packetId, catalogTrackName);
4679
+ if (overlay === void 0) return allowanceMs;
4680
+ const overlaySpanMs = overlay.interleaveDepthMs ?? 0;
4681
+ const overlayWaitMs = overlaySpanMs + Math.max(allowanceMs, overlay.reorderToleranceMs ?? 0);
4682
+ return overlaySpanMs > 0 && overlayWaitMs < waitMs ? overlayWaitMs : void 0;
4683
+ }
4684
+ /**
4685
+ * Bring an open block's wait in to its late-source wait, when it has one.
4686
+ * Never later than it is armed: only a source can complete such a block,
4687
+ * so a repair of its group (paced across the span) must not keep it open.
4688
+ */
4689
+ #shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName) {
4690
+ if (!this.#activeBlocks.has(key)) return;
4691
+ const config = this.#trackConfigs.get(packetId);
4692
+ if (config === void 0) return;
4693
+ const waitMs = this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config);
4694
+ if (waitMs === void 0) return;
4695
+ const armedAtMs = this.#blockWaitDeadlinesMs.get(key);
4696
+ this.#armBlockTimeout(
4697
+ sbn,
4698
+ packetId,
4699
+ catalogTrackName,
4700
+ armedAtMs === void 0 ? waitMs : Math.min(waitMs, armedAtMs - this.#receiptNow())
4701
+ );
4702
+ }
4202
4703
  /**
4203
4704
  * Record a block's authored SSB_length from a repair symbol. Returns false,
4204
4705
  * leaving the block unchanged, when the symbol contradicts the block: a
@@ -4296,12 +4797,13 @@ var FECManager = class _FECManager {
4296
4797
  * the inactivity deadline on each symbol, records the symbol's in-band
4297
4798
  * classification evidence, and marks the block clean when all of its
4298
4799
  * authored source symbols arrived: the SSB_length a repair symbol declared,
4299
- * otherwise K.
4800
+ * otherwise K. `held` marks a source held unplaced since it arrived and
4801
+ * placed only now (see #noteSbnSeen).
4300
4802
  *
4301
4803
  * Throws for a packetId that was never configured, so a classified block
4302
4804
  * never reads the manager-global K or timeout.
4303
4805
  */
4304
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
4806
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
4305
4807
  const trackConfig = this.#trackConfigs.get(packetId);
4306
4808
  if (trackConfig === void 0) {
4307
4809
  throw new Error(
@@ -4317,7 +4819,8 @@ var FECManager = class _FECManager {
4317
4819
  catalogTrackName,
4318
4820
  "source",
4319
4821
  evidence.packetSequenceNumber,
4320
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
4822
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
4823
+ held
4321
4824
  );
4322
4825
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
4323
4826
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -4353,6 +4856,15 @@ var FECManager = class _FECManager {
4353
4856
  this.#completeCleanBlock(key, sbn, packetId, catalogTrackName);
4354
4857
  return;
4355
4858
  }
4859
+ if (this.#blockRebuiltEsis.has(key) && this.#completeWhenSourcesPresent(
4860
+ key,
4861
+ sbn,
4862
+ this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? authoredLength,
4863
+ packetId,
4864
+ catalogTrackName
4865
+ )) {
4866
+ return;
4867
+ }
4356
4868
  this.noteBlockActivity(sbn, packetId, catalogTrackName, true);
4357
4869
  }
4358
4870
  #completeCleanBlock(key, sbn, packetId, catalogTrackName) {
@@ -4361,7 +4873,9 @@ var FECManager = class _FECManager {
4361
4873
  this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
4362
4874
  this.#blockSourceCounts.delete(key);
4363
4875
  this.#blockSourceEsis.delete(key);
4876
+ this.#blockRebuiltEsis.delete(key);
4364
4877
  this.#blockAuthoredLengths.delete(key);
4878
+ this.#isoSpanKeys.delete(key);
4365
4879
  this.#blockRepairRsIds.delete(key);
4366
4880
  this.#blockRsbLengths.delete(key);
4367
4881
  this.#markTerminal(key, sbn, packetId, true);
@@ -4392,6 +4906,19 @@ var FECManager = class _FECManager {
4392
4906
  #receiptNow() {
4393
4907
  return this.#receiptAtMs ?? performance.now();
4394
4908
  }
4909
+ /**
4910
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
4911
+ * scope: counted from the receipt time, as the timer of a symbol fed when
4912
+ * it was received was, less the whole ms since. So it fires on the tick
4913
+ * that timer would have, never later than a delay counted from now, and
4914
+ * its handler still re-arms a timer that fires before its deadline.
4915
+ * Counted from now, a deadline set from the receipt time is rounded up
4916
+ * from another fraction of a ms (BLO-52085).
4917
+ */
4918
+ #receiptTimerDelayMs(deadlineMs, minMs) {
4919
+ const receivedAtMs = this.#receiptAtMs;
4920
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
4921
+ }
4395
4922
  /**
4396
4923
  * A held packet admitted late arms from its (earlier) receipt time; that
4397
4924
  * never pulls in a deadline later activity already armed. Outside a
@@ -4427,10 +4954,20 @@ var FECManager = class _FECManager {
4427
4954
  this.#repairDeadlineMs(trackConfig)
4428
4955
  );
4429
4956
  }
4430
- this.#armBlockTimeout(sbn, packetId, catalogTrackName, timeoutMs);
4957
+ if (!sourceProgress && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) !== void 0) {
4958
+ this.#shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName);
4959
+ return;
4960
+ }
4961
+ this.#armBlockTimeout(
4962
+ sbn,
4963
+ packetId,
4964
+ catalogTrackName,
4965
+ this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) ?? timeoutMs
4966
+ );
4431
4967
  }
4432
4968
  #failBlock(sbn, packetId, catalogTrackName) {
4433
4969
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
4970
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
4434
4971
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
4435
4972
  this.#clearRepairDeadline(key);
4436
4973
  this.#clearBlockTimer(key);
@@ -4440,6 +4977,7 @@ var FECManager = class _FECManager {
4440
4977
  }
4441
4978
  this.#blockSourceCounts.delete(key);
4442
4979
  this.#blockSourceEsis.delete(key);
4980
+ this.#blockRebuiltEsis.delete(key);
4443
4981
  this.#blockAuthoredLengths.delete(key);
4444
4982
  this.#blockRepairRsIds.delete(key);
4445
4983
  this.#blockRsbLengths.delete(key);
@@ -4449,7 +4987,8 @@ var FECManager = class _FECManager {
4449
4987
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
4450
4988
  this.#fecStats.blocksFailed++;
4451
4989
  this.#statsForPacket(packetId).blocksFailed++;
4452
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
4990
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
4991
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
4453
4992
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
4454
4993
  }
4455
4994
  /**
@@ -4478,7 +5017,9 @@ var FECManager = class _FECManager {
4478
5017
  this.#retireBlockClass(key, block.sbn, block.packetId, block.catalogTrackName);
4479
5018
  this.#blockSourceCounts.delete(key);
4480
5019
  this.#blockSourceEsis.delete(key);
5020
+ this.#blockRebuiltEsis.delete(key);
4481
5021
  this.#blockAuthoredLengths.delete(key);
5022
+ this.#isoSpanKeys.delete(key);
4482
5023
  this.#blockRepairRsIds.delete(key);
4483
5024
  this.#blockRsbLengths.delete(key);
4484
5025
  this.#clearBlockTimer(key);
@@ -4569,7 +5110,9 @@ var FECManager = class _FECManager {
4569
5110
  this.#blockKeysBySbn.clear();
4570
5111
  this.#blockSourceCounts.clear();
4571
5112
  this.#blockSourceEsis.clear();
5113
+ this.#blockRebuiltEsis.clear();
4572
5114
  this.#blockAuthoredLengths.clear();
5115
+ this.#isoSpanKeys.clear();
4573
5116
  this.#blockRepairRsIds.clear();
4574
5117
  this.#blockRsbLengths.clear();
4575
5118
  this.#heldLayerStates.clear();
@@ -4594,6 +5137,7 @@ var FECManager = class _FECManager {
4594
5137
  this.#blockAnchorsMs.clear();
4595
5138
  this.#blockCatalogTrackNames.clear();
4596
5139
  this.#classifiers.clear();
5140
+ this.#noSpanRaps.clear();
4597
5141
  this.#streamGeometries.clear();
4598
5142
  this.#failedBlocks.clear();
4599
5143
  this.#resolvedBlockClasses.clear();