@blockcast/mmt-container 0.4.0 → 0.4.1-main.2e0aa69d293d

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 (220) hide show
  1. package/README.md +37 -21
  2. package/dist/align.d.ts +24 -18
  3. package/dist/align.d.ts.map +1 -1
  4. package/dist/align.js +23 -4
  5. package/dist/align.js.map +2 -2
  6. package/dist/browser-runtime.js +5070 -908
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +76 -39
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +321 -205
  11. package/dist/carp-catalog.js.map +3 -3
  12. package/dist/catalog-fec-params.d.ts +12 -4
  13. package/dist/catalog-fec-params.d.ts.map +1 -1
  14. package/dist/catalog-fec-params.js +40 -17
  15. package/dist/catalog-fec-params.js.map +3 -3
  16. package/dist/catalog-network-source.d.ts +28 -7
  17. package/dist/catalog-network-source.d.ts.map +1 -1
  18. package/dist/catalog-network-source.js +21 -1
  19. package/dist/catalog-network-source.js.map +2 -2
  20. package/dist/catalog-validator.d.ts +4 -3
  21. package/dist/catalog-validator.d.ts.map +1 -1
  22. package/dist/catalog-validator.js +0 -29
  23. package/dist/catalog-validator.js.map +3 -3
  24. package/dist/cmcd-producer.d.ts +13 -1
  25. package/dist/cmcd-producer.d.ts.map +1 -1
  26. package/dist/cmcd-producer.js +14 -0
  27. package/dist/cmcd-producer.js.map +2 -2
  28. package/dist/delivery-catalog.js +115 -235
  29. package/dist/delivery-catalog.js.map +4 -4
  30. package/dist/fec-manager.d.ts +113 -1
  31. package/dist/fec-manager.d.ts.map +1 -1
  32. package/dist/fec-manager.js +464 -66
  33. package/dist/fec-manager.js.map +4 -4
  34. package/dist/fec-state.d.ts +2 -1
  35. package/dist/fec-state.d.ts.map +1 -1
  36. package/dist/fec-state.js +18 -3
  37. package/dist/fec-state.js.map +3 -3
  38. package/dist/fec-worker-setup.d.ts +10 -0
  39. package/dist/fec-worker-setup.d.ts.map +1 -1
  40. package/dist/fec-worker-setup.js +15 -4
  41. package/dist/fec-worker-setup.js.map +2 -2
  42. package/dist/held-layer-admission.d.ts +58 -0
  43. package/dist/held-layer-admission.d.ts.map +1 -0
  44. package/dist/held-layer-admission.js +105 -0
  45. package/dist/held-layer-admission.js.map +7 -0
  46. package/dist/index.d.ts +5 -5
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +8 -8
  49. package/dist/index.js.map +2 -2
  50. package/dist/iso-block-locator.d.ts +39 -1
  51. package/dist/iso-block-locator.d.ts.map +1 -1
  52. package/dist/iso-block-locator.js +109 -17
  53. package/dist/iso-block-locator.js.map +3 -3
  54. package/dist/mfu-reassembler.js +21 -13
  55. package/dist/mfu-reassembler.js.map +2 -2
  56. package/dist/mmtp-container-parser.d.ts.map +1 -1
  57. package/dist/mmtp-container-parser.js +93 -22
  58. package/dist/mmtp-container-parser.js.map +2 -2
  59. package/dist/mmtp-container-parser.no-modules.js +3692 -1213
  60. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  61. package/dist/mmtp-decode-pipeline.js +93 -22
  62. package/dist/mmtp-decode-pipeline.js.map +2 -2
  63. package/dist/mmtp-fec-session.d.ts +192 -0
  64. package/dist/mmtp-fec-session.d.ts.map +1 -0
  65. package/dist/mmtp-fec-session.js +640 -0
  66. package/dist/mmtp-fec-session.js.map +7 -0
  67. package/dist/mmtp-router.d.ts +101 -32
  68. package/dist/mmtp-router.d.ts.map +1 -1
  69. package/dist/mmtp-router.js +422 -189
  70. package/dist/mmtp-router.js.map +2 -2
  71. package/dist/multicast-auth-catalog.d.ts +94 -92
  72. package/dist/multicast-auth-catalog.d.ts.map +1 -1
  73. package/dist/multicast-auth-catalog.js +746 -131
  74. package/dist/multicast-auth-catalog.js.map +4 -4
  75. package/dist/multicast-input.d.ts +31 -8
  76. package/dist/multicast-input.d.ts.map +1 -1
  77. package/dist/multicast-input.js +299 -35
  78. package/dist/multicast-input.js.map +3 -3
  79. package/dist/multicast-manager.d.ts +140 -12
  80. package/dist/multicast-manager.d.ts.map +1 -1
  81. package/dist/multicast-manager.js +4104 -605
  82. package/dist/multicast-manager.js.map +4 -4
  83. package/dist/multicast-transport.d.ts +16 -3
  84. package/dist/multicast-transport.d.ts.map +1 -1
  85. package/dist/multicast-transport.js +127 -240
  86. package/dist/multicast-transport.js.map +4 -4
  87. package/dist/multicast-unwrap.js +21 -13
  88. package/dist/multicast-unwrap.js.map +2 -2
  89. package/dist/no-modules.d.ts +5 -3
  90. package/dist/no-modules.d.ts.map +1 -1
  91. package/dist/no-modules.js +3643 -1197
  92. package/dist/no-modules.js.map +4 -4
  93. package/dist/phase14-catalog-override.d.ts +1 -1
  94. package/dist/phase14-catalog-override.d.ts.map +1 -1
  95. package/dist/phase14-catalog-override.js +2 -2
  96. package/dist/phase14-catalog-override.js.map +2 -2
  97. package/dist/repair-fetch.d.ts +90 -6
  98. package/dist/repair-fetch.d.ts.map +1 -1
  99. package/dist/repair-fetch.js +160 -32
  100. package/dist/repair-fetch.js.map +3 -3
  101. package/dist/repair-layers.d.ts +2 -0
  102. package/dist/repair-layers.d.ts.map +1 -1
  103. package/dist/repair-layers.js +19 -2
  104. package/dist/repair-layers.js.map +2 -2
  105. package/dist/sample-combiner.d.ts +7 -1
  106. package/dist/sample-combiner.d.ts.map +1 -1
  107. package/dist/sample-combiner.js +14 -2
  108. package/dist/sample-combiner.js.map +2 -2
  109. package/dist/signaling.d.ts +2 -2
  110. package/dist/signaling.d.ts.map +1 -1
  111. package/dist/signaling.js +3 -3
  112. package/dist/signaling.js.map +2 -2
  113. package/dist/switching-set-alignment.d.ts +1 -1
  114. package/dist/switching-set-alignment.js.map +1 -1
  115. package/dist/timestamp-codec.js +21 -13
  116. package/dist/timestamp-codec.js.map +2 -2
  117. package/dist/wasm-mfu-reassembler.js.map +1 -1
  118. package/dist/wasm-mmtp-container-parser.js +93 -22
  119. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  120. package/package.json +6 -18
  121. package/schemas/catalog.schema.json +133 -38
  122. package/src/align.ts +52 -21
  123. package/src/carp-catalog.ts +188 -68
  124. package/src/catalog-fec-params.ts +28 -3
  125. package/src/catalog-network-source.ts +49 -7
  126. package/src/catalog-validator.ts +4 -11
  127. package/src/cmcd-producer.ts +23 -1
  128. package/src/fec-manager.ts +378 -63
  129. package/src/fec-state.ts +11 -4
  130. package/src/fec-worker-setup.ts +30 -2
  131. package/src/held-layer-admission.ts +161 -0
  132. package/src/index.ts +32 -19
  133. package/src/iso-block-locator.ts +110 -7
  134. package/src/mmtp-container-parser.ts +75 -7
  135. package/src/mmtp-fec-session.ts +606 -0
  136. package/src/mmtp-router.ts +453 -236
  137. package/src/multicast-auth-catalog.ts +196 -231
  138. package/src/multicast-input.ts +148 -124
  139. package/src/multicast-manager.ts +447 -53
  140. package/src/multicast-transport.ts +23 -5
  141. package/src/no-modules.ts +8 -7
  142. package/src/phase14-catalog-override.ts +3 -3
  143. package/src/repair-fetch.ts +306 -42
  144. package/src/repair-layers.ts +22 -2
  145. package/src/sample-combiner.ts +15 -2
  146. package/src/signaling.ts +2 -2
  147. package/src/switching-set-alignment.ts +1 -1
  148. package/test-vectors/align.json +108 -32
  149. package/test-vectors/bc-provenance-v2.json +1526 -0
  150. package/test-vectors/catalog/README.md +71 -4
  151. package/test-vectors/catalog/negative/fec-block-profile-missing.json +1 -1
  152. package/test-vectors/catalog/negative/fec-block-profile-retired.json +1 -1
  153. package/test-vectors/catalog/negative/fec-block-profile-unknown.json +1 -1
  154. package/test-vectors/catalog/negative/fec-iso-symbol-size-below-floor.json +28 -0
  155. package/test-vectors/catalog/negative/fec-reed-solomon-iso-symbol-size-13.json +28 -0
  156. package/test-vectors/catalog/negative/fec-reed-solomon-k-plus-p-over-255.json +39 -0
  157. package/test-vectors/catalog/negative/fec-reed-solomon-overlay-over-255.json +40 -0
  158. package/test-vectors/catalog/negative/fec-repair-overlay-source-symbols-zero.json +43 -0
  159. package/test-vectors/catalog/negative/fec-repair-symbols-zero.json +28 -0
  160. package/test-vectors/catalog/negative/fec-source-symbols-zero.json +28 -0
  161. package/test-vectors/catalog/negative/fec-symbol-size-zero.json +28 -0
  162. package/test-vectors/catalog/negative/init-data-inline-without-data.json +22 -0
  163. package/test-vectors/catalog/negative/mmtp-mode-mpu.json +15 -0
  164. package/test-vectors/catalog/negative/multicast-amt-dns-without-relay.json +37 -0
  165. package/test-vectors/catalog/negative/multicast-amt-driad-with-relay.json +38 -0
  166. package/test-vectors/catalog/negative/multicast-auth-asm-missing-sender-address.json +77 -0
  167. package/test-vectors/catalog/negative/multicast-auth-duplicate-first-epoch.json +56 -0
  168. package/test-vectors/catalog/negative/multicast-auth-duplicate-kid.json +56 -0
  169. package/test-vectors/catalog/negative/multicast-auth-endpoint-auth-without-object-auth.json +38 -0
  170. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-auth.json +49 -0
  171. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-bandwidth.json +55 -0
  172. package/test-vectors/catalog/negative/multicast-auth-manifest-port-equals-port.json +56 -0
  173. package/test-vectors/catalog/negative/multicast-auth-manifest-timer-out-of-range.json +56 -0
  174. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-above-max.json +56 -0
  175. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-below-min.json +56 -0
  176. package/test-vectors/catalog/negative/multicast-auth-root-dotted-key.json +55 -0
  177. package/test-vectors/catalog/negative/multicast-auth-sender-address-on-ssm.json +57 -0
  178. package/test-vectors/catalog/negative/multicast-auth-version-1.json +56 -0
  179. package/test-vectors/catalog/negative/multicast-auth-version-3.json +56 -0
  180. package/test-vectors/catalog/negative/multicast-auth-version-missing.json +55 -0
  181. package/test-vectors/catalog/negative/multicast-endpoint-foreign-namespace-track.json +44 -0
  182. package/test-vectors/catalog/negative/multicast-endpoint-protocol-amt.json +38 -0
  183. package/test-vectors/catalog/negative/multicast-endpoint-protocol-atsc3.json +38 -0
  184. package/test-vectors/catalog/negative/presentation-anchor-unsafe.json +16 -0
  185. package/test-vectors/catalog/positive/fec-algorithm-unimplemented.json +29 -0
  186. package/test-vectors/catalog/positive/fec-iso-ssbg1.json +1 -1
  187. package/test-vectors/catalog/positive/fec-multicast.json +1 -1
  188. package/test-vectors/catalog/positive/fec-reed-solomon-layered.json +50 -0
  189. package/test-vectors/catalog/positive/mmt01-12-1-init-ref-anchor.json +29 -0
  190. package/test-vectors/catalog/positive/multicast-amt-discovery-omitted.json +37 -0
  191. package/test-vectors/catalog/positive/multicast-amt-dns-relay.json +38 -0
  192. package/test-vectors/catalog/positive/multicast-amt-manual-relay.json +3 -3
  193. package/test-vectors/catalog/{negative/multicast-endpoint-missing-protocol-and-source.json → positive/multicast-asm-unprotected.json} +10 -5
  194. package/test-vectors/catalog/positive/multicast-auth-asm-sender.json +78 -0
  195. package/test-vectors/catalog/positive/multicast-auth-rotation.json +39 -38
  196. package/test-vectors/catalog/positive/multicast-draft01-4-1-example.json +81 -0
  197. package/test-vectors/catalog/positive/multicast-draft01-7-2-6-example.json +70 -0
  198. package/test-vectors/catalog/positive/presentation-anchor-negative.json +27 -0
  199. package/test-vectors/catalog/section-codes.json +31 -1
  200. package/test-vectors/catalog-multicast-auth-v1.json +38 -20
  201. package/test-vectors/catalog-validation.json +101 -5
  202. package/test-vectors/catalog-validator-public-api.mjs +14 -9
  203. package/test-vectors/generate-bc-provenance-v2.mjs +252 -0
  204. package/dist/fec-codec.d.ts +0 -32
  205. package/dist/fec-codec.d.ts.map +0 -1
  206. package/dist/fec-codec.js +0 -47
  207. package/dist/fec-codec.js.map +0 -7
  208. package/dist/manifest-auth-plan.d.ts +0 -30
  209. package/dist/manifest-auth-plan.d.ts.map +0 -1
  210. package/dist/manifest-auth-plan.js +0 -1266
  211. package/dist/manifest-auth-plan.js.map +0 -7
  212. package/dist/source-auth.d.ts +0 -2
  213. package/dist/source-auth.d.ts.map +0 -1
  214. package/dist/source-auth.js +0 -1209
  215. package/dist/source-auth.js.map +0 -7
  216. package/src/fec-codec.ts +0 -61
  217. package/src/manifest-auth-plan.ts +0 -107
  218. package/src/source-auth.ts +0 -1
  219. package/test-vectors/generate-source-auth-fixture.mjs +0 -114
  220. package/test-vectors/source-auth-v1.json +0 -61
