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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +5 -2
  2. package/dist/block-policy.d.ts +88 -16
  3. package/dist/block-policy.d.ts.map +1 -1
  4. package/dist/block-policy.js +164 -56
  5. package/dist/block-policy.js.map +3 -3
  6. package/dist/browser-runtime.js +1284 -174
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +40 -1
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +163 -10
  11. package/dist/carp-catalog.js.map +4 -4
  12. package/dist/catalog-fec-params.d.ts +1 -1
  13. package/dist/catalog-fec-params.d.ts.map +1 -1
  14. package/dist/catalog-fec-params.js +48 -1
  15. package/dist/catalog-fec-params.js.map +3 -3
  16. package/dist/catalog-network-source.js +34 -0
  17. package/dist/catalog-network-source.js.map +3 -3
  18. package/dist/cmaf-block-assembler.js +92 -1
  19. package/dist/cmaf-block-assembler.js.map +2 -2
  20. package/dist/codec-utils.d.ts.map +1 -1
  21. package/dist/codec-utils.js +92 -1
  22. package/dist/codec-utils.js.map +2 -2
  23. package/dist/delivery-catalog.js +68 -0
  24. package/dist/delivery-catalog.js.map +4 -4
  25. package/dist/delta-fallback-config.js +39 -1
  26. package/dist/delta-fallback-config.js.map +4 -4
  27. package/dist/fec-manager.d.ts +155 -10
  28. package/dist/fec-manager.d.ts.map +1 -1
  29. package/dist/fec-manager.js +596 -81
  30. package/dist/fec-manager.js.map +4 -4
  31. package/dist/fec-state.d.ts +17 -5
  32. package/dist/fec-state.d.ts.map +1 -1
  33. package/dist/fec-state.js +41 -1
  34. package/dist/fec-state.js.map +3 -3
  35. package/dist/fec-worker-setup.js +34 -0
  36. package/dist/fec-worker-setup.js.map +3 -3
  37. package/dist/held-layer-admission.js +34 -0
  38. package/dist/held-layer-admission.js.map +3 -3
  39. package/dist/index.d.ts +6 -5
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +9 -1
  42. package/dist/index.js.map +2 -2
  43. package/dist/iso-block-locator.d.ts +16 -0
  44. package/dist/iso-block-locator.d.ts.map +1 -1
  45. package/dist/iso-block-locator.js +62 -0
  46. package/dist/iso-block-locator.js.map +3 -3
  47. package/dist/mfu-reassembler.js +34 -0
  48. package/dist/mfu-reassembler.js.map +3 -3
  49. package/dist/mmtp-container-parser.d.ts +30 -2
  50. package/dist/mmtp-container-parser.d.ts.map +1 -1
  51. package/dist/mmtp-container-parser.js +140 -2
  52. package/dist/mmtp-container-parser.js.map +3 -3
  53. package/dist/mmtp-container-parser.no-modules.js +293 -18
  54. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  55. package/dist/mmtp-decode-pipeline.js +140 -2
  56. package/dist/mmtp-decode-pipeline.js.map +3 -3
  57. package/dist/mmtp-fec-session.js +34 -0
  58. package/dist/mmtp-fec-session.js.map +3 -3
  59. package/dist/mmtp-mode-selection.d.ts +48 -0
  60. package/dist/mmtp-mode-selection.d.ts.map +1 -0
  61. package/dist/mmtp-mode-selection.js +79 -0
  62. package/dist/mmtp-mode-selection.js.map +7 -0
  63. package/dist/mmtp-router.d.ts +66 -8
  64. package/dist/mmtp-router.d.ts.map +1 -1
  65. package/dist/mmtp-router.js +348 -27
  66. package/dist/mmtp-router.js.map +4 -4
  67. package/dist/multicast-auth-catalog.js +42 -2
  68. package/dist/multicast-auth-catalog.js.map +3 -3
  69. package/dist/multicast-input.js +42 -2
  70. package/dist/multicast-input.js.map +3 -3
  71. package/dist/multicast-manager.d.ts +108 -1
  72. package/dist/multicast-manager.d.ts.map +1 -1
  73. package/dist/multicast-manager.js +1067 -138
  74. package/dist/multicast-manager.js.map +4 -4
  75. package/dist/multicast-transport.js +68 -0
  76. package/dist/multicast-transport.js.map +4 -4
  77. package/dist/multicast-unwrap.js +34 -0
  78. package/dist/multicast-unwrap.js.map +3 -3
  79. package/dist/no-modules.d.ts +1 -0
  80. package/dist/no-modules.d.ts.map +1 -1
  81. package/dist/no-modules.js +295 -19
  82. package/dist/no-modules.js.map +4 -4
  83. package/dist/phase14-catalog-override.d.ts +2 -1
  84. package/dist/phase14-catalog-override.d.ts.map +1 -1
  85. package/dist/phase14-catalog-override.js +69 -2
  86. package/dist/phase14-catalog-override.js.map +3 -3
  87. package/dist/repair-fetch.d.ts +2 -0
  88. package/dist/repair-fetch.d.ts.map +1 -1
  89. package/dist/repair-fetch.js +52 -2
  90. package/dist/repair-fetch.js.map +3 -3
  91. package/dist/repair-layer-subscriptions.js +34 -0
  92. package/dist/repair-layer-subscriptions.js.map +3 -3
  93. package/dist/signaling.js +34 -0
  94. package/dist/signaling.js.map +3 -3
  95. package/dist/timestamp-codec.js +34 -0
  96. package/dist/timestamp-codec.js.map +3 -3
  97. package/dist/wasm-mfu-reassembler.js +34 -0
  98. package/dist/wasm-mfu-reassembler.js.map +3 -3
  99. package/dist/wasm-mmtp-container-parser.js +140 -2
  100. package/dist/wasm-mmtp-container-parser.js.map +3 -3
  101. package/package.json +5 -5
  102. package/schemas/catalog.schema.json +2 -2
  103. package/src/block-policy.ts +324 -83
  104. package/src/carp-catalog.ts +165 -5
  105. package/src/catalog-fec-params.ts +1 -0
  106. package/src/codec-utils.ts +121 -1
  107. package/src/fec-manager.ts +534 -41
  108. package/src/fec-state.ts +21 -5
  109. package/src/index.ts +23 -0
  110. package/src/iso-block-locator.ts +34 -0
  111. package/src/mmtp-container-parser.ts +57 -11
  112. package/src/mmtp-mode-selection.ts +80 -0
  113. package/src/mmtp-router.ts +287 -42
  114. package/src/multicast-manager.ts +218 -10
  115. package/src/no-modules.ts +3 -0
  116. package/src/phase14-catalog-override.ts +14 -3
  117. package/src/repair-fetch.ts +27 -2
  118. package/test-vectors/catalog/README.md +36 -2
  119. package/test-vectors/catalog/mmtp-siblings/ambiguous-sibling.json +158 -0
  120. package/test-vectors/catalog/mmtp-siblings/ladder-bitrate-only.json +231 -0
  121. package/test-vectors/catalog/mmtp-siblings/ladder-four-rungs.json +405 -0
  122. package/test-vectors/catalog/mmtp-siblings/ladder-other-names.json +231 -0
  123. package/test-vectors/catalog/mmtp-siblings/mmtp-mode-unknown.json +143 -0
  124. package/test-vectors/catalog/mmtp-siblings/multicast-endpoint-lists-datagram-track.json +143 -0
  125. package/test-vectors/catalog/mmtp-siblings/no-sibling.json +79 -0
  126. package/test-vectors/catalog/mmtp-siblings/rendition-mismatch.json +143 -0
  127. package/test-vectors/catalog/mmtp-siblings/stream-delivery-mode.json +143 -0
  128. package/test-vectors/catalog/mmtp-siblings/timescale-mismatch.json +143 -0
  129. package/test-vectors/catalog/mmtp-siblings/valid-pair.json +142 -0
  130. package/test-vectors/catalog/section-codes.json +3 -3
  131. package/test-vectors/catalog-validation.json +266 -7
  132. package/test-vectors/moq/mmtp-mode-selection.json +259 -0
