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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +5 -2
  2. package/dist/block-policy.d.ts +88 -16
  3. package/dist/block-policy.d.ts.map +1 -1
  4. package/dist/block-policy.js +164 -56
  5. package/dist/block-policy.js.map +3 -3
  6. package/dist/browser-runtime.js +2163 -303
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +40 -1
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +163 -10
  11. package/dist/carp-catalog.js.map +4 -4
  12. package/dist/catalog-fec-params.d.ts +1 -1
  13. package/dist/catalog-fec-params.d.ts.map +1 -1
  14. package/dist/catalog-fec-params.js +48 -1
  15. package/dist/catalog-fec-params.js.map +3 -3
  16. package/dist/catalog-network-source.js +34 -0
  17. package/dist/catalog-network-source.js.map +3 -3
  18. package/dist/cmaf-block-assembler.js +92 -1
  19. package/dist/cmaf-block-assembler.js.map +2 -2
  20. package/dist/codec-utils.d.ts.map +1 -1
  21. package/dist/codec-utils.js +92 -1
  22. package/dist/codec-utils.js.map +2 -2
  23. package/dist/delivery-catalog.js +68 -0
  24. package/dist/delivery-catalog.js.map +4 -4
  25. package/dist/delta-fallback-config.js +39 -1
  26. package/dist/delta-fallback-config.js.map +4 -4
  27. package/dist/fec-manager.d.ts +222 -21
  28. package/dist/fec-manager.d.ts.map +1 -1
  29. package/dist/fec-manager.js +875 -131
  30. package/dist/fec-manager.js.map +4 -4
  31. package/dist/fec-state.d.ts +17 -5
  32. package/dist/fec-state.d.ts.map +1 -1
  33. package/dist/fec-state.js +41 -1
  34. package/dist/fec-state.js.map +3 -3
  35. package/dist/fec-worker-setup.js +34 -0
  36. package/dist/fec-worker-setup.js.map +3 -3
  37. package/dist/held-layer-admission.js +34 -0
  38. package/dist/held-layer-admission.js.map +3 -3
  39. package/dist/index.d.ts +6 -5
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +9 -1
  42. package/dist/index.js.map +2 -2
  43. package/dist/iso-block-locator.d.ts +55 -13
  44. package/dist/iso-block-locator.d.ts.map +1 -1
  45. package/dist/iso-block-locator.js +142 -25
  46. package/dist/iso-block-locator.js.map +3 -3
  47. package/dist/media-router.js.map +1 -1
  48. package/dist/mfu-reassembler.js +34 -0
  49. package/dist/mfu-reassembler.js.map +3 -3
  50. package/dist/mmtp-container-parser.d.ts +72 -10
  51. package/dist/mmtp-container-parser.d.ts.map +1 -1
  52. package/dist/mmtp-container-parser.js +260 -18
  53. package/dist/mmtp-container-parser.js.map +3 -3
  54. package/dist/mmtp-container-parser.no-modules.js +411 -34
  55. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  56. package/dist/mmtp-decode-pipeline.js +260 -18
  57. package/dist/mmtp-decode-pipeline.js.map +3 -3
  58. package/dist/mmtp-fec-session.js +34 -0
  59. package/dist/mmtp-fec-session.js.map +3 -3
  60. package/dist/mmtp-mode-selection.d.ts +48 -0
  61. package/dist/mmtp-mode-selection.d.ts.map +1 -0
  62. package/dist/mmtp-mode-selection.js +79 -0
  63. package/dist/mmtp-mode-selection.js.map +7 -0
  64. package/dist/mmtp-router.d.ts +94 -16
  65. package/dist/mmtp-router.d.ts.map +1 -1
  66. package/dist/mmtp-router.js +754 -78
  67. package/dist/mmtp-router.js.map +4 -4
  68. package/dist/multicast-auth-catalog.js +42 -2
  69. package/dist/multicast-auth-catalog.js.map +3 -3
  70. package/dist/multicast-input.js +42 -2
  71. package/dist/multicast-input.js.map +3 -3
  72. package/dist/multicast-manager.d.ts +121 -4
  73. package/dist/multicast-manager.d.ts.map +1 -1
  74. package/dist/multicast-manager.js +1774 -248
  75. package/dist/multicast-manager.js.map +4 -4
  76. package/dist/multicast-transport.js +70 -2
  77. package/dist/multicast-transport.js.map +4 -4
  78. package/dist/multicast-unwrap.js +34 -0
  79. package/dist/multicast-unwrap.js.map +3 -3
  80. package/dist/no-modules.d.ts +1 -0
  81. package/dist/no-modules.d.ts.map +1 -1
  82. package/dist/no-modules.js +415 -35
  83. package/dist/no-modules.js.map +4 -4
  84. package/dist/phase14-catalog-override.d.ts +2 -1
  85. package/dist/phase14-catalog-override.d.ts.map +1 -1
  86. package/dist/phase14-catalog-override.js +69 -2
  87. package/dist/phase14-catalog-override.js.map +3 -3
  88. package/dist/repair-fetch.d.ts +38 -8
  89. package/dist/repair-fetch.d.ts.map +1 -1
  90. package/dist/repair-fetch.js +336 -27
  91. package/dist/repair-fetch.js.map +3 -3
  92. package/dist/repair-layer-subscriptions.js +34 -0
  93. package/dist/repair-layer-subscriptions.js.map +3 -3
  94. package/dist/signaling.js +34 -0
  95. package/dist/signaling.js.map +3 -3
  96. package/dist/timestamp-codec.js +34 -0
  97. package/dist/timestamp-codec.js.map +3 -3
  98. package/dist/track-session.d.ts.map +1 -1
  99. package/dist/track-session.js +1 -0
  100. package/dist/track-session.js.map +2 -2
  101. package/dist/wasm-mfu-reassembler.js +34 -0
  102. package/dist/wasm-mfu-reassembler.js.map +3 -3
  103. package/dist/wasm-mmtp-container-parser.js +260 -18
  104. package/dist/wasm-mmtp-container-parser.js.map +3 -3
  105. package/package.json +5 -5
  106. package/schemas/catalog.schema.json +2 -2
  107. package/src/block-policy.ts +324 -83
  108. package/src/carp-catalog.ts +165 -5
  109. package/src/catalog-fec-params.ts +1 -0
  110. package/src/codec-utils.ts +121 -1
  111. package/src/fec-manager.ts +835 -66
  112. package/src/fec-state.ts +21 -5
  113. package/src/index.ts +25 -0
  114. package/src/iso-block-locator.ts +148 -31
  115. package/src/mmtp-container-parser.ts +259 -24
  116. package/src/mmtp-mode-selection.ts +80 -0
  117. package/src/mmtp-router.ts +774 -86
  118. package/src/multicast-manager.ts +262 -16
  119. package/src/no-modules.ts +3 -0
  120. package/src/phase14-catalog-override.ts +14 -3
  121. package/src/repair-fetch.ts +389 -50
  122. package/src/track-session.ts +3 -0
  123. package/test-vectors/catalog/README.md +36 -2
  124. package/test-vectors/catalog/mmtp-siblings/ambiguous-sibling.json +158 -0
  125. package/test-vectors/catalog/mmtp-siblings/ladder-bitrate-only.json +231 -0
  126. package/test-vectors/catalog/mmtp-siblings/ladder-four-rungs.json +405 -0
  127. package/test-vectors/catalog/mmtp-siblings/ladder-other-names.json +231 -0
  128. package/test-vectors/catalog/mmtp-siblings/mmtp-mode-unknown.json +143 -0
  129. package/test-vectors/catalog/mmtp-siblings/multicast-endpoint-lists-datagram-track.json +143 -0
  130. package/test-vectors/catalog/mmtp-siblings/no-sibling.json +79 -0
  131. package/test-vectors/catalog/mmtp-siblings/rendition-mismatch.json +143 -0
  132. package/test-vectors/catalog/mmtp-siblings/stream-delivery-mode.json +143 -0
  133. package/test-vectors/catalog/mmtp-siblings/timescale-mismatch.json +143 -0
  134. package/test-vectors/catalog/mmtp-siblings/valid-pair.json +142 -0
  135. package/test-vectors/catalog/section-codes.json +3 -3
  136. package/test-vectors/catalog-validation.json +266 -7
  137. package/test-vectors/moq/mmtp-mode-selection.json +259 -0
@@ -24,7 +24,7 @@ import {
24
24
  type MoqRepairFrame,
25
25
  } from "@blockcast/mmt-base";
26
26
  import { USER_AGENT_VERIFIED } from "@blockcast/mmt-transport";
27
- import type { FECManager, IsoHeldSource, WasmFecDecoder } from "./fec-manager.js";
27
+ import type { FECManager, IsoHeldSource, IsoSpanFailure, RebuiltSourceFeed, WasmFecDecoder } from "./fec-manager.js";
28
28
  import type { IsoPlacedSource, IsoRepairPlacement } from "./iso-block-locator.js";
29
29
  import { isMfuReassemblyError } from "./mfu-reassembler.js";
