@blockcast/mmt-container 2.2.0-main.e75bbd7576a6 → 2.2.0-main.ef09fa701ea8

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 +994 -162
  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 +75 -14
  10. package/dist/fec-manager.d.ts.map +1 -1
  11. package/dist/fec-manager.js +315 -65
  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 +69 -10
  23. package/dist/mmtp-container-parser.d.ts.map +1 -1
  24. package/dist/mmtp-container-parser.js +226 -18
  25. package/dist/mmtp-container-parser.js.map +2 -2
  26. package/dist/mmtp-container-parser.no-modules.js +225 -19
  27. package/dist/mmtp-container-parser.no-modules.js.map +3 -3
  28. package/dist/mmtp-decode-pipeline.js +226 -18
  29. package/dist/mmtp-decode-pipeline.js.map +2 -2
  30. package/dist/mmtp-router.d.ts +20 -9
  31. package/dist/mmtp-router.d.ts.map +1 -1
  32. package/dist/mmtp-router.js +409 -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 +814 -135
  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 +226 -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 +226 -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 +329 -39
  54. package/src/index.ts +2 -0
  55. package/src/iso-block-locator.ts +114 -31
  56. package/src/mmtp-container-parser.ts +257 -24
  57. package/src/mmtp-router.ts +287 -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,15 @@ 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
+ rapNext?: boolean,
977
+ ): number | undefined;
958
978
 
959
979
 
960
980
  /**
@@ -1009,6 +1029,7 @@ export interface FECManagerLike {
1009
1029
  packetId: number,
1010
1030
  catalogTrackName: string | undefined,
1011
1031
  blockClass: BlockClass,
1032
+ span?: IsoSpanFailure,
1012
1033
  ) => void)
1013
1034
  | null;
1014
1035
 
@@ -1155,6 +1176,17 @@ export class MmtpRouter {
1155
1176
  * an MPU no member of which arrived).
1156
1177
  */
1157
1178
  #unstampedSsIdSeqOffsetByStream = new Map<string, number>();
1179
+ /**
1180
+ * The same, shown by the overlay alone, before any base recovery did: a
1181
+ * packet it rebuilt whose base copy carries its protected psn
1182
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
1183
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
1184
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
1185
+ * make the base drop a late base copy of a keyframe the overlay never
1186
+ * finished, and lift a block's late-source cut, which nothing before
1187
+ * this offset did.
1188
+ */
1189
+ #overlayUnstampedSsIdSeqOffsetByStream = new Map<string, number>();
1158
1190
  /**
1159
1191
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
1160
1192
  * not parsed, typically because its overlap copy was parsed first
@@ -1203,6 +1235,7 @@ export class MmtpRouter {
1203
1235
  packetId: number,
1204
1236
  catalogTrackName: string | undefined,
1205
1237
  blockClass: BlockClass,
1238
+ span?: IsoSpanFailure,
1206
1239
  ) => void)
1207
1240
  | null = null;
1208
1241
  /** Typed observer of every gap decision the release gate makes. */
@@ -1212,6 +1245,8 @@ export class MmtpRouter {
1212
1245
  // end: a synchronous recovery completes its block BEFORE routing the
1213
1246
  // recovered frames, and releasing a held gap in between would strand them.
1214
1247
  #fecPokeDepth = 0;
1248
+ /** FecReleaseGate.wakeAt timers, by media stream key. */
1249
+ readonly #fecWakes = new Map<string, { atMs: number; timer: ReturnType<typeof setTimeout> }>();
1215
1250
  #pendingFecPokes = new Map<string, { packetId: number; catalogTrackName?: string }>();
1216
1251
  // ── Phase 14: per-role packetId dispatch (D-26, D-27, D-28) ───────
1217
1252
  /** Maps packetId → TrackRole. Default: 'single' when absent (legacy path). */
@@ -1300,6 +1335,7 @@ export class MmtpRouter {
1300
1335
  packetId: number,
1301
1336
  catalogTrackName: string | undefined,
1302
1337
  blockClass: BlockClass,
1338
+ span?: IsoSpanFailure,
1303
1339
  ) => void;
1304
1340
  /** Internal gap-decision sink owned by the composing transport. */
1305
1341
  onFrameGap?: (decision: FrameGapDecision) => void;
@@ -1533,6 +1569,7 @@ export class MmtpRouter {
1533
1569
  packetId: number,
1534
1570
  catalogTrackName: string | undefined,
1535
1571
  blockClass: BlockClass,
1572
+ span?: IsoSpanFailure,
1536
1573
  ) => void)
