@blockcast/mmt-container 0.4.1 → 0.5.0-main.6f3380bce0c1

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 (72) hide show
  1. package/README.md +2 -2
  2. package/dist/browser-runtime.js +3407 -376
  3. package/dist/browser-runtime.js.map +4 -4
  4. package/dist/cmcd-producer.d.ts +5 -1
  5. package/dist/cmcd-producer.d.ts.map +1 -1
  6. package/dist/cmcd-producer.js.map +2 -2
  7. package/dist/delivery-catalog.js +18 -2
  8. package/dist/delivery-catalog.js.map +2 -2
  9. package/dist/fec-manager.d.ts +13 -16
  10. package/dist/fec-manager.d.ts.map +1 -1
  11. package/dist/fec-manager.js +137 -76
  12. package/dist/fec-manager.js.map +3 -3
  13. package/dist/held-layer-admission.d.ts +58 -0
  14. package/dist/held-layer-admission.d.ts.map +1 -0
  15. package/dist/held-layer-admission.js +105 -0
  16. package/dist/held-layer-admission.js.map +7 -0
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js.map +2 -2
  19. package/dist/mmtp-container-parser.no-modules.js +2682 -1023
  20. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  21. package/dist/mmtp-fec-session.d.ts +36 -3
  22. package/dist/mmtp-fec-session.d.ts.map +1 -1
  23. package/dist/mmtp-fec-session.js +114 -5
  24. package/dist/mmtp-fec-session.js.map +3 -3
  25. package/dist/mmtp-router.d.ts +64 -28
  26. package/dist/mmtp-router.d.ts.map +1 -1
  27. package/dist/mmtp-router.js +286 -203
  28. package/dist/mmtp-router.js.map +2 -2
  29. package/dist/multicast-auth-catalog.d.ts +10 -2
  30. package/dist/multicast-auth-catalog.d.ts.map +1 -1
  31. package/dist/multicast-auth-catalog.js +422 -22
  32. package/dist/multicast-auth-catalog.js.map +4 -4
  33. package/dist/multicast-manager.d.ts +48 -9
  34. package/dist/multicast-manager.d.ts.map +1 -1
  35. package/dist/multicast-manager.js +3349 -354
  36. package/dist/multicast-manager.js.map +4 -4
  37. package/dist/multicast-transport.d.ts +4 -1
  38. package/dist/multicast-transport.d.ts.map +1 -1
  39. package/dist/multicast-transport.js +20 -3
  40. package/dist/multicast-transport.js.map +2 -2
  41. package/dist/no-modules.d.ts +1 -2
  42. package/dist/no-modules.d.ts.map +1 -1
  43. package/dist/no-modules.js +2668 -1007
  44. package/dist/no-modules.js.map +4 -4
  45. package/dist/repair-fetch.d.ts +10 -1
  46. package/dist/repair-fetch.d.ts.map +1 -1
  47. package/dist/repair-fetch.js +5 -2
  48. package/dist/repair-fetch.js.map +2 -2
  49. package/package.json +5 -14
  50. package/src/cmcd-producer.ts +6 -1
  51. package/src/fec-manager.ts +74 -127
  52. package/src/held-layer-admission.ts +161 -0
  53. package/src/index.ts +5 -9
  54. package/src/mmtp-fec-session.ts +76 -3
  55. package/src/mmtp-router.ts +341 -272
  56. package/src/multicast-auth-catalog.ts +81 -8
  57. package/src/multicast-manager.ts +189 -48
  58. package/src/multicast-transport.ts +6 -2
  59. package/src/no-modules.ts +1 -6
  60. package/src/repair-fetch.ts +24 -4
  61. package/dist/manifest-auth-plan.d.ts +0 -31
  62. package/dist/manifest-auth-plan.d.ts.map +0 -1
  63. package/dist/manifest-auth-plan.js +0 -426
  64. package/dist/manifest-auth-plan.js.map +0 -7
  65. package/dist/source-auth.d.ts +0 -2
  66. package/dist/source-auth.d.ts.map +0 -1
  67. package/dist/source-auth.js +0 -3912
  68. package/dist/source-auth.js.map +0 -7
  69. package/src/manifest-auth-plan.ts +0 -55
  70. package/src/source-auth.ts +0 -1
  71. package/test-vectors/generate-source-auth-fixture.mjs +0 -114
  72. 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. */
@@ -558,6 +562,9 @@ export interface FECManagerLike {
558
562
  catalogTrackName?: string,
559
563
  ): Uint8Array | null;
560
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
+
561
568
  /** A block's RSB_length, from one of its repair symbols (optional). */