@@ -27,6 +27,7 @@ import {
27
27
  serial32Precedes,
28
28
  ssbg1FitsSymbol,
29
29
  type FecBlockProfile,
30
+ type FecInstanceGeometry,
30
31
  admitMmtpRepairObject,
31
32
  parseMoqRepairFrameWithHeader,
32
33
  type MMTPHeader,
@@ -54,6 +55,7 @@ import {
54
55
 
55
56
  import { HeldLayerAdmission, heldLayerAnchorHorizon, type FecFailClosedReason } from './held-layer-admission.js'
56
57
  import type { MmtpDeliveryProvenance } from './mfu-reassembler.js'
58
+ import type { AuthoredTiming } from './authored-timing.js'
57
59
  import type {
58
60
  FecWorkerClient,
59
61
  FecTrackStats,
@@ -137,6 +139,20 @@ export interface FecStats {
137
139
  workers: Array<FecTrackStats & { packetId: number }>
138
140
  /** Main-thread repair symbols rejected before dispatch because their size did not match T. */
139
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
148
+ /**
149
+ * Repair packets the router dropped before any FEC instance saw them,
150
+ * because it could not name the track they repair (BLO-55759): the physical
151
+ * PID is not in the catalog (`unregistered`), or no endpoint on this ingress
152
+ * holds its catalog owner (`ownerAbsent`) or more than one does
153
+ * (`ownerAmbiguous`). Cumulative.
154
+ */
155
+ unresolvedRepairOwnerDrops: UnresolvedRepairOwnerDrops
140
156
  /**
141
157
  * Repair objects discarded on admission (draft-ramadan-moq-fec-core-00 7.5,
142
158
  * draft-ramadan-moq-mmt-02 7.3), per FEC instance and reason. The instance
@@ -147,6 +163,10 @@ export interface FecStats {
147
163
  workerErrors: Record<string, number>
148
164
  }
149
165
 
166
+ /** Why the router could not name a repair packet's owning track. */
167
+ export type UnresolvedRepairOwnerReason = 'unregistered' | 'ownerAbsent' | 'ownerAmbiguous'
168
+ export type UnresolvedRepairOwnerDrops = Record<UnresolvedRepairOwnerReason, number>
169
+
150
170
  /** One FEC instance's repair-object admission discards, by reason. */
151
171
  export type FecRepairObjectRejects = {
152
172
  packetId: number
@@ -168,7 +188,22 @@ export interface FecPacketStats {
168
188
  packetLossRate: number
169
189
  }
170
190
 
171
- export type FecSymbolSource = 'multicast' | 'moq'
191
+ /**
192
+ * The transport a symbol arrived on: a multicast/AMT leg, a reliable MoQ
193
+ * subscription (unicast fallback or an overlap copy), or an "mfu-datagram"
194
+ * subscription (mmt-02 4.3.1), which is a lossy unicast leg. The loss rules
195
+ * ask one of two questions of it, and the answers differ on an ordered
196
+ * relay. Is the symbol in the publisher's own send order: `source !== 'moq'`
197
+ * (late-source shortening, startup partial blocks). Did it reach this
198
+ * manager as a datagram of its own, on a path that loses and reorders:
199
+ * FECManager #lossyDatagramPath (the late-source allowance of a loss-free
200
+ * range, the FEC deadline of a run no repair delimited, the delivery-gap
201
+ * sample). Only the ordered-relay frontier is multicast's.
202
+ */
203
+ export type FecSymbolSource = 'multicast' | 'moq' | 'moq-datagram'
204
+
205
+ /** The lossy paths the delivery-gap estimator samples, each with its own window. */
206
+ export type DeliveryGapPath = 'multicast' | 'moq-datagram'
172
207
 
173
208
  /**
174
209
  * What feedRebuiltSourceSymbol did with a rebuilt source: whether its block
@@ -192,6 +227,13 @@ export interface IsoHeldSource {
192
227
  readonly evidence: SourceSymbolEvidence
193
228
  /** Larger than one ssbg_mode1 symbol: counted, never decoded. */
194
229
  readonly oversized: boolean
230
+ /**
231
+ * Receipt time (performance.now() clock; holdIsoSource stamps it when
232
+ * absent): a run's FEC deadline is anchored at it (isoRepairlessWaitMs),
233
+ * and a loss-free range's late-source allowance counts from it
234
+ * (#lossFreeRunReadyAtMs).
235
+ */
236
+ readonly arrivedAtMs?: number
195
237
  }
196
238
 
197
239
  /**
@@ -263,6 +305,8 @@ export interface FecBlockPathCount {
263
305
  catalogTrackName?: string
264
306
  multicastSymbols: number
265
307
  moqSymbols: number
308
+ /** Symbols of an "mfu-datagram" leg: lossy, counted apart from reliable MoQ. */
309
+ datagramSymbols: number
266
310
  complete: boolean
267
311
  }
268
312
 
@@ -322,6 +366,8 @@ export interface FECManagerConfig {
322
366
  * block `unknown` (fail-closed: protected).
323
367
  */
324
368
  geometry?: BlockClassifierGeometry
369
+ /** The track's catalog group duration in ms: one term of an "mfu-datagram" leg's ledger retention. */
370
+ groupDurationMs?: number
325
371
  /**
326
372
  * fec-01 6.3.9: the source track's base repair layers (catalog
327
373
  * `TrackFecParams.repairLayers`). Layer i's held total is
@@ -359,6 +405,7 @@ interface ResolvedFECTrackConfig {
359
405
  trackKind?: TrackKind
360
406
  codec?: string
361
407
  geometry?: BlockClassifierGeometry
408
+ groupDurationMs?: number
362
409
  repairLayers?: readonly FecRepairLayer[]
363
410
  heldLayers?: readonly number[]
364
411
  }
@@ -529,7 +576,12 @@ export class FECManager {
529
576
  #repairHoldUntilMs = new Map<string, number>()
530
577
  // Receiver-measured multicast delivery gap: the late-symbol wait's jitter
531
578
  // term (see DeliveryGapEstimator for the statistic and why).
532
- #deliveryGaps = new DeliveryGapEstimator()
579
+ // One estimator per lossy path, so a hybrid session never lets one leg's
580
+ // stall widen the other's wait; the wait reads the larger peak.
581
+ #deliveryGaps: Record<DeliveryGapPath, DeliveryGapEstimator> = {
582
+ multicast: new DeliveryGapEstimator(),
583
+ 'moq-datagram': new DeliveryGapEstimator(),
584
+ }
533
585
  #lifecycleTrace: FecLifecycleTrace[] = []
534
586
  // Worker-backed timeouts enqueue cleanup behind all prior symbol messages.
535
587
  // Failure remains pending until cleanupComplete acknowledges that queue drain.
@@ -570,7 +622,8 @@ export class FECManager {
570
622
  #ssbLengthConflictCount = 0
571
623
  #blockRepairRsIds = new Map<string, Set<number>>()
572
624
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
573
- // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
625
+ // symbols its repair group carries; 0 for a repair-less span no repair can
626
+ // state (#openIsoSpan). Same lifecycle as #blockRepairRsIds.
574
627
  #blockRsbLengths = new Map<string, number>()
575
628
  /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
576
629
  #heldLayerStates = new Map<string, HeldLayerAdmission>()
@@ -725,6 +778,14 @@ export class FECManager {
725
778
  // iso-ssbg1-v1 block location per stream (streamKey). A source belongs to a
726
779
  // block only once a repair symbol stated the block's (SS_Start, SSB_length).
727
780
  #isoLocators = new Map<string, IsoBlockLocator<IsoHeldSource>>()
781
+ // The ts of the run behind the gap the release gate last asked about, per
782
+ // stream (isoRepairlessWaitMs), keyed on the frame before the gap: kept, as
783
+ // the source it came from may retire before the run's deadline, and the
784
+ // earliest found wins, so a late frame that becomes the head restarts
785
+ // nothing. It stays until the next run gap: a source discontinuity drops
786
+ // it, and one older than twice the hold ceiling is not this gap's.
787
+ // `counted` once the deadline passed (onUndelimitedRunGap).
788
+ #runAnchors = new Map<string, { fromSsId: number; tsMs: number; counted: boolean }>()
728
789
  #deferIsoGaps = false
729
790
  #isoRepairRefusedCount = 0
730
791
  #isoSourceOversizeCount = 0
@@ -763,6 +824,8 @@ export class FECManager {
763
824
  #workerErrorCounts = new Map<string, number>()
764
825
  #decoderUnavailableEvents = 0
765
826
  #repairSymbolSizeMismatchCount = 0
827
+ #unlistedRepairTrackRefusals = 0
828
+ readonly #unresolvedRepairOwnerDrops: UnresolvedRepairOwnerDrops = { unregistered: 0, ownerAbsent: 0, ownerAmbiguous: 0 }
766
829
 
767
830
  // Event callbacks — block lifecycle notifications for MmtpRouter wiring.
768
831
  // NOTE: For sync WASM path, recovery routing is handled by MmtpRouter from
@@ -882,6 +945,25 @@ export class FECManager {
882
945
  onSourceDiscontinuity:
883
946
  | ((packetId: number, catalogTrackName: string | undefined) => void)
884
947
  | null = null
948
+ /** The FEC deadline of a run no repair delimited passed, releasing the gap behind it (once per gap). */
949
+ onUndelimitedRunGap:
950
+ | ((packetId: number, catalogTrackName: string | undefined) => void)
951
+ | null = null
952
+ /**
953
+ * The span and tolerance the catalog states for a keyframe overlay
954
+ * installed over a source track (draft-ramadan-moq-mmt-02 7.4.1: the
955
+ * overlay instance's own interleaveDepthMs and reorderToleranceMs), or
956
+ * undefined while none is installed. A stated block only a late source
957
+ * can complete, and a frame whose gap may hide a RAP behind a span only a
958
+ * late source can fill, also wait for that overlay's repair
959
+ * (#overlayLateWaitMs).
960
+ */
961
+ keyframeOverlayTiming:
962
+ | ((
963
+ packetId: number,
964
+ catalogTrackName: string | undefined,
965
+ ) => Pick<FecInstanceGeometry, 'interleaveDepthMs' | 'reorderToleranceMs'> | undefined)
966
+ | null = null
885
967
 
886
968
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
887
969
  /**
@@ -1774,6 +1856,7 @@ export class FECManager {
1774
1856
  // one continuous SBN sequence.
1775
1857
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity()
1776
1858
  this.#noSpanRaps.delete(streamKey)
1859
+ this.#runAnchors.delete(streamKey)
1777
1860
  this.#highestSbn.set(streamKey, { sbn, atMs: now })
1778
1861
  this.#sourceFrontiers.set(streamKey, { sbn, atMs: now })
1779
1862
  if (psn === undefined) this.#sourceAnchors.delete(streamKey)
@@ -2003,7 +2086,7 @@ export class FECManager {
2003
2086
  consider(geometry, this.#parseStreamKey(streamKey).packetId)
2004
2087
  }
2005
2088
  for (const [packetId, config] of this.#trackConfigs) consider(config.geometry, packetId)
2006
- this.#deliveryGaps.setWindowMs(windowMs)
2089
+ for (const estimator of Object.values(this.#deliveryGaps)) estimator.setWindowMs(windowMs)
2007
2090
  }
2008
2091
 
2009
2092
  /**
@@ -2017,7 +2100,7 @@ export class FECManager {
2017
2100
  * stream order and never feeds the estimator.
2018
2101
  */
2019
2102
  #multicastWaitMs(config: ResolvedFECTrackConfig): number {
2020
- return this.#waitForGapMs(config, this.#deliveryGaps.peakGapMs(performance.now()))
2103
+ return this.#waitForGapMs(config, this.#peakDeliveryGapMs())
2021
2104
  }
2022
2105
 
2023
2106
  /**
@@ -2025,7 +2108,7 @@ export class FECManager {
2025
2108
  * catalog window, so this is a catalog quantity that no measurement moves.
2026
2109
  */
2027
2110
  #maxMulticastWaitMs(config: ResolvedFECTrackConfig): number {
2028
- return this.#waitForGapMs(config, this.#deliveryGaps.windowMs ?? 0)
2111
+ return this.#waitForGapMs(config, this.#deliveryGaps.multicast.windowMs ?? 0)
2029
2112
  }
2030
2113
 
2031
2114
  #waitForGapMs(config: ResolvedFECTrackConfig, gapMs: number): number {
@@ -2290,6 +2373,9 @@ export class FECManager {
2290
2373
  ...((config.geometry ?? previous.geometry) === undefined
2291
2374
  ? {}
2292
2375
  : { geometry: config.geometry ?? previous.geometry }),
2376
+ ...((config.groupDurationMs ?? previous.groupDurationMs) === undefined
2377
+ ? {}
2378
+ : { groupDurationMs: config.groupDurationMs ?? previous.groupDurationMs }),
2293
2379
  ...((config.repairLayers ?? previous.repairLayers) === undefined
2294
2380
  ? {}
2295
2381
  : { repairLayers: config.repairLayers ?? previous.repairLayers }),
@@ -2446,6 +2532,11 @@ export class FECManager {
2446
2532
  }
2447
2533
  }
2448
2534
 
2535
+ /** Count a repair packet the router dropped for want of an owning track (BLO-55759). */
2536
+ countUnresolvedRepairOwner(reason: UnresolvedRepairOwnerReason): void {
2537
+ this.#unresolvedRepairOwnerDrops[reason]++
2538
+ }
2539
+
2449
2540
  get fecStats(): FecStats {
2450
2541
  const s = this.#fecStats
2451
2542
  const affected = s.blocksRecovered + s.blocksFailed
@@ -2491,6 +2582,8 @@ export class FECManager {
2491
2582
  packetId,
2492
2583
  })),
2493
2584
  repairSymbolSizeMismatches: this.#repairSymbolSizeMismatchCount,
2585
+ unlistedRepairTrackRefusals: this.#unlistedRepairTrackRefusals,
2586
+ unresolvedRepairOwnerDrops: { ...this.#unresolvedRepairOwnerDrops },
2494
2587
  repairObjectRejects: [...this.#repairObjectRejects.values()].map((r) => ({ ...r })),
2495
2588
  workerErrors: Object.fromEntries(this.#workerErrorCounts),
2496
2589
  }
@@ -2523,6 +2616,17 @@ export class FECManager {
2523
2616
  this.#startupRepairFailOpenPackets.clear()
2524
2617
  }
2525
2618
 
2619
+ /**
2620
+ * Start a new "mfu-datagram" leg (mmt-02 4.3.1) without discarding
2621
+ * track/decoder state: the same join-boundary rules as a multicast join,
2622
+ * since the leg starts at an arbitrary datagram too. It resets the whole
2623
+ * join boundary of this manager, a multicast ordered-relay frontier
2624
+ * included, so a host gives the leg a manager of its own.
2625
+ */
2626
+ beginLegJoin(): void {
2627
+ this.beginMulticastJoin()
2628
+ }
2629
+
2526
2630
  /** How the multicast leg currently delivers symbols. */
2527
2631
  get multicastSymbolDelivery(): MulticastSymbolDelivery {
2528
2632
  return this.#multicastSymbolDelivery
@@ -2548,8 +2652,11 @@ export class FECManager {
2548
2652
  }
2549
2653
  if (delivery === this.#multicastSymbolDelivery) return
2550
2654
  // A different delivery path: gaps measured on the old one say nothing
2551
- // about it (and ordered-relay never feeds the estimator).
2552
- this.#deliveryGaps.reset()
2655
+ // about it (and ordered-relay never feeds the estimator), and a run
2656
+ // anchored on its receipts is not timed on the new one. The leg's
2657
+ // estimator is not the multicast provider's to reset.
2658
+ this.#deliveryGaps.multicast.reset()
2659
+ this.#runAnchors.clear()
2553
2660
  if (delivery === 'ordered-relay') {
2554
2661
  for (const [packetId, config] of this.#trackConfigs) {
2555
2662
  this.#orderedHorizonBlocksFor(packetId, config)
@@ -2643,6 +2750,7 @@ export class FECManager {
2643
2750
  resetMap(this.#highestSbn)
2644
2751
  resetMap(this.#sourceFrontiers)
2645
2752
  resetMap(this.#isoLocators)
2753
+ resetMap(this.#runAnchors)
2646
2754
  resetMap(this.#sourceAnchors)
2647
2755
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName))
2648
2756
  this.#noSpanRaps.delete(this.#streamKey(packetId, catalogTrackName))
@@ -2760,6 +2868,7 @@ export class FECManager {
2760
2868
  dropMap(this.#highestSbn)
2761
2869
  dropMap(this.#sourceFrontiers)
2762
2870
  dropMap(this.#isoLocators)
2871
+ dropMap(this.#runAnchors)
2763
2872
  dropMap(this.#sourceAnchors)
2764
2873
  dropMap(this.#classifiers)
2765
2874
  dropMap(this.#noSpanRaps)
@@ -2855,14 +2964,16 @@ export class FECManager {
2855
2964
  this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? this.#trackConfig(packetId).k
2856
2965
  const isSourceSymbol = esi >= 0 && esi < sourceSymbols
2857
2966
  const isStartupPartial = this.#startupPartialBlocks.has(blockKey)
2967
+ // The join-boundary rules are about loss, so they hold on every lossy
2968
+ // path: a reliable MoQ symbol is never a join partial.
2858
2969
  const isReadyMulticastRepair =
2859
2970
  this.#startupRequireRepairReady &&
2860
- source === 'multicast' &&
2971
+ source !== 'moq' &&
2861
2972
  !isSourceSymbol &&
2862
2973
  this.#startupRepairReadyPackets.has(streamKey)
2863
2974
  const awaitingMulticastRepair =
2864
2975
  this.#startupRequireRepairReady &&
2865
- source === 'multicast' &&
2976
+ source !== 'moq' &&
2866
2977
  !this.#startupRepairReadyPackets.has(streamKey) &&
2867
2978
  !this.#startupRepairFailOpenPackets.has(streamKey)
2868
2979
  if (awaitingMulticastRepair) {
@@ -2930,6 +3041,7 @@ export class FECManager {
2930
3041
  ...(catalogTrackName === undefined ? {} : { catalogTrackName }),
2931
3042
  multicastSymbols: 0,
2932
3043
  moqSymbols: 0,
3044
+ datagramSymbols: 0,
2933
3045
  complete: false,
2934
3046
  }
2935
3047
  // The block's absolute anchor (fecBlockDeadlineMs): the receiver-local
@@ -2940,6 +3052,7 @@ export class FECManager {
2940
3052
  const anchorMs = this.#blockAnchorsMs.get(blockKey)
2941
3053
  if (anchorMs === undefined || receivedAtMs < anchorMs) this.#blockAnchorsMs.set(blockKey, receivedAtMs)
2942
3054
  if (source === 'multicast') counts.multicastSymbols++
3055
+ else if (source === 'moq-datagram') counts.datagramSymbols++
2943
3056
  else counts.moqSymbols++
2944
3057
  this.#blockPathCounts.set(blockKey, counts)
2945
3058
  this.#observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName)
@@ -2965,7 +3078,7 @@ export class FECManager {
2965
3078
  }
2966
3079
  }
2967
3080
 
2968
- if (isSourceSymbol && source === 'multicast') {
3081
+ if (isSourceSymbol && source !== 'moq') {
2969
3082
  this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), (sbn + esi) >>> 0, packetId, catalogTrackName)
2970
3083
  }
2971
3084
 
@@ -3071,8 +3184,22 @@ export class FECManager {
3071
3184
  * DeliveryGapEstimator). Datagram delivery only.
3072
3185
  */
3073
3186
  noteMulticastArrival(packetId: number, packetSequenceNumber: number): void {
3074
- if (this.#multicastSymbolDelivery !== 'datagram') return
3075
- this.#deliveryGaps.noteArrival(performance.now(), packetId, packetSequenceNumber)
3187
+ this.noteArrival('multicast', packetId, packetSequenceNumber)
3188
+ }
3189
+ /**
3190
+ * Record one MMTP packet arrival on a lossy path for that path's
3191
+ * delivery-gap measurement: the multicast leg (datagram delivery only; an
3192
+ * ordered relay settles by stream order) or an "mfu-datagram" leg, whose
3193
+ * datagrams are always a lossy path (#lossyDatagramPath).
3194
+ */
3195
+ noteArrival(path: DeliveryGapPath, packetId: number, packetSequenceNumber: number): void {
3196
+ if (!this.#lossyDatagramPath(path)) return
3197
+ this.#deliveryGaps[path].noteArrival(performance.now(), packetId, packetSequenceNumber)
3198
+ }
3199
+ /** The largest delivery gap any lossy path measured over its window. */
3200
+ #peakDeliveryGapMs(): number {
3201
+ const now = performance.now()
3202
+ return Math.max(...Object.values(this.#deliveryGaps).map((estimator) => estimator.peakGapMs(now)))
3076
3203
  }
3077
3204
  /**
3078
3205
  * Resolved per-track multicast late-symbol wait in milliseconds: the span
@@ -3086,16 +3213,18 @@ export class FECManager {
3086
3213
  * Largest multicast delivery gap measured over the current window (ms), and
3087
3214
  * that window (undefined: held since the last reset). Diagnostics.
3088
3215
  */
3089
- multicastDeliveryGap(): { peakGapMs: number; windowMs: number | undefined } {
3216
+ multicastDeliveryGap(path: DeliveryGapPath = 'multicast'): { peakGapMs: number; windowMs: number | undefined } {
3090
3217
  return {
3091
- peakGapMs: this.#deliveryGaps.peakGapMs(performance.now()),
3092
- windowMs: this.#deliveryGaps.windowMs,
3218
+ peakGapMs: this.#deliveryGaps[path].peakGapMs(performance.now()),
3219
+ windowMs: this.#deliveryGaps[path].windowMs,
3093
3220
  }
3094
3221
  }
3095
3222
  /**
3096
3223
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
3097
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
3098
- * Undefined for a block that is not open.
3224
+ * (SSB_length) and RSB_length (each undefined until a repair stated it; a
3225
+ * repair-less span states its length, and RSB_length 0 when it is longer
3226
+ * than K, since no repair can reach it). Undefined for a block that is not
3227
+ * open.
3099
3228
  */
3100
3229
  blockSymbolCounts(
3101
3230
  sbn: number,
@@ -3200,6 +3329,27 @@ export class FECManager {
3200
3329
  const config = this.#trackConfigs.get(packetId)
3201
3330
  return config === undefined ? undefined : this.#blockLifetimeMs(config)
3202
3331
  }
3332
+ /**
3333
+ * How long an "mfu-datagram" leg's duplicate ledgers must remember a packet
3334
+ * so a legal reorder never reads as a publisher restart: one block span,
3335
+ * the reorder tolerance (`timeoutMs` is span + tolerance) and one group,
3336
+ * since a datagram may trail the stream by a whole group behind a joining
3337
+ * FETCH (mmt-02 6.1 step 3). The group is the catalog group duration
3338
+ * (`groupDurationMs`), whatever the track kind; a video track configured
3339
+ * without one falls back to its keyframe interval (one GOP per group).
3340
+ * Undefined for an unconfigured packet id.
3341
+ */
3342
+ datagramLegLedgerRetentionMsForPacket(packetId: number): number | undefined {
3343
+ const config = this.#trackConfigs.get(packetId)
3344
+ if (config === undefined) return undefined
3345
+ const geometry = config.geometry
3346
+ const groupMs = config.groupDurationMs ?? (
3347
+ geometry?.trackKind === 'video' && geometry.mode === 'classifying'
3348
+ ? (geometry.keyframeInterval.ticks / geometry.keyframeInterval.timescale) * 1000
3349
+ : 0
3350
+ )
3351
+ return config.timeoutMs + (Number.isFinite(groupMs) ? groupMs : 0)
3352
+ }
3203
3353
  /**
3204
3354
  * How long a terminal (clean, recovered or failed) block stays authoritative,
3205
3355
  * for late symbols and for the in-order release gate. It is also the gate's
@@ -3230,7 +3380,7 @@ export class FECManager {
3230
3380
  }
3231
3381
  const trackConfig = this.#trackConfigs.get(packetId)
3232
3382
  if (trackConfig === undefined) return undefined
3233
- return Math.max(1, trackConfig.timeoutMs - this.#repairDeadlineMs(trackConfig))
3383
+ return Math.max(1, this.#repairGraceMs(trackConfig, this.#multicastWaitMs(trackConfig)))
3234
3384
  }
3235
3385
 
3236
3386
  /** True once configureTrack/setFecDecoder/setFecWorker configured this packetId. */
@@ -3278,6 +3428,9 @@ export class FECManager {
3278
3428
  for (const key of [...this.#isoLocators.keys()]) {
3279
3429
  if (this.#belongsToPacket(key, packetId)) this.#isoLocators.delete(key)
3280
3430
  }
3431
+ for (const key of [...this.#runAnchors.keys()]) {
3432
+ if (this.#belongsToPacket(key, packetId)) this.#runAnchors.delete(key)
3433
+ }
3281
3434
  }
3282
3435
 
3283
3436
  /**
@@ -3341,9 +3494,9 @@ export class FECManager {
3341
3494
  ): boolean {
3342
3495
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName)
3343
3496
  const evictedBefore = locator.heldEvicted
3344
- const held = locator.hold(ssId, source)
3497
+ const held = locator.hold(ssId, source.arrivedAtMs === undefined ? { ...source, arrivedAtMs: this.#receiptNow() } : source)
3345
3498
  this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName)
3346
- if (held && source.source === 'multicast') this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName)
3499
+ if (held && source.source !== 'moq') this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName)
3347
3500
  const evicted = locator.heldEvicted - evictedBefore
3348
3501
  if (evicted > 0) {
3349
3502
  const before = this.#isoHeldEvictedCount
@@ -3465,6 +3618,17 @@ export class FECManager {
3465
3618
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
3466
3619
  * SS_ID of which vanished resolves through its deadline like any vanished
3467
3620
  * block.
3621
+ *
3622
+ * A span longer than K holds more than one block (SSB_length <= K), and the
3623
+ * locator states no block inside a span, only one exactly its range
3624
+ * (IsoBlockLocator.placeRepair): no repair, multicast or FETCHed, can ever
3625
+ * reach it. Its repair group is empty, so the repair scheduler FETCHes no
3626
+ * Group of it (group-cannot-complete). Every span still keeps its whole
3627
+ * wait (#lateSourceWaitMs): failing it early released the frames behind it
3628
+ * past a keyframe the overlay was still rebuilding (BLO-52085). The release
3629
+ * gate lets those frames go once only a late source can fill the gap
3630
+ * before them, as long after they arrived as the gap's decision allows
3631
+ * (isoRepairlessWaitMs).
3468
3632
  */
3469
3633
  #openIsoSpan(
3470
3634
  span: { readonly block: IsoBlockRange; readonly placed: readonly unknown[] },
@@ -3472,9 +3636,15 @@ export class FECManager {
3472
3636
  catalogTrackName: string | undefined,
3473
3637
  ): void {
3474
3638
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName)
3639
+ // A span's key is always new here. An authored length is set only here or
3640
+ // from a repair stating that block (#noteAuthoredLength), and the locator
3641
+ // opens a span only where no repair stated a block, so none can precede
3642
+ // it. Were one to, the guard would skip the RSB_length 0 that keeps the
3643
+ // repair scheduler from FETCHing a long span's first Group.
3475
3644
  if (!this.#blockAuthoredLengths.has(key)) {
3476
3645
  this.#blockAuthoredLengths.set(key, span.block.length)
3477
3646
  this.#isoSpanKeys.add(key)
3647
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0)
3478
3648
  }
3479
3649
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true)
3480
3650
  }
@@ -3483,7 +3653,12 @@ export class FECManager {
3483
3653
  * Resolution of the SS_IDs strictly between two released frames' SS_IDs on
3484
3654
  * an iso-ssbg1-v1 stream, for in-order frame release: null while a block
3485
3655
  * that could hold them is pending or not yet stated by a repair, else the
3486
- * starts of the blocks that failed or vanished.
3656
+ * starts of the blocks that failed or vanished. SS_IDs no repair has
3657
+ * delimited yet that all arrived lost nothing and wait for no repair, only
3658
+ * the late-source allowance after the datagram of a lossy path that clocks
3659
+ * them arrived (#lossFreeRunReadyAtMs), and not even that when none of them
3660
+ * came as one; one missing makes a run that waits as one block
3661
+ * (isoRepairlessWaitMs).
3487
3662
  *
3488
3663
  * `untracked` reads as the release gate reads it (MmtpRouter
3489
3664
  * #createFecReleaseGate): a block holding either released frame's SS_ID
@@ -3501,7 +3676,19 @@ export class FECManager {
3501
3676
  ): readonly number[] | null {
3502
3677
  if (!serial32Precedes(fromSsId, toSsId) || serial32Distance(fromSsId, toSsId) <= 1) return []
3503
3678
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))
3504
- if (!locator || !locator.coversBetween(fromSsId, toSsId)) return null
3679
+ if (!locator) return null
3680
+ // SS_IDs past coverage that all arrived lost nothing, so no repair need
3681
+ // delimit them; a run of them the receiver lacks is one block, which
3682
+ // isoRepairlessWaitMs times.
3683
+ const run = locator.undelimitedBetween(fromSsId, toSsId)
3684
+ if (run?.missing !== undefined) return null
3685
+ if (run !== null) {
3686
+ const config = this.#trackConfigs.get(packetId)
3687
+ const readyAtMs = config === undefined ? undefined : this.#lossFreeRunReadyAtMs(config, locator, run.start, toSsId)
3688
+ if (readyAtMs !== undefined && this.#receiptNow() < readyAtMs) return null
3689
+ }
3690
+ if (locator.coverageEnd === undefined) return []
3691
+ if (!locator.coversBetween(fromSsId, run?.start ?? toSsId)) return null
3505
3692
  const highest = this.highestSbn(packetId, catalogTrackName)
3506
3693
  const lost: number[] = []
3507
3694
  for (const block of locator.blocksBetween(fromSsId, toSsId)) {
@@ -3523,6 +3710,220 @@ export class FECManager {
3523
3710
  return lost
3524
3711
  }
3525
3712
 
3713
+ /**
3714
+ * When undelimited SS_IDs from `runStart` up to `toSsId` that all arrived
3715
+ * stop holding its frame: the late-source allowance after the receipt of
3716
+ * a datagram of a lossy path (#lossyDatagramPath: a multicast datagram, or
3717
+ * one of an "mfu-datagram" leg). Until then a frame between them may still
3718
+ * complete from a packet with no SS_ID (an untagged FT=0/FT=1 reordered
3719
+ * behind the next frame), and a repair may delimit them. The receipt is
3720
+ * `toSsId`'s own when it is held from such a datagram. Otherwise (its
3721
+ * packet came only as an overlap copy or from a MoQ stream, or was evicted
3722
+ * or retired) it is the newest among those SS_IDs, every one of which is
3723
+ * held and states its path. So the time moves at most once, when the
3724
+ * head's own datagram copy arrives while its frame waits or its held
3725
+ * source is dropped, and never on a later ask.
3726
+ *
3727
+ * Undefined, so the range releases at once, when no SS_ID of it came as
3728
+ * such a datagram: a MoQ arrival, an ordered relay's and the frame's own
3729
+ * are no clock for datagram reordering (#lossyReceiptMs). Undefined too
3730
+ * on a track with no catalog span, which states no allowance: the local
3731
+ * timeout is a cleanup bound, and isoRepairlessWaitMs arms no wake there,
3732
+ * so a wait would hold the frame until the next packet. The cost, on
3733
+ * multicast and on the leg too: an untagged FT=0/FT=1 reordered behind
3734
+ * the next frame of such a track is dropped stale.
3735
+ */
3736
+ #lossFreeRunReadyAtMs(
3737
+ config: ResolvedFECTrackConfig,
3738
+ locator: IsoBlockLocator<IsoHeldSource>,
3739
+ runStart: number,
3740
+ toSsId: number,
3741
+ ): number | undefined {
3742
+ if (!FECManager.#hasCatalogTiming(config)) return undefined
3743
+ let clockMs = this.#lossyReceiptMs(locator.heldSource(toSsId))
3744
+ if (clockMs === undefined) {
3745
+ for (let ssId = runStart; ssId !== toSsId; ssId = (ssId + 1) >>> 0) {
3746
+ const atMs = this.#lossyReceiptMs(locator.heldSource(ssId))
3747
+ if (atMs !== undefined && (clockMs === undefined || atMs > clockMs)) clockMs = atMs
3748
+ }
3749
+ }
3750
+ if (clockMs === undefined) return undefined
3751
+ return clockMs + Math.max(0, this.#multicastWaitMs(config) - config.interleaveDepthMs)
3752
+ }
3753
+
3754
+ /**
3755
+ * Receipt time of a held source that came as a datagram of a lossy path
3756
+ * (#lossyDatagramPath), else undefined: a MoQ stream and an ordered relay
3757
+ * deliver in order, so their arrivals clock no reorder allowance and no
3758
+ * FEC deadline. The path is the one the feed stated (IsoHeldSource.source,
3759
+ * and MulticastSymbolDelivery for a multicast source), never a guess.
3760
+ */
3761
+ #lossyReceiptMs(held: IsoHeldSource | undefined): number | undefined {
3762
+ return held !== undefined && this.#lossyDatagramPath(held.source) ? held.arrivedAtMs : undefined
3763
+ }
3764
+
3765
+ /**
3766
+ * The one path predicate of the loss gates: whether a symbol fed as
3767
+ * `source` reached this manager as a datagram of its own, on a path that
3768
+ * loses and reorders (mmt-02 Section 2, a datagram leg). A multicast
3769
+ * symbol does unless its provider declared an ordered relay. An
3770
+ * "mfu-datagram" object always does (4.3.1): MulticastSymbolDelivery is
3771
+ * the multicast provider's statement and is never read for the leg. A MoQ
3772
+ * stream object never does, a stream copy of the leg included.
3773
+ */
3774
+ #lossyDatagramPath(source: FecSymbolSource): boolean {
3775
+ return source === 'moq-datagram' || (source === 'multicast' && this.#multicastSymbolDelivery === 'datagram')
3776
+ }
3777
+
3778
+ /**
3779
+ * The release gate's wait, from a frame's arrival, for the SS_IDs strictly
3780
+ * between two released frames' SS_IDs once only a late source can still
3781
+ * fill them, else undefined. That is when every one missing (neither
3782
+ * arrived nor held) lies in a repair-less span longer than K, which no
3783
+ * repair can state a block of (#openIsoSpan), or in a stated block its
3784
+ * own repair group cannot complete every SS_ID of which it misses lies
3785
+ * between them (so the gap's decision covers all it lost), and a source of
3786
+ * a lossy leg (multicast, or an "mfu-datagram" leg's datagram) at or past
3787
+ * `toSsId` arrived, so each is lost or reordered behind it (a MoQ source
3788
+ * shows nothing: MoQ streams overtake one another). The span or block
3789
+ * itself keeps its own wait.
3790
+ *
3791
+ * The wait is the late-symbol allowance, unless `rapMayHide`: the gap may
3792
+ * hold a RAP packet an installed keyframe overlay can still rebuild (its
3793
+ * decision stalls, or it ends at a RAP that may lie past a whole MPU).
3794
+ * Then the frame waits as a stated block its group cannot complete does
3795
+ * (#overlayLateWaitMs): the allowance alone with no overlay installed, the
3796
+ * overlay's span plus the larger of the allowance and its tolerance, or,
3797
+ * for an overlay that states no span, the span's whole wait (undefined).
3798
+ * So does `rapNext` (the gap ends at the RAP that opens the next MPU) when
3799
+ * the gap holds a stated block's loss.
3800
+ *
3801
+ * A run of SS_IDs no repair has delimited yet, one of which never arrived,
3802
+ * is one block of its own instead (draft-ramadan-moq-fec-multicast-00,
3803
+ * Receiver Repair Policy; on an "mfu-datagram" leg fec-core-00 9.3 and
3804
+ * mmt-02 5.3.3): the frame then waits for that block's FEC deadline,
3805
+ * whatever the flags: ts plus the whole multicast wait (fec-core-00 9.3),
3806
+ * ts the receipt of the lowest held source above the run that came as a
3807
+ * datagram of a lossy path (#lossyDatagramPath), up to the newest
3808
+ * (fec-multicast-00, Deadline Anchoring; under reordering at or after the
3809
+ * draft's first signal, never before). The wait returned counts from
3810
+ * `arrivedAtMs`, the frame's arrival; without it, it is the whole wait.
3811
+ * With no such source held (never arrived, retired, or evicted, or every
3812
+ * one from a MoQ stream or an ordered relay) the frame keeps the hold
3813
+ * ceiling: a stream arrival is no clock for a datagram deadline.
3814
+ */
3815
+ isoRepairlessWaitMs(
3816
+ packetId: number,
3817
+ catalogTrackName: string | undefined,
3818
+ fromSsId: number,
3819
+ toSsId: number,
3820
+ rapMayHide = false,
3821
+ rapNext = false,
3822
+ arrivedAtMs?: number,
3823
+ ): number | undefined {
3824
+ const config = this.#trackConfigs.get(packetId)
3825
+ if (config === undefined || !FECManager.#hasCatalogTiming(config)) return undefined
3826
+ const streamKey = this.#streamKey(packetId, catalogTrackName)
3827
+ const locator = this.#isoLocators.get(streamKey)
3828
+ if (locator === undefined) return undefined
3829
+ const run = locator.undelimitedBetween(fromSsId, toSsId)
3830
+ const readyAtMs = run === null || run.missing !== undefined ? undefined : this.#lossFreeRunReadyAtMs(config, locator, run.start, toSsId)
3831
+ if (readyAtMs !== undefined && this.#receiptNow() < readyAtMs) {
3832
+ return Math.max(0, readyAtMs - (arrivedAtMs ?? this.#receiptNow()))
3833
+ }
3834
+ const newestSource = locator.newestSource
3835
+ if (newestSource === undefined || serial32Precedes(newestSource, toSsId)) return undefined
3836
+ // A run past coverage the receiver lacks an SS_ID of is one block of the
3837
+ // instance. A repair may delimit it until its FEC deadline, so once the
3838
+ // delimited SS_IDs before it resolved the frame waits for that deadline,
3839
+ // longer than any overlay wait. Only a held datagram of a lossy path
3840
+ // anchors it (#lossyReceiptMs): an overlap copy is never held, and a MoQ
3841
+ // stream overtakes the others. A multicast source on an ordered relay is
3842
+ // none either, so the scan below finds no ts there and the frame keeps
3843
+ // the hold ceiling, as a pause there says nothing of loss. The delivery
3844
+ // mode is not read here on its own: it is the multicast provider's
3845
+ // statement, and would deny an "mfu-datagram" leg's run its deadline.
3846
+ // Settle a run by stream order (#withinOrderedHorizon) if a relay ever
3847
+ // runs without repair.
3848
+ if (run?.missing !== undefined) {
3849
+ if (this.isoSpanResolution(packetId, catalogTrackName, fromSsId, run.start) === null) return undefined
3850
+ // An anchor older than twice the hold ceiling is another run's: the
3851
+ // gate flushes a frame at the ceiling, so the same `from` SS_ID came
3852
+ // again (a publisher restart that reuses SS_IDs, or the 2^32 wrap).
3853
+ const kept = this.#runAnchors.get(streamKey)
3854
+ const anchor =
3855
+ kept?.fromSsId === fromSsId &&
3856
+ this.#receiptNow() - kept.tsMs <= 2 * (config.interleaveDepthMs + 2 * this.#blockLifetimeMs(config))
3857
+ ? kept
3858
+ : undefined
3859
+ let tsMs = anchor?.tsMs
3860
+ for (let ssId = (run.missing + 1) >>> 0; !serial32Precedes(newestSource, ssId); ssId = (ssId + 1) >>> 0) {
3861
+ const atMs = this.#lossyReceiptMs(locator.heldSource(ssId))
3862
+ if (atMs === undefined) continue
3863
+ if (tsMs === undefined || atMs < tsMs) tsMs = atMs
3864
+ break
3865
+ }
3866
+ if (tsMs === undefined) return undefined
3867
+ const waitMs = this.#multicastWaitMs(config)
3868
+ let counted = anchor?.counted === true
3869
+ if (!counted && tsMs + waitMs <= this.#receiptNow()) {
3870
+ counted = true
3871
+ this.onUndelimitedRunGap?.(packetId, catalogTrackName)
3872
+ }
3873
+ this.#runAnchors.set(streamKey, { fromSsId, tsMs, counted })
3874
+ return arrivedAtMs === undefined ? waitMs : Math.max(0, tsMs + waitMs - arrivedAtMs)
3875
+ }
3876
+ // SS_IDs past coverage that all arrived hold no loss, so they wait for no
3877
+ // repair to delimit them.
3878
+ if (!locator.coversBetween(fromSsId, run?.start ?? toSsId)) return undefined
3879
+ let repairless = false
3880
+ let stated = false
3881
+ for (const block of locator.blocksBetween(fromSsId, toSsId)) {
3882
+ const key = this.#blockKey(block.start, packetId, catalogTrackName)
3883
+ if (this.#completedBlocks.has(key)) continue
3884
+ if (block.span && block.length > locator.kMax) {
3885
+ repairless = true
3886
+ continue
3887
+ }
3888
+ const received = this.#blockSourceEsis.get(key)
3889
+ const rebuilt = this.#blockRebuiltEsis.get(key)
3890
+ let missesInGap = false
3891
+ let missesOutside = false
3892
+ // A rebuilt source is present outside the gap but missed inside it.
3893
+ // Outside, the question is what the block's decoder lacks beyond this
3894
+ // gap, and it holds a rebuilt source (#groupCannotComplete). Inside, it
3895
+ // is what the base path lost between the two frames. A base recovery
3896
+ // does not route a rebuilt packet again (MmtpRouter
3897
+ // #routeVerifiedFecSymbols), so only the overlay route delivers it, and
3898
+ // its frame may not have reached the gate yet (a head held for its FT=1,
3899
+ // BLO-53369). The two differ only when every SS_ID a block misses in the
3900
+ // gap was rebuilt: the later frame then waits for the gap's blocks to
3901
+ // resolve (undefined), which is conservative.
3902
+ for (let esi = 0; esi < block.length; esi++) {
3903
+ const ssId = serial32Add(block.start, esi)
3904
+ if (received?.has(esi) || locator.isHeld(ssId)) continue
3905
+ if (serial32Precedes(fromSsId, ssId) && serial32Precedes(ssId, toSsId)) missesInGap = true
3906
+ else if (!rebuilt?.has(esi)) missesOutside = true
3907
+ }
3908
+ if (!missesInGap) continue
3909
+ // A stated block its own group cannot complete (#lateSourceWaitMs) is
3910
+ // one too, when every SS_ID it misses lies in this gap: the gap's
3911
+ // decision then covers all it lost, so the overlay can rebuild none of
3912
+ // it unless `rapMayHide` or `rapNext`.
3913
+ if (missesOutside || block.span || !this.#groupCannotComplete(key)) return undefined
3914
+ repairless = stated = true
3915
+ }
3916
+ if (!repairless) return undefined
3917
+ // A gap into the next MPU (`rapNext`) may hold that MPU's FT=0, an overlay
3918
+ // member; rebuilt, it is one more source of a stated block, which its group
3919
+ // may then complete. Such a block keeps #741's overlay wait; a span longer
3920
+ // than K has no group to complete and keeps #742's allowance.
3921
+ const waitMs = rapMayHide || (stated && rapNext)
3922
+ ? this.#overlayLateWaitMs(packetId, catalogTrackName, config)
3923
+ : this.#multicastWaitMs(config) - config.interleaveDepthMs
3924
+ return waitMs === undefined ? undefined : Math.max(0, waitMs)
3925
+ }
3926
+
3526
3927
  /**
3527
3928
  * iso-ssbg1-v1 block location: repair symbols it refused, oversize sources,
3528
3929
  * the sources held now for a block no repair has stated yet, and the held
@@ -3596,11 +3997,43 @@ export class FECManager {
3596
3997
  * it does not. A stream with no classifier yet has shown nothing against it,
3597
3998
  * and neither has a stream without catalog timing until it releases two
3598
3999
  * RAPs inside one MPU.
4000
+ *
4001
+ * With catalog timing and a `gap` inside one MPU, between the authored
4002
+ * timing of the frames on either side, it also takes the catalog keyframe
4003
+ * interval to rule a keyframe out of the gap
4004
+ * (`BlockClassifier.keyframeFreeBetween`, fec-multicast-00 Block
4005
+ * Classification item 3), and no source held between the frames' SS_IDs
4006
+ * may carry the RAP flag or another MPU's number (item 1 read on the held
4007
+ * packets: a RAP the loss cut in two is never released, so the frames
4008
+ * alone cannot show it); anything unknown counts as a keyframe.
3599
4009
  */
3600
- mpuBoundsRapsFor(packetId: number, catalogTrackName?: string): boolean {
4010
+ mpuBoundsRapsFor(
4011
+ packetId: number,
4012
+ catalogTrackName?: string,
4013
+ gap?: {
4014
+ readonly mpu: number
4015
+ readonly from?: AuthoredTiming
4016
+ readonly to?: AuthoredTiming
4017
+ readonly fromSsId?: number
4018
+ readonly toSsId?: number
4019
+ },
4020
+ ): boolean {
3601
4021
  const streamKey = this.#streamKey(packetId, catalogTrackName)
3602
4022
  if (!this.#hasCatalogTimingForPacket(packetId)) return this.#noSpanRaps.get(streamKey)?.inside !== true
3603
- return this.#classifiers.get(streamKey)?.mpuBoundsRaps ?? true
4023
+ const classifier = this.#classifiers.get(streamKey)
4024
+ if (gap === undefined) return classifier?.mpuBoundsRaps ?? true
4025
+ const { mpu, from, to, fromSsId, toSsId } = gap
4026
+ if (fromSsId !== undefined && toSsId !== undefined) {
4027
+ const run = this.#isoLocators.get(streamKey)?.undelimitedBetween(
4028
+ fromSsId,
4029
+ toSsId,
4030
+ ({ evidence }) => evidence.rap || (evidence.mpu !== undefined && evidence.mpu !== mpu),
4031
+ )
4032
+ if (run?.flagged) return false
4033
+ }
4034
+ return classifier !== undefined && from !== undefined && to !== undefined &&
4035
+ from.mediaTimescale === to.mediaTimescale &&
4036
+ classifier.keyframeFreeBetween(mpu, from.decodeTime, to.decodeTime, from.mediaTimescale)
3604
4037
  }
3605
4038
 
3606
4039
  /** A block's class now, or frozen at its resolution. */
@@ -3627,7 +4060,9 @@ export class FECManager {
3627
4060
 
3628
4061
  /**
3629
4062
  * Record a RAP frame released in order, for the classifier's RAP-spacing
3630
- * invariant (consecutive MPUs exactly one keyframe interval apart).
4063
+ * invariant (consecutive MPUs exactly one keyframe interval apart) and,
4064
+ * with its decode time, as the MPU start gap decisions measure the catalog
4065
+ * keyframe interval from (mpuBoundsRapsFor).
3631
4066
  */
3632
4067
  noteReleasedRap(
3633
4068
  packetId: number,
@@ -3635,6 +4070,7 @@ export class FECManager {
3635
4070
  mpu: number,
3636
4071
  presentationTime: bigint,
3637
4072
  mediaTimescale: number,
4073
+ decodeTime?: bigint,
3638
4074
  ): void {
3639
4075
  if (!this.#trackConfigs.has(packetId)) return
3640
4076
  if (!this.#hasCatalogTimingForPacket(packetId)) {
@@ -3652,6 +4088,7 @@ export class FECManager {
3652
4088
  mpu,
3653
4089
  presentationTime,
3654
4090
  mediaTimescale,
4091
+ decodeTime,
3655
4092
  ),
3656
4093
  )
3657
4094
  }
@@ -4422,7 +4859,10 @@ export class FECManager {
4422
4859
  this.#layerAnchorHorizon(packetId),
4423
4860
  this.#sourceFrontiers.get(streamKey)?.sbn,
4424
4861
  )
4425
- if (verdict === 'discard') return false
4862
+ if (verdict === 'discard') {
4863
+ this.#unlistedRepairTrackRefusals++
4864
+ return false
4865
+ }
4426
4866
  if (verdict !== undefined) {
4427
4867
  this.#failClosed(streamKey, verdict, packetId, catalogTrackName)
4428
4868
  return false
@@ -4609,9 +5049,11 @@ export class FECManager {
4609
5049
  * its sources in send order, so one that moves the stream's newest source
4610
5050
  * position past a block leaves the sources that block still misses
4611
5051
  * reordered behind it at best: it shortens the wait of every block it
4612
- * passed that only a late source can complete. MoQ is left out: its streams
4613
- * can overtake one another, so a MoQ source shows nothing about the sources
4614
- * sent before it.
5052
+ * passed that only a late source can complete. Reliable MoQ is left out:
5053
+ * its streams can overtake one another, so a MoQ source shows nothing
5054
+ * about the sources sent before it. An "mfu-datagram" leg is in: its
5055
+ * datagrams leave the publisher in send order and reorder only within the
5056
+ * path's tolerance, as multicast does.
4615
5057
  */
4616
5058
  #noteMulticastSource(
4617
5059
  locator: IsoBlockLocator<IsoHeldSource>,
@@ -4624,7 +5066,7 @@ export class FECManager {
4624
5066
  // The blocks whose last SS_ID lies in [previous, ssId): this source
4625
5067
  // passed them and the previous newest one had not.
4626
5068
  for (const block of locator.blocksBetween((previous - 1) >>> 0, ssId)) {
4627
- if (block.span || !serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue
5069
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue
4628
5070
  this.#shortenUnrecoverableWait(
4629
5071
  this.#blockKey(block.start, packetId, catalogTrackName),
4630
5072
  block.start,
@@ -4643,7 +5085,13 @@ export class FECManager {
4643
5085
  * covers repair symbols paced after its sources, buys it nothing: it waits
4644
5086
  * the late-symbol allowance alone, the multicast wait less the span (the
4645
5087
  * catalog tolerance or the measured delivery gap). Undefined for any other
4646
- * block.
5088
+ * block. While a keyframe overlay is installed, the block waits for its
5089
+ * repair too (#overlayLateWaitMs). A repair-less span keeps its whole
5090
+ * wait, even one longer than K whose group is empty (#openIsoSpan): its
5091
+ * resolution is what releases the frames behind it, and failing it early
5092
+ * released them past a keyframe the overlay was still rebuilding, which
5093
+ * then arrived stale. The release gate lets them go instead
5094
+ * (isoRepairlessWaitMs).
4647
5095
  */
4648
5096
  #lateSourceWaitMs(
4649
5097
  key: string,
@@ -4652,20 +5100,64 @@ export class FECManager {
4652
5100
  catalogTrackName: string | undefined,
4653
5101
  config: ResolvedFECTrackConfig,
4654
5102
  ): number | undefined {
5103
+ if (this.#isoSpanKeys.has(key) || !this.#groupCannotComplete(key)) return undefined
5104
+ const authoredLength = this.#blockAuthoredLengths.get(key)!
5105
+ const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource
5106
+ if (newestSource === undefined || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
5107
+ return undefined
5108
+ }
5109
+ return this.#overlayLateWaitMs(packetId, catalogTrackName, config)
5110
+ }
5111
+
5112
+ /**
5113
+ * A repair stated the block, and its sources plus every symbol its repair
5114
+ * group carries (RSB_length) are short of its SSB_length.
5115
+ */
5116
+ #groupCannotComplete(key: string): boolean {
4655
5117
  const authoredLength = this.#blockAuthoredLengths.get(key)
4656
5118
  const rsbLength = this.#blockRsbLengths.get(key)
4657
- if (authoredLength === undefined || rsbLength === undefined) return undefined
5119
+ if (authoredLength === undefined || rsbLength === undefined) return false
4658
5120
  // A source another instance rebuilt (feedRebuiltSourceSymbol) is one the
4659
5121
  // decoder holds: the group need only cover what neither delivered.
4660
5122
  let present = this.#blockSourceCounts.get(key) ?? 0
4661
5123
  const received = this.#blockSourceEsis.get(key)
4662
5124
  for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++
4663
- if (present + rsbLength >= authoredLength) return undefined
4664
- const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource
4665
- if (newestSource === undefined || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
4666
- return undefined
4667
- }
4668
- return this.#multicastWaitMs(config) - config.interleaveDepthMs
5125
+ return present + rsbLength < authoredLength
5126
+ }
5127
+
5128
+ /**
5129
+ * How long a loss only a late source or an installed keyframe overlay can
5130
+ * still fill waits once a later source passed it: the late-symbol
5131
+ * allowance alone (the multicast wait less the span) while no overlay is
5132
+ * installed. An installed one (keyframeOverlayTiming) may still rebuild a
5133
+ * RAP packet the loss took: a second FEC instance over the same packets
5134
+ * (draft-ramadan-moq-mmt-02 7.4), whose repair is paced across its own
5135
+ * span, unrelated to the base's. That packet can complete a stated block
5136
+ * (feedRebuiltSourceSymbol), or play behind a span; giving the loss up
5137
+ * first lets the release gate pass the keyframe, whose rebuild then lands
5138
+ * stale. The overlay repair of a packet the loss took goes out within the
5139
+ * overlay's span of that packet (fec-core-00 9.3), and the later source was
5140
+ * sent after it, so the loss waits that span plus the larger of the
5141
+ * allowance and the overlay's own tolerance. An overlay that states no
5142
+ * span (its block may then span keyframes), or one whose wait is not
5143
+ * shorter than the whole multicast wait, leaves the whole wait: undefined.
5144
+ */
5145
+ #overlayLateWaitMs(
5146
+ packetId: number,
5147
+ catalogTrackName: string | undefined,
5148
+ config: ResolvedFECTrackConfig,
5149
+ ): number | undefined {
5150
+ const waitMs = this.#multicastWaitMs(config)
5151
+ const allowanceMs = waitMs - config.interleaveDepthMs
5152
+ // Read live. The late-source cut only ever shortens a block's deadline
5153
+ // (#shortenUnrecoverableWait), so a block it armed at the bare allowance
5154
+ // before an overlay was installed, or between a dispose and a reinstall,
5155
+ // keeps that deadline until a source of its own re-arms it.
5156
+ const overlay = this.keyframeOverlayTiming?.(packetId, catalogTrackName)
5157
+ if (overlay === undefined) return allowanceMs
5158
+ const overlaySpanMs = overlay.interleaveDepthMs ?? 0
5159
+ const overlayWaitMs = overlaySpanMs + Math.max(allowanceMs, overlay.reorderToleranceMs ?? 0)
5160
+ return overlaySpanMs > 0 && overlayWaitMs < waitMs ? overlayWaitMs : undefined
4669
5161
  }
4670
5162
 
4671
5163
  /**
@@ -5206,7 +5698,7 @@ export class FECManager {
5206
5698
  ): MmtpDeliveryProvenance {
5207
5699
  const counts = this.blockPathCount(sbn, packetId, catalogTrackName)
5208
5700
  if (!counts) return 'unknown'
5209
- if (counts.moqSymbols > 0) return 'mixed'
5701
+ if (counts.moqSymbols > 0 || counts.datagramSymbols > 0) return 'mixed'
5210
5702
  if (counts.multicastSymbols > 0) return 'multicast'
5211
5703
  return 'unknown'
5212
5704
  }
@@ -5241,7 +5733,7 @@ export class FECManager {
5241
5733
  this.#activeBlockDeadlinesMs.clear()
5242
5734
  this.#blockWaitDeadlinesMs.clear()
5243
5735
  this.#repairHoldUntilMs.clear()
5244
- this.#deliveryGaps.reset()
5736
+ for (const estimator of Object.values(this.#deliveryGaps)) estimator.reset()
5245
5737
  this.#pendingWorkerCleanups.clear()
5246
5738
  this.#pendingWorkerCleanupClients.clear()
5247
5739
  for (const bound of this.#pendingWorkerCleanupBounds.values()) clearTimeout(bound.handle)
@@ -5292,6 +5784,7 @@ export class FECManager {
5292
5784
  this.#highestSbn.clear()
5293
5785
  this.#sourceFrontiers.clear()
5294
5786
  this.#isoLocators.clear()
5787
+ this.#runAnchors.clear()
5295
5788
  this.#sourceAnchors.clear()
5296
5789
  this.#trackConfigs.clear()
5297
5790
  this.#fecDecoders.clear()