@@ -67,10 +67,8 @@ import {
67
67
  type DuplicateHorizon,
68
68
  } from "./duplicate-ledger.js";
69
69
  import type {
70
- ManifestAuthMode,
71
- ManifestObjectIdentity,
72
- ManifestTrackContext,
73
- ManifestVerifier,
70
+ BcProvenanceV2Receiver,
71
+ BcpV2RecordPath,
74
72
  } from "@blockcast/mmt-manifest-verify";
75
73
 
76
74
  // ─── Constants ─────────────────────────────────────────────────────
@@ -177,6 +175,12 @@ export type RoutedFrameMeta = {
177
175
 
178
176
  export interface MmtpIngressContext {
179
177
  tracks: readonly Readonly<{ name: string; packetId: number }>[];
178
+ /**
179
+ * The bc-provenance v2 flow (draft-ramadan-moq-multicast-01 7.2.7) that
180
+ * delivered the packet, when its endpoint is protected: the key a receiver
181
+ * was registered under with `registerProvenanceFlow`.
182
+ */
183
+ flow?: string;
180
184
  }
181
185
 
182
186
  /** One physical stream: an MMTP packet ID and the catalog track it carries. */
@@ -435,10 +439,11 @@ export type RoutedPacketMeta = {
435
439
  /**
436
440
  * The MMTP header RAP flag: the packet starts a random access point. On a
437
441
  * `recovered` packet it is read from the FEC-reconstructed header, which is
438
- * byte-exact, so it is the flag the publisher sent. The router's own gap
439
- * decisions deliberately ignore it for recovered frames (`#isRapForGap`
440
- * judges those by bitstream only); a host using it as a tier-switch commit
441
- * point should decide explicitly whether a recovered RAP qualifies.
442
+ * byte-exact outside packet_sequence_number, so it is the flag the
443
+ * publisher sent. The router's own gap decisions deliberately ignore it for
444
+ * recovered frames (`#isRapForGap` judges those by bitstream only); a host
445
+ * using it as a tier-switch commit point should decide explicitly whether a
446
+ * recovered RAP qualifies.
442
447
  */
443
448
  rap: boolean;
444
449
  /** True when FEC reconstructed this source packet. */
@@ -557,9 +562,33 @@ export interface FECManagerLike {
557
562
  catalogTrackName?: string,
558
563
  ): Uint8Array | null;
559
564
 
565
+ /** How long ago the stream's oldest open block with an FEC deadline took its first symbol (optional). */
566
+ oldestOpenBlockAgeMs?(packetId: number, catalogTrackName: string): number | undefined;
567
+
560
568
  /** A block's RSB_length, from one of its repair symbols (optional). */
561
569
  noteRepairGroupLength?(sbn: number, packetId: number, rsbLength: number, catalogTrackName?: string): void;
562
570
 
571
+ /** fec-01 4.5: refuse a repair header whose block length the track's scheme
572
+ * forbids, before it touches block state (optional). */
573
+ admitRepairBlockLength?(packetId: number, ssbLength: number, rsbLength: number, rsId: number): boolean;
574
+ admitRepairLayerTotal?(
575
+ packetId: number,
576
+ catalogTrackName: string | undefined,
577
+ repairTrackName: string | undefined,
578
+ ssStart: number,
579
+ rsbLength: number,
580
+ ): boolean;
581
+
582
+ /** Validate a repair symbol's size before it touches block state; counts a
583
+ * mismatch on `repairSymbolSizeMismatches` (optional). */
584
+ admitRepairSymbolSize?(
585
+ packetId: number,
586
+ ssStart: number,
587
+ ssbLength: number,
588
+ rsId: number,
589
+ byteLength: number,
590
+ ): boolean;
591
+
563
592
  /** Feed a repair symbol to the FEC decoder for a given track.
564
593
  * Returns recovered block bytes if recovery completes, else null. */
565
594
  feedRepairSymbol(
@@ -681,6 +710,8 @@ export interface FECManagerLike {
681
710
  catalogTrackName: string | undefined,
682
711
  ssId: number,
683
712
  ): { sbn: number; esi: number } | null;
713
+ /** Begin a fresh decode epoch for one stream, dropping what it holds (FECManager.resetTrack). */
714
+ resetTrack?(packetId: number, catalogTrackName: string): void;
684
715
  /** iso-ssbg1-v1: hold a first-arrival source until a repair states its block. */
685
716
  holdIsoSource?(
686
717
  packetId: number,
@@ -695,6 +726,13 @@ export interface FECManagerLike {
695
726
  ssStart: number,
696
727
  ssbLength: number,
697
728
  ): IsoRepairPlacement<IsoHeldSource>;
729
+ /** iso-ssbg1-v1: turn the pending holes in a range into spans, with the sources they place. */
730
+ closeIsoHoles?(
731
+ packetId: number,
732
+ catalogTrackName: string | undefined,
733
+ start: number,
734
+ length: number,
735
+ ): readonly { readonly block: { readonly start: number }; readonly placed: readonly IsoPlacedSource<IsoHeldSource>[] }[];
698
736
  /** iso-ssbg1-v1: resolution of the SS_IDs strictly between two released frames. */
699
737
  isoSpanResolution?(
700
738
  packetId: number,
@@ -775,26 +813,6 @@ export interface FECManagerLike {
775
813
 
776
814
  // ─── MmtpRouter ─────────────────────────────────────────────────────
777
815
 
778
- export interface ManifestIdentityResolutionInput {
779
- packetId: number;
780
- sbn: number;
781
- esi: number;
782
- /**
783
- * The packet's SS_ID and its MPU's mpu_sequence_number. Under
784
- * iso-ssbg1-v1 blocks vary in length, so a packet's media group comes from
785
- * its own MPU header, never from SBN arithmetic (BLO-35597 D2a).
786
- */
787
- ssId?: number;
788
- mpuSequenceNumber?: number;
789
- catalogTrackName?: string;
790
- recovered: boolean;
791
- sourceSymbolFormat: "full-mmtp-packet" | "fec-padded-recovery";
792
- }
793
-
794
- export type ManifestIdentityResolver = (
795
- input: ManifestIdentityResolutionInput,
796
- ) => ManifestObjectIdentity | null;
797
-
798
816
  /**
799
817
  * Classification evidence carried by one first-arrival network source
800
818
  * packet: the MMTP header R bit and the MPU / data-unit identity it states
@@ -831,26 +849,22 @@ export class MmtpRouter {
831
849
  readonly #fecManager: FECManagerLike | null;
832
850
  #defaultFecMapper: FecBlockMapper | null;
833
851
  #fecMappersByPacketId = new Map<number, FecBlockMapper>();
834
- readonly #manifestVerifier: ManifestVerifier | null;
835
- readonly #ownsManifestVerifier: boolean;
836
- readonly #resolveManifestIdentity:
837
- | ((
838
- packetId: number,
839
- sbn: number,
840
- esi: number,
841
- catalogTrackName?: string,
842
- ) => ManifestObjectIdentity | null)
843
- | null;
844
- readonly #resolveManifestIdentityForRoute: ManifestIdentityResolver | null;
845
- #manifestRecoveryQueues = new Map<
852
+ /** Protected flows: one 7.2.7 receiver each, and the ingress its datagrams arrive with. */
853
+ readonly #provenance = new Map<
846
854
  string,
847
- Array<{
848
- blockId: number;
849
- result: ProcessFecBlockResult;
850
- ownerPacketId: number;
851
- catalogTrackName?: string;
852
- }>
855
+ { receiver: BcProvenanceV2Receiver; ingress: MmtpIngressContext; protected?: boolean }
853
856
  >();
857
+ #onFlowProtected: ((flow: string) => void) | null = null;
858
+ #unadmittedListedDrops = 0;
859
+ /** The ingress a held datagram arrived with; the receiver returns the same bytes on release. */
860
+ readonly #heldIngress = new WeakMap<Uint8Array, MmtpIngressContext>();
861
+ #unicastRepair = false;
862
+ /** How to route a held unicast (MoQ) datagram once a record admits it. */
863
+ readonly #heldReplay = new WeakMap<Uint8Array, () => void>();
864
+ /** The flow whose receiver admitted a stream's source datagrams, by packetId then catalog track name: recovered packets answer to it. */
865
+ readonly #provenanceStreamFlow = new Map<number, Map<string | undefined, string>>();
866
+ #unregisteredFlowDrops = 0;
867
+ #ambiguousRecoveredDrops = 0;
854
868
 
855
869
  // Temp state set by #processMMTP before calling parser.feed(),
856
870
  // read by the parser's onFrame callback for CMAF assembly + dedup.
@@ -896,6 +910,18 @@ export class MmtpRouter {
896
910
  // MSE recovery routes through CmafBlockAssembler and can reorder by block; the
897
911
  // direct callback path has to preserve decode order before frames leave libmmt.
898
912
  #latestVideoSeqByStream = new Map<string, number>();
913
+ /**
914
+ * Per stream, SS_ID - packet_sequence_number (mod 2^32) of its latest
915
+ * first-arrival FEC source packet. A recovered source symbol's wire
916
+ * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
917
+ */
918
+ #ssIdSeqOffsetByStream = new Map<string, number>();
919
+ /**
920
+ * Streams whose multicast leg delivered a RAP-flagged source packet that was
921
+ * not parsed, typically because its overlap copy was parsed first
922
+ * (BLO-49179). The next video keyframe emitted on the stream consumes it.
923
+ */
924
+ #multicastRapTwinByStream = new Set<string>();
899
925
  #lastDirectSourceVideoTsByStream = new Map<string, number>();
900
926
  #lastDirectEmittedVideoTsByStream = new Map<string, number>();
901
927
  #pendingDirectRecoveredVideoByStream = new Map<string, Map<string, PendingRecoveredVideoFrame>>();
@@ -988,11 +1014,14 @@ export class MmtpRouter {
988
1014
  */
989
1015
  #onPublisherRestart: ((packetId: number, catalogTrackName: string) => void) | null;
990
1016
  #publisherRestarts = 0;
1017
+ #restampedRecoveredSeqs = 0;
991
1018
  /** Inits delivered with no onTrackInit handler for their packetId (MOQT-01). */
992
1019
  #unmappedInitDeliveries = 0;
993
1020
  // FEC Payload IDs left unread because their (owner) packetId had no
994
1021
  // configured fec.blockProfile (see #noteUnreadableFecPayloadId).
995
1022
  #fecPayloadIdsWithoutProfile = 0;
1023
+ // Repair packets discarded by the fec-01 4.5 block-length rule.
1024
+ #repairBlockLengthDiscards = 0;
996
1025
 
997
1026
  /** The staged in-place stream switch, if any (stageStreamSwitch). */
998
1027
  #staged: StreamSwitchState | null = null;
@@ -1012,16 +1041,6 @@ export class MmtpRouter {
1012
1041
  * Pass a reader when its inputs are measured later; see
1013
1042
  * setKeyframeLostTimeoutMs. */
1014
1043
  keyframeLostTimeoutMs?: number | (() => number);
1015
- manifestVerifier?: ManifestVerifier;
1016
- /** Existing behavior is router ownership; shared browser plans opt into caller ownership. */
1017
- manifestVerifierOwnership?: "caller" | "router";
1018
- resolveManifestIdentity?: (
1019
- packetId: number,
1020
- sbn: number,
1021
- esi: number,
1022
- catalogTrackName?: string,
1023
- ) => ManifestObjectIdentity | null;
1024
- resolveManifestIdentityForRoute?: ManifestIdentityResolver;
1025
1044
  /** Internal terminal-failure sink owned by the composing transport. */
1026
1045
  onBlockFailed?: (
1027
1046
  sbn: number,
@@ -1044,10 +1063,6 @@ export class MmtpRouter {
1044
1063
  this.#fecManager = config?.fecManager ?? null;
1045
1064
  this.#onFrameGap = config?.onFrameGap ?? null;
1046
1065
  this.#defaultFecMapper = config?.fecMapper ?? null;
1047
- this.#manifestVerifier = config?.manifestVerifier ?? null;
1048
- this.#ownsManifestVerifier = config?.manifestVerifierOwnership !== "caller";
1049
- this.#resolveManifestIdentity = config?.resolveManifestIdentity ?? null;
1050
- this.#resolveManifestIdentityForRoute = config?.resolveManifestIdentityForRoute ?? null;
1051
1066
 
1052
1067
  // Create MMTP parser — handles MFU extraction, reassembly, keyframe detection.
1053
1068
  // Its MFUReassembler is the single reassembler for BOTH the source path
@@ -1119,6 +1134,19 @@ export class MmtpRouter {
1119
1134
  : { catalogTrackName: meta.catalogTrackName }),
1120
1135
  };
1121
1136
  if (meta.source) frameMeta.source = meta.source;
1137
+ // During make-before-break the overlap copy usually wins the parse ledger,
1138
+ // so almost every frame is head-attributed to "moq" and multicast takeover
1139
+ // waited on a rare multicast-won keyframe (BLO-49179: 34 s, 38 s, or past
1140
+ // the 30 s window). A RAP whose multicast twin the ledger dropped is
1141
+ // multicast delivering keyframes, so the next keyframe routes as multicast:
1142
+ // this one if the twin beat its tail, else at most one GOP later.
1143
+ // deliveryProvenance is unchanged and stays 'mixed'.
1144
+ if (isVideo && frameMeta.keyframe) {
1145
+ const twinSeen = this.#multicastRapTwinByStream.delete(
1146
+ this.#mediaStreamKey(packetId, frameMeta.catalogTrackName),
1147
+ );
1148
+ if (twinSeen && frameMeta.source === "moq") frameMeta.source = "multicast";
1149
+ }
1122
1150
  // Forward whenever present, not when truthy: 'unknown' is a verdict the
1123
1151
  // parser reached, not a value to drop.
1124
1152
  if (meta.deliveryProvenance !== undefined)
@@ -1364,6 +1392,15 @@ export class MmtpRouter {
1364
1392
  return this.#publisherRestarts;
1365
1393
  }
1366
1394
 
1395
+ /**
1396
+ * FEC-recovered source symbols whose reconstructed header named a
1397
+ * packet_sequence_number other than the wire sequence their SS_ID maps to:
1398
+ * a hop re-stamped the sequence after the sender protected the packet.
1399
+ */
1400
+ get restampedRecoveredSequenceCount(): number {
1401
+ return this.#restampedRecoveredSeqs;
1402
+ }
1403
+
1367
1404
  /**
1368
1405
  * Packets whose Source or Repair FEC Payload ID was left unread because
1369
1406
  * their (owner) packetId had no configured `fec.blockProfile`: FEC not
@@ -1376,6 +1413,15 @@ export class MmtpRouter {
1376
1413
  return this.#fecPayloadIdsWithoutProfile;
1377
1414
  }
1378
1415
 
1416
+ /**
1417
+ * Repair packets discarded at admission by the fec-01 4.5 rule (RS_ID not
1418
+ * below RSB_length, or a reed-solomon SSB_length + RSB_length above 255),
1419
+ * before they touched any block state.
1420
+ */
1421
+ get repairBlockLengthDiscards(): number {
1422
+ return this.#repairBlockLengthDiscards;
1423
+ }
1424
+
1379
1425
  get reassembler(): MfuReassemblerBackend {
1380
1426
  return this.#parser.reassembler;
1381
1427
  }
@@ -1747,32 +1793,185 @@ export class MmtpRouter {
1747
1793
  });
1748
1794
  }
1749
1795
 
1750
- registerManifestTrack(context: ManifestTrackContext): void {
1751
- if (!this.#manifestVerifier) throw new Error("manifest verifier is not configured");
1752
- this.#manifestVerifier.registerTrack(context);
1796
+ /**
1797
+ * Protect a flow (draft-ramadan-moq-multicast-01 7.2.7): every multicast
1798
+ * datagram whose ingress names `ingress.flow`, source and repair alike, is
1799
+ * admitted by `receiver` before anything reads it, and an unadmitted one is
1800
+ * held or dropped. The caller owns the receiver's configuration; the router
1801
+ * releases it on `releaseProvenanceFlow` and on dispose.
1802
+ */
1803
+ registerProvenanceFlow(
1804
+ ingress: MmtpIngressContext & { flow: string },
1805
+ receiver: BcProvenanceV2Receiver,
1806
+ ): void {
1807
+ this.#provenance.get(ingress.flow)?.receiver.release();
1808
+ this.#provenance.set(ingress.flow, { receiver, ingress });
1809
+ receiver.keepPendingAgeMs = () => this.#oldestOpenBlockAgeMs(ingress.flow);
1753
1810
  }
1754
1811
 
1755
- feedManifestFrame(trackName: string, frame: Uint8Array): void {
1756
- this.#manifestVerifier?.ingestManifestFrame(trackName, frame);
1812
+ /**
1813
+ * Declare that this receiver can request unicast repair (a repair FETCH
1814
+ * scheduler is wired): a protected flow then keeps the pending entries of
1815
+ * its open blocks for the repair to consume (7.2.7 step 2).
1816
+ */
1817
+ setUnicastRepair(enabled: boolean): void {
1818
+ this.#unicastRepair = enabled;
1757
1819
  }
1758
1820
 
1759
- setManifestAuthMode(mode: ManifestAuthMode): void {
1760
- this.#manifestVerifier?.setMode(mode);
1761
- if (mode !== "enforce") {
1762
- for (const queue of this.#manifestRecoveryQueues.values()) {
1763
- for (const item of queue) {
1764
- this.#routeProcessedFecSymbols(
1765
- item.blockId,
1766
- item.result,
1767
- item.ownerPacketId,
1768
- item.catalogTrackName,
1769
- );
1821
+ #oldestOpenBlockAgeMs(flow: string): number | undefined {
1822
+ const entry = this.#provenance.get(flow);
1823
+ if (!this.#unicastRepair || !entry) return undefined;
1824
+ let age: number | undefined;
1825
+ for (const { name, packetId } of entry.ingress.tracks) {
1826
+ const a = name ? this.#fecManager?.oldestOpenBlockAgeMs?.(packetId, name) : undefined;
1827
+ if (a !== undefined && (age === undefined || a > age)) age = a;
1828
+ }
1829
+ return age;
1830
+ }
1831
+
1832
+ /**
1833
+ * Replace a registered flow's ingress (a rendition switch staged, committed
1834
+ * or cancelled) while keeping its receiver; a no-op for an unregistered flow.
1835
+ */
1836
+ updateProvenanceFlowIngress(ingress: MmtpIngressContext & { flow: string }): void {
1837
+ const entry = this.#provenance.get(ingress.flow);
1838
+ if (!entry) return;
1839
+ this.#provenance.set(ingress.flow, { ...entry, ingress });
1840
+ // A protected flow newly listing a track drops its MoQ copies from now
1841
+ // on, so discard what its FEC instance holds of them first (7.2.7).
1842
+ if (entry.protected) {
1843
+ for (const { name, packetId } of ingress.tracks) {
1844
+ if (name && !entry.ingress.tracks.some((t) => t.name === name && t.packetId === packetId)) {
1845
+ this.#fecManager?.resetTrack?.(packetId, name);
1770
1846
  }
1771
1847
  }
1772
- this.#manifestRecoveryQueues.clear();
1773
1848
  }
1774
1849
  }
1775
1850
 
1851
+ /**
1852
+ * Called once per protection of a flow: at the admission that makes this
1853
+ * router's consumers protected under it (7.2.7), after their unadmitted
1854
+ * holdings of its listed tracks are discarded. Again after an unprotect.
1855
+ */
1856
+ onProvenanceFlowProtected(cb: ((flow: string) => void) | null): void {
1857
+ this.#onFlowProtected = cb;
1858
+ }
1859
+
1860
+ /**
1861
+ * The receiver ceased to hold the flow's endpoint on failover (7.2.7): drop
1862
+ * its state and hold queues (no expiry counted) and un-protect its tracks,
1863
+ * which then take MoQ again. The registration stays, so multicast resuming
1864
+ * protects the flow anew at its next admission.
1865
+ */
1866
+ unprotectProvenanceFlow(flow: string): void {
1867
+ const entry = this.#provenance.get(flow);
1868
+ if (!entry) return;
1869
+ entry.receiver.release();
1870
+ entry.protected = false;
1871
+ }
1872
+
1873
+ /** MoQ packets of a track a protected flow lists, dropped on its unicast path: duplicate, overflow, or listed by more than one flow. */
1874
+ get unadmittedListedDropCount(): number {
1875
+ return this.#unadmittedListedDrops;
1876
+ }
1877
+
1878
+ /**
1879
+ * The admission that makes this router protected under `flow` (7.2.7):
1880
+ * its FEC instances discard what they hold of the flow's listed tracks so
1881
+ * no unadmitted symbol stands for an admitted one, then notify. Before it
1882
+ * nothing of the flow was admitted, so every such symbol is unadmitted.
1883
+ * The playback parse ledger is kept: it records MoQ copies already played,
1884
+ * not holdings, and clearing it re-emits that media (audio twice).
1885
+ * The FEC reset is the whole 7.2.7 discard here: no keyframe-overlay
1886
+ * instance exists to hold anything (repair-layers.ts is the catalog
1887
+ * contract only, no decoder), and packet_id 0 is never a listed track
1888
+ * (`ingressHasPacketId`), so nothing of it is held for the flow.
1889
+ */
1890
+ #noteFlowAdmitted(flow: string): void {
1891
+ const entry = this.#provenance.get(flow);
1892
+ if (!entry || entry.protected) return;
1893
+ entry.protected = true;
1894
+ for (const { name, packetId } of entry.ingress.tracks) {
1895
+ if (name) this.#fecManager?.resetTrack?.(packetId, name);
1896
+ }
1897
+ this.#onFlowProtected?.(flow);
1898
+ }
1899
+
1900
+ /**
1901
+ * Admit a MoQ datagram of `packetId` on the unicast path of the protected
1902
+ * flow that lists it (7.2.7). `unlisted`: no protected flow lists it, so it
1903
+ * is read as before. A held datagram is routed by `replay` when a record
1904
+ * admits it; one more than one protected flow lists is dropped. So is an
1905
+ * overlap copy: it never enters FEC accounting, so admitting it would leave
1906
+ * its multicast twin a duplicate and the block one symbol short.
1907
+ */
1908
+ #admitUnicast(
1909
+ packetId: number,
1910
+ packet: Uint8Array,
1911
+ replay: () => void,
1912
+ overlapCopy = false,
1913
+ ): "unlisted" | "admitted" | "held" | "dropped" {
1914
+ let receiver: BcProvenanceV2Receiver | undefined;
1915
+ for (const entry of this.#provenance.values()) {
1916
+ if (!entry.protected || !ingressHasPacketId(entry.ingress, packetId)) continue;
1917
+ if (receiver || overlapCopy) {
1918
+ this.#unadmittedListedDrops++;
1919
+ return "dropped";
1920
+ }
1921
+ receiver = entry.receiver;
1922
+ }
1923
+ if (!receiver) return "unlisted";
1924
+ const { verdict } = receiver.onDatagram(packet, "unicast");
1925
+ if (verdict === "admitted") return "admitted";
1926
+ if (verdict === "held") {
1927
+ this.#heldReplay.set(packet, replay);
1928
+ return "held";
1929
+ }
1930
+ this.#unadmittedListedDrops++;
1931
+ return "dropped";
1932
+ }
1933
+
1934
+ /**
1935
+ * Feed one bc-provenance record of `flow`: a datagram from `manifestPort`
1936
+ * (`multicast`) or an object of the manifest track (`mirror`). Held
1937
+ * datagrams the record admits are routed before this returns.
1938
+ */
1939
+ feedProvenanceRecord(flow: string, record: Uint8Array, path: BcpV2RecordPath): string {
1940
+ const entry = this.#provenance.get(flow);
1941
+ if (!entry || this.#disposed) return "unregistered";
1942
+ const result = entry.receiver.onRecord(record, path);
1943
+ if (result.admitted.length > 0) {
1944
+ this.#noteFlowAdmitted(flow);
1945
+ this.#withDeferredFecPokes(() => {
1946
+ for (const datagram of result.admitted) {
1947
+ const replay = this.#heldReplay.get(datagram);
1948
+ if (replay) replay();
1949
+ else this.#processMMTP(datagram, "multicast", true, this.#heldIngress.get(datagram) ?? entry.ingress, false, true);
1950
+ }
1951
+ });
1952
+ }
1953
+ return result.verdict;
1954
+ }
1955
+
1956
+ /** The receiver ceased to hold the flow: its hold queues are dropped, not expired. */
1957
+ releaseProvenanceFlow(flow: string): void {
1958
+ this.#provenance.get(flow)?.receiver.release();
1959
+ this.#provenance.delete(flow);
1960
+ for (const byName of this.#provenanceStreamFlow.values()) {
1961
+ for (const [name, bound] of byName) if (bound === flow) byName.delete(name);
1962
+ }
1963
+ }
1964
+
1965
+ /** Multicast datagrams dropped because their ingress names a flow with no registered receiver. */
1966
+ get unregisteredFlowDropCount(): number {
1967
+ return this.#unregisteredFlowDrops;
1968
+ }
1969
+
1970
+ /** Recovered packets dropped because more than one protected flow could own their stream. */
1971
+ get ambiguousRecoveredDropCount(): number {
1972
+ return this.#ambiguousRecoveredDrops;
1973
+ }
1974
+
1776
1975
  /**
1777
1976
  * Main entry point: feed a raw MMTP packet for processing.
1778
1977
  *
@@ -1790,12 +1989,11 @@ export class MmtpRouter {
1790
1989
  feedPacket(
1791
1990
  packet: Uint8Array,
1792
1991
  source: "multicast" | "moq",
1793
- manifestIdentity?: ManifestObjectIdentity,
1794
1992
  ingress?: MmtpIngressContext,
1795
1993
  ): void {
1796
1994
  if (this.#disposed) return;
1797
1995
  this.#withDeferredFecPokes(() => {
1798
- this.#processMMTP(packet, source, manifestIdentity, false, ingress);
1996
+ this.#processMMTP(packet, source, false, ingress);
1799
1997
  });
1800
1998
  }
1801
1999
 
@@ -1831,7 +2029,7 @@ export class MmtpRouter {
1831
2029
  feedOverlapCopy(packet: Uint8Array, ingress?: MmtpIngressContext): void {
1832
2030
  if (this.#disposed) return;
1833
2031
  this.#withDeferredFecPokes(() => {
1834
- this.#processMMTP(packet, "moq", undefined, false, ingress, true);
2032
+ this.#processMMTP(packet, "moq", false, ingress, true);
1835
2033
  });
1836
2034
  }
1837
2035
 
@@ -1843,10 +2041,11 @@ export class MmtpRouter {
1843
2041
  packet: Uint8Array,
1844
2042
  ownerPacketIdHint?: number,
1845
2043
  catalogTrackName?: string,
2044
+ repairTrackName?: string,
1846
2045
  ): void {
1847
2046
  if (this.#disposed) return;
1848
2047
  this.#withDeferredFecPokes(() => {
1849
- this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName);
2048
+ this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName);
1850
2049
  });
1851
2050
  }
1852
2051
 
@@ -1854,6 +2053,8 @@ export class MmtpRouter {
1854
2053
  packet: Uint8Array,
1855
2054
  ownerPacketIdHint: number | undefined,
1856
2055
  catalogTrackName: string | undefined,
2056
+ repairTrackName: string | undefined,
2057
+ admitted = false,
1857
2058
  ): void {
1858
2059
  // One header parse per packet, as on the multicast repair branch: mmt-fec's
1859
2060
  // parseRepairPacket() parsed it once more before this parse (BLO-36599).
@@ -1884,6 +2085,11 @@ export class MmtpRouter {
1884
2085
  );
1885
2086
  }
1886
2087
 
2088
+ if (ownerPacketId != null && !admitted) {
2089
+ const admit = this.#admitUnicast(ownerPacketId, packet, () =>
2090
+ this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, true));
2091
+ if (admit === "held" || admit === "dropped") return;
2092
+ }
1887
2093
  if (ownerPacketId != null && this.#fecManager) {
1888
2094
  this.#moqRepairPidCounts[repairPacketId] =
1889
2095
  (this.#moqRepairPidCounts[repairPacketId] || 0) + 1;
@@ -1901,7 +2107,7 @@ export class MmtpRouter {
1901
2107
  this.#noteUnreadableFecPayloadId(ownerPacketId, "repair");
1902
2108
  return;
1903
2109
  }
1904
- this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, "moq");
2110
+ this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, "moq", repairTrackName);
1905
2111
  }
1906
2112
  }
1907
2113
 
@@ -2007,6 +2213,7 @@ export class MmtpRouter {
2007
2213
  catalogTrackName: string | undefined,
2008
2214
  repair: { ssStart: number; ssbLength: number; rsbLength: number; rsId: number; symbolData: Uint8Array },
2009
2215
  source: "multicast" | "moq",
2216
+ repairTrackName?: string,
2010
2217
  ): void {
2011
2218
  const fec = this.#fecManager;
2012
2219
  if (!fec?.placeIsoRepair) {
@@ -2014,6 +2221,33 @@ export class MmtpRouter {
2014
2221
  `[MmtpRouter] packetId=${ownerPacketId} is iso-ssbg1-v1 but its FEC manager cannot place ISO blocks`,
2015
2222
  );
2016
2223
  }
2224
+ // fec-01 4.5: a reed-solomon block-length violation is discarded with the
2225
+ // block state unchanged, so it runs before any other admission.
2226
+ if (
2227
+ fec.admitRepairBlockLength &&
2228
+ !fec.admitRepairBlockLength(ownerPacketId, repair.ssbLength, repair.rsbLength, repair.rsId)
2229
+ ) {
2230
+ this.#repairBlockLengthDiscards++;
2231
+ return;
2232
+ }
2233
+ // A repair symbol that is not exactly T bytes is invalid: refuse it before
2234
+ // it can place a block or be swallowed by dedup, so it is always counted
2235
+ // and never reaches the decoder (BLO-48306).
2236
+ if (
2237
+ fec.admitRepairSymbolSize &&
2238
+ !fec.admitRepairSymbolSize(
2239
+ ownerPacketId,
2240
+ repair.ssStart,
2241
+ repair.ssbLength,
2242
+ repair.rsId,
2243
+ repair.symbolData.byteLength,
2244
+ )
2245
+ ) return;
2246
+ // fec-01 6.3.9: a held layer's total below its anchor fails the track's FEC closed.
2247
+ if (
2248
+ fec.admitRepairLayerTotal &&
2249
+ !fec.admitRepairLayerTotal(ownerPacketId, catalogTrackName, repairTrackName, repair.ssStart, repair.rsbLength)
2250
+ ) return;
2017
2251
  const placement = fec.placeIsoRepair(ownerPacketId, catalogTrackName, repair.ssStart, repair.ssbLength);
2018
2252
  if (placement.status !== "placed") return;
2019
2253
  const blockStart = placement.block.start;
@@ -2049,6 +2283,23 @@ export class MmtpRouter {
2049
2283
  }
2050
2284
  }
2051
2285
 
2286
+ /**
2287
+ * The range repair FETCH for an undelimited hole ended (draft-ramadan-moq-fec
2288
+ * §7.5): what no repair stated becomes repair-less spans, whose held sources
2289
+ * are fed exactly as a span a repair closed.
2290
+ */
2291
+ closeIsoHoles(
2292
+ ownerPacketId: number,
2293
+ catalogTrackName: string | undefined,
2294
+ start: number,
2295
+ length: number,
2296
+ ): void {
2297
+ const spans = this.#fecManager?.closeIsoHoles?.(ownerPacketId, catalogTrackName, start, length) ?? [];
2298
+ for (const span of spans) {
2299
+ this.#replayIsoSources(ownerPacketId, catalogTrackName, span.block.start, span.placed);
2300
+ }
2301
+ }
2302
+
2052
2303
  /**
2053
2304
  * Feed iso-ssbg1-v1 sources a repair just placed, in SS_ID order, exactly as
2054
2305
  * a first-arrival source is fed once its block is known: transport
@@ -2180,13 +2431,14 @@ export class MmtpRouter {
2180
2431
  this.#trackSynced.delete(streamKey);
2181
2432
  this.#droppedPreSyncVideo.delete(streamKey);
2182
2433
  this.#latestVideoSeqByStream.delete(streamKey);
2434
+ this.#ssIdSeqOffsetByStream.delete(streamKey);
2435
+ this.#multicastRapTwinByStream.delete(streamKey);
2183
2436
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
2184
2437
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
2185
2438
  this.#pendingDirectRecoveredVideoByStream.delete(streamKey);
2186
2439
  this.#lastDirectSourceAudioCursorByStream.delete(streamKey);
2187
2440
  this.#lastDirectEmittedAudioCursorByStream.delete(streamKey);
2188
2441
  this.#pendingDirectRecoveredAudioByStream.delete(streamKey);
2189
- this.#manifestRecoveryQueues.delete(streamKey);
2190
2442
  this.#deliveredVideoHighWaterByStream.delete(streamKey);
2191
2443
  this.#stream(packetId, catalogTrackName).duplicates.clear();
2192
2444
  const assemblersToReset = new Set<CmafBlockAssembler>();
@@ -2238,7 +2490,6 @@ export class MmtpRouter {
2238
2490
  this.#lastDirectSourceAudioCursorByStream.delete(key);
2239
2491
  this.#lastDirectEmittedAudioCursorByStream.delete(key);
2240
2492
  this.#pendingDirectRecoveredAudioByStream.delete(key);
2241
- this.#manifestRecoveryQueues.delete(key);
2242
2493
  this.#trackInitDelivered.delete(key);
2243
2494
  this.#parserDiagnostics.delete(key);
2244
2495
  this.#pendingFecPokes.delete(key);
@@ -2534,8 +2785,9 @@ export class MmtpRouter {
2534
2785
  this.#parserDiagnostics.clear();
2535
2786
  this.#catalogTrackNamesByPacketId.clear();
2536
2787
  this.#repairOwnersByPacketId.clear();
2537
- if (this.#ownsManifestVerifier) this.#manifestVerifier?.dispose();
2538
- this.#manifestRecoveryQueues.clear();
2788
+ for (const { receiver } of this.#provenance.values()) receiver.release();
2789
+ this.#provenance.clear();
2790
+ this.#provenanceStreamFlow.clear();
2539
2791
  for (const assembler of this.#mseAssemblers.values()) assembler.dispose();
2540
2792
  this.#mseAssemblers.clear();
2541
2793
  }
@@ -2889,7 +3141,6 @@ export class MmtpRouter {
2889
3141
  #processMMTP(
2890
3142
  packet: Uint8Array,
2891
3143
  source: "multicast" | "moq",
2892
- manifestIdentity?: ManifestObjectIdentity,
2893
3144
  manifestAdmitted = false,
2894
3145
  ingress?: MmtpIngressContext,
2895
3146
  overlapCopy = false,
@@ -2938,57 +3189,40 @@ export class MmtpRouter {
2938
3189
  this.#classifyPacketId(info.packetId) !== null &&
2939
3190
  this.#configuredBlockProfile(info.packetId) === undefined;
2940
3191
  if (fecUnreadable && !manifestAdmitted) this.#noteUnreadableFecPayloadId(info.packetId, "source");
3192
+ if (source === "multicast" && manifestAdmitted && !info.isRepair && ingress?.flow !== undefined) {
3193
+ let byName = this.#provenanceStreamFlow.get(info.packetId);
3194
+ if (!byName) this.#provenanceStreamFlow.set(info.packetId, (byName = new Map()));
3195
+ byName.set(catalogTrackNameForPacket(ingress, info.packetId), ingress.flow);
3196
+ }
2941
3197
 
2942
- if (!info.isRepair && this.#manifestVerifier && !manifestAdmitted) {
2943
- let identity = manifestIdentity;
2944
- if (!identity && info.fecPayloadId && !fecUnreadable && (this.#resolveManifestIdentityForRoute || this.#resolveManifestIdentity)) {
2945
- // A source resolves with its block coordinates (SS_Start, ESI), the
2946
- // pair a recovered symbol of the same block resolves with. SS_ID alone
2947
- // locates no block (C.5.3): until a repair states this source's block
2948
- // it has none, its identity stays absent, and the verifier's
2949
- // missing-identity policy below applies.
2950
- const catalogTrackName = catalogTrackNameForPacket(ingress, info.packetId);
2951
- const coordinates = this.#locateFecSource(info.packetId, catalogTrackName, info.fecPayloadId.ssId);
2952
- identity = coordinates === null ? undefined : (this.#resolveManifestIdentityForRoute
2953
- ? this.#resolveManifestIdentityForRoute({
2954
- packetId: info.packetId,
2955
- sbn: coordinates.sbn,
2956
- esi: coordinates.esi,
2957
- ...(catalogTrackName === undefined ? {} : { catalogTrackName }),
2958
- recovered: false,
2959
- sourceSymbolFormat: "full-mmtp-packet",
2960
- })
2961
- : this.#resolveManifestIdentity!(
2962
- info.packetId,
2963
- coordinates.sbn,
2964
- coordinates.esi,
2965
- catalogTrackName,
2966
- )) ?? undefined;
2967
- }
2968
- if (identity) {
2969
- identity = {
2970
- ...identity,
2971
- packetId: info.packetId,
2972
- ...(info.fecPayloadId ? { ssId: info.fecPayloadId.ssId } : {}),
2973
- };
2974
- const authenticated = info.fecPayloadId ? packet.subarray(0, packet.length - 4) : packet;
2975
- // A `stall` admission quarantines the packet and releases it later,
2976
- // after the stream has moved on; a synchronous release happens inside
2977
- // admitObject, before this flag is set.
2978
- let quarantined = false;
2979
- const admission = this.#manifestVerifier.admitObject(identity, authenticated, () => {
2980
- if (!this.#disposed) {
2981
- this.#processMMTP(packet, source, identity, true, ingress, overlapCopy, quarantined);
2982
- }
2983
- });
2984
- quarantined = admission.action === "stall";
3198
+ // A protected flow admits every datagram, repair included, before it is
3199
+ // read (7.2.7): an unadmitted repair symbol never reaches the decoder.
3200
+ if (source === "multicast" && !manifestAdmitted && ingress?.flow !== undefined) {
3201
+ const protectedFlow = this.#provenance.get(ingress.flow);
3202
+ // Named but not registered (before registration, after release): the
3203
+ // flow is protected, so nothing admits this datagram. Fail closed.
3204
+ if (!protectedFlow) {
3205
+ this.#unregisteredFlowDrops++;
3206
+ debugRouter(`[MmtpRouter] Dropping multicast packet pid=${info.packetId}: flow ${ingress.flow} has no receiver`);
2985
3207
  return;
2986
3208
  }
2987
- if (
2988
- this.#manifestVerifier.config.mode === "enforce" &&
2989
- this.#manifestVerifier.config.onMissingManifest === "stall"
2990
- ) {
2991
- console.warn(`[MmtpRouter] manifest identity absent; stalling packetId=${info.packetId}`);
3209
+ // Held: released by a record (feedProvenanceRecord) or expired. Duplicate / overflow: dropped.
3210
+ const { verdict } = protectedFlow.receiver.onDatagram(packet, "multicast");
3211
+ if (verdict === "admitted") {
3212
+ this.#noteFlowAdmitted(ingress.flow);
3213
+ this.#processMMTP(packet, source, true, ingress, overlapCopy);
3214
+ }
3215
+ else if (verdict === "held") this.#heldIngress.set(packet, ingress!);
3216
+ return;
3217
+ }
3218
+
3219
+ // A MoQ packet of a track a protected flow lists is a datagram of that
3220
+ // flow on its unicast path (7.2.7): admitted before it is read, or held.
3221
+ if (source === "moq" && !manifestAdmitted) {
3222
+ const admit = this.#admitUnicast(info.packetId, packet, () =>
3223
+ this.#processMMTP(packet, source, true, ingress, overlapCopy, true), overlapCopy);
3224
+ if (admit !== "unlisted") {
3225
+ if (admit === "admitted") this.#processMMTP(packet, source, true, ingress, overlapCopy);
2992
3226
  return;
2993
3227
  }
2994
3228
  }
@@ -3079,8 +3313,8 @@ export class MmtpRouter {
3079
3313
  // Start a fresh epoch for the stream before this packet is looked up.
3080
3314
  // The reset needs the catalog identity, so a stream without one is not
3081
3315
  // checked; an overlap copy is MoQ bytes and says nothing about the
3082
- // multicast publisher, and neither does a packet the manifest verifier
3083
- // quarantined: it predates the horizon because it waited, not because the
3316
+ // multicast publisher, and neither does a packet a provenance hold queue
3317
+ // released: it predates the horizon because it waited, not because the
3084
3318
  // publisher restarted.
3085
3319
  if (
3086
3320
  source === "multicast" &&
@@ -3205,6 +3439,13 @@ export class MmtpRouter {
3205
3439
  parseSourceSymbol = !duplicates.parsedSymbols.has(info.fecPayloadId.ssId);
3206
3440
  }
3207
3441
 
3442
+ if (fecPayloadId && !overlapCopy) {
3443
+ this.#ssIdSeqOffsetByStream.set(
3444
+ this.#mediaStreamKey(info.packetId, catalogTrackName),
3445
+ (fecPayloadId.ssId - info.sequenceNumber) >>> 0,
3446
+ );
3447
+ }
3448
+
3208
3449
  // Parse only the first copy of an FEC source symbol. A late direct copy
3209
3450
  // of a worker-recovered fragment has the same SBN/ESI and fragment
3210
3451
  // counter; feeding it again can make the MFU buffer non-contiguous even
@@ -3231,6 +3472,11 @@ export class MmtpRouter {
3231
3472
  // An FEC source frame is anchored by its own SS_ID (C.5.2).
3232
3473
  ...(fecSource && fecPayloadId ? { fecSbn: fecPayloadId.ssId } : {}),
3233
3474
  }, parsed);
3475
+ } else if (source === "multicast" && info.rapFlag) {
3476
+ // Usually the twin of a RAP its overlap copy already parsed.
3477
+ this.#multicastRapTwinByStream.add(
3478
+ this.#mediaStreamKey(info.packetId, catalogTrackName),
3479
+ );
3234
3480
  }
3235
3481
  // The frame this packet completed can commit an in-place switch that
3236
3482
  // retires this very packet ID. Its FEC state is gone then, and feeding
@@ -3959,115 +4205,63 @@ export class MmtpRouter {
3959
4205
  this.#routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
3960
4206
  }
3961
4207
 
4208
+ /**
4209
+ * A recovered source packet of a protected flow is admitted on its own
4210
+ * digest: its bytes with the SS_ID it was sent with (SS_Start + ESI)
4211
+ * appended are the datagram the record listed (7.2.7). One that no record
4212
+ * lists is dropped; holding it would let it out later as a multicast arrival.
4213
+ */
3962
4214
  #routeVerifiedFecSymbols(
3963
4215
  blockId: number,
3964
4216
  result: ProcessFecBlockResult,
3965
4217
  ownerPacketId?: number,
3966
4218
  catalogTrackName?: string,
3967
4219
  ): void {
3968
- if (!this.#manifestVerifier || ownerPacketId == null) {
3969
- this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
3970
- return;
3971
- }
3972
- if (!this.#resolveManifestIdentity && !this.#resolveManifestIdentityForRoute) {
3973
- console.warn(`[MmtpRouter] manifest identity resolver unavailable; recovered media is fail-open for packetId=${ownerPacketId} block=${blockId}`);
3974
- this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
3975
- return;
4220
+ const receiver = ownerPacketId == null ? undefined : this.#provenanceFor(ownerPacketId, catalogTrackName);
4221
+ if (receiver === "ambiguous") {
4222
+ this.#ambiguousRecoveredDrops += result.symbols.length;
4223
+ result = { ...result, symbols: [] };
4224
+ } else if (receiver) {
4225
+ result = {
4226
+ ...result,
4227
+ symbols: result.symbols.filter((sym) => {
4228
+ const wire = new Uint8Array(sym.rawSymbol.byteLength + 4);
4229
+ wire.set(sym.rawSymbol);
4230
+ new DataView(wire.buffer).setUint32(sym.rawSymbol.byteLength, this.#fecAnchorForRecovered(blockId, sym.index));
4231
+ return receiver.admitRecovered(wire);
4232
+ }),
4233
+ };
3976
4234
  }
3977
- const queueKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
3978
- const queue = this.#manifestRecoveryQueues.get(queueKey) ?? [];
3979
- queue.push({ blockId, result, ownerPacketId, catalogTrackName });
3980
- this.#manifestRecoveryQueues.set(queueKey, queue);
3981
- if (queue.length > 1) return;
3982
- const drain = (): void => {
3983
- const next = queue[0];
3984
- if (!next) {
3985
- this.#manifestRecoveryQueues.delete(queueKey);
3986
- return;
3987
- }
3988
- this.#admitRecoveredResult(
3989
- next.blockId,
3990
- next.result,
3991
- next.ownerPacketId,
3992
- next.catalogTrackName,
3993
- () => {
3994
- queue.shift();
3995
- drain();
3996
- },
3997
- );
3998
- };
3999
- drain();
4235
+ this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
4000
4236
  }
4001
4237
 
4002
- #admitRecoveredResult(
4003
- blockId: number,
4004
- result: ProcessFecBlockResult,
4005
- ownerPacketId: number,
4238
+ /**
4239
+ * The receiver a recovered packet of `packetId` answers to: the flow that
4240
+ * admitted the stream's source datagrams. Before any was admitted, the one
4241
+ * flow whose registration lists the stream; more than one (a repair flow
4242
+ * also lists its owners' source tracks) cannot be told apart, so none.
4243
+ */
4244
+ #provenanceFor(
4245
+ packetId: number,
4006
4246
  catalogTrackName: string | undefined,
4007
- done: () => void,
4008
- ): void {
4009
- const verifier = this.#manifestVerifier;
4010
- const resolveIdentity = this.#resolveManifestIdentity;
4011
- const resolveIdentityForRoute = this.#resolveManifestIdentityForRoute;
4012
- if (!verifier) {
4013
- this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
4014
- done();
4015
- return;
4016
- }
4017
- if (!resolveIdentity && !resolveIdentityForRoute) throw new Error("manifest identity resolver disappeared during admission");
4018
- const symbols = result.symbols;
4019
- const admitNext = (index: number): void => {
4020
- const symbol = symbols[index];
4021
- if (!symbol) {
4022
- done();
4023
- return;
4024
- }
4025
- const identity = resolveIdentityForRoute
4026
- ? resolveIdentityForRoute({
4027
- packetId: ownerPacketId,
4028
- sbn: blockId,
4029
- esi: symbol.index,
4030
- ...(catalogTrackName === undefined ? {} : { catalogTrackName }),
4031
- recovered: true,
4032
- sourceSymbolFormat: "fec-padded-recovery",
4033
- })
4034
- : resolveIdentity!(ownerPacketId, blockId, symbol.index, catalogTrackName);
4035
- if (!identity) {
4036
- console.warn(`[MmtpRouter] manifest identity unresolved; recovered symbol is fail-open for packetId=${ownerPacketId} block=${blockId} esi=${symbol.index}`);
4037
- this.#routeProcessedFecSymbols(
4038
- blockId,
4039
- { ...result, symbols: [symbol] },
4040
- ownerPacketId,
4041
- catalogTrackName,
4042
- );
4043
- admitNext(index + 1);
4044
- return;
4247
+ ): BcProvenanceV2Receiver | "ambiguous" | undefined {
4248
+ // A caller that names no track matches every name the packet id was admitted under.
4249
+ const byName = this.#provenanceStreamFlow.get(packetId);
4250
+ const flows = new Set(
4251
+ catalogTrackName === undefined || !byName
4252
+ ? byName?.values()
4253
+ : byName.has(catalogTrackName) ? [byName.get(catalogTrackName)!] : [],
4254
+ );
4255
+ if (flows.size > 1) return "ambiguous";
4256
+ for (const bound of flows) return this.#provenance.get(bound)?.receiver ?? "ambiguous";
4257
+ let match: BcProvenanceV2Receiver | undefined;
4258
+ for (const { receiver, ingress } of this.#provenance.values()) {
4259
+ if (ingress.tracks.some((t) => t.packetId === packetId && (catalogTrackName === undefined || t.name === catalogTrackName))) {
4260
+ if (match) return "ambiguous";
4261
+ match = receiver;
4045
4262
  }
4046
- const admission = verifier.admitObject(
4047
- {
4048
- ...identity,
4049
- packetId: ownerPacketId,
4050
- },
4051
- symbol.rawSymbol,
4052
- () => {
4053
- if (!this.#disposed) {
4054
- this.#routeProcessedFecSymbols(
4055
- blockId,
4056
- { ...result, symbols: [symbol] },
4057
- ownerPacketId,
4058
- catalogTrackName,
4059
- );
4060
- }
4061
- admitNext(index + 1);
4062
- },
4063
- // A stalled symbol that is later discarded instead of played must still
4064
- // advance this loop; enforce mode never calls the release callback for
4065
- // it (BLO-30095).
4066
- () => admitNext(index + 1),
4067
- );
4068
- if (admission.action === "drop") admitNext(index + 1);
4069
- };
4070
- admitNext(0);
4263
+ }
4264
+ return match;
4071
4265
  }
4072
4266
 
4073
4267
  #routeProcessedFecSymbols(
@@ -4080,6 +4274,28 @@ export class MmtpRouter {
4080
4274
  // which track this block belongs to — resolves per-track, then legacy fallback.
4081
4275
  if (ownerPacketId == null) return; // no track association
4082
4276
  if (this.#classifyPacketId(ownerPacketId) === null) return; // unknown track
4277
+ // A recovered symbol's header names the sequence the sender protected. A
4278
+ // hop that re-stamps packet_sequence_number after protection (cast's
4279
+ // publisher-rotation bridge) leaves the decode mixing every received
4280
+ // source's re-stamped bytes into it. The reassembler addresses a
4281
+ // fragmented data unit by sequence + fragment counter, and the source
4282
+ // dedup reads the same number, so that fragment would park under a
4283
+ // foreign address until its data unit times out. Its SS_ID still names
4284
+ // its wire sequence, through the offset every received source states.
4285
+ const ssIdSeqOffset = this.#ssIdSeqOffsetByStream.get(
4286
+ this.#mediaStreamKey(ownerPacketId, catalogTrackName),
4287
+ );
4288
+ if (ssIdSeqOffset !== undefined) {
4289
+ result = {
4290
+ ...result,
4291
+ symbols: result.symbols.map((sym) => {
4292
+ const wire = (this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset) >>> 0;
4293
+ if (wire === sym.packetSequenceNumber) return sym;
4294
+ this.#restampedRecoveredSeqs++;
4295
+ return { ...sym, packetSequenceNumber: wire };
4296
+ }),
4297
+ };
4298
+ }
4083
4299
  this.#stream(ownerPacketId, catalogTrackName).duplicates.advance(blockId);
4084
4300
 
4085
4301
  // A recovered symbol is a function of EVERY symbol that entered its block,
@@ -4100,7 +4316,8 @@ export class MmtpRouter {
4100
4316
  ) ?? 'unknown';
4101
4317
 
4102
4318
  for (const sym of result.symbols) {
4103
- // The block processor read these from the recovered packet's own header.
4319
+ // The block processor read these from the recovered packet's own
4320
+ // header; the sequence is the wire one derived above.
4104
4321
  this.#routeTrackPacket(sym.rawSymbol, ownerPacketId, sym.packetSequenceNumber, {
4105
4322
  mmtpTimestamp: sym.fragment.timestamp,
4106
4323
  rap: sym.fragment.rapFlag,