562
569
  noteRepairGroupLength?(sbn: number, packetId: number, rsbLength: number, catalogTrackName?: string): void;
563
570
 
@@ -703,6 +710,8 @@ export interface FECManagerLike {
703
710
  catalogTrackName: string | undefined,
704
711
  ssId: number,
705
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;
706
715
  /** iso-ssbg1-v1: hold a first-arrival source until a repair states its block. */
707
716
  holdIsoSource?(
708
717
  packetId: number,
@@ -804,26 +813,6 @@ export interface FECManagerLike {
804
813
 
805
814
  // ─── MmtpRouter ─────────────────────────────────────────────────────
806
815
 
807
- export interface ManifestIdentityResolutionInput {
808
- packetId: number;
809
- sbn: number;
810
- esi: number;
811
- /**
812
- * The packet's SS_ID and its MPU's mpu_sequence_number. Under
813
- * iso-ssbg1-v1 blocks vary in length, so a packet's media group comes from
814
- * its own MPU header, never from SBN arithmetic (BLO-35597 D2a).
815
- */
816
- ssId?: number;
817
- mpuSequenceNumber?: number;
818
- catalogTrackName?: string;
819
- recovered: boolean;
820
- sourceSymbolFormat: "full-mmtp-packet" | "fec-padded-recovery";
821
- }
822
-
823
- export type ManifestIdentityResolver = (
824
- input: ManifestIdentityResolutionInput,
825
- ) => ManifestObjectIdentity | null;
826
-
827
816
  /**
828
817
  * Classification evidence carried by one first-arrival network source
829
818
  * packet: the MMTP header R bit and the MPU / data-unit identity it states
@@ -860,26 +849,22 @@ export class MmtpRouter {
860
849
  readonly #fecManager: FECManagerLike | null;
861
850
  #defaultFecMapper: FecBlockMapper | null;
862
851
  #fecMappersByPacketId = new Map<number, FecBlockMapper>();
863
- readonly #manifestVerifier: ManifestVerifier | null;
864
- readonly #ownsManifestVerifier: boolean;
865
- readonly #resolveManifestIdentity:
866
- | ((
867
- packetId: number,
868
- sbn: number,
869
- esi: number,
870
- catalogTrackName?: string,
871
- ) => ManifestObjectIdentity | null)
872
- | null;
873
- readonly #resolveManifestIdentityForRoute: ManifestIdentityResolver | null;
874
- #manifestRecoveryQueues = new Map<
852
+ /** Protected flows: one 7.2.7 receiver each, and the ingress its datagrams arrive with. */
853
+ readonly #provenance = new Map<
875
854
  string,
876
- Array<{
877
- blockId: number;
878
- result: ProcessFecBlockResult;
879
- ownerPacketId: number;
880
- catalogTrackName?: string;
881
- }>
855
+ { receiver: BcProvenanceV2Receiver; ingress: MmtpIngressContext; protected?: boolean }
882
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;
883
868
 
884
869
  // Temp state set by #processMMTP before calling parser.feed(),
885
870
  // read by the parser's onFrame callback for CMAF assembly + dedup.
@@ -1056,16 +1041,6 @@ export class MmtpRouter {
1056
1041
  * Pass a reader when its inputs are measured later; see
1057
1042
  * setKeyframeLostTimeoutMs. */
1058
1043
  keyframeLostTimeoutMs?: number | (() => number);
1059
- manifestVerifier?: ManifestVerifier;
1060
- /** Existing behavior is router ownership; shared browser plans opt into caller ownership. */
1061
- manifestVerifierOwnership?: "caller" | "router";
1062
- resolveManifestIdentity?: (
1063
- packetId: number,
1064
- sbn: number,
1065
- esi: number,
1066
- catalogTrackName?: string,
1067
- ) => ManifestObjectIdentity | null;
1068
- resolveManifestIdentityForRoute?: ManifestIdentityResolver;
1069
1044
  /** Internal terminal-failure sink owned by the composing transport. */
1070
1045
  onBlockFailed?: (
1071
1046
  sbn: number,
@@ -1088,10 +1063,6 @@ export class MmtpRouter {
1088
1063
  this.#fecManager = config?.fecManager ?? null;
1089
1064
  this.#onFrameGap = config?.onFrameGap ?? null;
1090
1065
  this.#defaultFecMapper = config?.fecMapper ?? null;
1091
- this.#manifestVerifier = config?.manifestVerifier ?? null;
1092
- this.#ownsManifestVerifier = config?.manifestVerifierOwnership !== "caller";
1093
- this.#resolveManifestIdentity = config?.resolveManifestIdentity ?? null;
1094
- this.#resolveManifestIdentityForRoute = config?.resolveManifestIdentityForRoute ?? null;
1095
1066
 
1096
1067
  // Create MMTP parser — handles MFU extraction, reassembly, keyframe detection.
1097
1068
  // Its MFUReassembler is the single reassembler for BOTH the source path
@@ -1822,32 +1793,185 @@ export class MmtpRouter {
1822
1793
  });
1823
1794
  }
1824
1795
 
1825
- registerManifestTrack(context: ManifestTrackContext): void {
1826
- if (!this.#manifestVerifier) throw new Error("manifest verifier is not configured");
1827
- 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);
1810
+ }
1811
+
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;
1828
1819
  }
1829
1820
 
1830
- feedManifestFrame(trackName: string, frame: Uint8Array): void {
1831
- this.#manifestVerifier?.ingestManifestFrame(trackName, frame);
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;
1832
1830
  }
1833
1831
 
1834
- setManifestAuthMode(mode: ManifestAuthMode): void {
1835
- this.#manifestVerifier?.setMode(mode);
1836
- if (mode !== "enforce") {
1837
- for (const queue of this.#manifestRecoveryQueues.values()) {
1838
- for (const item of queue) {
1839
- this.#routeProcessedFecSymbols(
1840
- item.blockId,
1841
- item.result,
1842
- item.ownerPacketId,
1843
- item.catalogTrackName,
1844
- );
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);
1845
1846
  }
1846
1847
  }
1847
- this.#manifestRecoveryQueues.clear();
1848
1848
  }
1849
1849
  }
1850
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
+
1851
1975
  /**
1852
1976
  * Main entry point: feed a raw MMTP packet for processing.
1853
1977
  *
@@ -1865,12 +1989,11 @@ export class MmtpRouter {
1865
1989
  feedPacket(
1866
1990
  packet: Uint8Array,
1867
1991
  source: "multicast" | "moq",
1868
- manifestIdentity?: ManifestObjectIdentity,
1869
1992
  ingress?: MmtpIngressContext,
1870
1993
  ): void {
1871
1994
  if (this.#disposed) return;
1872
1995
  this.#withDeferredFecPokes(() => {
1873
- this.#processMMTP(packet, source, manifestIdentity, false, ingress);
1996
+ this.#processMMTP(packet, source, false, ingress);
1874
1997
  });
1875
1998
  }
1876
1999
 
@@ -1906,7 +2029,7 @@ export class MmtpRouter {
1906
2029
  feedOverlapCopy(packet: Uint8Array, ingress?: MmtpIngressContext): void {
1907
2030
  if (this.#disposed) return;
1908
2031
  this.#withDeferredFecPokes(() => {
1909
- this.#processMMTP(packet, "moq", undefined, false, ingress, true);
2032
+ this.#processMMTP(packet, "moq", false, ingress, true);
1910
2033
  });
1911
2034
  }
1912
2035
 
@@ -1931,6 +2054,7 @@ export class MmtpRouter {
1931
2054
  ownerPacketIdHint: number | undefined,
1932
2055
  catalogTrackName: string | undefined,
1933
2056
  repairTrackName: string | undefined,
2057
+ admitted = false,
1934
2058
  ): void {
1935
2059
  // One header parse per packet, as on the multicast repair branch: mmt-fec's
1936
2060
  // parseRepairPacket() parsed it once more before this parse (BLO-36599).
@@ -1961,6 +2085,11 @@ export class MmtpRouter {
1961
2085
  );
1962
2086
  }
1963
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
+ }
1964
2093
  if (ownerPacketId != null && this.#fecManager) {
1965
2094
  this.#moqRepairPidCounts[repairPacketId] =
1966
2095
  (this.#moqRepairPidCounts[repairPacketId] || 0) + 1;
@@ -2147,10 +2276,11 @@ export class MmtpRouter {
2147
2276
  catalogTrackName,
2148
2277
  );
2149
2278
  if (recovered && !alreadyCompleted) {
2150
- fec.cancelBlockTimeout(blockStart, ownerPacketId, catalogTrackName);
2151
- fec.countRecovery(ownerPacketId, blockStart, catalogTrackName);
2152
- fec.markBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
2153
- this.#routeRecoveredBlock(blockStart, recovered, ownerPacketId, catalogTrackName);
2279
+ this.#routeRecoveredBlock(blockStart, recovered, ownerPacketId, catalogTrackName, () => {
2280
+ fec.cancelBlockTimeout(blockStart, ownerPacketId, catalogTrackName);
2281
+ fec.countRecovery(ownerPacketId, blockStart, catalogTrackName);
2282
+ fec.markBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
2283
+ });
2154
2284
  }
2155
2285
  }
2156
2286
 
@@ -2203,10 +2333,11 @@ export class MmtpRouter {
2203
2333
  const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
2204
2334
  const recovered = fec.feedSourceSymbol(ownerPacketId, ssId, payload.symbolData, catalogTrackName);
2205
2335
  if (!recovered || alreadyCompleted) continue;
2206
- fec.cancelBlockTimeout(blockStart, ownerPacketId, catalogTrackName);
2207
- fec.countRecovery(ownerPacketId, blockStart, catalogTrackName);
2208
- fec.markBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
2209
- this.#routeRecoveredBlock(blockStart, recovered, ownerPacketId, catalogTrackName);
2336
+ this.#routeRecoveredBlock(blockStart, recovered, ownerPacketId, catalogTrackName, () => {
2337
+ fec.cancelBlockTimeout(blockStart, ownerPacketId, catalogTrackName);
2338
+ fec.countRecovery(ownerPacketId, blockStart, catalogTrackName);
2339
+ fec.markBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
2340
+ });
2210
2341
  }
2211
2342
  }
2212
2343
 
@@ -2244,10 +2375,14 @@ export class MmtpRouter {
2244
2375
  data: Uint8Array,
2245
2376
  packetId: number,
2246
2377
  catalogTrackName?: string,
2247
- ): void {
2378
+ ): boolean {
2248
2379
  // A Worker-recovered block arrives here whole: defer the gate's drains
2249
2380
  // until all its frames are in, as the in-band recovery path does.
2250
- this.#withDeferredFecPokes(() => this.#routeRecoveredBlock(blockId, data, packetId, catalogTrackName));
2381
+ let recovered = false;
2382
+ this.#withDeferredFecPokes(() => {
2383
+ recovered = this.#routeRecoveredBlock(blockId, data, packetId, catalogTrackName);
2384
+ });
2385
+ return recovered;
2251
2386
  }
2252
2387
 
2253
2388
  /** Route a single recovered source symbol through the parser + dedup pipeline.
@@ -2258,10 +2393,10 @@ export class MmtpRouter {
2258
2393
  packetId: number,
2259
2394
  esi = 0,
2260
2395
  catalogTrackName?: string,
2261
- ): void {
2396
+ ): boolean {
2262
2397
  const blockProfile = this.#blockProfileFor(packetId);
2263
2398
  const result = processFecSymbol(data, { ownerPacketId: packetId, index: esi, blockProfile });
2264
- this.#routeVerifiedFecSymbols(blockId, result, packetId, catalogTrackName);
2399
+ return this.#routeVerifiedFecSymbols(blockId, result, packetId, catalogTrackName);
2265
2400
  }
2266
2401
 
2267
2402
  // ── Keyframe timer cancellation ─────────────────────────────────
@@ -2310,7 +2445,6 @@ export class MmtpRouter {
2310
2445
  this.#lastDirectSourceAudioCursorByStream.delete(streamKey);
2311
2446
  this.#lastDirectEmittedAudioCursorByStream.delete(streamKey);
2312
2447
  this.#pendingDirectRecoveredAudioByStream.delete(streamKey);
2313
- this.#manifestRecoveryQueues.delete(streamKey);
2314
2448
  this.#deliveredVideoHighWaterByStream.delete(streamKey);
2315
2449
  this.#stream(packetId, catalogTrackName).duplicates.clear();
2316
2450
  const assemblersToReset = new Set<CmafBlockAssembler>();
@@ -2362,7 +2496,6 @@ export class MmtpRouter {
2362
2496
  this.#lastDirectSourceAudioCursorByStream.delete(key);
2363
2497
  this.#lastDirectEmittedAudioCursorByStream.delete(key);
2364
2498
  this.#pendingDirectRecoveredAudioByStream.delete(key);
2365
- this.#manifestRecoveryQueues.delete(key);
2366
2499
  this.#trackInitDelivered.delete(key);
2367
2500
  this.#parserDiagnostics.delete(key);
2368
2501
  this.#pendingFecPokes.delete(key);
@@ -2658,8 +2791,9 @@ export class MmtpRouter {
2658
2791
  this.#parserDiagnostics.clear();
2659
2792
  this.#catalogTrackNamesByPacketId.clear();
2660
2793
  this.#repairOwnersByPacketId.clear();
2661
- if (this.#ownsManifestVerifier) this.#manifestVerifier?.dispose();
2662
- this.#manifestRecoveryQueues.clear();
2794
+ for (const { receiver } of this.#provenance.values()) receiver.release();
2795
+ this.#provenance.clear();
2796
+ this.#provenanceStreamFlow.clear();
2663
2797
  for (const assembler of this.#mseAssemblers.values()) assembler.dispose();
2664
2798
  this.#mseAssemblers.clear();
2665
2799
  }
@@ -3013,7 +3147,6 @@ export class MmtpRouter {
3013
3147
  #processMMTP(
3014
3148
  packet: Uint8Array,
3015
3149
  source: "multicast" | "moq",
3016
- manifestIdentity?: ManifestObjectIdentity,
3017
3150
  manifestAdmitted = false,
3018
3151
  ingress?: MmtpIngressContext,
3019
3152
  overlapCopy = false,
@@ -3062,57 +3195,40 @@ export class MmtpRouter {
3062
3195
  this.#classifyPacketId(info.packetId) !== null &&
3063
3196
  this.#configuredBlockProfile(info.packetId) === undefined;
3064
3197
  if (fecUnreadable && !manifestAdmitted) this.#noteUnreadableFecPayloadId(info.packetId, "source");
3198
+ if (source === "multicast" && manifestAdmitted && !info.isRepair && ingress?.flow !== undefined) {
3199
+ let byName = this.#provenanceStreamFlow.get(info.packetId);
3200
+ if (!byName) this.#provenanceStreamFlow.set(info.packetId, (byName = new Map()));
3201
+ byName.set(catalogTrackNameForPacket(ingress, info.packetId), ingress.flow);
3202
+ }
3065
3203
 
3066
- if (!info.isRepair && this.#manifestVerifier && !manifestAdmitted) {
3067
- let identity = manifestIdentity;
3068
- if (!identity && info.fecPayloadId && !fecUnreadable && (this.#resolveManifestIdentityForRoute || this.#resolveManifestIdentity)) {
3069
- // A source resolves with its block coordinates (SS_Start, ESI), the
3070
- // pair a recovered symbol of the same block resolves with. SS_ID alone
3071
- // locates no block (C.5.3): until a repair states this source's block
3072
- // it has none, its identity stays absent, and the verifier's
3073
- // missing-identity policy below applies.
3074
- const catalogTrackName = catalogTrackNameForPacket(ingress, info.packetId);
3075
- const coordinates = this.#locateFecSource(info.packetId, catalogTrackName, info.fecPayloadId.ssId);
3076
- identity = coordinates === null ? undefined : (this.#resolveManifestIdentityForRoute
3077
- ? this.#resolveManifestIdentityForRoute({
3078
- packetId: info.packetId,
3079
- sbn: coordinates.sbn,
3080
- esi: coordinates.esi,
3081
- ...(catalogTrackName === undefined ? {} : { catalogTrackName }),
3082
- recovered: false,
3083
- sourceSymbolFormat: "full-mmtp-packet",
3084
- })
3085
- : this.#resolveManifestIdentity!(
3086
- info.packetId,
3087
- coordinates.sbn,
3088
- coordinates.esi,
3089
- catalogTrackName,
3090
- )) ?? undefined;
3091
- }
3092
- if (identity) {
3093
- identity = {
3094
- ...identity,
3095
- packetId: info.packetId,
3096
- ...(info.fecPayloadId ? { ssId: info.fecPayloadId.ssId } : {}),
3097
- };
3098
- const authenticated = info.fecPayloadId ? packet.subarray(0, packet.length - 4) : packet;
3099
- // A `stall` admission quarantines the packet and releases it later,
3100
- // after the stream has moved on; a synchronous release happens inside
3101
- // admitObject, before this flag is set.
3102
- let quarantined = false;
3103
- const admission = this.#manifestVerifier.admitObject(identity, authenticated, () => {
3104
- if (!this.#disposed) {
3105
- this.#processMMTP(packet, source, identity, true, ingress, overlapCopy, quarantined);
3106
- }
3107
- });
3108
- quarantined = admission.action === "stall";
3204
+ // A protected flow admits every datagram, repair included, before it is
3205
+ // read (7.2.7): an unadmitted repair symbol never reaches the decoder.
3206
+ if (source === "multicast" && !manifestAdmitted && ingress?.flow !== undefined) {
3207
+ const protectedFlow = this.#provenance.get(ingress.flow);
3208
+ // Named but not registered (before registration, after release): the
3209
+ // flow is protected, so nothing admits this datagram. Fail closed.
3210
+ if (!protectedFlow) {
3211
+ this.#unregisteredFlowDrops++;
3212
+ debugRouter(`[MmtpRouter] Dropping multicast packet pid=${info.packetId}: flow ${ingress.flow} has no receiver`);
3109
3213
  return;
3110
3214
  }
3111
- if (
3112
- this.#manifestVerifier.config.mode === "enforce" &&
3113
- this.#manifestVerifier.config.onMissingManifest === "stall"
3114
- ) {
3115
- console.warn(`[MmtpRouter] manifest identity absent; stalling packetId=${info.packetId}`);
3215
+ // Held: released by a record (feedProvenanceRecord) or expired. Duplicate / overflow: dropped.
3216
+ const { verdict } = protectedFlow.receiver.onDatagram(packet, "multicast");
3217
+ if (verdict === "admitted") {
3218
+ this.#noteFlowAdmitted(ingress.flow);
3219
+ this.#processMMTP(packet, source, true, ingress, overlapCopy);
3220
+ }
3221
+ else if (verdict === "held") this.#heldIngress.set(packet, ingress!);
3222
+ return;
3223
+ }
3224
+
3225
+ // A MoQ packet of a track a protected flow lists is a datagram of that
3226
+ // flow on its unicast path (7.2.7): admitted before it is read, or held.
3227
+ if (source === "moq" && !manifestAdmitted) {
3228
+ const admit = this.#admitUnicast(info.packetId, packet, () =>
3229
+ this.#processMMTP(packet, source, true, ingress, overlapCopy, true), overlapCopy);
3230
+ if (admit !== "unlisted") {
3231
+ if (admit === "admitted") this.#processMMTP(packet, source, true, ingress, overlapCopy);
3116
3232
  return;
3117
3233
  }
3118
3234
  }
@@ -3203,8 +3319,8 @@ export class MmtpRouter {
3203
3319
  // Start a fresh epoch for the stream before this packet is looked up.
3204
3320
  // The reset needs the catalog identity, so a stream without one is not
3205
3321
  // checked; an overlap copy is MoQ bytes and says nothing about the
3206
- // multicast publisher, and neither does a packet the manifest verifier
3207
- // quarantined: it predates the horizon because it waited, not because the
3322
+ // multicast publisher, and neither does a packet a provenance hold queue
3323
+ // released: it predates the horizon because it waited, not because the
3208
3324
  // publisher restarted.
3209
3325
  if (
3210
3326
  source === "multicast" &&
@@ -3433,37 +3549,24 @@ export class MmtpRouter {
3433
3549
  sourceFec.symbolData,
3434
3550
  catalogTrackName,
3435
3551
  );
3436
- if (recovered) {
3437
- if (!alreadyCompleted && this.#classifyPacketId(info.packetId) !== null) {
3438
- if (catalogTrackName === undefined) {
3439
- this.#fecManager.cancelBlockTimeout(sourceFec.sbn, info.packetId);
3440
- } else {
3441
- this.#fecManager.cancelBlockTimeout(
3442
- sourceFec.sbn,
3443
- info.packetId,
3444
- catalogTrackName,
3445
- );
3446
- }
3447
- }
3448
- // Only route recovered blocks that needed actual repair.
3449
- if (!alreadyCompleted) {
3450
- this.#fecManager.countRecovery(info.packetId, sourceFec.sbn, catalogTrackName);
3552
+ // Only route recovered blocks that needed actual repair; complete
3553
+ // one only once admission has released its recovered packets.
3554
+ if (recovered && !alreadyCompleted) {
3555
+ const fec = this.#fecManager;
3556
+ const sbn = sourceFec.sbn;
3557
+ const packetId = info.packetId;
3558
+ const tracked = this.#classifyPacketId(packetId) !== null;
3559
+ this.#routeRecoveredBlock(sbn, recovered, packetId, catalogTrackName, () => {
3451
3560
  if (catalogTrackName === undefined) {
3452
- this.#fecManager.markBlockCompleted(sourceFec.sbn, info.packetId);
3561
+ if (tracked) fec.cancelBlockTimeout(sbn, packetId);
3562
+ fec.countRecovery(packetId, sbn, catalogTrackName);
3563
+ fec.markBlockCompleted(sbn, packetId);
3453
3564
  } else {
3454
- this.#fecManager.markBlockCompleted(
3455
- sourceFec.sbn,
3456
- info.packetId,
3457
- catalogTrackName,
3458
- );
3565
+ if (tracked) fec.cancelBlockTimeout(sbn, packetId, catalogTrackName);
3566
+ fec.countRecovery(packetId, sbn, catalogTrackName);
3567
+ fec.markBlockCompleted(sbn, packetId, catalogTrackName);
3459
3568
  }
3460
- this.#routeRecoveredBlock(
3461
- sourceFec.sbn,
3462
- recovered,
3463
- info.packetId,
3464
- catalogTrackName,
3465
- );
3466
- }
3569
+ });
3467
3570
  }
3468
3571
  }
3469
3572
  }
@@ -4068,7 +4171,8 @@ export class MmtpRouter {
4068
4171
  recovered: Uint8Array,
4069
4172
  ownerPacketId?: number,
4070
4173
  catalogTrackName?: string,
4071
- ): void {
4174
+ complete?: () => void,
4175
+ ): boolean {
4072
4176
  // MMTP path: use processFecBlock for MMTP-wrapped recovery.
4073
4177
  // Recovered symbols are individual MMTP packets that may be fragments
4074
4178
  // (FI=1/2/3) of a larger MFU. Route through the reassembler so
@@ -4092,118 +4196,83 @@ export class MmtpRouter {
4092
4196
  ownerPacketId,
4093
4197
  blockProfile,
4094
4198
  });
4095
- this.#routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
4199
+ return this.#routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete);
4096
4200
  }
4097
4201
 
4202
+ /**
4203
+ * A recovered source packet of a protected flow is admitted on its own
4204
+ * digest: its bytes with the SS_ID it was sent with (SS_Start + ESI)
4205
+ * appended are the datagram the record listed (7.2.7). One that no record
4206
+ * lists is dropped; holding it would let it out later as a multicast arrival.
4207
+ * Returns whether the decode recovered the block: every packet it yields
4208
+ * that this router has not parsed already is admitted. A block one of whose
4209
+ * recovered packets is refused is unrecovered (7.2.7): its caller leaves it
4210
+ * open, so it reaches its FEC deadline and fails by class. Always true
4211
+ * outside a protected flow.
4212
+ */
4098
4213
  #routeVerifiedFecSymbols(
4099
4214
  blockId: number,
4100
4215
  result: ProcessFecBlockResult,
4101
4216
  ownerPacketId?: number,
4102
4217
  catalogTrackName?: string,
4103
- ): void {
4104
- if (!this.#manifestVerifier || ownerPacketId == null) {
4105
- this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
4106
- return;
4107
- }
4108
- if (!this.#resolveManifestIdentity && !this.#resolveManifestIdentityForRoute) {
4109
- console.warn(`[MmtpRouter] manifest identity resolver unavailable; recovered media is fail-open for packetId=${ownerPacketId} block=${blockId}`);
4110
- this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
4111
- return;
4218
+ complete?: () => void,
4219
+ ): boolean {
4220
+ const receiver = ownerPacketId == null ? undefined : this.#provenanceFor(ownerPacketId, catalogTrackName);
4221
+ let recovered = true;
4222
+ if (receiver) {
4223
+ const parsed = this.#stream(ownerPacketId!, catalogTrackName).duplicates.parsedSymbols;
4224
+ result = {
4225
+ ...result,
4226
+ symbols: result.symbols.filter((sym) => {
4227
+ const ssId = this.#fecAnchorForRecovered(blockId, sym.index);
4228
+ // A received copy was admitted on arrival; its recovered twin is a duplicate.
4229
+ if (parsed.has(ssId)) return false;
4230
+ let admitted = false;
4231
+ if (receiver === "ambiguous") {
4232
+ this.#ambiguousRecoveredDrops++;
4233
+ } else {
4234
+ const wire = new Uint8Array(sym.rawSymbol.byteLength + 4);
4235
+ wire.set(sym.rawSymbol);
4236
+ new DataView(wire.buffer).setUint32(sym.rawSymbol.byteLength, ssId);
4237
+ admitted = receiver.admitRecovered(wire);
4238
+ }
4239
+ if (!admitted) recovered = false;
4240
+ return admitted;
4241
+ }),
4242
+ };
4112
4243
  }
4113
- const queueKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
4114
- const queue = this.#manifestRecoveryQueues.get(queueKey) ?? [];
4115
- queue.push({ blockId, result, ownerPacketId, catalogTrackName });
4116
- this.#manifestRecoveryQueues.set(queueKey, queue);
4117
- if (queue.length > 1) return;
4118
- const drain = (): void => {
4119
- const next = queue[0];
4120
- if (!next) {
4121
- this.#manifestRecoveryQueues.delete(queueKey);
4122
- return;
4123
- }
4124
- this.#admitRecoveredResult(
4125
- next.blockId,
4126
- next.result,
4127
- next.ownerPacketId,
4128
- next.catalogTrackName,
4129
- () => {
4130
- queue.shift();
4131
- drain();
4132
- },
4133
- );
4134
- };
4135
- drain();
4244
+ if (recovered) complete?.();
4245
+ this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
4246
+ return recovered;
4136
4247
  }