30
30
  import type {
@@ -214,6 +214,92 @@ export interface KeyframeOverlayStats {
214
214
  restarts: number;
215
215
  unsequencedDropped: number;
216
216
  protectedDropped: number;
217
+ /** Rebuilt packets fed to their base block's decoder (joint decoding). */
218
+ baseFed: number;
219
+ /** Rebuilt packets the base never took: no base SS_ID could be determined,
220
+ * or only the overlay's own evidence did, which anchors the release gate
221
+ * alone (BLO-52085). */
222
+ baseUndetermined: number;
223
+ }
224
+
225
+ /**
226
+ * The newest received overlay member of one MPU. `psnOffset` (overlay SS_ID
227
+ * minus wire packet_sequence_number) restores a rebuilt packet's wire
228
+ * sequence; the member's own SS_IDs anchor a rebuilt packet's base SS_ID
229
+ * (overlayBaseSsId).
230
+ */
231
+ interface OverlayMemberAnchor {
232
+ readonly psnOffset: number;
233
+ readonly overlaySsId: number;
234
+ /** The member's base SS_ID, from its Source FEC Payload ID. */
235
+ readonly baseSsId?: number;
236
+ }
237
+
238
+ /**
239
+ * The base SS_ID of a packet the overlay rebuilt at `overlaySsId`, which an
240
+ * overlay coordinate alone never yields (draft-ramadan-moq-mmt-02 7.1). Both
241
+ * SS_IDs advance by one per packet along a run of consecutive overlay
242
+ * members, so base minus overlay SS_ID is the anchor's along a run the wire
243
+ * proves to be all members: one over which the rebuilt packet's protected
244
+ * packet_sequence_number (`headerPsn`) advanced from the anchor's exactly as
245
+ * the overlay SS_ID did (`restoredPsn`), so no other packet lies inside it.
246
+ * A hop that re-stamped packet_sequence_number after protection fails the
247
+ * test. Undefined when it fails.
248
+ */
249
+ function overlayBaseSsId(
250
+ anchor: OverlayMemberAnchor,
251
+ overlaySsId: number,
252
+ restoredPsn: number,
253
+ headerPsn: number,
254
+ ): number | undefined {
255
+ if (anchor.baseSsId === undefined || headerPsn !== restoredPsn) return undefined;
256
+ return serial32Add(anchor.baseSsId, (overlaySsId - anchor.overlaySsId) | 0);
257
+ }
258
+
259
+ /**
260
+ * The base SS_ID of a rebuilt packet no received member of its MPU anchors,
261
+ * from its protected packet_sequence_number (`headerPsn`). SS_ID advances by
262
+ * one per FEC source packet (mmt-02 7.1) and psn by one per packet, so on a
263
+ * track whose every packet is an FEC source packet the sender keeps
264
+ * SS_ID - psn fixed. `offset` (SS_ID - psn of the stream's latest received
265
+ * source) is that sender value while evidence showed it (`unstampedOffset`):
266
+ * a base recovery's (#unstampedSsIdSeqOffsetByStream), or the overlay's
267
+ * alone (#overlayUnstampedSsIdSeqOffsetByStream). A hop that re-stamps psn
268
+ * moves the offset away from the one shown, which voids it, as does a packet
269
+ * with no SS_ID between the packet that showed it and the latest received
270
+ * source (the shown span). Undefined without both.
271
+ * ponytail: exact only if every packet from the rebuilt one to the latest
272
+ * received source is an FEC source packet, as FFmpeg's muxer sends a track
273
+ * it protects. fec-core 8.3 lets a publisher leave one unprotected
274
+ * (FEC Type 0): outside the shown span it goes unseen, and each one puts the
275
+ * rebuilt packet a base slot off. If such a publisher appears, have mmt-02
276
+ * require FEC Type 1 across a protected track, or refuse a headerPsn outside
277
+ * the shown span.
278
+ */
279
+ function unstampedBaseSsId(
280
+ offset: number | undefined,
281
+ unstampedOffset: number | undefined,
282
+ headerPsn: number,
283
+ ): number | undefined {
284
+ if (offset === undefined || offset !== unstampedOffset) return undefined;
285
+ return (headerPsn + offset) >>> 0;
286
+ }
287
+
288
+ /** Base SS_IDs of overlay-routed packets kept per stream (see OverlayToBase). */
289
+ const OVERLAY_ROUTED_LIMIT = 1024;
290
+ /** Rebuilt sources kept per stream for a base block no repair stated yet. */
291
+ const OVERLAY_PENDING_LIMIT = 256;
292
+
293
+ /**
294
+ * One stream's keyframe-overlay recoveries on their way into its base
295
+ * decoder (joint decoding, BLO-52085).
296
+ */
297
+ interface OverlayToBase {
298
+ /** Base SS_IDs of the packets an overlay recovery routed (as media, or held
299
+ * for their FT=1): a base recovery does not route them a second time. */
300
+ readonly routed: Set<number>;
301
+ /** Rebuilt sources, by base SS_ID, whose base block no repair stated yet. */
302
+ readonly pending: Map<number, Uint8Array>;
217
303
  }
218
304
 
219
305
  interface OverlayInstance {
@@ -225,20 +311,40 @@ interface OverlayInstance {
225
311
  readonly k: number;
226
312
  /** The newest overlay symbol seen: its overlay SS_ID and wire sequence. */
227
313
  last?: { ssId: number; psn: number };
228
- /** MPU sequence number → overlay SS_ID − wire packet_sequence_number. */
229
- readonly offsets: Map<number, number>;
314
+ /** MPU sequence number → its newest received member. */
315
+ readonly offsets: Map<number, OverlayMemberAnchor>;
230
316
  /** Overlay blocks a MoQ symbol fed (multicast-02 7.2.7). */
231
317
  readonly moqBlocks: Set<number>;
318
+ /** Overlay SS_ID → protected packet_sequence_number of each packet rebuilt
319
+ * with no base SS_ID, until its base copy lands (#feedOverlaySource). */
320
+ readonly rebuilt: Map<number, number>;
232
321
  }
233
322
 
234
323
  /** Offsets kept per overlay, one per MPU: a keyframe's fragments share one. */
235
324
  const OVERLAY_OFFSET_MPUS = 16;
325
+ /** Rebuilt packets kept per overlay whose base copy has not landed (OverlayInstance.rebuilt).
326
+ * ponytail: this cap is the only eviction for a base copy that never lands
327
+ * (oldest first; an overlay epoch reset clears all). Bound records by SS_ID
328
+ * age instead if stale ones ever crowd out live ones. */
329
+ const OVERLAY_REBUILT_LIMIT = 256;
236
330
  /** A MoQ-fed overlay block is forgotten once it starts this many K_overlay
237
331
  * behind the newest overlay SS_ID: the overlay locator, which keeps a fixed
238
332
  * few blocks (no catalog timing), has retired it long before, so it can no
239
333
  * longer recover and be admitted as multicast-only. */
240
334
  const OVERLAY_MOQ_HORIZON_BLOCKS = 64;
241
335
 
336
+ /**
337
+ * Where a packet entered this router. `'multicast'` and `'moq'` are the
338
+ * transport attribution every frame carries (`MmtpSourcePath`);
339
+ * `'moq-datagram'` is an "mfu-datagram" subscription (mmt-02 4.3.1): a lossy
340
+ * unicast leg, so it takes every loss rule a multicast datagram takes (FEC
341
+ * holds, deadlines, startup partial blocks, the publisher-restart epoch,
342
+ * 7.2.7 unicast admission) and none of the multicast socket's (ingress
343
+ * flows, the ordered-relay frontier). Frames it yields are attributed
344
+ * `'moq'` and their provenance `'mixed'`: the bytes crossed QUIC.
345
+ */
346
+ export type MmtpIngestSource = MmtpSourcePath | "moq-datagram";
347
+
242
348
  export interface MmtpIngressContext {
243
349
  tracks: readonly Readonly<{ name: string; packetId: number }>[];
244
350
  /**
@@ -579,6 +685,7 @@ interface StreamLedgers {
579
685
  * the pair.
580
686
  */
581
687
  readonly duplicates: StreamDuplicateLedgers;
688
+ readonly overlayToBase: OverlayToBase;
582
689
  }
583
690
 
584
691
  const NO_FEC_MANAGER_HORIZON: DuplicateHorizon = Object.freeze({
@@ -666,6 +773,17 @@ export interface FECManagerLike {
666
773
  catalogTrackName?: string,
667
774
  ): Uint8Array | null;
668
775
 
776
+ /** Feed a source another FEC instance over the same packets rebuilt (a
777
+ * keyframe overlay) to its base block, which a repair must already have
778
+ * stated; not a network arrival (FECManager.feedRebuiltSourceSymbol).
779
+ * Optional: without it the overlay and the base decode apart. */
780
+ feedRebuiltSourceSymbol?(
781
+ packetId: number,
782
+ ssId: number,
783
+ symbolData: Uint8Array,
784
+ catalogTrackName?: string,
785
+ ): RebuiltSourceFeed;
786
+
669
787
  /** How long ago the stream's oldest open block with an FEC deadline took its first symbol (optional). */
670
788
  oldestOpenBlockAgeMs?(packetId: number, catalogTrackName: string): number | undefined;
671
789
 
@@ -675,6 +793,8 @@ export interface FECManagerLike {
675
793
  /** fec-01 4.5: refuse a repair header whose block length the track's scheme
676
794
  * forbids, before it touches block state (optional). */
677
795
  admitRepairBlockLength?(packetId: number, ssbLength: number, rsbLength: number, rsId: number): boolean;
796
+ /** Count a repair packet dropped because its owning track could not be named (optional). */
797
+ countUnresolvedRepairOwner?(reason: "unregistered" | "ownerAbsent" | "ownerAmbiguous"): void;
678
798
  /** core-00 7.5 / mmt-02 7.3 admission of one repair object of the named
679
799
  * instance; counts a discard per instance (optional). */
680
800
  admitRepairObject?(
@@ -716,13 +836,16 @@ export interface FECManagerLike {
716
836
  /** Delivery-gap sample for one multicast packet (FECManager.noteMulticastArrival). */
717
837
  noteMulticastArrival?(packetId: number, packetSequenceNumber: number): void;
718
838
 
839
+ /** Delivery-gap sample for one packet of a lossy path, keyed by path (FECManager.noteArrival). */
840
+ noteArrival?(path: "multicast" | "moq-datagram", packetId: number, packetSequenceNumber: number): void;
841
+
719
842
  /** Record a transport symbol for first-arrival-wins dedup and path counters. */
720
843
  feedSymbolFromSource(
721
844
  packetId: number,
722
845
  sbn: number,
723
846
  esi: number,
724
847
  data: Uint8Array,
725
- source: "multicast" | "moq",
848
+ source: MmtpIngestSource,
726
849
  catalogTrackName?: string,
727
850
  ): boolean;
728
851
 
@@ -737,13 +860,14 @@ export interface FECManagerLike {
737
860
 
738
861
  /** Track a first-arrival network source symbol for block completion and
739
862
  * classification. Refreshes the inactivity deadline and marks clean when
740
- * K arrive. */
863
+ * K arrive. `held`: a source held unplaced since it arrived, placed now. */
741
864
  trackBlock(
742
865
  sbn: number,
743
866
  packetId: number,
744
867
  catalogTrackName: string | undefined,
745
868
  esi: number,
746
869
  evidence: SourceSymbolEvidence,
870
+ held?: boolean,
747
871
  ): void;
748
872
 
749
873
  /** True once the packetId has a per-track FEC configuration. */
@@ -782,16 +906,32 @@ export interface FECManagerLike {
782
906
  catalogTrackName?: string,
783
907
  ): { mode: ClassifierMode; reason: ClassifierReason | null };
784
908
 
785
- /** Whether an MPU boundary still bounds the stream's RAPs. */
786
- mpuBoundsRapsFor?(packetId: number, catalogTrackName?: string): boolean;
909
+ /**
910
+ * Whether an MPU boundary still bounds the stream's RAPs; given a gap
911
+ * inside one MPU, whether the catalog keyframe interval also rules a
912
+ * keyframe out of it and no source held in the gap carries part of a RAP
913
+ * (FECManager.mpuBoundsRapsFor).
914
+ */
915
+ mpuBoundsRapsFor?(
916
+ packetId: number,
917
+ catalogTrackName?: string,
918
+ gap?: {
919
+ readonly mpu: number;
920
+ readonly from?: AuthoredTiming;
921
+ readonly to?: AuthoredTiming;
922
+ readonly fromSsId?: number;
923
+ readonly toSsId?: number;
924
+ },
925
+ ): boolean;
787
926
 
788
- /** Record a RAP released in order (RAP-spacing invariant). */
927
+ /** Record a RAP released in order (RAP-spacing invariant; its decode time anchors the MPU's keyframe instants). */
789
928
  noteReleasedRap?(
790
929
  packetId: number,
791
930
  catalogTrackName: string | undefined,
792
931
  mpu: number,
793
932
  presentationTime: bigint,
794
933
  mediaTimescale: number,
934
+ decodeTime?: bigint,
795
935
  ): void;
796
936
 
797
937
  /** Refresh the block inactivity deadline after accepted repair progress. */
@@ -859,6 +999,16 @@ export interface FECManagerLike {
859
999
  fromSsId: number,
860
1000
  toSsId: number,
861
1001
  ): readonly number[] | null;
1002
+ /** iso-ssbg1-v1: how long a frame that arrived at `arrivedAtMs` waits once only a late source can fill the SS_IDs before it, longer when they may hold a RAP an installed keyframe overlay can still rebuild, or behind a run no repair has delimited until its FEC deadline (FECManager.isoRepairlessWaitMs). */
1003
+ isoRepairlessWaitMs?(
1004
+ packetId: number,
1005
+ catalogTrackName: string | undefined,
1006
+ fromSsId: number,
1007
+ toSsId: number,
1008
+ rapMayHide?: boolean,
1009
+ rapNext?: boolean,
1010
+ arrivedAtMs?: number,
1011
+ ): number | undefined;
862
1012
 
863
1013
 
864
1014
  /**
@@ -867,6 +1017,8 @@ export interface FECManagerLike {
867
1017
  * how long the router keeps a stream's duplicate ledgers.
868
1018
  */
869
1019
  blockLifetimeMsForPacket?(packetId: number): number | undefined;
1020
+ /** Duplicate-ledger retention an "mfu-datagram" leg needs (FECManager.datagramLegLedgerRetentionMsForPacket). */
1021
+ datagramLegLedgerRetentionMsForPacket?(packetId: number): number | undefined;
870
1022
 
871
1023
  /** FEC symbol size T in bytes (0 = unknown / no FEC). */
872
1024
  readonly symbolSize: number;
@@ -913,6 +1065,7 @@ export interface FECManagerLike {
913
1065
  packetId: number,
914
1066
  catalogTrackName: string | undefined,
915
1067
  blockClass: BlockClass,
1068
+ span?: IsoSpanFailure,
916
1069
  ) => void)
917
1070
  | null;
918
1071
 
@@ -935,9 +1088,10 @@ export interface FECManagerLike {
935
1088
  /**
936
1089
  * Classification evidence carried by one first-arrival network source
937
1090
  * packet: the MMTP header R bit and the MPU / data-unit identity it states
938
- * (movie fragment, sample, DU offset). `idx` is the 0-based sample position
939
- * (`sample_number` is 1-based). The packet_sequence_number rides along for
940
- * FECManager's forward-jump bound.
1091
+ * (movie fragment, sample, DU offset). `idx` is the sample's 0-based
1092
+ * position within its movie fragment (`sample_number` is 1-based);
1093
+ * BlockClassifier turns it and the fragment into an MPU position. The
1094
+ * packet_sequence_number rides along for FECManager's forward-jump bound.
941
1095
  */
942
1096
  function sourceSymbolEvidence(
943
1097
  packet: Uint8Array,
@@ -981,6 +1135,7 @@ export class MmtpRouter {
981
1135
  readonly #provenance = new Map<string, ProvenanceEntry>();
982
1136
  #onFlowProtected: ((flow: string) => void) | null = null;
983
1137
  #unadmittedListedDrops = 0;
1138
+ #admittedSourceDatagrams = 0;
984
1139
  #unlistedRepairSetAside = 0;
985
1140
  readonly #assistBlocks = new Map<string, AssistBlock>();
986
1141
  readonly #assistFailures = new Map<string, number>();
@@ -997,6 +1152,20 @@ export class MmtpRouter {
997
1152
  /** The flow whose receiver admitted a stream's source datagrams, by packetId then catalog track name: recovered packets answer to it. */
998
1153
  readonly #provenanceStreamFlow = new Map<number, Map<string | undefined, string>>();
999
1154
  #unregisteredFlowDrops = 0;
1155
+ /** "mfu-datagram" leg packets of a packet id the ingress does not name (never the signaling flow). */
1156
+ #datagramLegIngressDrops = 0;
1157
+ /** "mfu-datagram" leg packets of the signaling flow (packet id 0): expected, one per group. */
1158
+ #datagramLegSignalingPackets = 0;
1159
+ /**
1160
+ * The streams a live "mfu-datagram" leg has fed, catalog track names by
1161
+ * packet id: their ledgers and release gate take the leg's bounds. A stream
1162
+ * leaves when its leg does: `endDatagramLeg`, `resetTrack`, `dispose`, or
1163
+ * the first multicast packet of its packet id (the ordered switch retires
1164
+ * the leg first). The "mfu" sibling shares the packet id, never the name.
1165
+ */
1166
+ readonly #datagramLegStreams = new Map<number, Set<string | undefined>>();
1167
+ /** The leg's presentation budget (setDatagramLegPresentationBudget), or null: no presentation bound. */
1168
+ #datagramLegPresentationBudgetMs: ((packetId: number, catalogTrackName?: string) => number) | null = null;
1000
1169
  #ambiguousRecoveredDrops = 0;
1001
1170
 
1002
1171
  // Temp state set by #processMMTP before calling parser.feed(),
@@ -1049,6 +1218,26 @@ export class MmtpRouter {
1049
1218
  * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
1050
1219
  */
1051
1220
  #ssIdSeqOffsetByStream = new Map<string, number>();
1221
+ /**
1222
+ * Per stream, the SS_ID offset at which a base recovery last showed the
1223
+ * sender's own packet_sequence_number: a recovered packet's header psn
1224
+ * equal to its SS_ID minus that offset. While it equals the stream's
1225
+ * current offset, no hop re-stamps the stream, and a packet's protected psn
1226
+ * names its base SS_ID within unstampedBaseSsId's limits (joint decoding of
1227
+ * an MPU no member of which arrived).
1228
+ */
1229
+ #unstampedSsIdSeqOffsetByStream = new Map<string, number>();
1230
+ /**
1231
+ * The same, shown by the overlay alone, before any base recovery did: a
1232
+ * packet it rebuilt whose base copy carries its protected psn
1233
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
1234
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
1235
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
1236
+ * make the base drop a late base copy of a keyframe the overlay never
1237
+ * finished, and lift a block's late-source cut, which nothing before
1238
+ * this offset did.
1239
+ */
1240
+ #overlayUnstampedSsIdSeqOffsetByStream = new Map<string, number>();
1052
1241
  /**
1053
1242
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
1054
1243
  * not parsed, typically because its overlap copy was parsed first
@@ -1097,6 +1286,7 @@ export class MmtpRouter {
1097
1286
  packetId: number,
1098
1287
  catalogTrackName: string | undefined,
1099
1288
  blockClass: BlockClass,
1289
+ span?: IsoSpanFailure,
1100
1290
  ) => void)
1101
1291
  | null = null;
1102
1292
  /** Typed observer of every gap decision the release gate makes. */
@@ -1106,6 +1296,8 @@ export class MmtpRouter {
1106
1296
  // end: a synchronous recovery completes its block BEFORE routing the
1107
1297
  // recovered frames, and releasing a held gap in between would strand them.
1108
1298
  #fecPokeDepth = 0;
1299
+ /** FecReleaseGate.wakeAt timers, by media stream key. */
1300
+ readonly #fecWakes = new Map<string, { atMs: number; timer: ReturnType<typeof setTimeout> }>();
1109
1301
  #pendingFecPokes = new Map<string, { packetId: number; catalogTrackName?: string }>();
1110
1302
  // ── Phase 14: per-role packetId dispatch (D-26, D-27, D-28) ───────
1111
1303
  /** Maps packetId → TrackRole. Default: 'single' when absent (legacy path). */
@@ -1126,7 +1318,7 @@ export class MmtpRouter {
1126
1318
  #restampedStreams = new Set<string>();
1127
1319
  #overlayStats: KeyframeOverlayStats = {
1128
1320
  repairDropped: 0, ownerRefused: 0, recovered: 0, restarts: 0,
1129
- unsequencedDropped: 0, protectedDropped: 0,
1321
+ unsequencedDropped: 0, protectedDropped: 0, baseFed: 0, baseUndetermined: 0,
1130
1322
  };
1131
1323
  /** Callback fired when a delta-track FEC block completes or fails. */
1132
1324
  #onDeltaBlockCompleteCb:
@@ -1194,6 +1386,7 @@ export class MmtpRouter {
1194
1386
  packetId: number,
1195
1387
  catalogTrackName: string | undefined,
1196
1388
  blockClass: BlockClass,
1389
+ span?: IsoSpanFailure,
1197
1390
  ) => void;
1198
1391
  /** Internal gap-decision sink owned by the composing transport. */
1199
1392
  onFrameGap?: (decision: FrameGapDecision) => void;
@@ -1427,6 +1620,7 @@ export class MmtpRouter {
1427
1620
  packetId: number,
1428
1621
  catalogTrackName: string | undefined,
1429
1622
  blockClass: BlockClass,
1623
+ span?: IsoSpanFailure,
1430
1624
  ) => void)
1431
1625
  | undefined,
1432
1626
  ): void {
@@ -1479,6 +1673,7 @@ export class MmtpRouter {
1479
1673
  packetId: number,
1480
1674
  catalogTrackName: string | undefined,
1481
1675
  blockClass: BlockClass,
1676
+ span?: IsoSpanFailure,
1482
1677
  ) => {
1483
1678
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
1484
1679
  if (
@@ -1487,8 +1682,13 @@ export class MmtpRouter {
1487
1682
  ) {
1488
1683
  this.#onDeltaBlockCompleteCb?.(packetId, true); // failed=true
1489
1684
  }
1490
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
1491
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
1685
+ if (span === undefined) {
1686
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
1687
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
1688
+ } else {
1689
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
1690
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
1691
+ }
1492
1692
  };
1493
1693
  }
1494
1694
  }
@@ -1518,10 +1718,14 @@ export class MmtpRouter {
1518
1718
  if (blockSpanMs === undefined || blockLifetimeMs === undefined) return NO_FEC_GEOMETRY_HORIZON;
1519
1719
  // FECManager reports 0 for a stream the catalog gave no block span.
1520
1720
  if (blockSpanMs === 0) return NO_BLOCK_SPAN_HORIZON;
1521
- return {
1522
- kind: "fec-horizon",
1523
- retentionMs: duplicateRetentionMs({ blockSpanMs, blockLifetimeMs }),
1524
- };
1721
+ let retentionMs = duplicateRetentionMs({ blockSpanMs, blockLifetimeMs });
1722
+ // An "mfu-datagram" leg's datagrams may trail a joining FETCH by a whole
1723
+ // group: remember at least span + tolerance + group, or the lag reads as
1724
+ // a publisher restart (mmt-02 4.3.1, 6.1 step 3).
1725
+ if (this.#datagramLegStreams.has(packetId)) {
1726
+ retentionMs = Math.max(retentionMs, fec.datagramLegLedgerRetentionMsForPacket?.(packetId) ?? 0);
1727
+ }
1728
+ return { kind: "fec-horizon", retentionMs };
1525
1729
  }
1526
1730
 
1527
1731
  /**
@@ -1541,8 +1745,9 @@ export class MmtpRouter {
1541
1745
 
1542
1746
  /**
1543
1747
  * FEC-recovered source symbols whose reconstructed header named a
1544
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
1545
- * a hop re-stamped the sequence after the sender protected the packet.
1748
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
1749
+ * or, rebuilt by the overlay, than their base copy carries: a hop
1750
+ * re-stamped the sequence after the sender protected the packet.
1546
1751
  */
1547
1752
  get restampedRecoveredSequenceCount(): number {
1548
1753
  return this.#restampedRecoveredSeqs;
@@ -1766,6 +1971,11 @@ export class MmtpRouter {
1766
1971
  ): CmafBlockAssembler {
1767
1972
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
1768
1973
  const previous = this.#mseAssemblers.get(assemblerKey);
1974
+ // The new assembler has no source cursor: the release gate must not hold
1975
+ // an overlay keyframe for one either (FecReleaseSequencer.#cursorPassed).
1976
+ // What the gate holds that unanchored had already released to the
1977
+ // assembler being replaced goes to it first, and plays with its flush.
1978
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
1769
1979
  if (previous) {
1770
1980
  previous.flush();
1771
1981
  previous.dispose();
@@ -1837,6 +2047,7 @@ export class MmtpRouter {
1837
2047
  packetId: number,
1838
2048
  catalogTrackName: string | undefined,
1839
2049
  blockClass: BlockClass,
2050
+ span?: IsoSpanFailure,
1840
2051
  ) => void,
1841
2052
  ): void {
1842
2053
  this.#onBlockFailed = cb;
@@ -1941,7 +2152,7 @@ export class MmtpRouter {
1941
2152
  const leg = this.#overlayLegs.get(repairPacketId);
1942
2153
  if (!leg) throw new Error(`[MmtpRouter] packetId=${repairPacketId} is no known keyframe-overlay leg`);
1943
2154
  const inst: OverlayInstance = {
1944
- repairPacketId, streamName, leg: { ...leg }, fec, k, offsets: new Map(), moqBlocks: new Set(),
2155
+ repairPacketId, streamName, leg: { ...leg }, fec, k, offsets: new Map(), moqBlocks: new Set(), rebuilt: new Map(),
1945
2156
  };
1946
2157
  this.#overlays.set(repairPacketId, inst);
1947
2158
  return () => {
@@ -1976,6 +2187,13 @@ export class MmtpRouter {
1976
2187
  */
1977
2188
  resetKeyframeOverlays(sourcePacketId: number, catalogTrackName?: string): void {
1978
2189
  for (const inst of this.#overlaysForSource(sourcePacketId, catalogTrackName)) this.#resetOverlay(inst);
2190
+ // The base restarted with it: base SS_IDs kept for joint decoding name
2191
+ // the old epoch's packets.
2192
+ for (const [name, stream] of this.#streams.get(sourcePacketId) ?? []) {
2193
+ if (catalogTrackName !== undefined && name !== catalogTrackName) continue;
2194
+ stream.overlayToBase.routed.clear();
2195
+ stream.overlayToBase.pending.clear();
2196
+ }
1979
2197
  }
1980
2198
 
1981
2199
  #resetOverlay(inst: OverlayInstance): void {
@@ -1983,6 +2201,7 @@ export class MmtpRouter {
1983
2201
  inst.last = undefined;
1984
2202
  inst.offsets.clear();
1985
2203
  inst.moqBlocks.clear();
2204
+ inst.rebuilt.clear();
1986
2205
  }
1987
2206
 
1988
2207
  #overlaysForSource(sourcePacketId: number, catalogTrackName: string | undefined): OverlayInstance[] {
@@ -2012,7 +2231,7 @@ export class MmtpRouter {
2012
2231
  repairPacketId: number,
2013
2232
  packet: Uint8Array,
2014
2233
  header: MMTPHeader,
2015
- source: "multicast" | "moq",
2234
+ source: MmtpIngestSource,
2016
2235
  ): void {
2017
2236
  const repair = inst ? parseMoqRepairFrameWithHeader(packet, header) : null;
2018
2237
  if (!inst || !repair) {
@@ -2028,7 +2247,7 @@ export class MmtpRouter {
2028
2247
  const blockStart = placement.block.start;
2029
2248
  if (placement.span !== undefined) this.#replayOverlaySources(inst, placement.span.block.start, placement.span.placed);
2030
2249
  this.#replayOverlaySources(inst, blockStart, placement.placed);
2031
- if (source === "moq") this.#noteOverlayMoqBlock(inst, blockStart);
2250
+ if (source !== "multicast") this.#noteOverlayMoqBlock(inst, blockStart);
2032
2251
  const alreadyCompleted = fec.isBlockCompleted(blockStart, pid, name);
2033
2252
  const recovered = fec.feedRepairSymbol(pid, repair.ssStart, repair.ssbLength, repair.rsId, repair.symbolData, name);
2034
2253
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, blockStart, recovered);
@@ -2041,7 +2260,7 @@ export class MmtpRouter {
2041
2260
  ): void {
2042
2261
  const { fec, repairPacketId: pid, streamName: name } = inst;
2043
2262
  for (const { ssId, payload } of placed) {
2044
- if (payload.source === "moq") this.#noteOverlayMoqBlock(inst, blockStart);
2263
+ if (payload.source !== "multicast") this.#noteOverlayMoqBlock(inst, blockStart);
2045
2264
  if (payload.oversized) continue;
2046
2265
  const alreadyCompleted = fec.isBlockCompleted(blockStart, pid, name);
2047
2266
  const recovered = fec.feedSourceSymbol(pid, ssId, payload.symbolData, name);
@@ -2053,7 +2272,15 @@ export class MmtpRouter {
2053
2272
  * A source packet that carries a 0x8B01 overlay SS_ID is also a symbol of
2054
2273
  * every overlay installed for its source, at that SS_ID, with the bytes the
2055
2274
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
2056
- * included (7.1, 7.4.3).
2275
+ * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
2276
+ * FEC reads it.
2277
+ *
2278
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
2279
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
2280
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
2281
+ * the stream unstamped at the SS_ID offset it states, for the release gate
2282
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
2283
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
2057
2284
  */
2058
2285
  #feedOverlaySource(
2059
2286
  packetId: number,
@@ -2062,17 +2289,36 @@ export class MmtpRouter {
2062
2289
  header: MMTPHeader,
2063
2290
  sequenceNumber: number,
2064
2291
  rapFlag: boolean,
2065
- source: MmtpSourcePath,
2292
+ source: MmtpIngestSource,
2293
+ baseSsId: number | undefined,
2066
2294
  ): void {
2067
2295
  if (this.#overlays.size === 0) return;
2068
2296
  const ssId = keyframeOverlaySsId(header);
2069
2297
  if (ssId === undefined) return;
2298
+ let rebuiltPsn: number | undefined;
2070
2299
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
2071
2300
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
2301
+ // After the restart check: a new epoch forgets the old one's packets.
2302
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
2303
+ inst.rebuilt.delete(ssId);
2072
2304
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
2073
2305
  if (identity !== null) {
2306
+ // The newest member anchors its MPU; one with no base SS_ID leaves the
2307
+ // MPU no base anchor rather than keep an older member's. A member that
2308
+ // is no FEC source packet of the base takes an overlay SS_ID and a psn
2309
+ // but no base SS_ID, so past it an older anchor would put each rebuilt
2310
+ // packet one base slot high, and overlayBaseSsId's psn test would pass
2311
+ // it. That costs a conforming stream nothing: every member carries the
2312
+ // base trailer (7.4.3), unread only while the base track is
2313
+ // unconfigured (fecUnreadable), which joint decoding skips, and a base
2314
+ // release (MulticastManager) resets or removes the overlay, so no
2315
+ // readable member precedes an unread one in its MPU.
2074
2316
  inst.offsets.delete(identity.mpuSequenceNumber);
2075
- inst.offsets.set(identity.mpuSequenceNumber, (ssId - sequenceNumber) >>> 0);
2317
+ inst.offsets.set(identity.mpuSequenceNumber, {
2318
+ psnOffset: (ssId - sequenceNumber) >>> 0,
2319
+ overlaySsId: ssId,
2320
+ ...(baseSsId === undefined ? {} : { baseSsId }),
2321
+ });
2076
2322
  if (inst.offsets.size > OVERLAY_OFFSET_MPUS) inst.offsets.delete(inst.offsets.keys().next().value!);
2077
2323
  }
2078
2324
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -2086,12 +2332,24 @@ export class MmtpRouter {
2086
2332
  });
2087
2333
  continue;
2088
2334
  }
2089
- if (source === "moq") this.#noteOverlayMoqBlock(inst, coords.sbn);
2335
+ if (source !== "multicast") this.#noteOverlayMoqBlock(inst, coords.sbn);
2090
2336
  if (oversized) continue;
2091
2337
  const alreadyCompleted = fec.isBlockCompleted(coords.sbn, pid, name);
2092
2338
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
2093
2339
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
2094
2340
  }
2341
+ if (rebuiltPsn === undefined || this.#classifyPacketId(packetId) === null) return;
2342
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
2343
+ if (rebuiltPsn !== sequenceNumber) {
2344
+ // Counted only. Marked re-stamped (#restampedStreams), the stream would
2345
+ // drop every later rebuilt packet no member anchors, which the overlay
2346
+ // route delivers unanchored until a base recovery shows the re-stamp:
2347
+ // a keyframe whose base copy is lost too would never play.
2348
+ this.#restampedRecoveredSeqs++;
2349
+ } else if (baseSsId !== undefined) {
2350
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
2351
+ if (offset === ((baseSsId - sequenceNumber) >>> 0)) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
2352
+ }
2095
2353
  }
2096
2354
 
2097
2355
  #noteOverlayMoqBlock(inst: OverlayInstance, blockStart: number): void {
@@ -2132,11 +2390,16 @@ export class MmtpRouter {
2132
2390
 
2133
2391
  /**
2134
2392
  * Route an overlay-recovered block's packets as source media of the
2135
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
2136
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
2137
- * base re-stamp, no block advance. Each packet's wire sequence is restored
2138
- * from its keyframe's own offset; without one, a stream the base never
2139
- * re-stamped keeps the header's sequence and any other drops the packet.
2393
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
2394
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
2395
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
2396
+ * base FEC recovered does, so it waits behind base frames still in flight,
2397
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
2398
+ * longer than unanchored; one whose base SS_ID is undetermined has no
2399
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
2400
+ * advance. Each packet's wire sequence is restored from its keyframe's own
2401
+ * offset; without one, a stream the base never re-stamped keeps the
2402
+ * header's sequence and any other drops the packet.
2140
2403
  */
2141
2404
  #routeOverlayRecovered(inst: OverlayInstance, blockStart: number, recovered: Uint8Array): void {
2142
2405
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -2159,27 +2422,181 @@ export class MmtpRouter {
2159
2422
  const streamKey = this.#mediaStreamKey(sourcePacketId, sourceName);
2160
2423
  const restamped = this.#restampedStreams.has(streamKey);
2161
2424
  const restored = new Set<number>();
2425
+ // The base SS_IDs determined independently, by overlay ESI; those the
2426
+ // overlay alone showed anchor the release gate, not the base decoder.
2427
+ const baseSsIds = new Map<number, number>();
2428
+ const gateOnly = new Set<number>();
2162
2429
  const symbols = result.symbols.flatMap((sym) => {
2163
- const offset = inst.offsets.get(sym.fragment.mpuSequenceNumber);
2164
- if (offset !== undefined) {
2165
- const packetSequenceNumber = (serial32Add(blockStart, sym.index) - offset) >>> 0;
2430
+ const overlaySsId = serial32Add(blockStart, sym.index);
2431
+ const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
2432
+ if (anchor !== undefined) {
2433
+ const packetSequenceNumber = (overlaySsId - anchor.psnOffset) >>> 0;
2166
2434
  restored.add(packetSequenceNumber);
2167
- return [{ ...sym, packetSequenceNumber }];
2435
+ const out = { ...sym, packetSequenceNumber };
2436
+ const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
2437
+ if (baseSsId !== undefined) {
2438
+ baseSsIds.set(sym.index, baseSsId);
2439
+ // Its protected psn is the wire sequence its member gives it, at
2440
+ // the base SS_ID that member gives it: at the stream's current
2441
+ // SS_ID offset, the stream unstamped, as a base recovery shows it
2442
+ // (#routeProcessedFecSymbols). A re-stamping hop fails the psn test.
2443
+ // Only for a packet the base did not receive: a received member's
2444
+ // slot holds the bytes it arrived with (the decoder keeps a
2445
+ // received source as given), whose psn is the wire one whatever a
2446
+ // hop did, so it passes the test against itself.
2447
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
2448
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) &&
2449
+ offset === ((baseSsId - packetSequenceNumber) >>> 0)) {
2450
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
2451
+ }
2452
+ }
2453
+ return [out];
2168
2454
  }
2169
2455
  // A stream re-stamped by a bridge that no base recovery has shown yet
2170
2456
  // keeps the header's sequence too: from received packets alone the
2171
- // router cannot tell (their psn is the wire one). Base recovery or a
2172
- // FETCH still covers such a keyframe.
2173
- if (!restamped) return [sym];
2457
+ // router cannot tell (their psn is the wire one), and the base copy of
2458
+ // a packet the overlay rebuilt only counts a re-stamp. Base recovery or
2459
+ // a FETCH still covers such a keyframe.
2460
+ if (!restamped) {
2461
+ // No member of this MPU arrived to anchor a base SS_ID. Evidence that
2462
+ // the stream is unstamped at its current offset determines one from
2463
+ // the packet's protected psn instead (unstampedBaseSsId): a base
2464
+ // recovery's, or else the overlay's own, which anchors the release
2465
+ // gate only (#overlayUnstampedSsIdSeqOffsetByStream). Without it, the
2466
+ // packet's base copy, if it lands, shows whether it is
2467
+ // (#feedOverlaySource).
2468
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
2469
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
2470
+ const baseSsId = fedSsId ??
2471
+ unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
2472
+ if (baseSsId !== undefined) {
2473
+ baseSsIds.set(sym.index, baseSsId);
2474
+ if (fedSsId === undefined) gateOnly.add(sym.index);
2475
+ } else {
2476
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
2477
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value!);
2478
+ }
2479
+ return [sym];
2480
+ }
2174
2481
  this.#overlayStats.unsequencedDropped++;
2175
2482
  return [];
2176
2483
  });
2177
2484
  this.#overlayStats.recovered++;
2485
+ // Each packet's MPU starts, in this decode, at the lowest base SS_ID
2486
+ // determined for it: the release gate's span ends there.
2487
+ const mpuFirst = new Map<number, number>();
2488
+ for (const sym of symbols) {
2489
+ const ssId = baseSsIds.get(sym.index);
2490
+ const mpu = sym.fragment.mpuSequenceNumber;
2491
+ const first = mpuFirst.get(mpu);
2492
+ if (ssId !== undefined && (first === undefined || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
2493
+ }
2494
+ const firstSsIds = new Map<number, number>();
2495
+ for (const sym of symbols) {
2496
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber)!);
2497
+ }
2178
2498
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
2179
2499
  deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
2500
+ baseSsIds,
2501
+ firstSsIds,
2180
2502
  });
2181
2503
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) =>
2182
2504
  restored.has(sym.packetSequenceNumber)));
2505
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0
2506
+ ? baseSsIds
2507
+ : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
2508
+ }
2509
+
2510
+ /**
2511
+ * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
2512
+ * its base block too, once its base SS_ID is determined (overlayBaseSsId,
2513
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
2514
+ * base recovery showed; `baseSsIds` holds no other),
2515
+ * so it is fed to the base decoder as a rebuilt source
2516
+ * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
2517
+ * fewer to solve, and its repair can recover the block's other packets.
2518
+ * A base block no repair has stated yet takes it when one does
2519
+ * (#feedPendingRebuilt).
2520
+ *
2521
+ * The overlay route already handled each packet fed (delivered it, or
2522
+ * held an untimed head for its FT=1), so a base recovery routes none of
2523
+ * them again (#routeVerifiedFecSymbols): a second recovered copy of a
2524
+ * held head would wait in the parser for timing its first copy consumed.
2525
+ * Only an overlay block decoded from multicast symbols alone is fed: with
2526
+ * a MoQ symbol in it, the base block's recovery would depend on bytes
2527
+ * that crossed no multicast socket, which the provenance counted from the
2528
+ * block's own arrivals cannot show.
2529
+ */
2530
+ #feedOverlayRecoveredToBase(
2531
+ inst: OverlayInstance,
2532
+ blockStart: number,
2533
+ symbols: ProcessFecBlockResult["symbols"],
2534
+ baseSsIds: ReadonlyMap<number, number>,
2535
+ ): void {
2536
+ const fec = this.#fecManager;
2537
+ const owner = inst.leg.sourcePacketId;
2538
+ const name = inst.leg.sourceCatalogTrackName;
2539
+ if (!fec?.feedRebuiltSourceSymbol || inst.moqBlocks.has(blockStart)) return;
2540
+ if (this.#classifyPacketId(owner) === null || fec.isTrackConfigured?.(owner) === false) return;
2541
+ const { duplicates, overlayToBase: { routed } } = this.#stream(owner, name);
2542
+ const feeds: Array<readonly [number, Uint8Array]> = [];
2543
+ for (const sym of symbols) {
2544
+ // A packet the base received already sits in its block.
2545
+ if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
2546
+ const ssId = baseSsIds.get(sym.index);
2547
+ if (ssId === undefined) {
2548
+ this.#overlayStats.baseUndetermined++;
2549
+ continue;
2550
+ }
2551
+ routed.delete(ssId);
2552
+ routed.add(ssId);
2553
+ if (routed.size > OVERLAY_ROUTED_LIMIT) routed.delete(routed.values().next().value!);
2554
+ feeds.push([ssId, sym.rawSymbol]);
2555
+ }
2556
+ // Any feed can recover the base block, whose routing must already skip
2557
+ // every packet this recovery routed: all are registered before the first.
2558
+ for (const [ssId, symbolData] of feeds) {
2559
+ // A recovery routed above can retire the owner (an in-place switch).
2560
+ if (this.#classifyPacketId(owner) === null) return;
2561
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
2562
+ }
2563
+ }
2564
+
2565
+ /** Feed one rebuilt source to its base block, or keep it until a repair states that block. */
2566
+ #feedRebuiltToBase(owner: number, name: string | undefined, ssId: number, symbolData: Uint8Array): void {
2567
+ const fec = this.#fecManager;
2568
+ if (!fec?.feedRebuiltSourceSymbol) return;
2569
+ const coords = fec.locateIsoSource?.(owner, name, ssId);
2570
+ if (coords == null) {
2571
+ const pending = this.#stream(owner, name).overlayToBase.pending;
2572
+ pending.delete(ssId);
2573
+ // Its own copy: the symbol is a view of the whole recovered block.
2574
+ pending.set(ssId, symbolData.slice());
2575
+ if (pending.size > OVERLAY_PENDING_LIMIT) pending.delete(pending.keys().next().value!);
2576
+ return;
2577
+ }
2578
+ const fed = fec.feedRebuiltSourceSymbol(owner, ssId, symbolData, name);
2579
+ if (!fed.taken) return;
2580
+ this.#overlayStats.baseFed++;
2581
+ if (fed.recovered === null) return;
2582
+ const sbn = coords.sbn;
2583
+ this.#routeRecoveredBlock(sbn, fed.recovered, owner, name, () => {
2584
+ fec.cancelBlockTimeout(sbn, owner, name);
2585
+ fec.countRecovery(owner, sbn, name);
2586
+ fec.markBlockCompleted(sbn, owner, name);
2587
+ });
2588
+ }
2589
+
2590
+ /** A repair stated `block`: the rebuilt sources that waited for it join it now. */
2591
+ #feedPendingRebuilt(owner: number, name: string | undefined, block: { start: number; length: number }): void {
2592
+ const pending = this.#streams.get(owner)?.get(name)?.overlayToBase.pending;
2593
+ if (pending === undefined || pending.size === 0) return;
2594
+ for (const [ssId, symbolData] of [...pending]) {
2595
+ if (this.#classifyPacketId(owner) === null) return;
2596
+ if (serial32Distance(block.start, ssId) >= block.length) continue;
2597
+ pending.delete(ssId);
2598
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
2599
+ }
2183
2600
  }
2184
2601
 
2185
2602
  /** fec-multicast-00 §6.6: report each base block whose RAP MFU fragments
@@ -2215,6 +2632,9 @@ export class MmtpRouter {
2215
2632
  const mpu = sym.fragment.mpuSequenceNumber;
2216
2633
  if (sym.fragmentType !== 2 || !sym.fragment.rapFlag || !ft0.has(mpu) || !ft1.has(mpu)) continue;
2217
2634
  if (!single.has(mpu) && !(first.has(mpu) && last.has(mpu))) continue;
2635
+ // Not overlayBaseSsId: a wrong sbn only keeps or wrongly stops a keyframe
2636
+ // FETCH (§6.6, a SHOULD; no symbol moves), and wire psn plus offset holds
2637
+ // under a constant re-stamp shift, which overlayBaseSsId's psn test refuses.
2218
2638
  const ssId = (sym.packetSequenceNumber + ssIdSeqOffset) >>> 0;
2219
2639
  // ponytail: a base block no repair has stated yet (an undelimited hole) is not reported.
2220
2640
  const sbn = this.#fecManager?.locateIsoSource?.(packetId, catalogTrackName, ssId)?.sbn;
@@ -2365,6 +2785,11 @@ export class MmtpRouter {
2365
2785
  return this.#unadmittedListedDrops;
2366
2786
  }
2367
2787
 
2788
+ /** Source datagrams (multicast or MoQ) a protected flow's bc-provenance v2 receiver released: admitted at once or held, then admitted by a record. Repair symbols and user-agent-admitted datagrams are not counted. Counted at release, before this router's own track checks: a released datagram those drop, which only a track change between hold and release can cause, still counts, so this is not a count of routed media. */
2789
+ get admittedSourceDatagramCount(): number {
2790
+ return this.#admittedSourceDatagrams;
2791
+ }
2792
+
2368
2793
  /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
2369
2794
  get unlistedRepairSetAsideCount(): number {
2370
2795
  return this.#unlistedRepairSetAside;
@@ -2656,6 +3081,51 @@ export class MmtpRouter {
2656
3081
  return this.#unregisteredFlowDrops;
2657
3082
  }
2658
3083
 
3084
+ /** "mfu-datagram" leg packets dropped because the leg's ingress does not name their packet id (packet id 0 apart). */
3085
+ get datagramLegIngressDropCount(): number {
3086
+ return this.#datagramLegIngressDrops;
3087
+ }
3088
+
3089
+ /** "mfu-datagram" leg packets of the MMTP signaling flow (packet id 0), which no track owns. */
3090
+ get datagramLegSignalingPacketCount(): number {
3091
+ return this.#datagramLegSignalingPackets;
3092
+ }
3093
+
3094
+ /**
3095
+ * The "mfu-datagram" leg's presentation bound (mmt-02 6.1 step 6): how
3096
+ * long after a frame arrives it must leave the release gate when the gap
3097
+ * before it holds no RAP, FT=0 or FT=1 data (the player's presentation
3098
+ * delay less its decode lead). The gap is then decided at the earlier of
3099
+ * the FEC block deadline and this bound; a gap that may hold a RAP keeps
3100
+ * the block deadline. Null, or a value that is not finite and positive:
3101
+ * the block deadline alone, as on multicast.
3102
+ */
3103
+ setDatagramLegPresentationBudget(budgetMs: ((packetId: number, catalogTrackName?: string) => number) | null): void {
3104
+ this.#datagramLegPresentationBudgetMs = budgetMs;
3105
+ }
3106
+
3107
+ /**
3108
+ * The "mfu-datagram" leg is over (unsubscribed, or switched to another
3109
+ * path): no stream keeps its presentation bound or its ledger retention.
3110
+ * Parser, FEC and ledger state stay, so the packet ids continue on the
3111
+ * next path without an epoch. A later leg datagram starts a leg again.
3112
+ */
3113
+ endDatagramLeg(): void {
3114
+ this.#datagramLegStreams.clear();
3115
+ this.#datagramLegPresentationBudgetMs = null;
3116
+ }
3117
+
3118
+ #datagramLegPresentationWaitMs(packetId: number, catalogTrackName: string | undefined): number | undefined {
3119
+ if (this.#datagramLegPresentationBudgetMs === null || this.#datagramLegStreams.get(packetId)?.has(catalogTrackName) !== true) return undefined;
3120
+ let budgetMs: number;
3121
+ try {
3122
+ budgetMs = this.#datagramLegPresentationBudgetMs(packetId, catalogTrackName);
3123
+ } catch {
3124
+ return undefined;
3125
+ }
3126
+ return Number.isFinite(budgetMs) && budgetMs > 0 ? budgetMs : undefined;
3127
+ }
3128
+
2659
3129
  /** Recovered packets dropped because more than one protected flow could own their stream. */
2660
3130
  get ambiguousRecoveredDropCount(): number {
2661
3131
  return this.#ambiguousRecoveredDrops;
@@ -2674,10 +3144,14 @@ export class MmtpRouter {
2674
3144
  * caller that forgot it silently attributed its bytes to a multicast socket
2675
3145
  * they may never have crossed — and that attribution is what the physical-
2676
3146
  * delivery evidence path is built on. Absence is not multicast; say which.
3147
+ * `"moq-datagram"` is an "mfu-datagram" subscription (MmtpIngestSource):
3148
+ * `ingress.tracks` MUST name the datagram catalog track for its packet id,
3149
+ * and a packet of a packet id it does not name is dropped and counted
3150
+ * (`datagramLegIngressDropCount`; the signaling flow, packet id 0, apart).
2677
3151
  */
2678
3152
  feedPacket(
2679
3153
  packet: Uint8Array,
2680
- source: "multicast" | "moq",
3154
+ source: MmtpIngestSource,
2681
3155
  ingress?: MmtpIngressContext,
2682
3156
  ): void {
2683
3157
  if (this.#disposed) return;
@@ -2734,17 +3208,21 @@ export class MmtpRouter {
2734
3208
 
2735
3209
  /**
2736
3210
  * Feed a repair packet from MoQ (reliable QUIC) — parses MMTP repair
2737
- * header and delegates to FECManager for FEC recovery.
3211
+ * header and delegates to FECManager for FEC recovery. `source` is
3212
+ * `"moq-datagram"` for a repair object of an "mfu-datagram" track's repair
3213
+ * track, which arrives as a datagram and so counts as an in-band symbol of
3214
+ * the leg; a FETCHed repair stays `"moq"` (RepairVia `quic`).
2738
3215
  */
2739
3216
  feedRepairPacket(
2740
3217
  packet: Uint8Array,
2741
3218
  ownerPacketIdHint?: number,
2742
3219
  catalogTrackName?: string,
2743
3220
  repairTrackName?: string,
3221
+ source: "moq" | "moq-datagram" = "moq",
2744
3222
  ): void {
2745
3223
  if (this.#disposed) return;
2746
3224
  this.#withDeferredFecPokes(() => {
2747
- this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName);
3225
+ this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source);
2748
3226
  });
2749
3227
  }
2750
3228
 
@@ -2753,6 +3231,7 @@ export class MmtpRouter {
2753
3231
  ownerPacketIdHint: number | undefined,
2754
3232
  catalogTrackName: string | undefined,
2755
3233
  repairTrackName: string | undefined,
3234
+ source: "moq" | "moq-datagram",
2756
3235
  admitted = false,
2757
3236
  ): void {
2758
3237
  // One header parse per packet, as on the multicast repair branch: mmt-fec's
@@ -2768,7 +3247,7 @@ export class MmtpRouter {
2768
3247
  const repairPacketId = header.packetId;
2769
3248
  const overlay = this.#overlayRepairTarget(repairPacketId, repairTrackName);
2770
3249
  if (overlay !== undefined) {
2771
- this.#routeOverlayRepair(overlay, repairPacketId, packet, header, "moq");
3250
+ this.#routeOverlayRepair(overlay, repairPacketId, packet, header, source);
2772
3251
  return;
2773
3252
  }
2774
3253
 
@@ -2796,7 +3275,7 @@ export class MmtpRouter {
2796
3275
  let unlisted = false;
2797
3276
  if (ownerPacketId != null && !admitted) {
2798
3277
  const admit = this.#admitUnicast(repairPacketId, packet, () =>
2799
- this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, true));
3278
+ this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source, true));
2800
3279
  if (admit === "held" || admit === "dropped") return;
2801
3280
  unlisted = admit === "unlisted";
2802
3281
  }
@@ -2820,7 +3299,7 @@ export class MmtpRouter {
2820
3299
  this.#noteUnreadableFecPayloadId(ownerPacketId, "repair");
2821
3300
  return;
2822
3301
  }
2823
- this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, "moq", repairTrackName);
3302
+ this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, source, repairTrackName);
2824
3303
  }
2825
3304
  }
2826
3305
 
@@ -2944,7 +3423,7 @@ export class MmtpRouter {
2944
3423
  ownerPacketId: number,
2945
3424
  catalogTrackName: string | undefined,
2946
3425
  repair: { ssStart: number; ssbLength: number; rsbLength: number; rsId: number; symbolData: Uint8Array },
2947
- source: "multicast" | "moq",
3426
+ source: MmtpIngestSource,
2948
3427
  repairTrackName?: string,
2949
3428
  ): void {
2950
3429
  const fec = this.#fecManager;
@@ -2999,6 +3478,11 @@ export class MmtpRouter {
2999
3478
  )) return;
3000
3479
  fec.noteBlockActivity?.(blockStart, ownerPacketId, catalogTrackName);
3001
3480
  fec.noteRepairGroupLength?.(blockStart, ownerPacketId, repair.rsbLength, catalogTrackName);
3481
+ // Rebuilt sources that waited for this block join it once the block took
3482
+ // a repair, so it has a deadline; still ahead of the repair, as the held
3483
+ // sources above are.
3484
+ this.#feedPendingRebuilt(ownerPacketId, catalogTrackName, placement.block);
3485
+ if (this.#classifyPacketId(ownerPacketId) === null) return;
3002
3486
  const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
3003
3487
  const recovered = fec.feedRepairSymbol(
3004
3488
  ownerPacketId,
@@ -3061,7 +3545,7 @@ export class MmtpRouter {
3061
3545
  catalogTrackName,
3062
3546
  )) continue;
3063
3547
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
3064
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
3548
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
3065
3549
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
3066
3550
  }
3067
3551
  if (payload.oversized) continue;
@@ -3087,6 +3571,7 @@ export class MmtpRouter {
3087
3571
  debugRouter(
3088
3572
  `[MmtpRouter] Dropping repair packet pid=${packetId}: physical PID is unregistered`,
3089
3573
  );
3574
+ this.#fecManager?.countUnresolvedRepairOwner?.("unregistered");
3090
3575
  return null;
3091
3576
  }
3092
3577
 
@@ -3100,6 +3585,7 @@ export class MmtpRouter {
3100
3585
  debugRouter(
3101
3586
  `[MmtpRouter] Dropping repair packet pid=${packetId}: catalog owner is ${owners.length === 0 ? "absent" : "ambiguous"}`,
3102
3587
  );
3588
+ this.#fecManager?.countUnresolvedRepairOwner?.(owners.length === 0 ? "ownerAbsent" : "ownerAmbiguous");
3103
3589
  return null;
3104
3590
  }
3105
3591
 
@@ -3170,6 +3656,9 @@ export class MmtpRouter {
3170
3656
  }
3171
3657
  this.#parser.resetTrack(packetId, catalogTrackName);
3172
3658
  this.resetKeyframeOverlays(packetId, catalogTrackName);
3659
+ // A new epoch is no leg stream until a leg datagram says so again.
3660
+ const legNames = this.#datagramLegStreams.get(packetId);
3661
+ if (legNames?.delete(catalogTrackName) && legNames.size === 0) this.#datagramLegStreams.delete(packetId);
3173
3662
  this.#restampedStreams.delete(this.#mediaStreamKey(packetId, catalogTrackName));
3174
3663
  const assistPrefix = assistKey(packetId, catalogTrackName, 0).slice(0, -1);
3175
3664
  for (const key of this.#assistBlocks.keys()) if (key.startsWith(assistPrefix)) this.#assistBlocks.delete(key);
@@ -3179,6 +3668,8 @@ export class MmtpRouter {
3179
3668
  this.#droppedPreSyncVideo.delete(streamKey);
3180
3669
  this.#latestVideoSeqByStream.delete(streamKey);
3181
3670
  this.#ssIdSeqOffsetByStream.delete(streamKey);
3671
+ this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
3672
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
3182
3673
  this.#multicastRapTwinByStream.delete(streamKey);
3183
3674
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
3184
3675
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -3310,6 +3801,12 @@ export class MmtpRouter {
3310
3801
  * the outgoing stream stops. The hold is bounded by the incoming stream's
3311
3802
  * own RAP cadence, so no timer is involved.
3312
3803
  *
3804
+ * While the switch is staged, the FEC release gate lets a keyframe the
3805
+ * overlay rebuilt reach it, on either side, when the keyframe did before
3806
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
3807
+ * decides on what each side delivered, and the commit discards the gate's
3808
+ * frames of the outgoing stream.
3809
+ *
3313
3810
  * The commit is one synchronous transition inside the frame path: the
3314
3811
  * outgoing stream's already-admitted frames are released (its queued FEC
3315
3812
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -3362,6 +3859,16 @@ export class MmtpRouter {
3362
3859
  droppedIncomingFrames: 0,
3363
3860
  };
3364
3861
  this.#staged = state;
3862
+ // Release what the outgoing stream's gate held only because it was
3863
+ // anchored (FecReleaseGate.releaseUnanchored): unanchored, it had already
3864
+ // reached the switch. Only a gate that holds a frame the overlay rebuilt
3865
+ // is poked: any other holds nothing for that reason, and a poke would
3866
+ // still force out a frame held past the hold limit, which before the
3867
+ // anchor waited for the next push. The incoming stream's gate is not
3868
+ // drained here: a RAP it released would commit before this call returns.
3869
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
3870
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
3871
+ }
3365
3872
  return {
3366
3873
  cancel: () => {
3367
3874
  if (this.#staged !== state) return false;
@@ -3456,7 +3963,24 @@ export class MmtpRouter {
3456
3963
  // same call. Nothing registers a packet ID mid-frame, so this drops
3457
3964
  // only frames that lost their registration.
3458
3965
  if (this.#classifyPacketId(meta.packetId) === null) return;
3459
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
3966
+ if (this.#staged !== null) {
3967
+ // A switch staged from this frame's commit (onCommit: the ladder walk)
3968
+ // pokes its outgoing stream's gate, the stream just committed to, whose
3969
+ // drain may be what released this frame. The poke waits until the
3970
+ // commit has delivered that stream's init, held GOP and RAP. Run now,
3971
+ // it would release the frames behind them ahead of them: a delta is
3972
+ // dropped there (its stream is not synced yet), and a keyframe plays
3973
+ // ahead of the init and leaves the commit's frames behind it.
3974
+ let consumed = false;
3975
+ this.#fecPokeDepth++;
3976
+ try {
3977
+ consumed = this.#interceptSwitchFrame(data, meta);
3978
+ } finally {
3979
+ this.#fecPokeDepth--;
3980
+ this.#flushPendingFecPokes();
3981
+ }
3982
+ if (consumed) return;
3983
+ }
3460
3984
  this.#deliverParsedFrame(data, meta);
3461
3985
  }
3462
3986
 
@@ -3523,8 +4047,11 @@ export class MmtpRouter {
3523
4047
  this.#disposed = true;
3524
4048
  this.#staged = null;
3525
4049
  this.cancelKeyframeLostTimer();
4050
+ for (const { timer } of this.#fecWakes.values()) clearTimeout(timer);
4051
+ this.#fecWakes.clear();
3526
4052
  this.#parser.dispose();
3527
4053
  this.#streams.clear();
4054
+ this.endDatagramLeg();
3528
4055
  this.#trackPacketCallbacks.clear();
3529
4056
  this.#latestVideoSeqByStream.clear();
3530
4057
  this.#lastDirectSourceVideoTsByStream.clear();
@@ -3649,12 +4176,17 @@ export class MmtpRouter {
3649
4176
  this.#parser.deferFecRelease(work);
3650
4177
  } finally {
3651
4178
  this.#fecPokeDepth--;
3652
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
3653
- const pokes = [...this.#pendingFecPokes.values()];
3654
- this.#pendingFecPokes.clear();
3655
- for (const poke of pokes) {
3656
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
3657
- }
4179
+ this.#flushPendingFecPokes();
4180
+ }
4181
+ }
4182
+
4183
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
4184
+ #flushPendingFecPokes(): void {
4185
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
4186
+ const pokes = [...this.#pendingFecPokes.values()];
4187
+ this.#pendingFecPokes.clear();
4188
+ for (const poke of pokes) {
4189
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
3658
4190
  }
3659
4191
  }
3660
4192
  }
@@ -3734,6 +4266,52 @@ export class MmtpRouter {
3734
4266
  if (!fec?.terminalRetentionMsForPacket) return Infinity;
3735
4267
  return fec.terminalRetentionMsForPacket(packetId) ?? 0;
3736
4268
  },
4269
+ // Once no repair can fill a gap (FECManager.isoRepairlessWaitMs: only a
4270
+ // late source can), its frame waits the late-symbol allowance when the
4271
+ // gap holds no RAP an installed keyframe overlay could still rebuild:
4272
+ // lost deltas of one MPU (delta-lost), the tail of the MPU before a RAP
4273
+ // that opens the next one while MPU boundaries bound RAPs (rap-next,
4274
+ // unless the gap holds a stated block's loss: the overlay may rebuild
4275
+ // that MPU's FT=0, and the block's group then complete it), or
4276
+ // an audio gap. A gap that may hold one (rap-lost, rap-unknown, or any
4277
+ // other rap-next, whose gap may hold a whole MPU and the keyframe the
4278
+ // overlay protects) waits for that overlay's repair too (BLO-52085
4279
+ // D4). A run no repair has delimited instead waits for its FEC
4280
+ // deadline, whatever the decision (FECManager.isoRepairlessWaitMs). The
4281
+ // FEC check comes first: most held gaps are not behind such a span, and
4282
+ // deciding one scans both frames' bitstreams.
4283
+ unrepairableWaitMs: (before, after, fromSbn, toSbn) => {
4284
+ const fec = this.#fecManager;
4285
+ const { packetId, catalogTrackName } = after.meta;
4286
+ const arrivedAtMs = after.arrivedAtMs;
4287
+ const allowanceMs = fec?.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, false, arrivedAtMs);
4288
+ // On an "mfu-datagram" leg a gap of delta data alone also goes at the
4289
+ // held frame's presentation time (mmt-02 6.1 step 6), repair pending
4290
+ // or not; a gap that may hold a RAP keeps the block deadline.
4291
+ const presentationMs = this.#datagramLegPresentationWaitMs(packetId, catalogTrackName);
4292
+ if (!fec || (allowanceMs === undefined && presentationMs === undefined)) return undefined;
4293
+ const decision = this.#decideGap(before, after, [], false);
4294
+ const mpu = before.meta.mpuSequenceNumber;
4295
+ const intoNextMpu = decision.reason === "rap-next" && mpu !== undefined &&
4296
+ after.meta.mpuSequenceNumber === ((mpu + 1) >>> 0) &&
4297
+ fec.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
4298
+ if (decision.action === "stall" || (decision.reason === "rap-next" && !intoNextMpu)) {
4299
+ return allowanceMs === undefined
4300
+ ? undefined
4301
+ : fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, true, false, arrivedAtMs);
4302
+ }
4303
+ const waitMs = allowanceMs === undefined
4304
+ ? undefined
4305
+ : decision.reason === "rap-next"
4306
+ ? fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, true, arrivedAtMs)
4307
+ : allowanceMs;
4308
+ // A track with no catalog span has no classifier, so nothing ruled a
4309
+ // keyframe out of a gap inside one MPU (FECManager.mpuBoundsRapsFor):
4310
+ // its delta-lost is unproven and never takes the presentation bound.
4311
+ if (decision.reason === "delta-lost" && !((fec.interleaveDepthMsForPacket?.(packetId) ?? 0) > 0)) return waitMs;
4312
+ if (presentationMs === undefined) return waitMs;
4313
+ return waitMs === undefined ? presentationMs : Math.min(waitMs, presentationMs);
4314
+ },
3737
4315
  decide: (before, after, lostBlocks, discontinuity) => {
3738
4316
  const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
3739
4317
  this.#onFrameGap?.(decision);
@@ -3743,6 +4321,28 @@ export class MmtpRouter {
3743
4321
  onRap: (packetId, catalogTrackName, ssId) => {
3744
4322
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
3745
4323
  },
4324
+ // One timer per stream, at the earliest wake asked: its drain re-arms
4325
+ // for the next frame still waiting.
4326
+ wakeAt: (packetId, catalogTrackName, atMs) => {
4327
+ if (this.#disposed) return;
4328
+ const key = this.#mediaStreamKey(packetId, catalogTrackName);
4329
+ const armed = this.#fecWakes.get(key);
4330
+ if (armed !== undefined && armed.atMs <= atMs) return;
4331
+ if (armed !== undefined) clearTimeout(armed.timer);
4332
+ const timer = setTimeout(() => {
4333
+ this.#fecWakes.delete(key);
4334
+ this.#requestFecPoke(packetId, catalogTrackName);
4335
+ }, Math.max(0, Math.ceil(atMs - performance.now())));
4336
+ this.#fecWakes.set(key, { atMs, timer });
4337
+ },
4338
+ // A staged switch commits on when each side's frames reach it
4339
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
4340
+ // they did unanchored.
4341
+ releaseUnanchored: (packetId, catalogTrackName) => {
4342
+ const staged = this.#staged;
4343
+ const stream = { packetId, ...(catalogTrackName === undefined ? {} : { catalogTrackName }) };
4344
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
4345
+ },
3746
4346
  onReleased: (data, meta) => {
3747
4347
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === undefined) return;
3748
4348
  const timing = meta.authoredTiming;
@@ -3753,6 +4353,7 @@ export class MmtpRouter {
3753
4353
  meta.mpuSequenceNumber,
3754
4354
  timing.presentationTime,
3755
4355
  timing.mediaTimescale,
4356
+ timing.decodeTime,
3756
4357
  );
3757
4358
  },
3758
4359
  };
@@ -3778,17 +4379,40 @@ export class MmtpRouter {
3778
4379
  ): FrameGapDecision {
3779
4380
  const { packetId, catalogTrackName } = after.meta;
3780
4381
  const trackKind = this.#classifyPacketId(packetId) === false ? "audio" : "video";
3781
- // Sample positions are MPU positions only while the classifier verified
3782
- // the geometry (one movie fragment per MPU, RAP at index 0).
4382
+ // decideGap counts the frames a delta-lost gap missed as the difference
4383
+ // of the two sides' sample_number. That is exact only within one movie
4384
+ // fragment, which numbers its samples consecutively, and is stated only
4385
+ // while the classifier verifies the geometry. Two fragments state no
4386
+ // count: an MPU of several multi-sample fragments still classifies while
4387
+ // the classifier received only one of them first-hand (BLO-55339).
4388
+ // ponytail: cross-fragment gaps report missingFrames null; count them from
4389
+ // BlockClassifier MPU positions when concealedFrames must cover them.
3783
4390
  const positionsTrusted =
3784
- this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying";
4391
+ this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying" &&
4392
+ before.meta.movieFragmentSequenceNumber === after.meta.movieFragmentSequenceNumber;
3785
4393
  // "Same MPU on both sides" proves a delta-only gap only while an MPU
3786
4394
  // boundary bounds the stream's RAPs. Once a RAP was seen inside an MPU
3787
4395
  // (or an MPU outran its GOP), a lost RAP can hide inside one MPU, so the
3788
4396
  // MPU is withheld and a non-RAP after the gap stalls as rap-unknown. A
3789
- // manager that cannot answer is treated as unable to prove it.
3790
- const mpuTrusted =
3791
- this.#fecManager?.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
4397
+ // manager that cannot answer is treated as unable to prove it. Inside
4398
+ // one video MPU the catalog keyframe interval must also rule a keyframe
4399
+ // out of the gap (fec-multicast-00 Block Classification item 3), and no
4400
+ // packet held in it may carry part of a RAP.
4401
+ const mpu = before.meta.mpuSequenceNumber;
4402
+ const sameMpu = trackKind === "video" && mpu !== undefined && after.meta.mpuSequenceNumber === mpu;
4403
+ const mpuTrusted = this.#fecManager?.mpuBoundsRapsFor?.(
4404
+ packetId,
4405
+ catalogTrackName,
4406
+ sameMpu
4407
+ ? {
4408
+ mpu,
4409
+ from: before.meta.authoredTiming,
4410
+ to: after.meta.authoredTiming,
4411
+ fromSsId: before.meta.fecSbn,
4412
+ toSsId: after.meta.fecSbnFirst ?? after.meta.fecSbn,
4413
+ }
4414
+ : undefined,
4415
+ ) === true;
3792
4416
  const evidence = (frame: { data: Uint8Array; meta: ParserFrameMeta }): GapFrameEvidence => {
3793
4417
  const timing = frame.meta.authoredTiming;
3794
4418
  const sampleNumber = frame.meta.sampleNumber;
@@ -3927,7 +4551,7 @@ export class MmtpRouter {
3927
4551
  */
3928
4552
  #processMMTP(
3929
4553
  packet: Uint8Array,
3930
- source: "multicast" | "moq",
4554
+ source: MmtpIngestSource,
3931
4555
  manifestAdmitted = false,
3932
4556
  ingress?: MmtpIngressContext,
3933
4557
  overlapCopy = false,
@@ -3938,28 +4562,55 @@ export class MmtpRouter {
3938
4562
  const parsed = this.#parser.parsePacket(packet);
3939
4563
  if (!parsed) return;
3940
4564
  const info = parsed.info;
4565
+ // manifestAdmitted is set only by a receiver release or the user agent's own verification.
4566
+ if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
3941
4567
  // Every multicast packet is a delivery-gap sample, including one dropped
3942
4568
  // below: the gap is a property of the link the FEC deadlines run on, not
3943
4569
  // of which packets this router routes. The re-entry after a manifest
3944
4570
  // admission is the same arrival, not a new one.
3945
4571
  if (source === "multicast" && !manifestAdmitted) {
3946
4572
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
4573
+ } else if (source === "moq-datagram" && !manifestAdmitted) {
4574
+ // The leg's own estimator: its stalls never widen the multicast wait.
4575
+ this.#fecManager?.noteArrival?.("moq-datagram", info.packetId, info.sequenceNumber);
3947
4576
  }
3948
- if (source === "multicast" && !ingressHasPacketId(ingress, info.packetId)) {
4577
+ if (source !== "moq" && !ingressHasPacketId(ingress, info.packetId)) {
4578
+ if (source === "moq-datagram") {
4579
+ // The signaling object (packet id 0, Object 0 of every group) is no
4580
+ // track's packet and carries no FEC Source Info: counted apart, so
4581
+ // the ingress-drop counter stays a misconfiguration signal.
4582
+ if (info.packetId === MMTP_SIGNALING_PACKET_ID) this.#datagramLegSignalingPackets++;
4583
+ else this.#datagramLegIngressDrops++;
4584
+ }
3949
4585
  debugRouter(
3950
- `[MmtpRouter] Dropping multicast packet pid=${info.packetId}: absent from ingress tracks`,
4586
+ `[MmtpRouter] Dropping ${source} packet pid=${info.packetId}: absent from ingress tracks`,
3951
4587
  );
3952
4588
  return;
3953
4589
  }
4590
+ if (source === "moq-datagram") {
4591
+ if (!info.isRepair) {
4592
+ let names = this.#datagramLegStreams.get(info.packetId);
4593
+ if (!names) this.#datagramLegStreams.set(info.packetId, (names = new Set()));
4594
+ names.add(catalogTrackNameForPacket(ingress, info.packetId));
4595
+ }
4596
+ } else if (source === "multicast") {
4597
+ // The ordered switch retires the leg before the first multicast packet
4598
+ // of its packet id: from here the stream is a multicast one, and the
4599
+ // leg's presentation bound and ledger retention no longer apply.
4600
+ this.#datagramLegStreams.delete(info.packetId);
4601
+ }
3954
4602
  const packetRole = this.#packetIdRoles.get(info.packetId);
3955
4603
  if (
3956
- source === "multicast" &&
4604
+ source !== "moq" &&
3957
4605
  this.#classifyPacketId(info.packetId) === null &&
3958
4606
  (!info.isRepair || packetRole !== "repair")
3959
4607
  ) {
3960
4608
  debugRouter(
3961
- `[MmtpRouter] Dropping multicast packet pid=${info.packetId}: physical PID is unregistered`,
4609
+ `[MmtpRouter] Dropping ${source} packet pid=${info.packetId}: physical PID is unregistered`,
3962
4610
  );
4611
+ // #resolveRepairOwnerPacketId's "unregistered" drop for every leg that is
4612
+ // not a MoQ stream: a multicast leg and a "moq-datagram" leg both count here.
4613
+ if (info.isRepair) this.#fecManager?.countUnresolvedRepairOwner?.("unregistered");
3963
4614
  return;
3964
4615
  }
3965
4616
  if (!info.isRepair && hasAmbiguousCatalogTrackName(ingress, info.packetId)) {
@@ -4017,7 +4668,8 @@ export class MmtpRouter {
4017
4668
 
4018
4669
  // A MoQ packet of a track a protected flow lists is a datagram of that
4019
4670
  // flow on its unicast path (7.2.7): admitted before it is read, or held.
4020
- if (source === "moq" && !manifestAdmitted) {
4671
+ // An "mfu-datagram" object is one too: it crossed QUIC, not the flow.
4672
+ if (source !== "multicast" && !manifestAdmitted) {
4021
4673
  const admit = this.#admitUnicast(info.packetId, packet, () =>
4022
4674
  this.#processMMTP(packet, source, true, ingress, overlapCopy, true), overlapCopy);
4023
4675
  if (admit !== "unlisted") {
@@ -4061,7 +4713,7 @@ export class MmtpRouter {
4061
4713
  // An unadmitted MoQ symbol reaching here is unlisted (#admitUnicast);
4062
4714
  // a flow-less multicast one is unverified.
4063
4715
  if (
4064
- ((flowless && this.#userAgentGoverns(ownerPacketId)) || (source === "moq" && !manifestAdmitted)) &&
4716
+ ((flowless && this.#userAgentGoverns(ownerPacketId)) || (source !== "multicast" && !manifestAdmitted)) &&
4065
4717
  this.#setAsideUnlistedRepair(ownerPacketId, catalogTrackNameForPacket(ingress, ownerPacketId), repair)
4066
4718
  ) return;
4067
4719
  this.#repairPidCounts[info.packetId] = (this.#repairPidCounts[info.packetId] || 0) + 1;
@@ -4142,9 +4794,10 @@ export class MmtpRouter {
4142
4794
  // checked; an overlap copy is MoQ bytes and says nothing about the
4143
4795
  // multicast publisher, and neither does a packet a provenance hold queue
4144
4796
  // released: it predates the horizon because it waited, not because the
4145
- // publisher restarted.
4797
+ // publisher restarted. An "mfu-datagram" leg is the publisher's own
4798
+ // datagrams, so it shows a restart as multicast does.
4146
4799
  if (
4147
- source === "multicast" &&
4800
+ source !== "moq" &&
4148
4801
  !overlapCopy &&
4149
4802
  !releasedFromQuarantine &&
4150
4803
  catalogTrackName !== undefined &&
@@ -4257,6 +4910,10 @@ export class MmtpRouter {
4257
4910
  evidence: sourceSymbolEvidence(packet, parsed.header, info.rapFlag, info.sequenceNumber),
4258
4911
  oversized: !(this.#fecManager.isoSourceFits?.(info.packetId, rawSymbol.length) ?? false),
4259
4912
  }) ?? false;
4913
+ // A held source can complete the SS_IDs a waiting frame's gap asks
4914
+ // for, or anchor its run, as a located one can complete a block:
4915
+ // ask the gate again, or the frame waits for the next packet.
4916
+ if (held) this.#requestFecPoke(info.packetId, catalogTrackName);
4260
4917
  parseSourceSymbol = held && !duplicates.parsedSymbols.has(ssId);
4261
4918
  }
4262
4919
  } else if (fecUnreadable && info.fecPayloadId) {
@@ -4401,6 +5058,7 @@ export class MmtpRouter {
4401
5058
  if (!overlapCopy && this.#classifyPacketId(info.packetId) !== null) {
4402
5059
  this.#feedOverlaySource(
4403
5060
  info.packetId, catalogTrackName, packet, parsed.header, info.sequenceNumber, info.rapFlag, source,
5061
+ fecPayloadId?.ssId,
4404
5062
  );
4405
5063
  }
4406
5064
  }
@@ -4421,10 +5079,11 @@ export class MmtpRouter {
4421
5079
  parserOptions?: {
4422
5080
  skipFecPayloadId?: boolean;
4423
5081
  recovered?: boolean;
4424
- source?: MmtpSourcePath;
5082
+ source?: MmtpIngestSource;
4425
5083
  deliveryProvenance?: MmtpDeliveryProvenance;
4426
5084
  catalogTrackName?: string;
4427
5085
  fecSbn?: number;
5086
+ fecSbnFirst?: number;
4428
5087
  },
4429
5088
  parsed?: ParsedMmtpPacket,
4430
5089
  ): void {
@@ -4444,10 +5103,13 @@ export class MmtpRouter {
4444
5103
  const feedOptions = {
4445
5104
  skipFecPayloadId: parserOptions?.skipFecPayloadId,
4446
5105
  recovered: parserOptions?.recovered,
4447
- source: parserOptions?.source,
5106
+ // Frame attribution is the transport path: an "mfu-datagram" object
5107
+ // crossed QUIC, so its frames are 'moq' (provenance 'mixed').
5108
+ source: parserOptions?.source === "moq-datagram" ? "moq" : parserOptions?.source,
4448
5109
  deliveryProvenance: parserOptions?.deliveryProvenance,
4449
5110
  catalogTrackName: parserOptions?.catalogTrackName,
4450
5111
  ...(parserOptions?.fecSbn === undefined ? {} : { fecSbn: parserOptions.fecSbn }),
5112
+ ...(parserOptions?.fecSbnFirst === undefined ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }),
4451
5113
  };
4452
5114
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
4453
5115
  else this.#parser.feed(packet, feedOptions);
@@ -4467,7 +5129,7 @@ export class MmtpRouter {
4467
5129
  sbn: number,
4468
5130
  esi: number,
4469
5131
  data: Uint8Array,
4470
- source: MmtpSourcePath,
5132
+ source: MmtpIngestSource,
4471
5133
  catalogTrackName?: string,
4472
5134
  ): boolean {
4473
5135
  const fecManager = this.#fecManager;
@@ -4629,6 +5291,7 @@ export class MmtpRouter {
4629
5291
  stream = {
4630
5292
  key: JSON.stringify([packetId, catalogTrackName ?? null]),
4631
5293
  duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId)),
5294
+ overlayToBase: { routed: new Set(), pending: new Map() },
4632
5295
  };
4633
5296
  byName.set(catalogTrackName, stream);
4634
5297
  }
@@ -4832,15 +5495,16 @@ export class MmtpRouter {
4832
5495
  ): void {
4833
5496
  const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);
4834
5497
  // The FEC release gate let this frame out in order: only once every
4835
- // block between it and the frame before it resolved, or because it
4836
- // starts where that frame ended. Nothing still in flight can precede it
4837
- // then, so it plays now, as a source frame does; holding it for the next
5498
+ // block between it and the frame before it resolved, because it starts
5499
+ // where that frame ended, or (one the overlay rebuilt) once the base
5500
+ // path passed it. Nothing still in flight can precede it then, so it
5501
+ // plays now, as a source frame does; holding it for the next
4838
5502
  // intact frame cost every repaired burst its length in decoder input
4839
- // (BLO-52085). An overlay recovery names no base block for the gate to
4840
- // wait on, so past a gap it may be ahead of frames still in flight (an
4841
- // overlay that outran the wire, BLO-53342): it keeps waiting for the
4842
- // source cursor below, unless it starts where the last emitted frame
4843
- // ended (on this direct path, the delivered high water).
5503
+ // (BLO-52085). An overlay recovery whose base SS_ID is undetermined names
5504
+ // no base block for the gate to wait on, so past a gap it may be ahead of
5505
+ // frames still in flight (an overlay that outran the wire, BLO-53342): it
5506
+ // keeps waiting for the source cursor below, unless it starts where the
5507
+ // last emitted frame ended (on this direct path, the delivered high water).
4844
5508
  if (this.#isFecTrack(packetId)) {
4845
5509
  const high = this.#deliveredVideoHighWaterByStream.get(streamKey);
4846
5510
  if (fecSbn !== undefined || (high !== undefined && authoredAdjacent(high, meta))) {
@@ -5086,6 +5750,17 @@ export class MmtpRouter {
5086
5750
  complete?: () => void,
5087
5751
  assisted = false,
5088
5752
  ): boolean {
5753
+ // A packet a keyframe overlay recovery routed before it fed the packet to
5754
+ // this block (#feedOverlayRecoveredToBase) is not routed again.
5755
+ const overlayRouted = ownerPacketId == null
5756
+ ? undefined
5757
+ : this.#streams.get(ownerPacketId)?.get(catalogTrackName)?.overlayToBase.routed;
5758
+ if (overlayRouted !== undefined && overlayRouted.size > 0) {
5759
+ result = {
5760
+ ...result,
5761
+ symbols: result.symbols.filter((sym) => !overlayRouted.has(this.#fecAnchorForRecovered(blockId, sym.index))),
5762
+ };
5763
+ }
5089
5764
  const entry = ownerPacketId == null ? undefined : this.#provenanceFor(ownerPacketId, catalogTrackName);
5090
5765
  const receiver = entry === undefined || entry === "ambiguous" ? entry : entry.receiver;
5091
5766
  const userAgent = !assisted && entry !== undefined && entry !== "ambiguous" && entry.protected === true && entry.userAgent === true;
@@ -5155,15 +5830,25 @@ export class MmtpRouter {
5155
5830
  catalogTrackName?: string,
5156
5831
  /** Set for a keyframe-overlay recovery: `blockId` is an overlay
5157
5832
  * coordinate, which yields no base SS_ID (mmt-02 7.2), and the packets'
5158
- * wire sequences are already restored. */
5159
- overlay?: { deliveryProvenance: MmtpDeliveryProvenance },
5833
+ * wire sequences are already restored. `baseSsIds` holds, by ESI, the
5834
+ * base SS_IDs determined independently: a packet's release-gate anchor;
5835
+ * `firstSsIds` the lowest of them in its MPU (FrameMeta.fecSbnFirst). */
5836
+ overlay?: {
5837
+ deliveryProvenance: MmtpDeliveryProvenance;
5838
+ baseSsIds: ReadonlyMap<number, number>;
5839
+ firstSsIds: ReadonlyMap<number, number>;
5840
+ },
5160
5841
  ): void {
5161
5842
  // Route recovered symbols to the track's callback. The ownerPacketId tells us
5162
5843
  // which track this block belongs to — resolves per-track, then legacy fallback.
5163
5844
  if (ownerPacketId == null) return; // no track association
5164
5845
  if (this.#classifyPacketId(ownerPacketId) === null) return; // unknown track
5165
- const fecSbnOf = (index: number): { fecSbn?: number } =>
5166
- overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
5846
+ const fecSbnOf = (index: number): { fecSbn?: number; fecSbnFirst?: number } => {
5847
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
5848
+ const fecSbn = overlay.baseSsIds.get(index);
5849
+ const fecSbnFirst = overlay.firstSsIds.get(index);
5850
+ return fecSbn === undefined || fecSbnFirst === undefined ? {} : { fecSbn, fecSbnFirst };
5851
+ };
5167
5852
  // A recovered symbol's header names the sequence the sender protected. A
5168
5853
  // hop that re-stamps packet_sequence_number after protection (cast's
5169
5854
  // publisher-rotation bridge) leaves the decode mixing every received
@@ -5179,7 +5864,10 @@ export class MmtpRouter {
5179
5864
  ...result,
5180
5865
  symbols: result.symbols.map((sym) => {
5181
5866
  const wire = (this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset) >>> 0;
5182
- if (wire === sym.packetSequenceNumber) return sym;
5867
+ if (wire === sym.packetSequenceNumber) {
5868
+ this.#unstampedSsIdSeqOffsetByStream.set(streamKey, ssIdSeqOffset);
5869
+ return sym;
5870
+ }
5183
5871
  this.#restampedRecoveredSeqs++;
5184
5872
  this.#restampedStreams.add(streamKey);
5185
5873
  return { ...sym, packetSequenceNumber: wire };