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

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 (111) hide show
  1. package/README.md +34 -19
  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 +2064 -388
  7. package/dist/browser-runtime.js.map +3 -3
  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 +163 -20
  28. package/dist/fec-manager.d.ts.map +1 -1
  29. package/dist/fec-manager.js +863 -110
  30. package/dist/fec-manager.js.map +3 -3
  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 +4 -4
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +8 -2
  40. package/dist/index.js.map +2 -2
  41. package/dist/iso-block-locator.d.ts +64 -13
  42. package/dist/iso-block-locator.d.ts.map +1 -1
  43. package/dist/iso-block-locator.js +125 -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.map +2 -2
  51. package/dist/mmtp-container-parser.d.ts +109 -12
  52. package/dist/mmtp-container-parser.d.ts.map +1 -1
  53. package/dist/mmtp-container-parser.js +312 -27
  54. package/dist/mmtp-container-parser.js.map +2 -2
  55. package/dist/mmtp-container-parser.no-modules.js +333 -32
  56. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  57. package/dist/mmtp-decode-pipeline.js +311 -27
  58. package/dist/mmtp-decode-pipeline.js.map +2 -2
  59. package/dist/mmtp-fec-session.js.map +2 -2
  60. package/dist/mmtp-router.d.ts +51 -12
  61. package/dist/mmtp-router.d.ts.map +1 -1
  62. package/dist/mmtp-router.js +723 -83
  63. package/dist/mmtp-router.js.map +3 -3
  64. package/dist/multicast-auth-catalog.js.map +2 -2
  65. package/dist/multicast-input.js.map +2 -2
  66. package/dist/multicast-manager.d.ts +31 -3
  67. package/dist/multicast-manager.d.ts.map +1 -1
  68. package/dist/multicast-manager.js +1698 -231
  69. package/dist/multicast-manager.js.map +3 -3
  70. package/dist/multicast-transport.js +28 -18
  71. package/dist/multicast-transport.js.map +2 -2
  72. package/dist/multicast-unwrap.js.map +2 -2
  73. package/dist/no-modules.d.ts +1 -0
  74. package/dist/no-modules.d.ts.map +1 -1
  75. package/dist/no-modules.js +333 -31
  76. package/dist/no-modules.js.map +4 -4
  77. package/dist/repair-fetch.d.ts +38 -8
  78. package/dist/repair-fetch.d.ts.map +1 -1
  79. package/dist/repair-fetch.js +286 -27
  80. package/dist/repair-fetch.js.map +3 -3
  81. package/dist/repair-layer-subscriptions.d.ts +6 -2
  82. package/dist/repair-layer-subscriptions.d.ts.map +1 -1
  83. package/dist/repair-layer-subscriptions.js +6 -3
  84. package/dist/repair-layer-subscriptions.js.map +2 -2
  85. package/dist/signaling.js.map +2 -2
  86. package/dist/timestamp-codec.js.map +2 -2
  87. package/dist/track-session.d.ts +1 -1
  88. package/dist/track-session.d.ts.map +1 -1
  89. package/dist/track-session.js +1 -0
  90. package/dist/track-session.js.map +2 -2
  91. package/dist/wasm-mfu-reassembler.js.map +2 -2
  92. package/dist/wasm-mmtp-container-parser.js +311 -27
  93. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  94. package/package.json +8 -5
  95. package/schemas/catalog.schema.json +4 -0
  96. package/src/block-policy.ts +324 -83
  97. package/src/catalog-fec-params.ts +37 -1
  98. package/src/cmcd-producer.ts +189 -179
  99. package/src/codec-utils.ts +121 -1
  100. package/src/fec-manager.ts +818 -42
  101. package/src/fec-worker-setup.ts +2 -2
  102. package/src/index.ts +11 -2
  103. package/src/iso-block-locator.ts +167 -31
  104. package/src/iso-bmff-timing.ts +40 -1
  105. package/src/mmtp-container-parser.ts +355 -32
  106. package/src/mmtp-router.ts +665 -50
  107. package/src/multicast-manager.ts +145 -16
  108. package/src/no-modules.ts +3 -0
  109. package/src/repair-fetch.ts +366 -50
  110. package/src/repair-layer-subscriptions.ts +13 -5
  111. package/src/track-session.ts +4 -1