1537
1574
  | undefined,
1538
1575
  ): void {
@@ -1585,6 +1622,7 @@ export class MmtpRouter {
1585
1622
  packetId: number,
1586
1623
  catalogTrackName: string | undefined,
1587
1624
  blockClass: BlockClass,
1625
+ span?: IsoSpanFailure,
1588
1626
  ) => {
1589
1627
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
1590
1628
  if (
@@ -1593,8 +1631,13 @@ export class MmtpRouter {
1593
1631
  ) {
1594
1632
  this.#onDeltaBlockCompleteCb?.(packetId, true); // failed=true
1595
1633
  }
1596
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
1597
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
1634
+ if (span === undefined) {
1635
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
1636
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
1637
+ } else {
1638
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
1639
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
1640
+ }
1598
1641
  };
1599
1642
  }
1600
1643
  }
@@ -1647,8 +1690,9 @@ export class MmtpRouter {
1647
1690
 
1648
1691
  /**
1649
1692
  * FEC-recovered source symbols whose reconstructed header named a
1650
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
1651
- * a hop re-stamped the sequence after the sender protected the packet.
1693
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
1694
+ * or, rebuilt by the overlay, than their base copy carries: a hop
1695
+ * re-stamped the sequence after the sender protected the packet.
1652
1696
  */
1653
1697
  get restampedRecoveredSequenceCount(): number {
1654
1698
  return this.#restampedRecoveredSeqs;
@@ -1872,6 +1916,11 @@ export class MmtpRouter {
1872
1916
  ): CmafBlockAssembler {
1873
1917
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
1874
1918
  const previous = this.#mseAssemblers.get(assemblerKey);
1919
+ // The new assembler has no source cursor: the release gate must not hold
1920
+ // an overlay keyframe for one either (FecReleaseSequencer.#cursorPassed).
1921
+ // What the gate holds that unanchored had already released to the
1922
+ // assembler being replaced goes to it first, and plays with its flush.
1923
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
1875
1924
  if (previous) {
1876
1925
  previous.flush();
1877
1926
  previous.dispose();
@@ -1943,6 +1992,7 @@ export class MmtpRouter {
1943
1992
  packetId: number,
1944
1993
  catalogTrackName: string | undefined,
1945
1994
  blockClass: BlockClass,
1995
+ span?: IsoSpanFailure,
1946
1996
  ) => void,
1947
1997
  ): void {
1948
1998
  this.#onBlockFailed = cb;
@@ -2047,7 +2097,7 @@ export class MmtpRouter {
2047
2097
  const leg = this.#overlayLegs.get(repairPacketId);
2048
2098
  if (!leg) throw new Error(`[MmtpRouter] packetId=${repairPacketId} is no known keyframe-overlay leg`);
2049
2099
  const inst: OverlayInstance = {
2050
- repairPacketId, streamName, leg: { ...leg }, fec, k, offsets: new Map(), moqBlocks: new Set(),
2100
+ repairPacketId, streamName, leg: { ...leg }, fec, k, offsets: new Map(), moqBlocks: new Set(), rebuilt: new Map(),
2051
2101
  };
2052
2102
  this.#overlays.set(repairPacketId, inst);
2053
2103
  return () => {
@@ -2096,6 +2146,7 @@ export class MmtpRouter {
2096
2146
  inst.last = undefined;
2097
2147
  inst.offsets.clear();
2098
2148
  inst.moqBlocks.clear();
2149
+ inst.rebuilt.clear();
2099
2150
  }
2100
2151
 
2101
2152
  #overlaysForSource(sourcePacketId: number, catalogTrackName: string | undefined): OverlayInstance[] {
@@ -2168,6 +2219,13 @@ export class MmtpRouter {
2168
2219
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
2169
2220
  * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
2170
2221
  * FEC reads it.
2222
+ *
2223
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
2224
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
2225
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
2226
+ * the stream unstamped at the SS_ID offset it states, for the release gate
2227
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
2228
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
2171
2229
  */
2172
2230
  #feedOverlaySource(
2173
2231
  packetId: number,
@@ -2182,8 +2240,12 @@ export class MmtpRouter {
2182
2240
  if (this.#overlays.size === 0) return;
2183
2241
  const ssId = keyframeOverlaySsId(header);
2184
2242
  if (ssId === undefined) return;
2243
+ let rebuiltPsn: number | undefined;
2185
2244
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
2186
2245
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
2246
+ // After the restart check: a new epoch forgets the old one's packets.
2247
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
2248
+ inst.rebuilt.delete(ssId);
2187
2249
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
2188
2250
  if (identity !== null) {
2189
2251
  // The newest member anchors its MPU; one with no base SS_ID leaves the
@@ -2221,6 +2283,18 @@ export class MmtpRouter {
2221
2283
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
2222
2284
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
2223
2285
  }
2286
+ if (rebuiltPsn === undefined || this.#classifyPacketId(packetId) === null) return;
2287
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
2288
+ if (rebuiltPsn !== sequenceNumber) {
2289
+ // Counted only. Marked re-stamped (#restampedStreams), the stream would
2290
+ // drop every later rebuilt packet no member anchors, which the overlay
2291
+ // route delivers unanchored until a base recovery shows the re-stamp:
2292
+ // a keyframe whose base copy is lost too would never play.
2293
+ this.#restampedRecoveredSeqs++;
2294
+ } else if (baseSsId !== undefined) {
2295
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
2296
+ if (offset === ((baseSsId - sequenceNumber) >>> 0)) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
2297
+ }
2224
2298
  }
2225
2299
 
2226
2300
  #noteOverlayMoqBlock(inst: OverlayInstance, blockStart: number): void {
@@ -2261,11 +2335,16 @@ export class MmtpRouter {
2261
2335
 
2262
2336
  /**
2263
2337
  * Route an overlay-recovered block's packets as source media of the
2264
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
2265
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
2266
- * base re-stamp, no block advance. Each packet's wire sequence is restored
2267
- * from its keyframe's own offset; without one, a stream the base never
2268
- * re-stamped keeps the header's sequence and any other drops the packet.
2338
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
2339
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
2340
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
2341
+ * base FEC recovered does, so it waits behind base frames still in flight,
2342
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
2343
+ * longer than unanchored; one whose base SS_ID is undetermined has no
2344
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
2345
+ * advance. Each packet's wire sequence is restored from its keyframe's own
2346
+ * offset; without one, a stream the base never re-stamped keeps the
2347
+ * header's sequence and any other drops the packet.
2269
2348
  */
2270
2349
  #routeOverlayRecovered(inst: OverlayInstance, blockStart: number, recovered: Uint8Array): void {
2271
2350
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -2288,51 +2367,96 @@ export class MmtpRouter {
2288
2367
  const streamKey = this.#mediaStreamKey(sourcePacketId, sourceName);
2289
2368
  const restamped = this.#restampedStreams.has(streamKey);
2290
2369
  const restored = new Set<number>();
2291
- const baseSsIds = new Map<ProcessFecBlockResult["symbols"][number], number>();
2370
+ // The base SS_IDs determined independently, by overlay ESI; those the
2371
+ // overlay alone showed anchor the release gate, not the base decoder.
2372
+ const baseSsIds = new Map<number, number>();
2373
+ const gateOnly = new Set<number>();
2292
2374
  const symbols = result.symbols.flatMap((sym) => {
2375
+ const overlaySsId = serial32Add(blockStart, sym.index);
2293
2376
  const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
2294
2377
  if (anchor !== undefined) {
2295
- const overlaySsId = serial32Add(blockStart, sym.index);
2296
2378
  const packetSequenceNumber = (overlaySsId - anchor.psnOffset) >>> 0;
2297
2379
  restored.add(packetSequenceNumber);
2298
2380
  const out = { ...sym, packetSequenceNumber };
2299
2381
  const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
2300
- if (baseSsId !== undefined) baseSsIds.set(out, baseSsId);
2382
+ if (baseSsId !== undefined) {
2383
+ baseSsIds.set(sym.index, baseSsId);
2384
+ // Its protected psn is the wire sequence its member gives it, at
2385
+ // the base SS_ID that member gives it: at the stream's current
2386
+ // SS_ID offset, the stream unstamped, as a base recovery shows it
2387
+ // (#routeProcessedFecSymbols). A re-stamping hop fails the psn test.
2388
+ // Only for a packet the base did not receive: a received member's
2389
+ // slot holds the bytes it arrived with (the decoder keeps a
2390
+ // received source as given), whose psn is the wire one whatever a
2391
+ // hop did, so it passes the test against itself.
2392
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
2393
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) &&
2394
+ offset === ((baseSsId - packetSequenceNumber) >>> 0)) {
2395
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
2396
+ }
2397
+ }
2301
2398
  return [out];
2302
2399
  }
2303
2400
  // A stream re-stamped by a bridge that no base recovery has shown yet
2304
2401
  // keeps the header's sequence too: from received packets alone the
2305
- // router cannot tell (their psn is the wire one). Base recovery or a
2306
- // FETCH still covers such a keyframe.
2402
+ // router cannot tell (their psn is the wire one), and the base copy of
2403
+ // a packet the overlay rebuilt only counts a re-stamp. Base recovery or
2404
+ // a FETCH still covers such a keyframe.
2307
2405
  if (!restamped) {
2308
- // No member of this MPU arrived to anchor a base SS_ID. A base
2309
- // recovery that showed the stream unstamped at its current offset
2310
- // determines one from the packet's protected psn instead
2311
- // (unstampedBaseSsId).
2312
- const baseSsId = unstampedBaseSsId(
2313
- this.#ssIdSeqOffsetByStream.get(streamKey),
2314
- this.#unstampedSsIdSeqOffsetByStream.get(streamKey),
2315
- sym.packetSequenceNumber,
2316
- );
2317
- if (baseSsId !== undefined) baseSsIds.set(sym, baseSsId);
2406
+ // No member of this MPU arrived to anchor a base SS_ID. Evidence that
2407
+ // the stream is unstamped at its current offset determines one from
2408
+ // the packet's protected psn instead (unstampedBaseSsId): a base
2409
+ // recovery's, or else the overlay's own, which anchors the release
2410
+ // gate only (#overlayUnstampedSsIdSeqOffsetByStream). Without it, the
2411
+ // packet's base copy, if it lands, shows whether it is
2412
+ // (#feedOverlaySource).
2413
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
2414
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
2415
+ const baseSsId = fedSsId ??
2416
+ unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
2417
+ if (baseSsId !== undefined) {
2418
+ baseSsIds.set(sym.index, baseSsId);
2419
+ if (fedSsId === undefined) gateOnly.add(sym.index);
2420
+ } else {
2421
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
2422
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value!);
2423
+ }
2318
2424
  return [sym];
2319
2425
  }
2320
2426
  this.#overlayStats.unsequencedDropped++;
2321
2427
  return [];
2322
2428
  });
2323
2429
  this.#overlayStats.recovered++;
2430
+ // Each packet's MPU starts, in this decode, at the lowest base SS_ID
2431
+ // determined for it: the release gate's span ends there.
2432
+ const mpuFirst = new Map<number, number>();
2433
+ for (const sym of symbols) {
2434
+ const ssId = baseSsIds.get(sym.index);
2435
+ const mpu = sym.fragment.mpuSequenceNumber;
2436
+ const first = mpuFirst.get(mpu);
2437
+ if (ssId !== undefined && (first === undefined || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
2438
+ }
2439
+ const firstSsIds = new Map<number, number>();
2440
+ for (const sym of symbols) {
2441
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber)!);
2442
+ }
2324
2443
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
2325
2444
  deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
2445
+ baseSsIds,
2446
+ firstSsIds,
2326
2447
  });
2327
2448
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) =>
2328
2449
  restored.has(sym.packetSequenceNumber)));
2329
- this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds);
2450
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0
2451
+ ? baseSsIds
2452
+ : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
2330
2453
  }
2331
2454
 
2332
2455
  /**
2333
2456
  * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
2334
2457
  * its base block too, once its base SS_ID is determined (overlayBaseSsId,
2335
- * from a received member of its MPU, else unstampedBaseSsId),
2458
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
2459
+ * base recovery showed; `baseSsIds` holds no other),
2336
2460
  * so it is fed to the base decoder as a rebuilt source
2337
2461
  * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
2338
2462
  * fewer to solve, and its repair can recover the block's other packets.
@@ -2352,7 +2476,7 @@ export class MmtpRouter {
2352
2476
  inst: OverlayInstance,
2353
2477
  blockStart: number,
2354
2478
  symbols: ProcessFecBlockResult["symbols"],
2355
- baseSsIds: ReadonlyMap<ProcessFecBlockResult["symbols"][number], number>,
2479
+ baseSsIds: ReadonlyMap<number, number>,
2356
2480
  ): void {
2357
2481
  const fec = this.#fecManager;
2358
2482
  const owner = inst.leg.sourcePacketId;
@@ -2364,7 +2488,7 @@ export class MmtpRouter {
2364
2488
  for (const sym of symbols) {
2365
2489
  // A packet the base received already sits in its block.
2366
2490
  if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
2367
- const ssId = baseSsIds.get(sym);
2491
+ const ssId = baseSsIds.get(sym.index);
2368
2492
  if (ssId === undefined) {
2369
2493
  this.#overlayStats.baseUndetermined++;
2370
2494
  continue;
@@ -3312,7 +3436,7 @@ export class MmtpRouter {
3312
3436
  catalogTrackName,
3313
3437
  )) continue;
3314
3438
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
3315
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
3439
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
3316
3440
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
3317
3441
  }
3318
3442
  if (payload.oversized) continue;
@@ -3431,6 +3555,7 @@ export class MmtpRouter {
3431
3555
  this.#latestVideoSeqByStream.delete(streamKey);
3432
3556
  this.#ssIdSeqOffsetByStream.delete(streamKey);
3433
3557
  this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
3558
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
3434
3559
  this.#multicastRapTwinByStream.delete(streamKey);
3435
3560
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
3436
3561
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -3562,6 +3687,12 @@ export class MmtpRouter {
3562
3687
  * the outgoing stream stops. The hold is bounded by the incoming stream's
3563
3688
  * own RAP cadence, so no timer is involved.
3564
3689
  *
3690
+ * While the switch is staged, the FEC release gate lets a keyframe the
3691
+ * overlay rebuilt reach it, on either side, when the keyframe did before
3692
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
3693
+ * decides on what each side delivered, and the commit discards the gate's
3694
+ * frames of the outgoing stream.
3695
+ *
3565
3696
  * The commit is one synchronous transition inside the frame path: the
3566
3697
  * outgoing stream's already-admitted frames are released (its queued FEC
3567
3698
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -3614,6 +3745,16 @@ export class MmtpRouter {
3614
3745
  droppedIncomingFrames: 0,
3615
3746
  };
3616
3747
  this.#staged = state;
3748
+ // Release what the outgoing stream's gate held only because it was
3749
+ // anchored (FecReleaseGate.releaseUnanchored): unanchored, it had already
3750
+ // reached the switch. Only a gate that holds a frame the overlay rebuilt
3751
+ // is poked: any other holds nothing for that reason, and a poke would
3752
+ // still force out a frame held past the hold limit, which before the
3753
+ // anchor waited for the next push. The incoming stream's gate is not
3754
+ // drained here: a RAP it released would commit before this call returns.
3755
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
3756
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
3757
+ }
3617
3758
  return {
3618
3759
  cancel: () => {
3619
3760
  if (this.#staged !== state) return false;
@@ -3708,7 +3849,24 @@ export class MmtpRouter {
3708
3849
  // same call. Nothing registers a packet ID mid-frame, so this drops
3709
3850
  // only frames that lost their registration.
3710
3851
  if (this.#classifyPacketId(meta.packetId) === null) return;
3711
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
3852
+ if (this.#staged !== null) {
3853
+ // A switch staged from this frame's commit (onCommit: the ladder walk)
3854
+ // pokes its outgoing stream's gate, the stream just committed to, whose
3855
+ // drain may be what released this frame. The poke waits until the
3856
+ // commit has delivered that stream's init, held GOP and RAP. Run now,
3857
+ // it would release the frames behind them ahead of them: a delta is
3858
+ // dropped there (its stream is not synced yet), and a keyframe plays
3859
+ // ahead of the init and leaves the commit's frames behind it.
3860
+ let consumed = false;
3861
+ this.#fecPokeDepth++;
3862
+ try {
3863
+ consumed = this.#interceptSwitchFrame(data, meta);
3864
+ } finally {
3865
+ this.#fecPokeDepth--;
3866
+ this.#flushPendingFecPokes();
3867
+ }
3868
+ if (consumed) return;
3869
+ }
3712
3870
  this.#deliverParsedFrame(data, meta);
3713
3871
  }
3714
3872
 
@@ -3775,6 +3933,8 @@ export class MmtpRouter {
3775
3933
  this.#disposed = true;
3776
3934
  this.#staged = null;
3777
3935
  this.cancelKeyframeLostTimer();
3936
+ for (const { timer } of this.#fecWakes.values()) clearTimeout(timer);
3937
+ this.#fecWakes.clear();
3778
3938
  this.#parser.dispose();
3779
3939
  this.#streams.clear();
3780
3940
  this.#trackPacketCallbacks.clear();
@@ -3901,12 +4061,17 @@ export class MmtpRouter {
3901
4061
  this.#parser.deferFecRelease(work);
3902
4062
  } finally {
3903
4063
  this.#fecPokeDepth--;
3904
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
3905
- const pokes = [...this.#pendingFecPokes.values()];
3906
- this.#pendingFecPokes.clear();
3907
- for (const poke of pokes) {
3908
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
3909
- }
4064
+ this.#flushPendingFecPokes();
4065
+ }
4066
+ }
4067
+
4068
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
4069
+ #flushPendingFecPokes(): void {
4070
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
4071
+ const pokes = [...this.#pendingFecPokes.values()];
4072
+ this.#pendingFecPokes.clear();
4073
+ for (const poke of pokes) {
4074
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
3910
4075
  }
3911
4076
  }
3912
4077
  }
@@ -3986,6 +4151,35 @@ export class MmtpRouter {
3986
4151
  if (!fec?.terminalRetentionMsForPacket) return Infinity;
3987
4152
  return fec.terminalRetentionMsForPacket(packetId) ?? 0;
3988
4153
  },
4154
+ // Once no repair can fill a gap (FECManager.isoRepairlessWaitMs: only a
4155
+ // late source can), its frame waits the late-symbol allowance when the
4156
+ // gap holds no RAP an installed keyframe overlay could still rebuild:
4157
+ // lost deltas of one MPU (delta-lost), the tail of the MPU before a RAP
4158
+ // that opens the next one while MPU boundaries bound RAPs (rap-next,
4159
+ // unless the gap holds a stated block's loss: the overlay may rebuild
4160
+ // that MPU's FT=0, and the block's group then complete it), or
4161
+ // an audio gap. A gap that may hold one (rap-lost, rap-unknown, or any
4162
+ // other rap-next, whose gap may hold a whole MPU and the keyframe the
4163
+ // overlay protects) waits for that overlay's repair too (BLO-52085
4164
+ // D4). The FEC check comes first: most held gaps are not behind such a
4165
+ // span, and deciding one scans both frames' bitstreams.
4166
+ unrepairableWaitMs: (before, after, fromSbn, toSbn) => {
4167
+ const fec = this.#fecManager;
4168
+ const { packetId, catalogTrackName } = after.meta;
4169
+ const allowanceMs = fec?.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn);
4170
+ if (!fec || allowanceMs === undefined) return undefined;
4171
+ const decision = this.#decideGap(before, after, [], false);
4172
+ const mpu = before.meta.mpuSequenceNumber;
4173
+ const intoNextMpu = decision.reason === "rap-next" && mpu !== undefined &&
4174
+ after.meta.mpuSequenceNumber === ((mpu + 1) >>> 0) &&
4175
+ fec.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
4176
+ if (decision.action === "stall" || (decision.reason === "rap-next" && !intoNextMpu)) {
4177
+ return fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, true);
4178
+ }
4179
+ return decision.reason === "rap-next"
4180
+ ? fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, true)
4181
+ : allowanceMs;
4182
+ },
3989
4183
  decide: (before, after, lostBlocks, discontinuity) => {
3990
4184
  const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
3991
4185
  this.#onFrameGap?.(decision);
@@ -3995,6 +4189,28 @@ export class MmtpRouter {
3995
4189
  onRap: (packetId, catalogTrackName, ssId) => {
3996
4190
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
3997
4191
  },
4192
+ // One timer per stream, at the earliest wake asked: its drain re-arms
4193
+ // for the next frame still waiting.
4194
+ wakeAt: (packetId, catalogTrackName, atMs) => {
4195
+ if (this.#disposed) return;
4196
+ const key = this.#mediaStreamKey(packetId, catalogTrackName);
4197
+ const armed = this.#fecWakes.get(key);
4198
+ if (armed !== undefined && armed.atMs <= atMs) return;
4199
+ if (armed !== undefined) clearTimeout(armed.timer);
4200
+ const timer = setTimeout(() => {
4201
+ this.#fecWakes.delete(key);
4202
+ this.#requestFecPoke(packetId, catalogTrackName);
4203
+ }, Math.max(0, Math.ceil(atMs - performance.now())));
4204
+ this.#fecWakes.set(key, { atMs, timer });
4205
+ },
4206
+ // A staged switch commits on when each side's frames reach it
4207
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
4208
+ // they did unanchored.
4209
+ releaseUnanchored: (packetId, catalogTrackName) => {
4210
+ const staged = this.#staged;
4211
+ const stream = { packetId, ...(catalogTrackName === undefined ? {} : { catalogTrackName }) };
4212
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
4213
+ },
3998
4214
  onReleased: (data, meta) => {
3999
4215
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === undefined) return;
4000
4216
  const timing = meta.authoredTiming;
@@ -4680,6 +4896,7 @@ export class MmtpRouter {
4680
4896
  deliveryProvenance?: MmtpDeliveryProvenance;
4681
4897
  catalogTrackName?: string;
4682
4898
  fecSbn?: number;
4899
+ fecSbnFirst?: number;
4683
4900
  },
4684
4901
  parsed?: ParsedMmtpPacket,
4685
4902
  ): void {
@@ -4703,6 +4920,7 @@ export class MmtpRouter {
4703
4920
  deliveryProvenance: parserOptions?.deliveryProvenance,
4704
4921
  catalogTrackName: parserOptions?.catalogTrackName,
4705
4922
  ...(parserOptions?.fecSbn === undefined ? {} : { fecSbn: parserOptions.fecSbn }),
4923
+ ...(parserOptions?.fecSbnFirst === undefined ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }),
4706
4924
  };
4707
4925
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
4708
4926
  else this.#parser.feed(packet, feedOptions);
@@ -5088,15 +5306,16 @@ export class MmtpRouter {
5088
5306
  ): void {
5089
5307
  const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);
5090
5308
  // The FEC release gate let this frame out in order: only once every
5091
- // block between it and the frame before it resolved, or because it
5092
- // starts where that frame ended. Nothing still in flight can precede it
5093
- // then, so it plays now, as a source frame does; holding it for the next
5309
+ // block between it and the frame before it resolved, because it starts
5310
+ // where that frame ended, or (one the overlay rebuilt) once the base
5311
+ // path passed it. Nothing still in flight can precede it then, so it
5312
+ // plays now, as a source frame does; holding it for the next
5094
5313
  // intact frame cost every repaired burst its length in decoder input
5095
- // (BLO-52085). An overlay recovery names no base block for the gate to
5096
- // wait on, so past a gap it may be ahead of frames still in flight (an
5097
- // overlay that outran the wire, BLO-53342): it keeps waiting for the
5098
- // source cursor below, unless it starts where the last emitted frame
5099
- // ended (on this direct path, the delivered high water).
5314
+ // (BLO-52085). An overlay recovery whose base SS_ID is undetermined names
5315
+ // no base block for the gate to wait on, so past a gap it may be ahead of
5316
+ // frames still in flight (an overlay that outran the wire, BLO-53342): it
5317
+ // keeps waiting for the source cursor below, unless it starts where the
5318
+ // last emitted frame ended (on this direct path, the delivered high water).
5100
5319
  if (this.#isFecTrack(packetId)) {
5101
5320
  const high = this.#deliveredVideoHighWaterByStream.get(streamKey);
5102
5321
  if (fecSbn !== undefined || (high !== undefined && authoredAdjacent(high, meta))) {
@@ -5422,15 +5641,25 @@ export class MmtpRouter {
5422
5641
  catalogTrackName?: string,
5423
5642
  /** Set for a keyframe-overlay recovery: `blockId` is an overlay
5424
5643
  * coordinate, which yields no base SS_ID (mmt-02 7.2), and the packets'
5425
- * wire sequences are already restored. */
5426
- overlay?: { deliveryProvenance: MmtpDeliveryProvenance },
5644
+ * wire sequences are already restored. `baseSsIds` holds, by ESI, the
5645
+ * base SS_IDs determined independently: a packet's release-gate anchor;
5646
+ * `firstSsIds` the lowest of them in its MPU (FrameMeta.fecSbnFirst). */
5647
+ overlay?: {
5648
+ deliveryProvenance: MmtpDeliveryProvenance;
5649
+ baseSsIds: ReadonlyMap<number, number>;
5650
+ firstSsIds: ReadonlyMap<number, number>;
5651
+ },
5427
5652
  ): void {
5428
5653
  // Route recovered symbols to the track's callback. The ownerPacketId tells us
5429
5654
  // which track this block belongs to — resolves per-track, then legacy fallback.
5430
5655
  if (ownerPacketId == null) return; // no track association
5431
5656
  if (this.#classifyPacketId(ownerPacketId) === null) return; // unknown track
5432
- const fecSbnOf = (index: number): { fecSbn?: number } =>
5433
- overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
5657
+ const fecSbnOf = (index: number): { fecSbn?: number; fecSbnFirst?: number } => {
5658
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
5659
+ const fecSbn = overlay.baseSsIds.get(index);
5660
+ const fecSbnFirst = overlay.firstSsIds.get(index);
5661
+ return fecSbn === undefined || fecSbnFirst === undefined ? {} : { fecSbn, fecSbnFirst };
5662
+ };
5434
5663
  // A recovered symbol's header names the sequence the sender protected. A
5435
5664
  // hop that re-stamps packet_sequence_number after protection (cast's
5436
5665
  // publisher-rotation bridge) leaves the decode mixing every received