@blockcast/mmt-container 2.2.0-main.2c4d96d3ffc2 → 2.2.0-main.34b53d33bace

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 (60) hide show
  1. package/dist/browser-runtime.js +954 -157
  2. package/dist/browser-runtime.js.map +3 -3
  3. package/dist/cmaf-block-assembler.js +92 -1
  4. package/dist/cmaf-block-assembler.js.map +2 -2
  5. package/dist/codec-utils.d.ts.map +1 -1
  6. package/dist/codec-utils.js +92 -1
  7. package/dist/codec-utils.js.map +2 -2
  8. package/dist/delta-fallback-config.js.map +1 -1
  9. package/dist/fec-manager.d.ts +71 -14
  10. package/dist/fec-manager.d.ts.map +1 -1
  11. package/dist/fec-manager.js +300 -60
  12. package/dist/fec-manager.js.map +2 -2
  13. package/dist/fec-worker-setup.js.map +1 -1
  14. package/dist/index.d.ts +1 -1
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js.map +2 -2
  17. package/dist/iso-block-locator.d.ts +39 -13
  18. package/dist/iso-block-locator.d.ts.map +1 -1
  19. package/dist/iso-block-locator.js +80 -25
  20. package/dist/iso-block-locator.js.map +2 -2
  21. package/dist/media-router.js.map +1 -1
  22. package/dist/mmtp-container-parser.d.ts +63 -10
  23. package/dist/mmtp-container-parser.d.ts.map +1 -1
  24. package/dist/mmtp-container-parser.js +218 -18
  25. package/dist/mmtp-container-parser.js.map +2 -2
  26. package/dist/mmtp-container-parser.no-modules.js +217 -19
  27. package/dist/mmtp-container-parser.no-modules.js.map +3 -3
  28. package/dist/mmtp-decode-pipeline.js +218 -18
  29. package/dist/mmtp-decode-pipeline.js.map +2 -2
  30. package/dist/mmtp-router.d.ts +22 -9
  31. package/dist/mmtp-router.d.ts.map +1 -1
  32. package/dist/mmtp-router.js +384 -51
  33. package/dist/mmtp-router.js.map +3 -3
  34. package/dist/multicast-manager.d.ts +26 -3
  35. package/dist/multicast-manager.d.ts.map +1 -1
  36. package/dist/multicast-manager.js +774 -130
  37. package/dist/multicast-manager.js.map +3 -3
  38. package/dist/multicast-transport.js +2 -2
  39. package/dist/multicast-transport.js.map +2 -2
  40. package/dist/no-modules.js +218 -18
  41. package/dist/no-modules.js.map +3 -3
  42. package/dist/repair-fetch.d.ts +38 -8
  43. package/dist/repair-fetch.d.ts.map +1 -1
  44. package/dist/repair-fetch.js +286 -27
  45. package/dist/repair-fetch.js.map +3 -3
  46. package/dist/track-session.d.ts.map +1 -1
  47. package/dist/track-session.js +1 -0
  48. package/dist/track-session.js.map +2 -2
  49. package/dist/wasm-mmtp-container-parser.js +218 -18
  50. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  51. package/package.json +5 -5
  52. package/src/codec-utils.ts +121 -1
  53. package/src/fec-manager.ts +316 -34
  54. package/src/index.ts +2 -0
  55. package/src/iso-block-locator.ts +114 -31
  56. package/src/mmtp-container-parser.ts +238 -21
  57. package/src/mmtp-router.ts +271 -58
  58. package/src/multicast-manager.ts +136 -16
  59. package/src/repair-fetch.ts +366 -50
  60. package/src/track-session.ts +3 -0
@@ -24,7 +24,7 @@ import {
24
24
  type MoqRepairFrame,
25
25
  } from "@blockcast/mmt-base";
26
26
  import { USER_AGENT_VERIFIED } from "@blockcast/mmt-transport";
27
- import type { FECManager, IsoHeldSource, RebuiltSourceFeed, WasmFecDecoder } from "./fec-manager.js";
27
+ import type { FECManager, IsoHeldSource, IsoSpanFailure, RebuiltSourceFeed, WasmFecDecoder } from "./fec-manager.js";
28
28
  import type { IsoPlacedSource, IsoRepairPlacement } from "./iso-block-locator.js";
29
29
  import { isMfuReassemblyError } from "./mfu-reassembler.js";