4137
4248
 
4138
- #admitRecoveredResult(
4139
- blockId: number,
4140
- result: ProcessFecBlockResult,
4141
- ownerPacketId: number,
4249
+ /**
4250
+ * The receiver a recovered packet of `packetId` answers to: the flow that
4251
+ * admitted the stream's source datagrams. Before any was admitted, the one
4252
+ * flow whose registration lists the stream; more than one (a repair flow
4253
+ * also lists its owners' source tracks) cannot be told apart, so none.
4254
+ */
4255
+ #provenanceFor(
4256
+ packetId: number,
4142
4257
  catalogTrackName: string | undefined,
4143
- done: () => void,
4144
- ): void {
4145
- const verifier = this.#manifestVerifier;
4146
- const resolveIdentity = this.#resolveManifestIdentity;
4147
- const resolveIdentityForRoute = this.#resolveManifestIdentityForRoute;
4148
- if (!verifier) {
4149
- this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
4150
- done();
4151
- return;
4152
- }
4153
- if (!resolveIdentity && !resolveIdentityForRoute) throw new Error("manifest identity resolver disappeared during admission");
4154
- const symbols = result.symbols;
4155
- const admitNext = (index: number): void => {
4156
- const symbol = symbols[index];
4157
- if (!symbol) {
4158
- done();
4159
- return;
4160
- }
4161
- const identity = resolveIdentityForRoute
4162
- ? resolveIdentityForRoute({
4163
- packetId: ownerPacketId,
4164
- sbn: blockId,
4165
- esi: symbol.index,
4166
- ...(catalogTrackName === undefined ? {} : { catalogTrackName }),
4167
- recovered: true,
4168
- sourceSymbolFormat: "fec-padded-recovery",
4169
- })
4170
- : resolveIdentity!(ownerPacketId, blockId, symbol.index, catalogTrackName);
4171
- if (!identity) {
4172
- console.warn(`[MmtpRouter] manifest identity unresolved; recovered symbol is fail-open for packetId=${ownerPacketId} block=${blockId} esi=${symbol.index}`);
4173
- this.#routeProcessedFecSymbols(
4174
- blockId,
4175
- { ...result, symbols: [symbol] },
4176
- ownerPacketId,
4177
- catalogTrackName,
4178
- );
4179
- admitNext(index + 1);
4180
- return;
4258
+ ): BcProvenanceV2Receiver | "ambiguous" | undefined {
4259
+ // A caller that names no track matches every name the packet id was admitted under.
4260
+ const byName = this.#provenanceStreamFlow.get(packetId);
4261
+ const flows = new Set(
4262
+ catalogTrackName === undefined || !byName
4263
+ ? byName?.values()
4264
+ : byName.has(catalogTrackName) ? [byName.get(catalogTrackName)!] : [],
4265
+ );
4266
+ if (flows.size > 1) return "ambiguous";
4267
+ for (const bound of flows) return this.#provenance.get(bound)?.receiver ?? "ambiguous";
4268
+ let match: BcProvenanceV2Receiver | undefined;
4269
+ for (const { receiver, ingress } of this.#provenance.values()) {
4270
+ if (ingress.tracks.some((t) => t.packetId === packetId && (catalogTrackName === undefined || t.name === catalogTrackName))) {
4271
+ if (match) return "ambiguous";
4272
+ match = receiver;
4181
4273
  }
4182
- const admission = verifier.admitObject(
4183
- {
4184
- ...identity,
4185
- packetId: ownerPacketId,
4186
- },
4187
- symbol.rawSymbol,
4188
- () => {
4189
- if (!this.#disposed) {
4190
- this.#routeProcessedFecSymbols(
4191
- blockId,
4192
- { ...result, symbols: [symbol] },
4193
- ownerPacketId,
4194
- catalogTrackName,
4195
- );
4196
- }
4197
- admitNext(index + 1);
4198
- },
4199
- // A stalled symbol that is later discarded instead of played must still
4200
- // advance this loop; enforce mode never calls the release callback for
4201
- // it (BLO-30095).
4202
- () => admitNext(index + 1),
4203
- );
4204
- if (admission.action === "drop") admitNext(index + 1);
4205
- };
4206
- admitNext(0);
4274
+ }
4275
+ return match;
4207
4276
  }
4208
4277
 
4209
4278
  #routeProcessedFecSymbols(