@@ -22,10 +22,12 @@ import {
22
22
  isoBlockContains,
23
23
  isoBlocksBehindLowerBound,
24
24
  parseFecBlockProfile,
25
+ serial32Add,
25
26
  serial32Distance,
26
27
  serial32Precedes,
27
28
  ssbg1FitsSymbol,
28
29
  type FecBlockProfile,
30
+ type FecInstanceGeometry,
29
31
  admitMmtpRepairObject,
30
32
  parseMoqRepairFrameWithHeader,
31
33
  type MMTPHeader,
@@ -53,6 +55,7 @@ import {
53
55
 
54
56
  import { HeldLayerAdmission, heldLayerAnchorHorizon, type FecFailClosedReason } from './held-layer-admission.js'
55
57
  import type { MmtpDeliveryProvenance } from './mfu-reassembler.js'
58
+ import type { AuthoredTiming } from './authored-timing.js'
56
59
  import type {
57
60
  FecWorkerClient,
58
61
  FecTrackStats,
@@ -136,6 +139,12 @@ export interface FecStats {
136
139
  workers: Array<FecTrackStats & { packetId: number }>
137
140
  /** Main-thread repair symbols rejected before dispatch because their size did not match T. */
138
141
  repairSymbolSizeMismatches: number
142
+ /**
143
+ * Repair packets discarded because they arrived on a repair track the
144
+ * catalog does not list for their instance (fec-01 6.3.9): they delimit no
145
+ * block and anchor nothing.
146
+ */
147
+ unlistedRepairTrackRefusals: number
139
148
  /**
140
149
  * Repair objects discarded on admission (draft-ramadan-moq-fec-core-00 7.5,
141
150
  * draft-ramadan-moq-mmt-02 7.3), per FEC instance and reason. The instance
@@ -169,6 +178,17 @@ export interface FecPacketStats {
169
178
 
170
179
  export type FecSymbolSource = 'multicast' | 'moq'
171
180
 
181
+ /**
182
+ * What feedRebuiltSourceSymbol did with a rebuilt source: whether its block
183
+ * took it, and the block the synchronous decoder recovered with it, if any.
184
+ */
185
+ export interface RebuiltSourceFeed {
186
+ readonly taken: boolean
187
+ readonly recovered: Uint8Array | null
188
+ }
189
+
190
+ const NOT_TAKEN: RebuiltSourceFeed = Object.freeze({ taken: false, recovered: null })
191
+
172
192
  /**
173
193
  * One iso-ssbg1-v1 first-arrival source symbol MmtpRouter holds until a repair
174
194
  * symbol states its block: the exact protected packet (no SS_ID, unpadded),
@@ -180,6 +200,13 @@ export interface IsoHeldSource {
180
200
  readonly evidence: SourceSymbolEvidence
181
201
  /** Larger than one ssbg_mode1 symbol: counted, never decoded. */
182
202
  readonly oversized: boolean
203
+ /**
204
+ * Receipt time (performance.now() clock; holdIsoSource stamps it when
205
+ * absent): a run's FEC deadline is anchored at it (isoRepairlessWaitMs),
206
+ * and a loss-free range's late-source allowance counts from it
207
+ * (#lossFreeRunReadyAtMs).
208
+ */
209
+ readonly arrivedAtMs?: number
183
210
  }
184
211
 
185
212
  /**
@@ -201,6 +228,25 @@ export interface UndelimitedIsoLoss {
201
228
  readonly previousBlockStart?: number
202
229
  }
203
230
 
231
+ /**
232
+ * A pending hole the stream ran more than the locator's horizon past before
233
+ * its range repair ended (BLO-52085): no repair can state its blocks any
234
+ * more, and the release gate no longer waits for it.
235
+ */
236
+ export type ExpiredIsoHole = Pick<UndelimitedIsoLoss, 'packetId' | 'catalogTrackName' | 'holeStart' | 'holeLength'>
237
+
238
+ /**
239
+ * What a failed iso-ssbg1-v1 repair-less span was: the `length` SS_IDs from
240
+ * its start, between two stated blocks, of which `sources` arrived. No repair
241
+ * stated the blocks inside it, so the receiver cannot tell its complete
242
+ * blocks from the ones that lost a source: the span failed, not the block
243
+ * that starts it.
244
+ */
245
+ export interface IsoSpanFailure {
246
+ readonly length: number
247
+ readonly sources: number
248
+ }
249
+
204
250
  /**
205
251
  * How the multicast leg hands its symbols to this manager.
206
252
  *
@@ -510,10 +556,21 @@ export class FECManager {
510
556
  // 'pending' forever, which would park every later frame of its stream in
511
557
  // the in-order release gate. Each entry owns its handle; the callback
512
558
  // checks it still owns the key, so a settled or reset key is never touched.
513
- #pendingWorkerCleanupBounds = new Map<string, { handle: ReturnType<typeof setTimeout> }>()
559
+ /**
560
+ * Per owed Worker cleanup: the bound on its acknowledgement, when its block
561
+ * was due, and when its cleanup was asked for (see `onCleanupComplete`).
562
+ */
563
+ #pendingWorkerCleanupBounds = new Map<
564
+ string,
565
+ { handle: ReturnType<typeof setTimeout>; dueAtMs: number; askedAtMs: number }
566
+ >()
514
567
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
515
568
  #blockSourceCounts = new Map<string, number>()
516
569
  #blockSourceEsis = new Map<string, Set<number>>()
570
+ // Source ESIs per block that another FEC instance rebuilt and fed in
571
+ // (feedRebuiltSourceSymbol). Kept apart from #blockSourceEsis: they are
572
+ // not network arrivals and never make a block clean.
573
+ #blockRebuiltEsis = new Map<string, Set<number>>()
517
574
  // Authored SSB_length per block (ISO/IEC 23008-1 §C.5.3), learned from the
518
575
  // first repair symbol. The FFmpeg moq_mmt publisher closes a block every D
519
576
  // media units, usually before it holds K symbols; under iso-ssbg1-v1
@@ -522,10 +579,14 @@ export class FECManager {
522
579
  // SSB_length source arrivals and recoverable from SSB_length received
523
580
  // symbols; waiting for K fails every one of them.
524
581
  #blockAuthoredLengths = new Map<string, number>()
582
+ // Keys whose authored length is a repair-less span's (#openIsoSpan), until
583
+ // a repair states the block there or the span resolves.
584
+ #isoSpanKeys = new Set<string>()
525
585
  #ssbLengthConflictCount = 0
526
586
  #blockRepairRsIds = new Map<string, Set<number>>()
527
587
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
528
- // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
588
+ // symbols its repair group carries; 0 for a repair-less span no repair can
589
+ // state (#openIsoSpan). Same lifecycle as #blockRepairRsIds.
529
590
  #blockRsbLengths = new Map<string, number>()
530
591
  /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
531
592
  #heldLayerStates = new Map<string, HeldLayerAdmission>()
@@ -644,6 +705,10 @@ export class FECManager {
644
705
  // ── Keyframe-protected repair policy (block-policy.ts) ──
645
706
  // One classifier per physical stream, built from that stream's geometry.
646
707
  #classifiers = new Map<string, BlockClassifier>()
708
+ // A stream without catalog timing has no classifier, so the last RAP it
709
+ // released stands in for one: "an MPU boundary bounds its RAPs" holds until
710
+ // a second RAP is released inside one MPU (BLO-52085).
711
+ #noSpanRaps = new Map<string, { mpu: number; presentationTime: bigint; inside: boolean }>()
647
712
  // Geometry a stream-scoped configuration gave one stream (streamKey). ABR
648
713
  // rungs can share a packetId with a different framerate or GOP, so the
649
714
  // packet-level geometry is only the geometry of a packet whose streams
@@ -676,6 +741,14 @@ export class FECManager {
676
741
  // iso-ssbg1-v1 block location per stream (streamKey). A source belongs to a
677
742
  // block only once a repair symbol stated the block's (SS_Start, SSB_length).
678
743
  #isoLocators = new Map<string, IsoBlockLocator<IsoHeldSource>>()
744
+ // The ts of the run behind the gap the release gate last asked about, per
745
+ // stream (isoRepairlessWaitMs), keyed on the frame before the gap: kept, as
746
+ // the source it came from may retire before the run's deadline, and the
747
+ // earliest found wins, so a late frame that becomes the head restarts
748
+ // nothing. It stays until the next run gap: a source discontinuity drops
749
+ // it, and one older than twice the hold ceiling is not this gap's.
750
+ // `counted` once the deadline passed (onUndelimitedRunGap).
751
+ #runAnchors = new Map<string, { fromSsId: number; tsMs: number; counted: boolean }>()
679
752
  #deferIsoGaps = false
680
753
  #isoRepairRefusedCount = 0
681
754
  #isoSourceOversizeCount = 0
@@ -714,6 +787,7 @@ export class FECManager {
714
787
  #workerErrorCounts = new Map<string, number>()
715
788
  #decoderUnavailableEvents = 0
716
789
  #repairSymbolSizeMismatchCount = 0
790
+ #unlistedRepairTrackRefusals = 0
717
791
 
718
792
  // Event callbacks — block lifecycle notifications for MmtpRouter wiring.
719
793
  // NOTE: For sync WASM path, recovery routing is handled by MmtpRouter from
@@ -725,13 +799,17 @@ export class FECManager {
725
799
  onBlockComplete:
726
800
  | ((sbn: number, packetId: number, catalogTrackName?: string) => void)
727
801
  | null = null
728
- /** A block reached its fail bound. `blockClass` is its class at failure. */
802
+ /**
803
+ * A block reached its fail bound. `blockClass` is its class at failure.
804
+ * `span` is set when what failed is a repair-less span starting at `sbn`.
805
+ */
729
806
  onBlockFailed:
730
807
  | ((
731
808
  sbn: number,
732
809
  packetId: number,
733
810
  catalogTrackName: string | undefined,
734
811
  blockClass: BlockClass,
812
+ span?: IsoSpanFailure,
735
813
  ) => void)
736
814
  | null = null
737
815
  /**
@@ -815,6 +893,8 @@ export class FECManager {
815
893
  * for it, which it must be.
816
894
  */
817
895
  #onUndelimitedLoss: ((loss: UndelimitedIsoLoss) => void) | null = null
896
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
897
+ #onIsoHoleExpired: ((hole: ExpiredIsoHole) => boolean) | null = null
818
898
  /** A block every symbol of which vanished was created by SBN evidence. */
819
899
  onBlockVanished:
820
900
  | ((sbn: number, packetId: number, catalogTrackName: string | undefined) => void)
@@ -827,6 +907,25 @@ export class FECManager {
827
907
  onSourceDiscontinuity:
828
908
  | ((packetId: number, catalogTrackName: string | undefined) => void)
829
909
  | null = null
910
+ /** The FEC deadline of a run no repair delimited passed, releasing the gap behind it (once per gap). */
911
+ onUndelimitedRunGap:
912
+ | ((packetId: number, catalogTrackName: string | undefined) => void)
913
+ | null = null
914
+ /**
915
+ * The span and tolerance the catalog states for a keyframe overlay
916
+ * installed over a source track (draft-ramadan-moq-mmt-02 7.4.1: the
917
+ * overlay instance's own interleaveDepthMs and reorderToleranceMs), or
918
+ * undefined while none is installed. A stated block only a late source
919
+ * can complete, and a frame whose gap may hide a RAP behind a span only a
920
+ * late source can fill, also wait for that overlay's repair
921
+ * (#overlayLateWaitMs).
922
+ */
923
+ keyframeOverlayTiming:
924
+ | ((
925
+ packetId: number,
926
+ catalogTrackName: string | undefined,
927
+ ) => Pick<FecInstanceGeometry, 'interleaveDepthMs' | 'reorderToleranceMs'> | undefined)
928
+ | null = null
830
929
 
831
930
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
832
931
  /**
@@ -1469,7 +1568,12 @@ export class FECManager {
1469
1568
  timer.handle = null
1470
1569
  this.#requestRepair(sbn, packetId, catalogTrackName)
1471
1570
  }
1472
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()))
1571
+ timer.handle = setTimeout(
1572
+ onFire,
1573
+ this.#receiptAtMs === undefined
1574
+ ? Math.max(0, deadlineMs - performance.now())
1575
+ : this.#receiptTimerDelayMs(deadlineMs, 0),
1576
+ )
1473
1577
  this.#repairDeadlines.set(key, timer)
1474
1578
  }
1475
1579
 
@@ -1663,6 +1767,12 @@ export class FECManager {
1663
1767
  * Vanished blocks are not enumerated here: their starts are unknown until a
1664
1768
  * repair states them. The SS_IDs between two stated blocks become one
1665
1769
  * repair-less span when the later block's repair arrives (placeIsoRepair).
1770
+ *
1771
+ * A `held` source arrived before its block was known and is fed only now
1772
+ * that a repair, a span or a closed hole placed it: how far its block start
1773
+ * then lies behind the frontier measures how long the receiver held it, not
1774
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
1775
+ * it (BLO-52085).
1666
1776
  */
1667
1777
  #noteSbnSeen(
1668
1778
  sbn: number,
@@ -1671,6 +1781,7 @@ export class FECManager {
1671
1781
  symbol: 'source' | 'repair',
1672
1782
  packetSequenceNumber?: number,
1673
1783
  ssId = sbn,
1784
+ held = false,
1674
1785
  ): void {
1675
1786
  const streamKey = this.#streamKey(packetId, catalogTrackName)
1676
1787
  // Arrival at FEC, not receipt (withReceiptTime): this bounds how far SS_ID
@@ -1706,6 +1817,8 @@ export class FECManager {
1706
1817
  // The classifier compares authored order with SBN order only within
1707
1818
  // one continuous SBN sequence.
1708
1819
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity()
1820
+ this.#noSpanRaps.delete(streamKey)
1821
+ this.#runAnchors.delete(streamKey)
1709
1822
  this.#highestSbn.set(streamKey, { sbn, atMs: now })
1710
1823
  this.#sourceFrontiers.set(streamKey, { sbn, atMs: now })
1711
1824
  if (psn === undefined) this.#sourceAnchors.delete(streamKey)
@@ -1726,7 +1839,7 @@ export class FECManager {
1726
1839
  }
1727
1840
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
1728
1841
  if (symbol === 'source' && window !== null && this.#blockPrecedes(sbn, previous.sbn) && (
1729
- this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId) ||
1842
+ (!held && this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId)) ||
1730
1843
  (psn !== undefined && anchor !== undefined && serial32Precedes(ssId, anchor.ssId) &&
1731
1844
  psn !== anchor.psn && !sentInOrder({ ssId, psn }, anchor))
1732
1845
  )) {
@@ -2080,21 +2193,28 @@ export class FECManager {
2080
2193
  this.#blockWaitDeadlinesMs.delete(key)
2081
2194
  this.#repairHoldUntilMs.delete(key)
2082
2195
  this.#traceLifecycle('timeout-queued', sbn, packetId, catalogTrackName)
2083
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName)
2196
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs)
2084
2197
  }
2085
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)))
2198
+ timer.handle = setTimeout(
2199
+ onFire,
2200
+ this.#receiptAtMs === undefined
2201
+ ? Math.max(1, Math.ceil(deadlineMs - nowMs))
2202
+ : this.#receiptTimerDelayMs(deadlineMs, 1),
2203
+ )
2086
2204
  this.#activeBlocks.set(key, timer)
2087
2205
  this.#indexBlockKey(key, sbn, packetId)
2088
2206
  }
2089
2207
 
2090
2208
  /**
2091
2209
  * Hand a block whose delivery is over to its decoder for finalization: the
2092
- * datagram deadline fired, or the ordered relay moved past it.
2210
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
2211
+ * is when it was due: its deadline, or now.
2093
2212
  */
2094
2213
  #finalizeExpiredBlock(
2095
2214
  sbn: number,
2096
2215
  packetId: number,
2097
2216
  catalogTrackName: string | undefined,
2217
+ dueAtMs = performance.now(),
2098
2218
  ): void {
2099
2219
  const key = this.#blockKey(sbn, packetId, catalogTrackName)
2100
2220
  // A vanished block that never received a symbol holds no decoder state
@@ -2118,7 +2238,7 @@ export class FECManager {
2118
2238
  if (workerClient) {
2119
2239
  this.#pendingWorkerCleanups.add(key)
2120
2240
  this.#pendingWorkerCleanupClients.set(key, workerClient)
2121
- this.#boundOwedCleanup(key, packetId, workerClient)
2241
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs)
2122
2242
  workerClient.cleanup(sbn)
2123
2243
  } else {
2124
2244
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client
@@ -2289,6 +2409,9 @@ export class FECManager {
2289
2409
  // sibling's change, but the first stream-scoped geometry on a packet
2290
2410
  // does change the siblings that have none (stream-geometry-absent).
2291
2411
  this.#bumpEpoch(packetId)
2412
+ for (const key of [...this.#noSpanRaps.keys()]) {
2413
+ if (this.#belongsToPacket(key, packetId)) this.#noSpanRaps.delete(key)
2414
+ }
2292
2415
  for (const [key, classifier] of [...this.#classifiers]) {
2293
2416
  if (!this.#belongsToPacket(key, packetId)) continue
2294
2417
  const stream = this.#parseStreamKey(key)
@@ -2413,6 +2536,7 @@ export class FECManager {
2413
2536
  packetId,
2414
2537
  })),
2415
2538
  repairSymbolSizeMismatches: this.#repairSymbolSizeMismatchCount,
2539
+ unlistedRepairTrackRefusals: this.#unlistedRepairTrackRefusals,
2416
2540
  repairObjectRejects: [...this.#repairObjectRejects.values()].map((r) => ({ ...r })),
2417
2541
  workerErrors: Object.fromEntries(this.#workerErrorCounts),
2418
2542
  }
@@ -2532,7 +2656,9 @@ export class FECManager {
2532
2656
  }
2533
2657
  resetMap(this.#blockSourceCounts)
2534
2658
  resetMap(this.#blockSourceEsis)
2659
+ resetMap(this.#blockRebuiltEsis)
2535
2660
  resetMap(this.#blockAuthoredLengths)
2661
+ resetSet(this.#isoSpanKeys)
2536
2662
  resetMap(this.#blockRepairRsIds)
2537
2663
  resetMap(this.#blockRsbLengths)
2538
2664
  resetMap(this.#heldLayerStates)
@@ -2563,8 +2689,10 @@ export class FECManager {
2563
2689
  resetMap(this.#highestSbn)
2564
2690
  resetMap(this.#sourceFrontiers)
2565
2691
  resetMap(this.#isoLocators)
2692
+ resetMap(this.#runAnchors)
2566
2693
  resetMap(this.#sourceAnchors)
2567
2694
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName))
2695
+ this.#noSpanRaps.delete(this.#streamKey(packetId, catalogTrackName))
2568
2696
  this.#bumpEpoch(packetId)
2569
2697
  for (const [sbn, keys] of this.#blockKeysBySbn) {
2570
2698
  for (const key of keys.keys()) {
@@ -2663,7 +2791,9 @@ export class FECManager {
2663
2791
  dropMap(this.#pendingWorkerCleanupClients)
2664
2792
  dropMap(this.#blockSourceCounts)
2665
2793
  dropMap(this.#blockSourceEsis)
2794
+ dropMap(this.#blockRebuiltEsis)
2666
2795
  dropMap(this.#blockAuthoredLengths)
2796
+ dropSet(this.#isoSpanKeys)
2667
2797
  dropMap(this.#blockRepairRsIds)
2668
2798
  dropMap(this.#blockRsbLengths)
2669
2799
  dropMap(this.#blockPathCounts)
@@ -2677,8 +2807,10 @@ export class FECManager {
2677
2807
  dropMap(this.#highestSbn)
2678
2808
  dropMap(this.#sourceFrontiers)
2679
2809
  dropMap(this.#isoLocators)
2810
+ dropMap(this.#runAnchors)
2680
2811
  dropMap(this.#sourceAnchors)
2681
2812
  dropMap(this.#classifiers)
2813
+ dropMap(this.#noSpanRaps)
2682
2814
  dropMap(this.#streamGeometries)
2683
2815
  dropSet(this.#pendingWorkerCleanups)
2684
2816
  dropSet(this.#completedBlocks)
@@ -2881,6 +3013,10 @@ export class FECManager {
2881
3013
  }
2882
3014
  }
2883
3015
 
3016
+ if (isSourceSymbol && source === 'multicast') {
3017
+ this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), (sbn + esi) >>> 0, packetId, catalogTrackName)
3018
+ }
3019
+
2884
3020
  return true
2885
3021
  }
2886
3022
 
@@ -3006,8 +3142,10 @@ export class FECManager {
3006
3142
  }
3007
3143
  /**
3008
3144
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
3009
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
3010
- * Undefined for a block that is not open.
3145
+ * (SSB_length) and RSB_length (each undefined until a repair stated it; a
3146
+ * repair-less span states its length, and RSB_length 0 when it is longer
3147
+ * than K, since no repair can reach it). Undefined for a block that is not
3148
+ * open.
3011
3149
  */
3012
3150
  blockSymbolCounts(
3013
3151
  sbn: number,
@@ -3090,8 +3228,9 @@ export class FECManager {
3090
3228
  return true
3091
3229
  }
3092
3230
  /**
3093
- * Drop a block's repair hold: its FETCH ended without delivering. The block
3094
- * falls back to its multicast wait, which may already have passed.
3231
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
3232
+ * back only a repair that cannot complete it. The block falls back to its
3233
+ * multicast wait, which may already have passed.
3095
3234
  */
3096
3235
  releaseRepairHold(sbn: number, packetId: number, catalogTrackName?: string): void {
3097
3236
  const key = this.#blockKey(sbn, packetId, catalogTrackName)
@@ -3141,7 +3280,7 @@ export class FECManager {
3141
3280
  }
3142
3281
  const trackConfig = this.#trackConfigs.get(packetId)
3143
3282
  if (trackConfig === undefined) return undefined
3144
- return Math.max(1, trackConfig.timeoutMs - this.#repairDeadlineMs(trackConfig))
3283
+ return Math.max(1, this.#repairGraceMs(trackConfig, this.#multicastWaitMs(trackConfig)))
3145
3284
  }
3146
3285
 
3147
3286
  /** True once configureTrack/setFecDecoder/setFecWorker configured this packetId. */
@@ -3189,6 +3328,9 @@ export class FECManager {
3189
3328
  for (const key of [...this.#isoLocators.keys()]) {
3190
3329
  if (this.#belongsToPacket(key, packetId)) this.#isoLocators.delete(key)
3191
3330
  }
3331
+ for (const key of [...this.#runAnchors.keys()]) {
3332
+ if (this.#belongsToPacket(key, packetId)) this.#runAnchors.delete(key)
3333
+ }
3192
3334
  }
3193
3335
 
3194
3336
  /**
@@ -3252,7 +3394,9 @@ export class FECManager {
3252
3394
  ): boolean {
3253
3395
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName)
3254
3396
  const evictedBefore = locator.heldEvicted
3255
- const held = locator.hold(ssId, source)
3397
+ const held = locator.hold(ssId, source.arrivedAtMs === undefined ? { ...source, arrivedAtMs: this.#receiptNow() } : source)
3398
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName)
3399
+ if (held && source.source === 'multicast') this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName)
3256
3400
  const evicted = locator.heldEvicted - evictedBefore
3257
3401
  if (evicted > 0) {
3258
3402
  const before = this.#isoHeldEvictedCount
@@ -3280,17 +3424,26 @@ export class FECManager {
3280
3424
  ssStart: number,
3281
3425
  ssbLength: number,
3282
3426
  ): IsoRepairPlacement<IsoHeldSource> {
3283
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength)
3427
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName)
3428
+ const placement = locator.placeRepair(ssStart, ssbLength)
3429
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName)
3284
3430
  if (placement.status !== 'placed') {
3285
3431
  this.#isoRepairRefusedCount++
3286
3432
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
3287
3433
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`)
3288
3434
  }
3435
+ // The repair FETCH of a span's first group brought back a shorter block:
3436
+ // the span holds more than one, so that group cannot complete it, and
3437
+ // holding the span (and every frame behind it) for the FETCH buys
3438
+ // nothing. It falls back to its multicast wait.
3439
+ if (placement.ofSpan !== undefined) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName)
3289
3440
  return placement
3290
3441
  }
3442
+ // A repair states the block at its SS_Start: a span the locator kept
3443
+ // there is now that one block (IsoBlockLocator.placeRepair).
3444
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName))
3291
3445
  if (placement.span !== undefined) this.#openIsoSpan(placement.span, packetId, catalogTrackName)
3292
3446
  if (placement.hole !== undefined) {
3293
- const locator = this.#isoLocatorFor(packetId, catalogTrackName)
3294
3447
  const hole = placement.hole.block
3295
3448
  const previous = locator.blockEndingAt(hole.start)
3296
3449
  const loss: UndelimitedIsoLoss = {
@@ -3312,18 +3465,38 @@ export class FECManager {
3312
3465
  * `handler`, instead of a repair-less span; null restores spans. Set by the
3313
3466
  * range repair scheduler; applies to every stream from its next gap. The
3314
3467
  * handler and the deferral are one setting, so no hole is ever created with
3315
- * nobody to close it.
3468
+ * nobody to close it. `onExpired` is told of each pending hole the stream
3469
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
3470
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
3471
+ * reported; otherwise the hole is discarded with its sources.
3316
3472
  */
3317
- setUndelimitedLossHandler(handler: ((loss: UndelimitedIsoLoss) => void) | null): void {
3473
+ setUndelimitedLossHandler(
3474
+ handler: ((loss: UndelimitedIsoLoss) => void) | null,
3475
+ onExpired: ((hole: ExpiredIsoHole) => boolean) | null = null,
3476
+ ): void {
3318
3477
  this.#onUndelimitedLoss = handler
3478
+ this.#onIsoHoleExpired = handler === null ? null : onExpired
3319
3479
  this.#deferIsoGaps = handler !== null
3320
3480
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps
3321
3481
  }
3322
3482
 
3483
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
3484
+ #settleExpiredIsoHoles(
3485
+ locator: IsoBlockLocator<IsoHeldSource>,
3486
+ packetId: number,
3487
+ catalogTrackName: string | undefined,
3488
+ ): void {
3489
+ for (const hole of locator.takeExpiredHoles()) {
3490
+ const expired: ExpiredIsoHole = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length }
3491
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length)
3492
+ }
3493
+ }
3494
+
3323
3495
  /**
3324
- * The range repair for a hole ended: every hole still pending inside
3325
- * `[start, start + length)` becomes a repair-less span. Returns those spans
3326
- * with the held sources they placed, for the caller to feed (MmtpRouter).
3496
+ * The range repair for a hole ended: every hole inside `[start, start +
3497
+ * length)`, pending or expired, becomes a repair-less span. Returns those
3498
+ * spans with the held sources they placed, for the caller to feed
3499
+ * (MmtpRouter).
3327
3500
  */
3328
3501
  closeIsoHoles(
3329
3502
  packetId: number,
@@ -3345,6 +3518,17 @@ export class FECManager {
3345
3518
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
3346
3519
  * SS_ID of which vanished resolves through its deadline like any vanished
3347
3520
  * block.
3521
+ *
3522
+ * A span longer than K holds more than one block (SSB_length <= K), and the
3523
+ * locator states no block inside a span, only one exactly its range
3524
+ * (IsoBlockLocator.placeRepair): no repair, multicast or FETCHed, can ever
3525
+ * reach it. Its repair group is empty, so the repair scheduler FETCHes no
3526
+ * Group of it (group-cannot-complete). Every span still keeps its whole
3527
+ * wait (#lateSourceWaitMs): failing it early released the frames behind it
3528
+ * past a keyframe the overlay was still rebuilding (BLO-52085). The release
3529
+ * gate lets those frames go once only a late source can fill the gap
3530
+ * before them, as long after they arrived as the gap's decision allows
3531
+ * (isoRepairlessWaitMs).
3348
3532
  */
3349
3533
  #openIsoSpan(
3350
3534
  span: { readonly block: IsoBlockRange; readonly placed: readonly unknown[] },
@@ -3352,7 +3536,16 @@ export class FECManager {
3352
3536
  catalogTrackName: string | undefined,
3353
3537
  ): void {
3354
3538
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName)
3355
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length)
3539
+ // A span's key is always new here. An authored length is set only here or
3540
+ // from a repair stating that block (#noteAuthoredLength), and the locator
3541
+ // opens a span only where no repair stated a block, so none can precede
3542
+ // it. Were one to, the guard would skip the RSB_length 0 that keeps the
3543
+ // repair scheduler from FETCHing a long span's first Group.
3544
+ if (!this.#blockAuthoredLengths.has(key)) {
3545
+ this.#blockAuthoredLengths.set(key, span.block.length)
3546
+ this.#isoSpanKeys.add(key)
3547
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0)
3548
+ }
3356
3549
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true)
3357
3550
  }
3358
3551
 
@@ -3360,7 +3553,12 @@ export class FECManager {
3360
3553
  * Resolution of the SS_IDs strictly between two released frames' SS_IDs on
3361
3554
  * an iso-ssbg1-v1 stream, for in-order frame release: null while a block
3362
3555
  * that could hold them is pending or not yet stated by a repair, else the
3363
- * starts of the blocks that failed or vanished.
3556
+ * starts of the blocks that failed or vanished. SS_IDs no repair has
3557
+ * delimited yet that all arrived lost nothing and wait for no repair, only
3558
+ * the late-source allowance after the multicast datagram that clocks them
3559
+ * arrived (#lossFreeRunReadyAtMs), and not even that when none of them came
3560
+ * as one; one missing makes a run that waits as one block
3561
+ * (isoRepairlessWaitMs).
3364
3562
  *
3365
3563
  * `untracked` reads as the release gate reads it (MmtpRouter
3366
3564
  * #createFecReleaseGate): a block holding either released frame's SS_ID
@@ -3378,7 +3576,19 @@ export class FECManager {
3378
3576
  ): readonly number[] | null {
3379
3577
  if (!serial32Precedes(fromSsId, toSsId) || serial32Distance(fromSsId, toSsId) <= 1) return []
3380
3578
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))
3381
- if (!locator || !locator.coversBetween(fromSsId, toSsId)) return null
3579
+ if (!locator) return null
3580
+ // SS_IDs past coverage that all arrived lost nothing, so no repair need
3581
+ // delimit them; a run of them the receiver lacks is one block, which
3582
+ // isoRepairlessWaitMs times.
3583
+ const run = locator.undelimitedBetween(fromSsId, toSsId)
3584
+ if (run?.missing !== undefined) return null
3585
+ if (run !== null) {
3586
+ const config = this.#trackConfigs.get(packetId)
3587
+ const readyAtMs = config === undefined ? undefined : this.#lossFreeRunReadyAtMs(config, locator, run.start, toSsId)
3588
+ if (readyAtMs !== undefined && this.#receiptNow() < readyAtMs) return null
3589
+ }
3590
+ if (locator.coverageEnd === undefined) return []
3591
+ if (!locator.coversBetween(fromSsId, run?.start ?? toSsId)) return null
3382
3592
  const highest = this.highestSbn(packetId, catalogTrackName)
3383
3593
  const lost: number[] = []
3384
3594
  for (const block of locator.blocksBetween(fromSsId, toSsId)) {
@@ -3400,6 +3610,204 @@ export class FECManager {
3400
3610
  return lost
3401
3611
  }
3402
3612
 
3613
+ /**
3614
+ * When undelimited SS_IDs from `runStart` up to `toSsId` that all arrived
3615
+ * stop holding its frame: the late-source allowance after a multicast
3616
+ * datagram receipt. Until then a frame between them may still complete
3617
+ * from a packet with no SS_ID (an untagged FT=0/FT=1 reordered behind the
3618
+ * next frame), and a repair may delimit them. The receipt is `toSsId`'s
3619
+ * own when it is held from a multicast datagram. Otherwise (its packet
3620
+ * came only as an overlap copy or from a MoQ stream, or was evicted or
3621
+ * retired) it is the newest among those SS_IDs, every one of which is
3622
+ * held and states its path. So the time moves at most once, when the
3623
+ * head's own multicast copy arrives while its frame waits or its held
3624
+ * source is dropped, and never on a later ask.
3625
+ *
3626
+ * Undefined, so the range releases at once, when no SS_ID of it came as a
3627
+ * multicast datagram: a MoQ arrival, an ordered relay's and the frame's
3628
+ * own are no clock for multicast reordering (#lossyReceiptMs). Undefined
3629
+ * too on a track with no catalog span, which states no allowance: the
3630
+ * local timeout is a cleanup bound, and isoRepairlessWaitMs arms no wake
3631
+ * there, so a wait would hold the frame until the next packet. The cost,
3632
+ * on multicast too: an untagged FT=0/FT=1 reordered behind the next frame
3633
+ * of such a track is dropped stale.
3634
+ */
3635
+ #lossFreeRunReadyAtMs(
3636
+ config: ResolvedFECTrackConfig,
3637
+ locator: IsoBlockLocator<IsoHeldSource>,
3638
+ runStart: number,
3639
+ toSsId: number,
3640
+ ): number | undefined {
3641
+ if (!FECManager.#hasCatalogTiming(config)) return undefined
3642
+ let clockMs = this.#lossyReceiptMs(locator.heldSource(toSsId))
3643
+ if (clockMs === undefined) {
3644
+ for (let ssId = runStart; ssId !== toSsId; ssId = (ssId + 1) >>> 0) {
3645
+ const atMs = this.#lossyReceiptMs(locator.heldSource(ssId))
3646
+ if (atMs !== undefined && (clockMs === undefined || atMs > clockMs)) clockMs = atMs
3647
+ }
3648
+ }
3649
+ if (clockMs === undefined) return undefined
3650
+ return clockMs + Math.max(0, this.#multicastWaitMs(config) - config.interleaveDepthMs)
3651
+ }
3652
+
3653
+ /**
3654
+ * Receipt time of a held source that came as a multicast datagram, the
3655
+ * one path that loses and reorders packets, else undefined: a MoQ stream
3656
+ * and an ordered relay deliver in order, so their arrivals clock no
3657
+ * reorder allowance and no FEC deadline. The path is the one the feed
3658
+ * stated (IsoHeldSource.source, MulticastSymbolDelivery), never a guess.
3659
+ */
3660
+ #lossyReceiptMs(held: IsoHeldSource | undefined): number | undefined {
3661
+ return held?.source === 'multicast' && this.#multicastSymbolDelivery === 'datagram' ? held.arrivedAtMs : undefined
3662
+ }
3663
+
3664
+ /**
3665
+ * The release gate's wait, from a frame's arrival, for the SS_IDs strictly
3666
+ * between two released frames' SS_IDs once only a late source can still
3667
+ * fill them, else undefined. That is when every one missing (neither
3668
+ * arrived nor held) lies in a repair-less span longer than K, which no
3669
+ * repair can state a block of (#openIsoSpan), or in a stated block its
3670
+ * own repair group cannot complete every SS_ID of which it misses lies
3671
+ * between them (so the gap's decision covers all it lost), and a multicast
3672
+ * source at or past `toSsId` arrived, so each is lost or reordered behind
3673
+ * it (a MoQ source shows nothing: MoQ streams overtake one another). The
3674
+ * span or block itself keeps its own wait.
3675
+ *
3676
+ * The wait is the late-symbol allowance, unless `rapMayHide`: the gap may
3677
+ * hold a RAP packet an installed keyframe overlay can still rebuild (its
3678
+ * decision stalls, or it ends at a RAP that may lie past a whole MPU).
3679
+ * Then the frame waits as a stated block its group cannot complete does
3680
+ * (#overlayLateWaitMs): the allowance alone with no overlay installed, the
3681
+ * overlay's span plus the larger of the allowance and its tolerance, or,
3682
+ * for an overlay that states no span, the span's whole wait (undefined).
3683
+ * So does `rapNext` (the gap ends at the RAP that opens the next MPU) when
3684
+ * the gap holds a stated block's loss.
3685
+ *
3686
+ * A run of SS_IDs no repair has delimited yet, one of which never arrived,
3687
+ * is one block of its own instead (draft-ramadan-moq-fec-multicast-00,
3688
+ * Receiver Repair Policy): on datagram delivery the frame then waits for
3689
+ * that block's FEC deadline, whatever the flags: ts plus the whole
3690
+ * multicast wait (fec-core-00 9.3), ts the arrival of the lowest held
3691
+ * multicast source above the run, up to the newest (fec-multicast-00,
3692
+ * Deadline Anchoring; under reordering at or after the draft's first
3693
+ * signal, never before). The wait returned counts from `arrivedAtMs`, the
3694
+ * frame's arrival; without it, it is the whole wait. With no such source
3695
+ * held (never arrived, retired, or evicted) the frame keeps the hold
3696
+ * ceiling: a MoQ arrival is no clock for a multicast deadline.
3697
+ */
3698
+ isoRepairlessWaitMs(
3699
+ packetId: number,
3700
+ catalogTrackName: string | undefined,
3701
+ fromSsId: number,
3702
+ toSsId: number,
3703
+ rapMayHide = false,
3704
+ rapNext = false,
3705
+ arrivedAtMs?: number,
3706
+ ): number | undefined {
3707
+ const config = this.#trackConfigs.get(packetId)
3708
+ if (config === undefined || !FECManager.#hasCatalogTiming(config)) return undefined
3709
+ const streamKey = this.#streamKey(packetId, catalogTrackName)
3710
+ const locator = this.#isoLocators.get(streamKey)
3711
+ if (locator === undefined) return undefined
3712
+ const run = locator.undelimitedBetween(fromSsId, toSsId)
3713
+ const readyAtMs = run === null || run.missing !== undefined ? undefined : this.#lossFreeRunReadyAtMs(config, locator, run.start, toSsId)
3714
+ if (readyAtMs !== undefined && this.#receiptNow() < readyAtMs) {
3715
+ return Math.max(0, readyAtMs - (arrivedAtMs ?? this.#receiptNow()))
3716
+ }
3717
+ const newestSource = locator.newestSource
3718
+ if (newestSource === undefined || serial32Precedes(newestSource, toSsId)) return undefined
3719
+ // A run past coverage the receiver lacks an SS_ID of is one block of the
3720
+ // instance. A repair may delimit it until its FEC deadline, so once the
3721
+ // delimited SS_IDs before it resolved the frame waits for that deadline,
3722
+ // longer than any overlay wait. Only a held multicast source anchors it:
3723
+ // an overlap copy is never held, and a MoQ stream overtakes the others.
3724
+ // Datagram delivery only: an ordered relay keeps the hold ceiling, as a
3725
+ // pause there says nothing of loss. Settle a run by stream order
3726
+ // (#withinOrderedHorizon) if a relay ever runs without repair.
3727
+ if (run?.missing !== undefined) {
3728
+ if (
3729
+ this.#multicastSymbolDelivery === 'ordered-relay' ||
3730
+ this.isoSpanResolution(packetId, catalogTrackName, fromSsId, run.start) === null
3731
+ ) {
3732
+ return undefined
3733
+ }
3734
+ // An anchor older than twice the hold ceiling is another run's: the
3735
+ // gate flushes a frame at the ceiling, so the same `from` SS_ID came
3736
+ // again (a publisher restart that reuses SS_IDs, or the 2^32 wrap).
3737
+ const kept = this.#runAnchors.get(streamKey)
3738
+ const anchor =
3739
+ kept?.fromSsId === fromSsId &&
3740
+ this.#receiptNow() - kept.tsMs <= 2 * (config.interleaveDepthMs + 2 * this.#blockLifetimeMs(config))
3741
+ ? kept
3742
+ : undefined
3743
+ let tsMs = anchor?.tsMs
3744
+ for (let ssId = (run.missing + 1) >>> 0; !serial32Precedes(newestSource, ssId); ssId = (ssId + 1) >>> 0) {
3745
+ const atMs = this.#lossyReceiptMs(locator.heldSource(ssId))
3746
+ if (atMs === undefined) continue
3747
+ if (tsMs === undefined || atMs < tsMs) tsMs = atMs
3748
+ break
3749
+ }
3750
+ if (tsMs === undefined) return undefined
3751
+ const waitMs = this.#multicastWaitMs(config)
3752
+ let counted = anchor?.counted === true
3753
+ if (!counted && tsMs + waitMs <= this.#receiptNow()) {
3754
+ counted = true
3755
+ this.onUndelimitedRunGap?.(packetId, catalogTrackName)
3756
+ }
3757
+ this.#runAnchors.set(streamKey, { fromSsId, tsMs, counted })
3758
+ return arrivedAtMs === undefined ? waitMs : Math.max(0, tsMs + waitMs - arrivedAtMs)
3759
+ }
3760
+ // SS_IDs past coverage that all arrived hold no loss, so they wait for no
3761
+ // repair to delimit them.
3762
+ if (!locator.coversBetween(fromSsId, run?.start ?? toSsId)) return undefined
3763
+ let repairless = false
3764
+ let stated = false
3765
+ for (const block of locator.blocksBetween(fromSsId, toSsId)) {
3766
+ const key = this.#blockKey(block.start, packetId, catalogTrackName)
3767
+ if (this.#completedBlocks.has(key)) continue
3768
+ if (block.span && block.length > locator.kMax) {
3769
+ repairless = true
3770
+ continue
3771
+ }
3772
+ const received = this.#blockSourceEsis.get(key)
3773
+ const rebuilt = this.#blockRebuiltEsis.get(key)
3774
+ let missesInGap = false
3775
+ let missesOutside = false
3776
+ // A rebuilt source is present outside the gap but missed inside it.
3777
+ // Outside, the question is what the block's decoder lacks beyond this
3778
+ // gap, and it holds a rebuilt source (#groupCannotComplete). Inside, it
3779
+ // is what the base path lost between the two frames. A base recovery
3780
+ // does not route a rebuilt packet again (MmtpRouter
3781
+ // #routeVerifiedFecSymbols), so only the overlay route delivers it, and
3782
+ // its frame may not have reached the gate yet (a head held for its FT=1,
3783
+ // BLO-53369). The two differ only when every SS_ID a block misses in the
3784
+ // gap was rebuilt: the later frame then waits for the gap's blocks to
3785
+ // resolve (undefined), which is conservative.
3786
+ for (let esi = 0; esi < block.length; esi++) {
3787
+ const ssId = serial32Add(block.start, esi)
3788
+ if (received?.has(esi) || locator.isHeld(ssId)) continue
3789
+ if (serial32Precedes(fromSsId, ssId) && serial32Precedes(ssId, toSsId)) missesInGap = true
3790
+ else if (!rebuilt?.has(esi)) missesOutside = true
3791
+ }
3792
+ if (!missesInGap) continue
3793
+ // A stated block its own group cannot complete (#lateSourceWaitMs) is
3794
+ // one too, when every SS_ID it misses lies in this gap: the gap's
3795
+ // decision then covers all it lost, so the overlay can rebuild none of
3796
+ // it unless `rapMayHide` or `rapNext`.
3797
+ if (missesOutside || block.span || !this.#groupCannotComplete(key)) return undefined
3798
+ repairless = stated = true
3799
+ }
3800
+ if (!repairless) return undefined
3801
+ // A gap into the next MPU (`rapNext`) may hold that MPU's FT=0, an overlay
3802
+ // member; rebuilt, it is one more source of a stated block, which its group
3803
+ // may then complete. Such a block keeps #741's overlay wait; a span longer
3804
+ // than K has no group to complete and keeps #742's allowance.
3805
+ const waitMs = rapMayHide || (stated && rapNext)
3806
+ ? this.#overlayLateWaitMs(packetId, catalogTrackName, config)
3807
+ : this.#multicastWaitMs(config) - config.interleaveDepthMs
3808
+ return waitMs === undefined ? undefined : Math.max(0, waitMs)
3809
+ }
3810
+
3403
3811
  /**
3404
3812
  * iso-ssbg1-v1 block location: repair symbols it refused, oversize sources,
3405
3813
  * the sources held now for a block no repair has stated yet, and the held
@@ -3470,11 +3878,46 @@ export class FECManager {
3470
3878
  /**
3471
3879
  * Whether an MPU boundary still bounds this stream's RAPs (see
3472
3880
  * `BlockClassifier.mpuBoundsRaps`). Gap decisions drop MPU evidence once
3473
- * it does not. A stream with no classifier yet has shown nothing against it.
3881
+ * it does not. A stream with no classifier yet has shown nothing against it,
3882
+ * and neither has a stream without catalog timing until it releases two
3883
+ * RAPs inside one MPU.
3884
+ *
3885
+ * With catalog timing and a `gap` inside one MPU, between the authored
3886
+ * timing of the frames on either side, it also takes the catalog keyframe
3887
+ * interval to rule a keyframe out of the gap
3888
+ * (`BlockClassifier.keyframeFreeBetween`, fec-multicast-00 Block
3889
+ * Classification item 3), and no source held between the frames' SS_IDs
3890
+ * may carry the RAP flag or another MPU's number (item 1 read on the held
3891
+ * packets: a RAP the loss cut in two is never released, so the frames
3892
+ * alone cannot show it); anything unknown counts as a keyframe.
3474
3893
  */
3475
- mpuBoundsRapsFor(packetId: number, catalogTrackName?: string): boolean {
3476
- if (!this.#hasCatalogTimingForPacket(packetId)) return false
3477
- return this.#classifiers.get(this.#streamKey(packetId, catalogTrackName))?.mpuBoundsRaps ?? true
3894
+ mpuBoundsRapsFor(
3895
+ packetId: number,
3896
+ catalogTrackName?: string,
3897
+ gap?: {
3898
+ readonly mpu: number
3899
+ readonly from?: AuthoredTiming
3900
+ readonly to?: AuthoredTiming
3901
+ readonly fromSsId?: number
3902
+ readonly toSsId?: number
3903
+ },
3904
+ ): boolean {
3905
+ const streamKey = this.#streamKey(packetId, catalogTrackName)
3906
+ if (!this.#hasCatalogTimingForPacket(packetId)) return this.#noSpanRaps.get(streamKey)?.inside !== true
3907
+ const classifier = this.#classifiers.get(streamKey)
3908
+ if (gap === undefined) return classifier?.mpuBoundsRaps ?? true
3909
+ const { mpu, from, to, fromSsId, toSsId } = gap
3910
+ if (fromSsId !== undefined && toSsId !== undefined) {
3911
+ const run = this.#isoLocators.get(streamKey)?.undelimitedBetween(
3912
+ fromSsId,
3913
+ toSsId,
3914
+ ({ evidence }) => evidence.rap || (evidence.mpu !== undefined && evidence.mpu !== mpu),
3915
+ )
3916
+ if (run?.flagged) return false
3917
+ }
3918
+ return classifier !== undefined && from !== undefined && to !== undefined &&
3919
+ from.mediaTimescale === to.mediaTimescale &&
3920
+ classifier.keyframeFreeBetween(mpu, from.decodeTime, to.decodeTime, from.mediaTimescale)
3478
3921
  }
3479
3922
 
3480
3923
  /** A block's class now, or frozen at its resolution. */
@@ -3501,7 +3944,9 @@ export class FECManager {
3501
3944
 
3502
3945
  /**
3503
3946
  * Record a RAP frame released in order, for the classifier's RAP-spacing
3504
- * invariant (consecutive MPUs exactly one keyframe interval apart).
3947
+ * invariant (consecutive MPUs exactly one keyframe interval apart) and,
3948
+ * with its decode time, as the MPU start gap decisions measure the catalog
3949
+ * keyframe interval from (mpuBoundsRapsFor).
3505
3950
  */
3506
3951
  noteReleasedRap(
3507
3952
  packetId: number,
@@ -3509,8 +3954,17 @@ export class FECManager {
3509
3954
  mpu: number,
3510
3955
  presentationTime: bigint,
3511
3956
  mediaTimescale: number,
3957
+ decodeTime?: bigint,
3512
3958
  ): void {
3513
- if (!this.#trackConfigs.has(packetId) || !this.#hasCatalogTimingForPacket(packetId)) return
3959
+ if (!this.#trackConfigs.has(packetId)) return
3960
+ if (!this.#hasCatalogTimingForPacket(packetId)) {
3961
+ const streamKey = this.#streamKey(packetId, catalogTrackName)
3962
+ const last = this.#noSpanRaps.get(streamKey)
3963
+ const inside = last?.inside === true ||
3964
+ (last?.mpu === mpu && last.presentationTime !== presentationTime)
3965
+ this.#noSpanRaps.set(streamKey, { mpu, presentationTime, inside })
3966
+ return
3967
+ }
3514
3968
  this.#applyClassifierChanges(
3515
3969
  packetId,
3516
3970
  catalogTrackName,
@@ -3518,6 +3972,7 @@ export class FECManager {
3518
3972
  mpu,
3519
3973
  presentationTime,
3520
3974
  mediaTimescale,
3975
+ decodeTime,
3521
3976
  ),
3522
3977
  )
3523
3978
  }
@@ -3820,13 +4275,27 @@ export class FECManager {
3820
4275
 
3821
4276
  client.onCleanupComplete((sbn: number) => {
3822
4277
  if (this.#releasedWorkerClients.has(client)) return
3823
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
4278
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client)
4279
+ const cleanupKeys = owed.filter((key) => {
3824
4280
  const block = this.#parseBlockKey(key)
3825
- return block.packetId === packetId &&
3826
- block.sbn === sbn &&
3827
- this.#pendingWorkerCleanupClients.get(key) === client
4281
+ return block.packetId === packetId && block.sbn === sbn
3828
4282
  })
3829
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, 'cleanup-ack')
4283
+ // A cleanup is a queue-drain barrier: the Worker took every symbol fed
4284
+ // before it was asked for first, so every block already due by then
4285
+ // is settled by this acknowledgement too, not one barrier later. The
4286
+ // client sends one barrier at a time, and the blocks a repair walk
4287
+ // stated in one span are due together (BLO-52085). That holds only
4288
+ // while no block is fed a symbol after its dueAtMs, which is its
4289
+ // receipt-scoped deadline, not when feeding stopped: a symbol fed
4290
+ // between that deadline and the block's timer, after another block's
4291
+ // barrier was asked for, would find the block settled (failed) one
4292
+ // barrier early. Walks end before D-28 (walkDeadlineAt), so that window
4293
+ // is the timer's lateness alone; whatever feeds a block past its dueAtMs
4294
+ // must leave it to its own barrier.
4295
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity))
4296
+ const due = owed.filter((key) =>
4297
+ !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs)
4298
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, 'cleanup-ack')
3830
4299
  })
3831
4300
 
3832
4301
  client.onError((msg: string, code?: FecWorkerErrorCode) => {
@@ -3908,9 +4377,11 @@ export class FECManager {
3908
4377
  * fail deadline already passed, so failing it is the decision that deadline
3909
4378
  * made. A late ack then finds nothing owed and is a no-op.
3910
4379
  */
3911
- #boundOwedCleanup(key: string, packetId: number, client: FecWorkerClient): void {
4380
+ #boundOwedCleanup(key: string, packetId: number, client: FecWorkerClient, dueAtMs: number): void {
3912
4381
  this.#clearOwedCleanupBound(key)
3913
4382
  const bound = {
4383
+ dueAtMs,
4384
+ askedAtMs: performance.now(),
3914
4385
  handle: setTimeout(() => {
3915
4386
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return
3916
4387
  this.#pendingWorkerCleanupBounds.delete(key)
@@ -4041,7 +4512,22 @@ export class FECManager {
4041
4512
  this.#isoSourceOversizeCount++
4042
4513
  return null
4043
4514
  }
4044
- const sbn = located.block.start
4515
+ return this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, located.block.start)
4516
+ }
4517
+
4518
+ /**
4519
+ * Hand one placed source symbol to the stream's decoder: its Worker, which
4520
+ * answers through onFrame (null here), or its synchronous decoder, whose
4521
+ * recovered block is returned. `sbn` is the SS_Start of the block a repair
4522
+ * stated for `ssId`.
4523
+ */
4524
+ #feedDecoderSource(
4525
+ packetId: number,
4526
+ ssId: number,
4527
+ symbolData: Uint8Array,
4528
+ catalogTrackName: string | undefined,
4529
+ sbn: number,
4530
+ ): Uint8Array | null {
4045
4531
  const blockKey = this.#blockKey(sbn, packetId, catalogTrackName)
4046
4532
  const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey)
4047
4533
 
@@ -4086,6 +4572,97 @@ export class FECManager {
4086
4572
  return recovered
4087
4573
  }
4088
4574
 
4575
+ /**
4576
+ * Feed a source symbol of this stream that another FEC instance over the
4577
+ * same packets rebuilt: a keyframe overlay recovery whose base SS_ID the
4578
+ * caller determined (draft-ramadan-moq-mmt-02 7.1, 7.4.4; joint decoding,
4579
+ * BLO-52085). It joins its block's decoder as a received source would, so
4580
+ * it reduces the erasures the block still has to solve, but it is not a
4581
+ * network arrival: no transport accounting, no classification evidence,
4582
+ * no deadline refresh, and it never makes a block clean.
4583
+ *
4584
+ * Only a block a repair stated takes one (a repair-less span has no
4585
+ * decoder block). A block that is terminal, or already holds that source,
4586
+ * does not. The symbol is the exact protected packet, unpadded, as
4587
+ * feedSourceSymbol takes it.
4588
+ *
4589
+ * `recovered` is the block the synchronous decoder completed with it; the
4590
+ * caller routes it and completes the block, as for any recovery. When
4591
+ * every source of the block is then present, received or rebuilt, and no
4592
+ * decoder returned it (a Worker answers asynchronously, and reports such a
4593
+ * block as clean on its own side), the block is completed here as
4594
+ * recovered, with nothing left to route.
4595
+ */
4596
+ feedRebuiltSourceSymbol(
4597
+ packetId: number,
4598
+ ssId: number,
4599
+ symbolData: Uint8Array,
4600
+ catalogTrackName?: string,
4601
+ ): RebuiltSourceFeed {
4602
+ if (!this.#hasBlockProfile(packetId)) return NOT_TAKEN
4603
+ const located = this.#isoLocatorFor(packetId, catalogTrackName).locate(ssId)
4604
+ if (located === null || located.block.span) return NOT_TAKEN
4605
+ if (!ssbg1FitsSymbol(symbolData.byteLength, this.#trackConfig(packetId).symbolSize)) return NOT_TAKEN
4606
+ const sbn = located.block.start
4607
+ const key = this.#blockKey(sbn, packetId, catalogTrackName)
4608
+ if (this.#completedBlocks.has(key) || this.#blockSourceEsis.get(key)?.has(located.esi)) return NOT_TAKEN
4609
+ let rebuilt = this.#blockRebuiltEsis.get(key)
4610
+ if (rebuilt?.has(located.esi)) return NOT_TAKEN
4611
+ if (rebuilt === undefined) {
4612
+ rebuilt = new Set()
4613
+ this.#blockRebuiltEsis.set(key, rebuilt)
4614
+ }
4615
+ const config = this.#trackConfigs.get(packetId)
4616
+ const wasShort = config !== undefined &&
4617
+ this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) !== undefined
4618
+ rebuilt.add(located.esi)
4619
+ const recovered = this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn)
4620
+ if (recovered === null && !this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName)) {
4621
+ // The late-source cut assumed only a late source could complete this
4622
+ // block; with this source its group can, so it gets a full multicast
4623
+ // wait again, counted from now.
4624
+ // ponytail: from now, not from its sources, so it can close up to one
4625
+ // multicast wait after its uncut deadline; at most once per block, since
4626
+ // a rebuilt source only adds to what the block holds and the cut cannot
4627
+ // apply to it again. Keep the uncut deadline and re-arm to it if a lab
4628
+ // run shows that wait.
4629
+ if (wasShort && this.#activeBlocks.has(key) &&
4630
+ this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config!) === undefined) {
4631
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, this.#multicastWaitMs(config!))
4632
+ }
4633
+ }
4634
+ return { taken: true, recovered }
4635
+ }
4636
+
4637
+ /**
4638
+ * A block that holds every one of its `length` sources, received or
4639
+ * rebuilt by another instance, with at least one rebuilt, is recovered:
4640
+ * every packet of it was delivered, by its own arrival or by the instance
4641
+ * that rebuilt it, so nothing is routed. Returns whether it completed it.
4642
+ */
4643
+ #completeWhenSourcesPresent(
4644
+ key: string,
4645
+ sbn: number,
4646
+ length: number,
4647
+ packetId: number,
4648
+ catalogTrackName: string | undefined,
4649
+ ): boolean {
4650
+ const rebuilt = this.#blockRebuiltEsis.get(key)
4651
+ if (rebuilt === undefined || this.#completedBlocks.has(key)) return false
4652
+ let present = rebuilt.size
4653
+ for (const esi of this.#blockSourceEsis.get(key) ?? []) if (!rebuilt.has(esi)) present++
4654
+ if (present < length) return false
4655
+ this.#traceLifecycle('recovered', sbn, packetId, catalogTrackName)
4656
+ this.countRecovery(packetId, sbn, catalogTrackName)
4657
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName)
4658
+ if (catalogTrackName === undefined) {
4659
+ this.onBlockComplete?.(sbn, packetId)
4660
+ } else {
4661
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName)
4662
+ }
4663
+ return true
4664
+ }
4665
+
4089
4666
  /**
4090
4667
  * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
4091
4668
  * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
@@ -4166,7 +4743,10 @@ export class FECManager {
4166
4743
  this.#layerAnchorHorizon(packetId),
4167
4744
  this.#sourceFrontiers.get(streamKey)?.sbn,
4168
4745
  )
4169
- if (verdict === 'discard') return false
4746
+ if (verdict === 'discard') {
4747
+ this.#unlistedRepairTrackRefusals++
4748
+ return false
4749
+ }
4170
4750
  if (verdict !== undefined) {
4171
4751
  this.#failClosed(streamKey, verdict, packetId, catalogTrackName)
4172
4752
  return false
@@ -4343,9 +4923,150 @@ export class FECManager {
4343
4923
  this.#completeCleanBlock(blockKey, sbn, packetId, catalogTrackName)
4344
4924
  return null
4345
4925
  }
4926
+ // Its K' is known now: a block this repair shows short of it waits less.
4927
+ if (recovered === null) this.#shortenUnrecoverableWait(blockKey, sbn, packetId, catalogTrackName)
4346
4928
  return recovered
4347
4929
  }
4348
4930
 
4931
+ /**
4932
+ * A first-arrival multicast source, held or placed. A datagram flow keeps
4933
+ * its sources in send order, so one that moves the stream's newest source
4934
+ * position past a block leaves the sources that block still misses
4935
+ * reordered behind it at best: it shortens the wait of every block it
4936
+ * passed that only a late source can complete. MoQ is left out: its streams
4937
+ * can overtake one another, so a MoQ source shows nothing about the sources
4938
+ * sent before it.
4939
+ */
4940
+ #noteMulticastSource(
4941
+ locator: IsoBlockLocator<IsoHeldSource>,
4942
+ ssId: number,
4943
+ packetId: number,
4944
+ catalogTrackName: string | undefined,
4945
+ ): void {
4946
+ const previous = locator.newestSource
4947
+ if (!locator.noteSource(ssId) || previous === undefined) return
4948
+ // The blocks whose last SS_ID lies in [previous, ssId): this source
4949
+ // passed them and the previous newest one had not.
4950
+ for (const block of locator.blocksBetween((previous - 1) >>> 0, ssId)) {
4951
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue
4952
+ this.#shortenUnrecoverableWait(
4953
+ this.#blockKey(block.start, packetId, catalogTrackName),
4954
+ block.start,
4955
+ packetId,
4956
+ catalogTrackName,
4957
+ )
4958
+ }
4959
+ }
4960
+
4961
+ /**
4962
+ * The wait of a block that only a late source can complete (BLO-52085): a
4963
+ * repair stated it, its received sources plus every symbol its repair group
4964
+ * carries (RSB_length) are short of K' (the repair scheduler's
4965
+ * group-cannot-complete), and a later source of the stream has arrived, so
4966
+ * a source it misses is lost or reordered behind that one. The span, which
4967
+ * covers repair symbols paced after its sources, buys it nothing: it waits
4968
+ * the late-symbol allowance alone, the multicast wait less the span (the
4969
+ * catalog tolerance or the measured delivery gap). Undefined for any other
4970
+ * block. While a keyframe overlay is installed, the block waits for its
4971
+ * repair too (#overlayLateWaitMs). A repair-less span keeps its whole
4972
+ * wait, even one longer than K whose group is empty (#openIsoSpan): its
4973
+ * resolution is what releases the frames behind it, and failing it early
4974
+ * released them past a keyframe the overlay was still rebuilding, which
4975
+ * then arrived stale. The release gate lets them go instead
4976
+ * (isoRepairlessWaitMs).
4977
+ */
4978
+ #lateSourceWaitMs(
4979
+ key: string,
4980
+ sbn: number,
4981
+ packetId: number,
4982
+ catalogTrackName: string | undefined,
4983
+ config: ResolvedFECTrackConfig,
4984
+ ): number | undefined {
4985
+ if (this.#isoSpanKeys.has(key) || !this.#groupCannotComplete(key)) return undefined
4986
+ const authoredLength = this.#blockAuthoredLengths.get(key)!
4987
+ const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource
4988
+ if (newestSource === undefined || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
4989
+ return undefined
4990
+ }
4991
+ return this.#overlayLateWaitMs(packetId, catalogTrackName, config)
4992
+ }
4993
+
4994
+ /**
4995
+ * A repair stated the block, and its sources plus every symbol its repair
4996
+ * group carries (RSB_length) are short of its SSB_length.
4997
+ */
4998
+ #groupCannotComplete(key: string): boolean {
4999
+ const authoredLength = this.#blockAuthoredLengths.get(key)
5000
+ const rsbLength = this.#blockRsbLengths.get(key)
5001
+ if (authoredLength === undefined || rsbLength === undefined) return false
5002
+ // A source another instance rebuilt (feedRebuiltSourceSymbol) is one the
5003
+ // decoder holds: the group need only cover what neither delivered.
5004
+ let present = this.#blockSourceCounts.get(key) ?? 0
5005
+ const received = this.#blockSourceEsis.get(key)
5006
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++
5007
+ return present + rsbLength < authoredLength
5008
+ }
5009
+
5010
+ /**
5011
+ * How long a loss only a late source or an installed keyframe overlay can
5012
+ * still fill waits once a later source passed it: the late-symbol
5013
+ * allowance alone (the multicast wait less the span) while no overlay is
5014
+ * installed. An installed one (keyframeOverlayTiming) may still rebuild a
5015
+ * RAP packet the loss took: a second FEC instance over the same packets
5016
+ * (draft-ramadan-moq-mmt-02 7.4), whose repair is paced across its own
5017
+ * span, unrelated to the base's. That packet can complete a stated block
5018
+ * (feedRebuiltSourceSymbol), or play behind a span; giving the loss up
5019
+ * first lets the release gate pass the keyframe, whose rebuild then lands
5020
+ * stale. The overlay repair of a packet the loss took goes out within the
5021
+ * overlay's span of that packet (fec-core-00 9.3), and the later source was
5022
+ * sent after it, so the loss waits that span plus the larger of the
5023
+ * allowance and the overlay's own tolerance. An overlay that states no
5024
+ * span (its block may then span keyframes), or one whose wait is not
5025
+ * shorter than the whole multicast wait, leaves the whole wait: undefined.
5026
+ */
5027
+ #overlayLateWaitMs(
5028
+ packetId: number,
5029
+ catalogTrackName: string | undefined,
5030
+ config: ResolvedFECTrackConfig,
5031
+ ): number | undefined {
5032
+ const waitMs = this.#multicastWaitMs(config)
5033
+ const allowanceMs = waitMs - config.interleaveDepthMs
5034
+ // Read live. The late-source cut only ever shortens a block's deadline
5035
+ // (#shortenUnrecoverableWait), so a block it armed at the bare allowance
5036
+ // before an overlay was installed, or between a dispose and a reinstall,
5037
+ // keeps that deadline until a source of its own re-arms it.
5038
+ const overlay = this.keyframeOverlayTiming?.(packetId, catalogTrackName)
5039
+ if (overlay === undefined) return allowanceMs
5040
+ const overlaySpanMs = overlay.interleaveDepthMs ?? 0
5041
+ const overlayWaitMs = overlaySpanMs + Math.max(allowanceMs, overlay.reorderToleranceMs ?? 0)
5042
+ return overlaySpanMs > 0 && overlayWaitMs < waitMs ? overlayWaitMs : undefined
5043
+ }
5044
+
5045
+ /**
5046
+ * Bring an open block's wait in to its late-source wait, when it has one.
5047
+ * Never later than it is armed: only a source can complete such a block,
5048
+ * so a repair of its group (paced across the span) must not keep it open.
5049
+ */
5050
+ #shortenUnrecoverableWait(
5051
+ key: string,
5052
+ sbn: number,
5053
+ packetId: number,
5054
+ catalogTrackName: string | undefined,
5055
+ ): void {
5056
+ if (!this.#activeBlocks.has(key)) return
5057
+ const config = this.#trackConfigs.get(packetId)
5058
+ if (config === undefined) return
5059
+ const waitMs = this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config)
5060
+ if (waitMs === undefined) return
5061
+ const armedAtMs = this.#blockWaitDeadlinesMs.get(key)
5062
+ this.#armBlockTimeout(
5063
+ sbn,
5064
+ packetId,
5065
+ catalogTrackName,
5066
+ armedAtMs === undefined ? waitMs : Math.min(waitMs, armedAtMs - this.#receiptNow()),
5067
+ )
5068
+ }
5069
+
4349
5070
  /**
4350
5071
  * Record a block's authored SSB_length from a repair symbol. Returns false,
4351
5072
  * leaving the block unchanged, when the symbol contradicts the block: a
@@ -4485,7 +5206,8 @@ export class FECManager {
4485
5206
  * the inactivity deadline on each symbol, records the symbol's in-band
4486
5207
  * classification evidence, and marks the block clean when all of its
4487
5208
  * authored source symbols arrived: the SSB_length a repair symbol declared,
4488
- * otherwise K.
5209
+ * otherwise K. `held` marks a source held unplaced since it arrived and
5210
+ * placed only now (see #noteSbnSeen).
4489
5211
  *
4490
5212
  * Throws for a packetId that was never configured, so a classified block
4491
5213
  * never reads the manager-global K or timeout.
@@ -4496,6 +5218,7 @@ export class FECManager {
4496
5218
  catalogTrackName: string | undefined,
4497
5219
  esi: number,
4498
5220
  evidence: SourceSymbolEvidence,
5221
+ held = false,
4499
5222
  ): void {
4500
5223
  const trackConfig = this.#trackConfigs.get(packetId)
4501
5224
  if (trackConfig === undefined) {
@@ -4517,6 +5240,7 @@ export class FECManager {
4517
5240
  'source',
4518
5241
  evidence.packetSequenceNumber,
4519
5242
  Number.isInteger(esi) ? (sbn + esi) >>> 0 : sbn,
5243
+ held,
4520
5244
  )
4521
5245
 
4522
5246
  // A source ESI at or past the block's authored SSB_length contradicts it;
@@ -4561,6 +5285,20 @@ export class FECManager {
4561
5285
  this.#completeCleanBlock(key, sbn, packetId, catalogTrackName)
4562
5286
  return
4563
5287
  }
5288
+ // A late arrival can be the last source a block lacked besides those
5289
+ // another instance rebuilt (feedRebuiltSourceSymbol).
5290
+ if (
5291
+ this.#blockRebuiltEsis.has(key) &&
5292
+ this.#completeWhenSourcesPresent(
5293
+ key,
5294
+ sbn,
5295
+ this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? authoredLength,
5296
+ packetId,
5297
+ catalogTrackName,
5298
+ )
5299
+ ) {
5300
+ return
5301
+ }
4564
5302
 
4565
5303
  this.noteBlockActivity(sbn, packetId, catalogTrackName, true)
4566
5304
 
@@ -4580,7 +5318,9 @@ export class FECManager {
4580
5318
  this.cancelBlockTimeout(sbn, packetId, catalogTrackName)
4581
5319
  this.#blockSourceCounts.delete(key)
4582
5320
  this.#blockSourceEsis.delete(key)
5321
+ this.#blockRebuiltEsis.delete(key)
4583
5322
  this.#blockAuthoredLengths.delete(key)
5323
+ this.#isoSpanKeys.delete(key)
4584
5324
  this.#blockRepairRsIds.delete(key)
4585
5325
  this.#blockRsbLengths.delete(key)
4586
5326
  // BLO-3323 L15: track which SBNs reached K source-symbol arrivals so the
@@ -4622,6 +5362,20 @@ export class FECManager {
4622
5362
  return this.#receiptAtMs ?? performance.now()
4623
5363
  }
4624
5364
 
5365
+ /**
5366
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
5367
+ * scope: counted from the receipt time, as the timer of a symbol fed when
5368
+ * it was received was, less the whole ms since. So it fires on the tick
5369
+ * that timer would have, never later than a delay counted from now, and
5370
+ * its handler still re-arms a timer that fires before its deadline.
5371
+ * Counted from now, a deadline set from the receipt time is rounded up
5372
+ * from another fraction of a ms (BLO-52085).
5373
+ */
5374
+ #receiptTimerDelayMs(deadlineMs: number, minMs: number): number {
5375
+ const receivedAtMs = this.#receiptAtMs!
5376
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs))
5377
+ }
5378
+
4625
5379
  /**
4626
5380
  * A held packet admitted late arms from its (earlier) receipt time; that
4627
5381
  * never pulls in a deadline later activity already armed. Outside a
@@ -4693,7 +5447,18 @@ export class FECManager {
4693
5447
  )
4694
5448
  }
4695
5449
 
4696
- this.#armBlockTimeout(sbn, packetId, catalogTrackName, timeoutMs)
5450
+ // A block only a late source can complete waits the late-symbol
5451
+ // allowance from its own sources' activity; nothing else moves it later.
5452
+ if (!sourceProgress && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) !== undefined) {
5453
+ this.#shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName)
5454
+ return
5455
+ }
5456
+ this.#armBlockTimeout(
5457
+ sbn,
5458
+ packetId,
5459
+ catalogTrackName,
5460
+ this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) ?? timeoutMs,
5461
+ )
4697
5462
  }
4698
5463
 
4699
5464
  #failBlock(
@@ -4702,6 +5467,9 @@ export class FECManager {
4702
5467
  catalogTrackName?: string,
4703
5468
  ): void {
4704
5469
  const key = this.#blockKey(sbn, packetId, catalogTrackName)
5470
+ const span: IsoSpanFailure | undefined = this.#isoSpanKeys.delete(key)
5471
+ ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 }
5472
+ : undefined
4705
5473
  this.#traceLifecycle('failed', sbn, packetId, catalogTrackName)
4706
5474
  this.#clearRepairDeadline(key)
4707
5475
  this.#clearBlockTimer(key)
@@ -4711,6 +5479,7 @@ export class FECManager {
4711
5479
  }
4712
5480
  this.#blockSourceCounts.delete(key)
4713
5481
  this.#blockSourceEsis.delete(key)
5482
+ this.#blockRebuiltEsis.delete(key)
4714
5483
  this.#blockAuthoredLengths.delete(key)
4715
5484
  this.#blockRepairRsIds.delete(key)
4716
5485
  this.#blockRsbLengths.delete(key)
@@ -4720,7 +5489,8 @@ export class FECManager {
4720
5489
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName)
4721
5490
  this.#fecStats.blocksFailed++
4722
5491
  this.#statsForPacket(packetId).blocksFailed++
4723
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass)
5492
+ if (span === undefined) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass)
5493
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span)
4724
5494
  this.onBlockResolved?.(sbn, packetId, catalogTrackName)
4725
5495
  }
4726
5496
 
@@ -4750,7 +5520,9 @@ export class FECManager {
4750
5520
  this.#retireBlockClass(key, block.sbn, block.packetId, block.catalogTrackName)
4751
5521
  this.#blockSourceCounts.delete(key)
4752
5522
  this.#blockSourceEsis.delete(key)
5523
+ this.#blockRebuiltEsis.delete(key)
4753
5524
  this.#blockAuthoredLengths.delete(key)
5525
+ this.#isoSpanKeys.delete(key)
4754
5526
  this.#blockRepairRsIds.delete(key)
4755
5527
  this.#blockRsbLengths.delete(key)
4756
5528
  this.#clearBlockTimer(key)
@@ -4858,7 +5630,9 @@ export class FECManager {
4858
5630
  this.#blockKeysBySbn.clear()
4859
5631
  this.#blockSourceCounts.clear()
4860
5632
  this.#blockSourceEsis.clear()
5633
+ this.#blockRebuiltEsis.clear()
4861
5634
  this.#blockAuthoredLengths.clear()
5635
+ this.#isoSpanKeys.clear()
4862
5636
  this.#blockRepairRsIds.clear()
4863
5637
  this.#blockRsbLengths.clear()
4864
5638
  this.#heldLayerStates.clear()
@@ -4883,6 +5657,7 @@ export class FECManager {
4883
5657
  this.#blockAnchorsMs.clear()
4884
5658
  this.#blockCatalogTrackNames.clear()
4885
5659
  this.#classifiers.clear()
5660
+ this.#noSpanRaps.clear()
4886
5661
  this.#streamGeometries.clear()
4887
5662
  this.#failedBlocks.clear()
4888
5663
  this.#resolvedBlockClasses.clear()
@@ -4891,6 +5666,7 @@ export class FECManager {
4891
5666
  this.#highestSbn.clear()
4892
5667
  this.#sourceFrontiers.clear()
4893
5668
  this.#isoLocators.clear()
5669
+ this.#runAnchors.clear()
4894
5670
  this.#sourceAnchors.clear()
4895
5671
  this.#trackConfigs.clear()
4896
5672
  this.#fecDecoders.clear()