30
30
  import type {
@@ -216,7 +216,9 @@ export interface KeyframeOverlayStats {
216
216
  protectedDropped: number;
217
217
  /** Rebuilt packets fed to their base block's decoder (joint decoding). */
218
218
  baseFed: number;
219
- /** Rebuilt packets the base never took: no base SS_ID could be determined. */
219
+ /** Rebuilt packets the base never took: no base SS_ID could be determined,
220
+ * or only the overlay's own evidence did, which anchors the release gate
221
+ * alone (BLO-52085). */
220
222
  baseUndetermined: number;
221
223
  }
222
224
 
@@ -260,12 +262,12 @@ function overlayBaseSsId(
260
262
  * one per FEC source packet (mmt-02 7.1) and psn by one per packet, so on a
261
263
  * track whose every packet is an FEC source packet the sender keeps
262
264
  * SS_ID - psn fixed. `offset` (SS_ID - psn of the stream's latest received
263
- * source) is that sender value while a base recovery showed it
264
- * (`unstampedOffset`): a recovered packet's header psn equal to its SS_ID
265
- * minus the same offset. A hop that re-stamps psn moves the offset away from
266
- * the one shown, which voids it, as does a packet with no SS_ID between the
267
- * recovered packet that showed it and the latest received source (the shown
268
- * span). Undefined without both.
265
+ * source) is that sender value while evidence showed it (`unstampedOffset`):
266
+ * a base recovery's (#unstampedSsIdSeqOffsetByStream), or the overlay's
267
+ * alone (#overlayUnstampedSsIdSeqOffsetByStream). A hop that re-stamps psn
268
+ * moves the offset away from the one shown, which voids it, as does a packet
269
+ * with no SS_ID between the packet that showed it and the latest received
270
+ * source (the shown span). Undefined without both.
269
271
  * ponytail: exact only if every packet from the rebuilt one to the latest
270
272
  * received source is an FEC source packet, as FFmpeg's muxer sends a track
271
273
  * it protects. fec-core 8.3 lets a publisher leave one unprotected
@@ -313,10 +315,18 @@ interface OverlayInstance {
313
315
  readonly offsets: Map<number, OverlayMemberAnchor>;
314
316
  /** Overlay blocks a MoQ symbol fed (multicast-02 7.2.7). */
315
317
  readonly moqBlocks: Set<number>;
318
+ /** Overlay SS_ID → protected packet_sequence_number of each packet rebuilt
319
+ * with no base SS_ID, until its base copy lands (#feedOverlaySource). */
320
+ readonly rebuilt: Map<number, number>;
316
321
  }
317
322
 
318
323
  /** Offsets kept per overlay, one per MPU: a keyframe's fragments share one. */
319
324
  const OVERLAY_OFFSET_MPUS = 16;
325
+ /** Rebuilt packets kept per overlay whose base copy has not landed (OverlayInstance.rebuilt).
326
+ * ponytail: this cap is the only eviction for a base copy that never lands
327
+ * (oldest first; an overlay epoch reset clears all). Bound records by SS_ID
328
+ * age instead if stale ones ever crowd out live ones. */
329
+ const OVERLAY_REBUILT_LIMIT = 256;
320
330
  /** A MoQ-fed overlay block is forgotten once it starts this many K_overlay
321
331
  * behind the newest overlay SS_ID: the overlay locator, which keeps a fixed
322
332
  * few blocks (no catalog timing), has retired it long before, so it can no
@@ -833,13 +843,14 @@ export interface FECManagerLike {
833
843
 
834
844
  /** Track a first-arrival network source symbol for block completion and
835
845
  * classification. Refreshes the inactivity deadline and marks clean when
836
- * K arrive. */
846
+ * K arrive. `held`: a source held unplaced since it arrived, placed now. */
837
847
  trackBlock(
838
848
  sbn: number,
839
849
  packetId: number,
840
850
  catalogTrackName: string | undefined,
841
851
  esi: number,
842
852
  evidence: SourceSymbolEvidence,
853
+ held?: boolean,
843
854
  ): void;
844
855
 
845
856
  /** True once the packetId has a per-track FEC configuration. */
@@ -955,6 +966,14 @@ export interface FECManagerLike {
955
966
  fromSsId: number,
956
967
  toSsId: number,
957
968
  ): readonly number[] | null;
969
+ /** iso-ssbg1-v1: how long a frame waits once only a late source can fill the SS_IDs before it, longer when they may hold a RAP an installed keyframe overlay can still rebuild (FECManager.isoRepairlessWaitMs). */
970
+ isoRepairlessWaitMs?(
971
+ packetId: number,
972
+ catalogTrackName: string | undefined,
973
+ fromSsId: number,
974
+ toSsId: number,
975
+ rapMayHide?: boolean,
976
+ ): number | undefined;
958
977
 
959
978
 
960
979
  /**
@@ -1009,6 +1028,7 @@ export interface FECManagerLike {
1009
1028
  packetId: number,
1010
1029
  catalogTrackName: string | undefined,
1011
1030
  blockClass: BlockClass,
1031
+ span?: IsoSpanFailure,
1012
1032
  ) => void)
1013
1033
  | null;
1014
1034
 
@@ -1077,6 +1097,7 @@ export class MmtpRouter {
1077
1097
  readonly #provenance = new Map<string, ProvenanceEntry>();
1078
1098
  #onFlowProtected: ((flow: string) => void) | null = null;
1079
1099
  #unadmittedListedDrops = 0;
1100
+ #admittedSourceDatagrams = 0;
1080
1101
  #unlistedRepairSetAside = 0;
1081
1102
  readonly #assistBlocks = new Map<string, AssistBlock>();
1082
1103
  readonly #assistFailures = new Map<string, number>();
@@ -1154,6 +1175,17 @@ export class MmtpRouter {
1154
1175
  * an MPU no member of which arrived).
1155
1176
  */
1156
1177
  #unstampedSsIdSeqOffsetByStream = new Map<string, number>();
1178
+ /**
1179
+ * The same, shown by the overlay alone, before any base recovery did: a
1180
+ * packet it rebuilt whose base copy carries its protected psn
1181
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
1182
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
1183
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
1184
+ * make the base drop a late base copy of a keyframe the overlay never
1185
+ * finished, and lift a block's late-source cut, which nothing before
1186
+ * this offset did.
1187
+ */
1188
+ #overlayUnstampedSsIdSeqOffsetByStream = new Map<string, number>();
1157
1189
  /**
1158
1190
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
1159
1191
  * not parsed, typically because its overlap copy was parsed first
@@ -1202,6 +1234,7 @@ export class MmtpRouter {
1202
1234
  packetId: number,
1203
1235
  catalogTrackName: string | undefined,
1204
1236
  blockClass: BlockClass,
1237
+ span?: IsoSpanFailure,
1205
1238
  ) => void)
1206
1239
  | null = null;
1207
1240
  /** Typed observer of every gap decision the release gate makes. */
@@ -1299,6 +1332,7 @@ export class MmtpRouter {
1299
1332
  packetId: number,
1300
1333
  catalogTrackName: string | undefined,
1301
1334
  blockClass: BlockClass,
1335
+ span?: IsoSpanFailure,
1302
1336
  ) => void;
1303
1337
  /** Internal gap-decision sink owned by the composing transport. */
1304
1338
  onFrameGap?: (decision: FrameGapDecision) => void;
@@ -1532,6 +1566,7 @@ export class MmtpRouter {
1532
1566
  packetId: number,
1533
1567
  catalogTrackName: string | undefined,
1534
1568
  blockClass: BlockClass,
1569
+ span?: IsoSpanFailure,
1535
1570
  ) => void)
1536
1571
  | undefined,
1537
1572
  ): void {
@@ -1584,6 +1619,7 @@ export class MmtpRouter {
1584
1619
  packetId: number,
1585
1620
  catalogTrackName: string | undefined,
1586
1621
  blockClass: BlockClass,
1622
+ span?: IsoSpanFailure,
1587
1623
  ) => {
1588
1624
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
1589
1625
  if (
@@ -1592,8 +1628,13 @@ export class MmtpRouter {
1592
1628
  ) {
1593
1629
  this.#onDeltaBlockCompleteCb?.(packetId, true); // failed=true
1594
1630
  }
1595
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
1596
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
1631
+ if (span === undefined) {
1632
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
1633
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
1634
+ } else {
1635
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
1636
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
1637
+ }
1597
1638
  };
1598
1639
  }
1599
1640
  }
@@ -1646,8 +1687,9 @@ export class MmtpRouter {
1646
1687
 
1647
1688
  /**
1648
1689
  * FEC-recovered source symbols whose reconstructed header named a
1649
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
1650
- * a hop re-stamped the sequence after the sender protected the packet.
1690
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
1691
+ * or, rebuilt by the overlay, than their base copy carries: a hop
1692
+ * re-stamped the sequence after the sender protected the packet.
1651
1693
  */
1652
1694
  get restampedRecoveredSequenceCount(): number {
1653
1695
  return this.#restampedRecoveredSeqs;
@@ -1871,6 +1913,11 @@ export class MmtpRouter {
1871
1913
  ): CmafBlockAssembler {
1872
1914
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
1873
1915
  const previous = this.#mseAssemblers.get(assemblerKey);
1916
+ // The new assembler has no source cursor: the release gate must not hold
1917
+ // an overlay keyframe for one either (FecReleaseSequencer.#cursorPassed).
1918
+ // What the gate holds that unanchored had already released to the
1919
+ // assembler being replaced goes to it first, and plays with its flush.
1920
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
1874
1921
  if (previous) {
1875
1922
  previous.flush();
1876
1923
  previous.dispose();
@@ -1942,6 +1989,7 @@ export class MmtpRouter {
1942
1989
  packetId: number,
1943
1990
  catalogTrackName: string | undefined,
1944
1991
  blockClass: BlockClass,
1992
+ span?: IsoSpanFailure,
1945
1993
  ) => void,
1946
1994
  ): void {
1947
1995
  this.#onBlockFailed = cb;
@@ -2046,7 +2094,7 @@ export class MmtpRouter {
2046
2094
  const leg = this.#overlayLegs.get(repairPacketId);
2047
2095
  if (!leg) throw new Error(`[MmtpRouter] packetId=${repairPacketId} is no known keyframe-overlay leg`);
2048
2096
  const inst: OverlayInstance = {
2049
- repairPacketId, streamName, leg: { ...leg }, fec, k, offsets: new Map(), moqBlocks: new Set(),
2097
+ repairPacketId, streamName, leg: { ...leg }, fec, k, offsets: new Map(), moqBlocks: new Set(), rebuilt: new Map(),
2050
2098
  };
2051
2099
  this.#overlays.set(repairPacketId, inst);
2052
2100
  return () => {
@@ -2095,6 +2143,7 @@ export class MmtpRouter {
2095
2143
  inst.last = undefined;
2096
2144
  inst.offsets.clear();
2097
2145
  inst.moqBlocks.clear();
2146
+ inst.rebuilt.clear();
2098
2147
  }
2099
2148
 
2100
2149
  #overlaysForSource(sourcePacketId: number, catalogTrackName: string | undefined): OverlayInstance[] {
@@ -2167,6 +2216,13 @@ export class MmtpRouter {
2167
2216
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
2168
2217
  * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
2169
2218
  * FEC reads it.
2219
+ *
2220
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
2221
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
2222
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
2223
+ * the stream unstamped at the SS_ID offset it states, for the release gate
2224
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
2225
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
2170
2226
  */
2171
2227
  #feedOverlaySource(
2172
2228
  packetId: number,
@@ -2181,8 +2237,12 @@ export class MmtpRouter {
2181
2237
  if (this.#overlays.size === 0) return;
2182
2238
  const ssId = keyframeOverlaySsId(header);
2183
2239
  if (ssId === undefined) return;
2240
+ let rebuiltPsn: number | undefined;
2184
2241
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
2185
2242
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
2243
+ // After the restart check: a new epoch forgets the old one's packets.
2244
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
2245
+ inst.rebuilt.delete(ssId);
2186
2246
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
2187
2247
  if (identity !== null) {
2188
2248
  // The newest member anchors its MPU; one with no base SS_ID leaves the
@@ -2220,6 +2280,18 @@ export class MmtpRouter {
2220
2280
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
2221
2281
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
2222
2282
  }
2283
+ if (rebuiltPsn === undefined || this.#classifyPacketId(packetId) === null) return;
2284
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
2285
+ if (rebuiltPsn !== sequenceNumber) {
2286
+ // Counted only. Marked re-stamped (#restampedStreams), the stream would
2287
+ // drop every later rebuilt packet no member anchors, which the overlay
2288
+ // route delivers unanchored until a base recovery shows the re-stamp:
2289
+ // a keyframe whose base copy is lost too would never play.
2290
+ this.#restampedRecoveredSeqs++;
2291
+ } else if (baseSsId !== undefined) {
2292
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
2293
+ if (offset === ((baseSsId - sequenceNumber) >>> 0)) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
2294
+ }
2223
2295
  }
2224
2296
 
2225
2297
  #noteOverlayMoqBlock(inst: OverlayInstance, blockStart: number): void {
@@ -2260,11 +2332,16 @@ export class MmtpRouter {
2260
2332
 
2261
2333
  /**
2262
2334
  * Route an overlay-recovered block's packets as source media of the
2263
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
2264
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
2265
- * base re-stamp, no block advance. Each packet's wire sequence is restored
2266
- * from its keyframe's own offset; without one, a stream the base never
2267
- * re-stamped keeps the header's sequence and any other drops the packet.
2335
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
2336
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
2337
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
2338
+ * base FEC recovered does, so it waits behind base frames still in flight,
2339
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
2340
+ * longer than unanchored; one whose base SS_ID is undetermined has no
2341
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
2342
+ * advance. Each packet's wire sequence is restored from its keyframe's own
2343
+ * offset; without one, a stream the base never re-stamped keeps the
2344
+ * header's sequence and any other drops the packet.
2268
2345
  */
2269
2346
  #routeOverlayRecovered(inst: OverlayInstance, blockStart: number, recovered: Uint8Array): void {
2270
2347
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -2287,51 +2364,96 @@ export class MmtpRouter {
2287
2364
  const streamKey = this.#mediaStreamKey(sourcePacketId, sourceName);
2288
2365
  const restamped = this.#restampedStreams.has(streamKey);
2289
2366
  const restored = new Set<number>();
2290
- const baseSsIds = new Map<ProcessFecBlockResult["symbols"][number], number>();
2367
+ // The base SS_IDs determined independently, by overlay ESI; those the
2368
+ // overlay alone showed anchor the release gate, not the base decoder.
2369
+ const baseSsIds = new Map<number, number>();
2370
+ const gateOnly = new Set<number>();
2291
2371
  const symbols = result.symbols.flatMap((sym) => {
2372
+ const overlaySsId = serial32Add(blockStart, sym.index);
2292
2373
  const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
2293
2374
  if (anchor !== undefined) {
2294
- const overlaySsId = serial32Add(blockStart, sym.index);
2295
2375
  const packetSequenceNumber = (overlaySsId - anchor.psnOffset) >>> 0;
2296
2376
  restored.add(packetSequenceNumber);
2297
2377
  const out = { ...sym, packetSequenceNumber };
2298
2378
  const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
2299
- if (baseSsId !== undefined) baseSsIds.set(out, baseSsId);
2379
+ if (baseSsId !== undefined) {
2380
+ baseSsIds.set(sym.index, baseSsId);
2381
+ // Its protected psn is the wire sequence its member gives it, at
2382
+ // the base SS_ID that member gives it: at the stream's current
2383
+ // SS_ID offset, the stream unstamped, as a base recovery shows it
2384
+ // (#routeProcessedFecSymbols). A re-stamping hop fails the psn test.
2385
+ // Only for a packet the base did not receive: a received member's
2386
+ // slot holds the bytes it arrived with (the decoder keeps a
2387
+ // received source as given), whose psn is the wire one whatever a
2388
+ // hop did, so it passes the test against itself.
2389
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
2390
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) &&
2391
+ offset === ((baseSsId - packetSequenceNumber) >>> 0)) {
2392
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
2393
+ }
2394
+ }
2300
2395
  return [out];
2301
2396
  }
2302
2397
  // A stream re-stamped by a bridge that no base recovery has shown yet
2303
2398
  // keeps the header's sequence too: from received packets alone the
2304
- // router cannot tell (their psn is the wire one). Base recovery or a
2305
- // FETCH still covers such a keyframe.
2399
+ // router cannot tell (their psn is the wire one), and the base copy of
2400
+ // a packet the overlay rebuilt only counts a re-stamp. Base recovery or
2401
+ // a FETCH still covers such a keyframe.
2306
2402
  if (!restamped) {
2307
- // No member of this MPU arrived to anchor a base SS_ID. A base
2308
- // recovery that showed the stream unstamped at its current offset
2309
- // determines one from the packet's protected psn instead
2310
- // (unstampedBaseSsId).
2311
- const baseSsId = unstampedBaseSsId(
2312
- this.#ssIdSeqOffsetByStream.get(streamKey),
2313
- this.#unstampedSsIdSeqOffsetByStream.get(streamKey),
2314
- sym.packetSequenceNumber,
2315
- );
2316
- if (baseSsId !== undefined) baseSsIds.set(sym, baseSsId);
2403
+ // No member of this MPU arrived to anchor a base SS_ID. Evidence that
2404
+ // the stream is unstamped at its current offset determines one from
2405
+ // the packet's protected psn instead (unstampedBaseSsId): a base
2406
+ // recovery's, or else the overlay's own, which anchors the release
2407
+ // gate only (#overlayUnstampedSsIdSeqOffsetByStream). Without it, the
2408
+ // packet's base copy, if it lands, shows whether it is
2409
+ // (#feedOverlaySource).
2410
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
2411
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
2412
+ const baseSsId = fedSsId ??
2413
+ unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
2414
+ if (baseSsId !== undefined) {
2415
+ baseSsIds.set(sym.index, baseSsId);
2416
+ if (fedSsId === undefined) gateOnly.add(sym.index);
2417
+ } else {
2418
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
2419
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value!);
2420
+ }
2317
2421
  return [sym];
2318
2422
  }
2319
2423
  this.#overlayStats.unsequencedDropped++;
2320
2424
  return [];
2321
2425
  });
2322
2426
  this.#overlayStats.recovered++;
2427
+ // Each packet's MPU starts, in this decode, at the lowest base SS_ID
2428
+ // determined for it: the release gate's span ends there.
2429
+ const mpuFirst = new Map<number, number>();
2430
+ for (const sym of symbols) {
2431
+ const ssId = baseSsIds.get(sym.index);
2432
+ const mpu = sym.fragment.mpuSequenceNumber;
2433
+ const first = mpuFirst.get(mpu);
2434
+ if (ssId !== undefined && (first === undefined || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
2435
+ }
2436
+ const firstSsIds = new Map<number, number>();
2437
+ for (const sym of symbols) {
2438
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber)!);
2439
+ }
2323
2440
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
2324
2441
  deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
2442
+ baseSsIds,
2443
+ firstSsIds,
2325
2444
  });
2326
2445
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) =>
2327
2446
  restored.has(sym.packetSequenceNumber)));
2328
- this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds);
2447
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0
2448
+ ? baseSsIds
2449
+ : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
2329
2450
  }
2330
2451
 
2331
2452
  /**
2332
2453
  * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
2333
2454
  * its base block too, once its base SS_ID is determined (overlayBaseSsId,
2334
- * from a received member of its MPU, else unstampedBaseSsId),
2455
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
2456
+ * base recovery showed; `baseSsIds` holds no other),
2335
2457
  * so it is fed to the base decoder as a rebuilt source
2336
2458
  * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
2337
2459
  * fewer to solve, and its repair can recover the block's other packets.
@@ -2351,7 +2473,7 @@ export class MmtpRouter {
2351
2473
  inst: OverlayInstance,
2352
2474
  blockStart: number,
2353
2475
  symbols: ProcessFecBlockResult["symbols"],
2354
- baseSsIds: ReadonlyMap<ProcessFecBlockResult["symbols"][number], number>,
2476
+ baseSsIds: ReadonlyMap<number, number>,
2355
2477
  ): void {
2356
2478
  const fec = this.#fecManager;
2357
2479
  const owner = inst.leg.sourcePacketId;
@@ -2363,7 +2485,7 @@ export class MmtpRouter {
2363
2485
  for (const sym of symbols) {
2364
2486
  // A packet the base received already sits in its block.
2365
2487
  if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
2366
- const ssId = baseSsIds.get(sym);
2488
+ const ssId = baseSsIds.get(sym.index);
2367
2489
  if (ssId === undefined) {
2368
2490
  this.#overlayStats.baseUndetermined++;
2369
2491
  continue;
@@ -2605,6 +2727,11 @@ export class MmtpRouter {
2605
2727
  return this.#unadmittedListedDrops;
2606
2728
  }
2607
2729
 
2730
+ /** Source datagrams (multicast or MoQ) a protected flow's bc-provenance v2 receiver released: admitted at once or held, then admitted by a record. Repair symbols and user-agent-admitted datagrams are not counted. Counted at release, before this router's own track checks: a released datagram those drop, which only a track change between hold and release can cause, still counts, so this is not a count of routed media. */
2731
+ get admittedSourceDatagramCount(): number {
2732
+ return this.#admittedSourceDatagrams;
2733
+ }
2734
+
2608
2735
  /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
2609
2736
  get unlistedRepairSetAsideCount(): number {
2610
2737
  return this.#unlistedRepairSetAside;
@@ -3306,7 +3433,7 @@ export class MmtpRouter {
3306
3433
  catalogTrackName,
3307
3434
  )) continue;
3308
3435
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
3309
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
3436
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
3310
3437
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
3311
3438
  }
3312
3439
  if (payload.oversized) continue;
@@ -3425,6 +3552,7 @@ export class MmtpRouter {
3425
3552
  this.#latestVideoSeqByStream.delete(streamKey);
3426
3553
  this.#ssIdSeqOffsetByStream.delete(streamKey);
3427
3554
  this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
3555
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
3428
3556
  this.#multicastRapTwinByStream.delete(streamKey);
3429
3557
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
3430
3558
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -3556,6 +3684,12 @@ export class MmtpRouter {
3556
3684
  * the outgoing stream stops. The hold is bounded by the incoming stream's
3557
3685
  * own RAP cadence, so no timer is involved.
3558
3686
  *
3687
+ * While the switch is staged, the FEC release gate lets a keyframe the
3688
+ * overlay rebuilt reach it, on either side, when the keyframe did before
3689
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
3690
+ * decides on what each side delivered, and the commit discards the gate's
3691
+ * frames of the outgoing stream.
3692
+ *
3559
3693
  * The commit is one synchronous transition inside the frame path: the
3560
3694
  * outgoing stream's already-admitted frames are released (its queued FEC
3561
3695
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -3608,6 +3742,16 @@ export class MmtpRouter {
3608
3742
  droppedIncomingFrames: 0,
3609
3743
  };
3610
3744
  this.#staged = state;
3745
+ // Release what the outgoing stream's gate held only because it was
3746
+ // anchored (FecReleaseGate.releaseUnanchored): unanchored, it had already
3747
+ // reached the switch. Only a gate that holds a frame the overlay rebuilt
3748
+ // is poked: any other holds nothing for that reason, and a poke would
3749
+ // still force out a frame held past the hold limit, which before the
3750
+ // anchor waited for the next push. The incoming stream's gate is not
3751
+ // drained here: a RAP it released would commit before this call returns.
3752
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
3753
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
3754
+ }
3611
3755
  return {
3612
3756
  cancel: () => {
3613
3757
  if (this.#staged !== state) return false;
@@ -3702,7 +3846,24 @@ export class MmtpRouter {
3702
3846
  // same call. Nothing registers a packet ID mid-frame, so this drops
3703
3847
  // only frames that lost their registration.
3704
3848
  if (this.#classifyPacketId(meta.packetId) === null) return;
3705
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
3849
+ if (this.#staged !== null) {
3850
+ // A switch staged from this frame's commit (onCommit: the ladder walk)
3851
+ // pokes its outgoing stream's gate, the stream just committed to, whose
3852
+ // drain may be what released this frame. The poke waits until the
3853
+ // commit has delivered that stream's init, held GOP and RAP. Run now,
3854
+ // it would release the frames behind them ahead of them: a delta is
3855
+ // dropped there (its stream is not synced yet), and a keyframe plays
3856
+ // ahead of the init and leaves the commit's frames behind it.
3857
+ let consumed = false;
3858
+ this.#fecPokeDepth++;
3859
+ try {
3860
+ consumed = this.#interceptSwitchFrame(data, meta);
3861
+ } finally {
3862
+ this.#fecPokeDepth--;
3863
+ this.#flushPendingFecPokes();
3864
+ }
3865
+ if (consumed) return;
3866
+ }
3706
3867
  this.#deliverParsedFrame(data, meta);
3707
3868
  }
3708
3869
 
@@ -3895,12 +4056,17 @@ export class MmtpRouter {
3895
4056
  this.#parser.deferFecRelease(work);
3896
4057
  } finally {
3897
4058
  this.#fecPokeDepth--;
3898
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
3899
- const pokes = [...this.#pendingFecPokes.values()];
3900
- this.#pendingFecPokes.clear();
3901
- for (const poke of pokes) {
3902
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
3903
- }
4059
+ this.#flushPendingFecPokes();
4060
+ }
4061
+ }
4062
+
4063
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
4064
+ #flushPendingFecPokes(): void {
4065
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
4066
+ const pokes = [...this.#pendingFecPokes.values()];
4067
+ this.#pendingFecPokes.clear();
4068
+ for (const poke of pokes) {
4069
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
3904
4070
  }
3905
4071
  }
3906
4072
  }
@@ -3980,6 +4146,30 @@ export class MmtpRouter {
3980
4146
  if (!fec?.terminalRetentionMsForPacket) return Infinity;
3981
4147
  return fec.terminalRetentionMsForPacket(packetId) ?? 0;
3982
4148
  },
4149
+ // Once no repair can fill a gap (FECManager.isoRepairlessWaitMs: only a
4150
+ // late source can), its frame waits the late-symbol allowance when the
4151
+ // gap holds no RAP an installed keyframe overlay could still rebuild:
4152
+ // lost deltas of one MPU (delta-lost), the tail of the MPU before a RAP
4153
+ // that opens the next one while MPU boundaries bound RAPs (rap-next), or
4154
+ // an audio gap. A gap that may hold one (rap-lost, rap-unknown, or any
4155
+ // other rap-next, whose gap may hold a whole MPU and the keyframe the
4156
+ // overlay protects) waits for that overlay's repair too (BLO-52085
4157
+ // D4). The FEC check comes first: most held gaps are not behind such a
4158
+ // span, and deciding one scans both frames' bitstreams.
4159
+ unrepairableWaitMs: (before, after, fromSbn, toSbn) => {
4160
+ const fec = this.#fecManager;
4161
+ const { packetId, catalogTrackName } = after.meta;
4162
+ const allowanceMs = fec?.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn);
4163
+ if (!fec || allowanceMs === undefined) return undefined;
4164
+ const decision = this.#decideGap(before, after, [], false);
4165
+ const mpu = before.meta.mpuSequenceNumber;
4166
+ const intoNextMpu = decision.reason === "rap-next" && mpu !== undefined &&
4167
+ after.meta.mpuSequenceNumber === ((mpu + 1) >>> 0) &&
4168
+ fec.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
4169
+ return decision.action === "stall" || (decision.reason === "rap-next" && !intoNextMpu)
4170
+ ? fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, true)
4171
+ : allowanceMs;
4172
+ },
3983
4173
  decide: (before, after, lostBlocks, discontinuity) => {
3984
4174
  const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
3985
4175
  this.#onFrameGap?.(decision);
@@ -3989,6 +4179,14 @@ export class MmtpRouter {
3989
4179
  onRap: (packetId, catalogTrackName, ssId) => {
3990
4180
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
3991
4181
  },
4182
+ // A staged switch commits on when each side's frames reach it
4183
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
4184
+ // they did unanchored.
4185
+ releaseUnanchored: (packetId, catalogTrackName) => {
4186
+ const staged = this.#staged;
4187
+ const stream = { packetId, ...(catalogTrackName === undefined ? {} : { catalogTrackName }) };
4188
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
4189
+ },
3992
4190
  onReleased: (data, meta) => {
3993
4191
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === undefined) return;
3994
4192
  const timing = meta.authoredTiming;
@@ -4184,6 +4382,8 @@ export class MmtpRouter {
4184
4382
  const parsed = this.#parser.parsePacket(packet);
4185
4383
  if (!parsed) return;
4186
4384
  const info = parsed.info;
4385
+ // manifestAdmitted is set only by a receiver release or the user agent's own verification.
4386
+ if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
4187
4387
  // Every multicast packet is a delivery-gap sample, including one dropped
4188
4388
  // below: the gap is a property of the link the FEC deadlines run on, not
4189
4389
  // of which packets this router routes. The re-entry after a manifest
@@ -4672,6 +4872,7 @@ export class MmtpRouter {
4672
4872
  deliveryProvenance?: MmtpDeliveryProvenance;
4673
4873
  catalogTrackName?: string;
4674
4874
  fecSbn?: number;
4875
+ fecSbnFirst?: number;
4675
4876
  },
4676
4877
  parsed?: ParsedMmtpPacket,
4677
4878
  ): void {
@@ -4695,6 +4896,7 @@ export class MmtpRouter {
4695
4896
  deliveryProvenance: parserOptions?.deliveryProvenance,
4696
4897
  catalogTrackName: parserOptions?.catalogTrackName,
4697
4898
  ...(parserOptions?.fecSbn === undefined ? {} : { fecSbn: parserOptions.fecSbn }),
4899
+ ...(parserOptions?.fecSbnFirst === undefined ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }),
4698
4900
  };
4699
4901
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
4700
4902
  else this.#parser.feed(packet, feedOptions);
@@ -5080,15 +5282,16 @@ export class MmtpRouter {
5080
5282
  ): void {
5081
5283
  const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);
5082
5284
  // The FEC release gate let this frame out in order: only once every
5083
- // block between it and the frame before it resolved, or because it
5084
- // starts where that frame ended. Nothing still in flight can precede it
5085
- // then, so it plays now, as a source frame does; holding it for the next
5285
+ // block between it and the frame before it resolved, because it starts
5286
+ // where that frame ended, or (one the overlay rebuilt) once the base
5287
+ // path passed it. Nothing still in flight can precede it then, so it
5288
+ // plays now, as a source frame does; holding it for the next
5086
5289
  // intact frame cost every repaired burst its length in decoder input
5087
- // (BLO-52085). An overlay recovery names no base block for the gate to
5088
- // wait on, so past a gap it may be ahead of frames still in flight (an
5089
- // overlay that outran the wire, BLO-53342): it keeps waiting for the
5090
- // source cursor below, unless it starts where the last emitted frame
5091
- // ended (on this direct path, the delivered high water).
5290
+ // (BLO-52085). An overlay recovery whose base SS_ID is undetermined names
5291
+ // no base block for the gate to wait on, so past a gap it may be ahead of
5292
+ // frames still in flight (an overlay that outran the wire, BLO-53342): it
5293
+ // keeps waiting for the source cursor below, unless it starts where the
5294
+ // last emitted frame ended (on this direct path, the delivered high water).
5092
5295
  if (this.#isFecTrack(packetId)) {
5093
5296
  const high = this.#deliveredVideoHighWaterByStream.get(streamKey);
5094
5297
  if (fecSbn !== undefined || (high !== undefined && authoredAdjacent(high, meta))) {
@@ -5414,15 +5617,25 @@ export class MmtpRouter {
5414
5617
  catalogTrackName?: string,
5415
5618
  /** Set for a keyframe-overlay recovery: `blockId` is an overlay
5416
5619
  * coordinate, which yields no base SS_ID (mmt-02 7.2), and the packets'
5417
- * wire sequences are already restored. */
5418
- overlay?: { deliveryProvenance: MmtpDeliveryProvenance },
5620
+ * wire sequences are already restored. `baseSsIds` holds, by ESI, the
5621
+ * base SS_IDs determined independently: a packet's release-gate anchor;
5622
+ * `firstSsIds` the lowest of them in its MPU (FrameMeta.fecSbnFirst). */
5623
+ overlay?: {
5624
+ deliveryProvenance: MmtpDeliveryProvenance;
5625
+ baseSsIds: ReadonlyMap<number, number>;
5626
+ firstSsIds: ReadonlyMap<number, number>;
5627
+ },
5419
5628
  ): void {
5420
5629
  // Route recovered symbols to the track's callback. The ownerPacketId tells us
5421
5630
  // which track this block belongs to — resolves per-track, then legacy fallback.
5422
5631
  if (ownerPacketId == null) return; // no track association
5423
5632
  if (this.#classifyPacketId(ownerPacketId) === null) return; // unknown track
5424
- const fecSbnOf = (index: number): { fecSbn?: number } =>
5425
- overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
5633
+ const fecSbnOf = (index: number): { fecSbn?: number; fecSbnFirst?: number } => {
5634
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
5635
+ const fecSbn = overlay.baseSsIds.get(index);
5636
+ const fecSbnFirst = overlay.firstSsIds.get(index);
5637
+ return fecSbn === undefined || fecSbnFirst === undefined ? {} : { fecSbn, fecSbnFirst };
5638
+ };
5426
5639
  // A recovered symbol's header names the sequence the sender protected. A
5427
5640
  // hop that re-stamps packet_sequence_number after protection (cast's
5428
5641
  // publisher-rotation bridge) leaves the decode mixing every received