@blockcast/mmt-container 0.4.0-main.bb90ce9247fa → 0.4.0-main.bbd83cb48eff

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 (89) hide show
  1. package/README.md +5 -3
  2. package/dist/browser-runtime.js +532 -333
  3. package/dist/browser-runtime.js.map +4 -4
  4. package/dist/carp-catalog.d.ts +5 -3
  5. package/dist/carp-catalog.d.ts.map +1 -1
  6. package/dist/carp-catalog.js +18 -5
  7. package/dist/carp-catalog.js.map +3 -3
  8. package/dist/catalog-fec-params.d.ts +5 -2
  9. package/dist/catalog-fec-params.d.ts.map +1 -1
  10. package/dist/catalog-fec-params.js +100 -36
  11. package/dist/catalog-fec-params.js.map +4 -4
  12. package/dist/catalog-network-source.js +3 -0
  13. package/dist/catalog-network-source.js.map +3 -3
  14. package/dist/delivery-catalog.js +84 -220
  15. package/dist/delivery-catalog.js.map +4 -4
  16. package/dist/fec-manager.d.ts +15 -0
  17. package/dist/fec-manager.d.ts.map +1 -1
  18. package/dist/fec-manager.js +99 -39
  19. package/dist/fec-manager.js.map +3 -3
  20. package/dist/fec-state.d.ts +3 -2
  21. package/dist/fec-state.d.ts.map +1 -1
  22. package/dist/fec-state.js +16 -9
  23. package/dist/fec-state.js.map +4 -4
  24. package/dist/fec-worker-setup.d.ts.map +1 -1
  25. package/dist/fec-worker-setup.js +13 -2
  26. package/dist/fec-worker-setup.js.map +3 -3
  27. package/dist/index.d.ts +1 -1
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +6 -0
  30. package/dist/index.js.map +2 -2
  31. package/dist/iso-block-locator.js +3 -0
  32. package/dist/iso-block-locator.js.map +3 -3
  33. package/dist/mfu-reassembler.js +24 -13
  34. package/dist/mfu-reassembler.js.map +3 -3
  35. package/dist/mmtp-container-parser.d.ts.map +1 -1
  36. package/dist/mmtp-container-parser.js +96 -22
  37. package/dist/mmtp-container-parser.js.map +3 -3
  38. package/dist/mmtp-container-parser.no-modules.js +124 -36
  39. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  40. package/dist/mmtp-decode-pipeline.js +96 -22
  41. package/dist/mmtp-decode-pipeline.js.map +3 -3
  42. package/dist/mmtp-router.d.ts +14 -4
  43. package/dist/mmtp-router.d.ts.map +1 -1
  44. package/dist/mmtp-router.js +139 -22
  45. package/dist/mmtp-router.js.map +3 -3
  46. package/dist/multicast-input.js +3 -0
  47. package/dist/multicast-input.js.map +3 -3
  48. package/dist/multicast-manager.d.ts +49 -0
  49. package/dist/multicast-manager.d.ts.map +1 -1
  50. package/dist/multicast-manager.js +437 -302
  51. package/dist/multicast-manager.js.map +4 -4
  52. package/dist/multicast-transport.d.ts +6 -2
  53. package/dist/multicast-transport.d.ts.map +1 -1
  54. package/dist/multicast-transport.js +93 -224
  55. package/dist/multicast-transport.js.map +4 -4
  56. package/dist/multicast-unwrap.js +24 -13
  57. package/dist/multicast-unwrap.js.map +3 -3
  58. package/dist/no-modules.js +123 -35
  59. package/dist/no-modules.js.map +4 -4
  60. package/dist/repair-fetch.js +3 -0
  61. package/dist/repair-fetch.js.map +3 -3
  62. package/dist/repair-layers.js +3 -0
  63. package/dist/repair-layers.js.map +3 -3
  64. package/dist/sample-combiner.d.ts +7 -1
  65. package/dist/sample-combiner.d.ts.map +1 -1
  66. package/dist/sample-combiner.js +14 -2
  67. package/dist/sample-combiner.js.map +2 -2
  68. package/dist/signaling.js +3 -0
  69. package/dist/signaling.js.map +3 -3
  70. package/dist/timestamp-codec.js +24 -13
  71. package/dist/timestamp-codec.js.map +3 -3
  72. package/dist/wasm-mfu-reassembler.js +3 -0
  73. package/dist/wasm-mfu-reassembler.js.map +3 -3
  74. package/dist/wasm-mmtp-container-parser.js +96 -22
  75. package/dist/wasm-mmtp-container-parser.js.map +3 -3
  76. package/package.json +5 -5
  77. package/src/carp-catalog.ts +33 -10
  78. package/src/catalog-fec-params.ts +38 -17
  79. package/src/fec-manager.ts +111 -49
  80. package/src/fec-state.ts +4 -9
  81. package/src/fec-worker-setup.ts +16 -1
  82. package/src/index.ts +5 -0
  83. package/src/mmtp-container-parser.ts +75 -7
  84. package/src/mmtp-router.ts +76 -5
  85. package/src/multicast-manager.ts +143 -7
  86. package/src/multicast-transport.ts +14 -3
  87. package/src/sample-combiner.ts +15 -2
  88. package/test-vectors/catalog/README.md +5 -1
  89. package/test-vectors/catalog-validation.json +95 -0
@@ -1034,8 +1034,23 @@ function isFmp4Box(data: Uint8Array): boolean {
1034
1034
  interface TimingStreamState {
1035
1035
  packetId: number
1036
1036
  resolver: IsoBmffTimingResolver
1037
+ /** FI=0/FI=1 heads that arrived before their sample's FT=1, oldest first. */
1038
+ awaitingTiming: AwaitingTimingHead[]
1037
1039
  }
1038
1040
 
1041
+ /** A head refused for missing timing, kept to be fed again when its FT=1 lands. */
1042
+ interface AwaitingTimingHead {
1043
+ packet: Uint8Array
1044
+ options: ParseHeaderOptions | undefined
1045
+ parsed: ParsedMmtpPacket
1046
+ mpuSequenceNumber: number
1047
+ movieFragmentSequenceNumber: number
1048
+ sampleNumber: number
1049
+ arrivedAt: number
1050
+ }
1051
+
1052
+ const MAX_AWAITING_TIMING_HEADS = 8
1053
+
1039
1054
  // ── MmtpContainerParser ─────────────────────────────────────────────
1040
1055
 
1041
1056
  export class MmtpContainerParser {
@@ -1098,6 +1113,7 @@ export class MmtpContainerParser {
1098
1113
  * reordering into the parser. */
1099
1114
  #reliableMoqStartupGate = new Map<string, number>()
1100
1115
  #disposed = false
1116
+ #replayingAwaitingTiming = false
1101
1117
  #fedObjects = 0
1102
1118
  #reassemblerFragmentsFed = 0
1103
1119
  #reassemblerDataUnitsReturned = 0
@@ -1446,7 +1462,10 @@ export class MmtpContainerParser {
1446
1462
  * a single failure bucket. Returns null so call sites stay `return this.#drop(...)`.
1447
1463
  */
1448
1464
  #drop(reason: MmtpFeedDropReason): null {
1449
- this.#countOutcome(`drop:${reason}`)
1465
+ // A replayed head was counted when it was fed; what befalls it now is a
1466
+ // side effect of the FT=1 that released it.
1467
+ if (this.#replayingAwaitingTiming) this.#countDeferredOutcome(reason)
1468
+ else this.#countOutcome(`drop:${reason}`)
1450
1469
  return null
1451
1470
  }
1452
1471
 
@@ -1471,6 +1490,12 @@ export class MmtpContainerParser {
1471
1490
  for (const combiner of this.#sampleCombiners.values()) {
1472
1491
  combiner.cleanupTimeouts(timeoutMs)
1473
1492
  }
1493
+ const now = Date.now()
1494
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
1495
+ while (awaitingTiming.length > 0 && now - awaitingTiming[0]!.arrivedAt > timeoutMs) {
1496
+ awaitingTiming.shift()
1497
+ }
1498
+ }
1474
1499
  }
1475
1500
 
1476
1501
  /**
@@ -1587,7 +1612,7 @@ export class MmtpContainerParser {
1587
1612
  // Fire onSourceSymbol BEFORE MFU extraction so the consumer-side FEC
1588
1613
  // pipeline (e.g. FecWorkerClient.feedSource) starts as early as possible.
1589
1614
  // Source-only: parseHeader already gates fecPayloadId on !isRepair.
1590
- if (info.fecPayloadId !== null && this.#sourceSymbolCb) {
1615
+ if (info.fecPayloadId !== null && this.#sourceSymbolCb && !this.#replayingAwaitingTiming) {
1591
1616
  // Strip the 4-byte fec_payload_id trailer per ISO 23008-1 §C.5.2.
1592
1617
  // Symbol-size zero-padding is the consumer's responsibility — FEC
1593
1618
  // symbol size is a FEC-config concern, not a parser concern.
@@ -1654,6 +1679,7 @@ export class MmtpContainerParser {
1654
1679
  }
1655
1680
  return this.#drop('fragment-timing-refused')
1656
1681
  }
1682
+ this.#replayAwaitingTiming(streamKey, resolver)
1657
1683
  return {
1658
1684
  kind: 'fragment',
1659
1685
  packet: info,
@@ -1679,7 +1705,18 @@ export class MmtpContainerParser {
1679
1705
  mfuDuHeader.movieFragmentSequenceNumber,
1680
1706
  mfuDuHeader.sampleNumber,
1681
1707
  )
1682
- if (!headTiming) return this.#drop('mfu-sample-timing-missing')
1708
+ if (!headTiming) {
1709
+ this.#awaitTiming(streamKey, {
1710
+ packet,
1711
+ options,
1712
+ parsed,
1713
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
1714
+ movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
1715
+ sampleNumber: mfuDuHeader.sampleNumber,
1716
+ arrivedAt: Date.now(),
1717
+ })
1718
+ return this.#drop('mfu-sample-timing-missing')
1719
+ }
1683
1720
  // A data unit's authored base offset is its position within the sample
1684
1721
  // (moqcast #37): 0 for a whole-sample DU, nonzero for one subsample DU
1685
1722
  // among siblings. Sizes below are therefore relative to that base, not
@@ -1781,11 +1818,12 @@ export class MmtpContainerParser {
1781
1818
  // a sample this stream declared, so it must be dropped outright -- letting
1782
1819
  // it buffer would occupy a combiner slot and could evict a legitimate
1783
1820
  // partitioned sample waiting on a sibling.
1784
- if (!resolver.sampleTiming(
1821
+ const assembledTiming = resolver.sampleTiming(
1785
1822
  assembled.mpuSequenceNumber,
1786
1823
  movieFragmentSequenceNumber,
1787
1824
  sampleNumber,
1788
- )) return this.#drop('assembled-timing-missing')
1825
+ )
1826
+ if (!assembledTiming) return this.#drop('assembled-timing-missing')
1789
1827
  if (assembled.mpuSequenceNumber !== mpu.mpuSequenceNumber)
1790
1828
  return this.#drop('assembled-mpu-mismatch')
1791
1829
 
@@ -1795,7 +1833,7 @@ export class MmtpContainerParser {
1795
1833
  // unpartitioned sample passes straight through with no buffering.
1796
1834
  let combined: CombinedSample | null
1797
1835
  try {
1798
- combined = this.#sampleCombinerFor(streamKey).addMfu(assembled)
1836
+ combined = this.#sampleCombinerFor(streamKey).addMfu(assembled, assembledTiming.size)
1799
1837
  } catch (error) {
1800
1838
  if (!(error instanceof SampleCombineError)) throw error
1801
1839
  console.warn(
@@ -2150,10 +2188,40 @@ export class MmtpContainerParser {
2150
2188
  if (existing) return existing.resolver
2151
2189
  if (!create) return null
2152
2190
  const resolver = new IsoBmffTimingResolver(this.#maxPendingTimingSamples)
2153
- this.#timingStreams.set(streamKey, { packetId, resolver })
2191
+ this.#timingStreams.set(streamKey, { packetId, resolver, awaitingTiming: [] })
2154
2192
  return resolver
2155
2193
  }
2156
2194
 
2195
+ #awaitTiming(streamKey: string, head: AwaitingTimingHead): void {
2196
+ const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming
2197
+ if (!awaitingTiming) return
2198
+ awaitingTiming.push(head)
2199
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift()
2200
+ }
2201
+
2202
+ /**
2203
+ * Feed again the heads whose timing the FT=1 just admitted declares. That
2204
+ * FT=1 can be an FEC recovery landing after its sample's FI=1, and neither
2205
+ * FEC path routes a source symbol that already arrived a second time.
2206
+ */
2207
+ #replayAwaitingTiming(streamKey: string, resolver: IsoBmffTimingResolver): void {
2208
+ const state = this.#timingStreams.get(streamKey)
2209
+ if (!state || state.awaitingTiming.length === 0) return
2210
+ const ready = state.awaitingTiming.filter(head => resolver.sampleTiming(
2211
+ head.mpuSequenceNumber,
2212
+ head.movieFragmentSequenceNumber,
2213
+ head.sampleNumber,
2214
+ ))
2215
+ if (ready.length === 0) return
2216
+ state.awaitingTiming = state.awaitingTiming.filter(head => !ready.includes(head))
2217
+ this.#replayingAwaitingTiming = true
2218
+ try {
2219
+ for (const head of ready) this.#feed(head.packet, head.options, head.parsed)
2220
+ } finally {
2221
+ this.#replayingAwaitingTiming = false
2222
+ }
2223
+ }
2224
+
2157
2225
  #dropTimingStream(streamKey: string): void {
2158
2226
  const state = this.#timingStreams.get(streamKey)
2159
2227
  if (!state) return
@@ -435,10 +435,11 @@ export type RoutedPacketMeta = {
435
435
  /**
436
436
  * The MMTP header RAP flag: the packet starts a random access point. On a
437
437
  * `recovered` packet it is read from the FEC-reconstructed header, which is
438
- * byte-exact, so it is the flag the publisher sent. The router's own gap
439
- * decisions deliberately ignore it for recovered frames (`#isRapForGap`
440
- * judges those by bitstream only); a host using it as a tier-switch commit
441
- * point should decide explicitly whether a recovered RAP qualifies.
438
+ * byte-exact outside packet_sequence_number, so it is the flag the
439
+ * publisher sent. The router's own gap decisions deliberately ignore it for
440
+ * recovered frames (`#isRapForGap` judges those by bitstream only); a host
441
+ * using it as a tier-switch commit point should decide explicitly whether a
442
+ * recovered RAP qualifies.
442
443
  */
443
444
  rap: boolean;
444
445
  /** True when FEC reconstructed this source packet. */
@@ -560,6 +561,16 @@ export interface FECManagerLike {
560
561
  /** A block's RSB_length, from one of its repair symbols (optional). */
561
562
  noteRepairGroupLength?(sbn: number, packetId: number, rsbLength: number, catalogTrackName?: string): void;
562
563
 
564
+ /** Validate a repair symbol's size before it touches block state; counts a
565
+ * mismatch on `repairSymbolSizeMismatches` (optional). */
566
+ admitRepairSymbolSize?(
567
+ packetId: number,
568
+ ssStart: number,
569
+ ssbLength: number,
570
+ rsId: number,
571
+ byteLength: number,
572
+ ): boolean;
573
+
563
574
  /** Feed a repair symbol to the FEC decoder for a given track.
564
575
  * Returns recovered block bytes if recovery completes, else null. */
565
576
  feedRepairSymbol(
@@ -896,6 +907,12 @@ export class MmtpRouter {
896
907
  // MSE recovery routes through CmafBlockAssembler and can reorder by block; the
897
908
  // direct callback path has to preserve decode order before frames leave libmmt.
898
909
  #latestVideoSeqByStream = new Map<string, number>();
910
+ /**
911
+ * Per stream, SS_ID - packet_sequence_number (mod 2^32) of its latest
912
+ * first-arrival FEC source packet. A recovered source symbol's wire
913
+ * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
914
+ */
915
+ #ssIdSeqOffsetByStream = new Map<string, number>();
899
916
  #lastDirectSourceVideoTsByStream = new Map<string, number>();
900
917
  #lastDirectEmittedVideoTsByStream = new Map<string, number>();
901
918
  #pendingDirectRecoveredVideoByStream = new Map<string, Map<string, PendingRecoveredVideoFrame>>();
@@ -988,6 +1005,7 @@ export class MmtpRouter {
988
1005
  */
989
1006
  #onPublisherRestart: ((packetId: number, catalogTrackName: string) => void) | null;
990
1007
  #publisherRestarts = 0;
1008
+ #restampedRecoveredSeqs = 0;
991
1009
  /** Inits delivered with no onTrackInit handler for their packetId (MOQT-01). */
992
1010
  #unmappedInitDeliveries = 0;
993
1011
  // FEC Payload IDs left unread because their (owner) packetId had no
@@ -1364,6 +1382,15 @@ export class MmtpRouter {
1364
1382
  return this.#publisherRestarts;
1365
1383
  }
1366
1384
 
1385
+ /**
1386
+ * FEC-recovered source symbols whose reconstructed header named a
1387
+ * packet_sequence_number other than the wire sequence their SS_ID maps to:
1388
+ * a hop re-stamped the sequence after the sender protected the packet.
1389
+ */
1390
+ get restampedRecoveredSequenceCount(): number {
1391
+ return this.#restampedRecoveredSeqs;
1392
+ }
1393
+
1367
1394
  /**
1368
1395
  * Packets whose Source or Repair FEC Payload ID was left unread because
1369
1396
  * their (owner) packetId had no configured `fec.blockProfile`: FEC not
@@ -2014,6 +2041,19 @@ export class MmtpRouter {
2014
2041
  `[MmtpRouter] packetId=${ownerPacketId} is iso-ssbg1-v1 but its FEC manager cannot place ISO blocks`,
2015
2042
  );
2016
2043
  }
2044
+ // A repair symbol that is not exactly T bytes is invalid: refuse it before
2045
+ // it can place a block or be swallowed by dedup, so it is always counted
2046
+ // and never reaches the decoder (BLO-48306).
2047
+ if (
2048
+ fec.admitRepairSymbolSize &&
2049
+ !fec.admitRepairSymbolSize(
2050
+ ownerPacketId,
2051
+ repair.ssStart,
2052
+ repair.ssbLength,
2053
+ repair.rsId,
2054
+ repair.symbolData.byteLength,
2055
+ )
2056
+ ) return;
2017
2057
  const placement = fec.placeIsoRepair(ownerPacketId, catalogTrackName, repair.ssStart, repair.ssbLength);
2018
2058
  if (placement.status !== "placed") return;
2019
2059
  const blockStart = placement.block.start;
@@ -2180,6 +2220,7 @@ export class MmtpRouter {
2180
2220
  this.#trackSynced.delete(streamKey);
2181
2221
  this.#droppedPreSyncVideo.delete(streamKey);
2182
2222
  this.#latestVideoSeqByStream.delete(streamKey);
2223
+ this.#ssIdSeqOffsetByStream.delete(streamKey);
2183
2224
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
2184
2225
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
2185
2226
  this.#pendingDirectRecoveredVideoByStream.delete(streamKey);
@@ -3205,6 +3246,13 @@ export class MmtpRouter {
3205
3246
  parseSourceSymbol = !duplicates.parsedSymbols.has(info.fecPayloadId.ssId);
3206
3247
  }
3207
3248
 
3249
+ if (fecPayloadId && !overlapCopy) {
3250
+ this.#ssIdSeqOffsetByStream.set(
3251
+ this.#mediaStreamKey(info.packetId, catalogTrackName),
3252
+ (fecPayloadId.ssId - info.sequenceNumber) >>> 0,
3253
+ );
3254
+ }
3255
+
3208
3256
  // Parse only the first copy of an FEC source symbol. A late direct copy
3209
3257
  // of a worker-recovered fragment has the same SBN/ESI and fragment
3210
3258
  // counter; feeding it again can make the MFU buffer non-contiguous even
@@ -4080,6 +4128,28 @@ export class MmtpRouter {
4080
4128
  // which track this block belongs to — resolves per-track, then legacy fallback.
4081
4129
  if (ownerPacketId == null) return; // no track association
4082
4130
  if (this.#classifyPacketId(ownerPacketId) === null) return; // unknown track
4131
+ // A recovered symbol's header names the sequence the sender protected. A
4132
+ // hop that re-stamps packet_sequence_number after protection (cast's
4133
+ // publisher-rotation bridge) leaves the decode mixing every received
4134
+ // source's re-stamped bytes into it. The reassembler addresses a
4135
+ // fragmented data unit by sequence + fragment counter, and the source
4136
+ // dedup reads the same number, so that fragment would park under a
4137
+ // foreign address until its data unit times out. Its SS_ID still names
4138
+ // its wire sequence, through the offset every received source states.
4139
+ const ssIdSeqOffset = this.#ssIdSeqOffsetByStream.get(
4140
+ this.#mediaStreamKey(ownerPacketId, catalogTrackName),
4141
+ );
4142
+ if (ssIdSeqOffset !== undefined) {
4143
+ result = {
4144
+ ...result,
4145
+ symbols: result.symbols.map((sym) => {
4146
+ const wire = (this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset) >>> 0;
4147
+ if (wire === sym.packetSequenceNumber) return sym;
4148
+ this.#restampedRecoveredSeqs++;
4149
+ return { ...sym, packetSequenceNumber: wire };
4150
+ }),
4151
+ };
4152
+ }
4083
4153
  this.#stream(ownerPacketId, catalogTrackName).duplicates.advance(blockId);
4084
4154
 
4085
4155
  // A recovered symbol is a function of EVERY symbol that entered its block,
@@ -4100,7 +4170,8 @@ export class MmtpRouter {
4100
4170
  ) ?? 'unknown';
4101
4171
 
4102
4172
  for (const sym of result.symbols) {
4103
- // The block processor read these from the recovered packet's own header.
4173
+ // The block processor read these from the recovered packet's own
4174
+ // header; the sequence is the wire one derived above.
4104
4175
  this.#routeTrackPacket(sym.rawSymbol, ownerPacketId, sym.packetSequenceNumber, {
4105
4176
  mmtpTimestamp: sym.fragment.timestamp,
4106
4177
  rap: sym.fragment.rapFlag,
@@ -46,7 +46,7 @@ import {
46
46
  type StreamSwitchCommit,
47
47
  type TrackPacketCallback,
48
48
  } from "./mmtp-router.js";
49
- import { isMulticastTrackPacketId } from "@blockcast/mmt-transport";
49
+ import { isMulticastTrackPacketId, type WindowMulticastGateway } from "@blockcast/mmt-transport";
50
50
  import {
51
51
  MulticastTransport,
52
52
  type MulticastFailbackReason,
@@ -83,6 +83,35 @@ import {
83
83
  } from "./carp-catalog.js";
84
84
  import { catalogFecUnavailable, type TrackFecUnavailable } from "./catalog-fec-params.js";
85
85
 
86
+ /**
87
+ * One dedicated repair group to join beside the media join: the shape
88
+ * `selectRepairEndpointsForTracks` (`@blockcast/mmt-transport`) returns.
89
+ */
90
+ export interface MulticastRepairEndpoint {
91
+ group: string;
92
+ source: string;
93
+ port: number;
94
+ mode?: string;
95
+ amtRelay?: string;
96
+ amtRelayPort?: number;
97
+ /** The repair packet IDs this group carries. */
98
+ packetIds: number[];
99
+ /** Each repair packet ID bound to the media packet ID it repairs. */
100
+ repairOwners: ReadonlyArray<{ packetId: number; ownerPacketId: number }>;
101
+ /** Ingress tracks: the owners' source tracks and the repair tracks. */
102
+ tracks: MmtpIngressContext["tracks"];
103
+ }
104
+
105
+ /**
106
+ * Opens one repair-group subscription through the caller's own provider (a
107
+ * hang bridge, for one): delivers each packet to `onPacket` and returns (or
108
+ * resolves to) the call that releases it.
109
+ */
110
+ export type MulticastRepairSubscribe = (
111
+ endpoint: MulticastRepairEndpoint,
112
+ onPacket: (packet: Uint8Array) => void,
113
+ ) => (() => void) | Promise<() => void>;
114
+
86
115
  export interface MulticastEndpointConfig {
87
116
  sourceAddress: string;
88
117
  groupAddress: string;
@@ -95,6 +124,12 @@ export interface MulticastEndpointConfig {
95
124
  amtRelay?: string;
96
125
  /** AMT relay port from player/UI overrides. Wins over `relayPort`. */
97
126
  amtRelayPort?: number;
127
+ /**
128
+ * `'driad'`: no relay is pinned; the window.multicast gateway runs RFC 8777
129
+ * DRIAD on `sourceAddress` and fails over across the relays it offers.
130
+ * Ignored when `amtRelay` is set.
131
+ */
132
+ amtDiscovery?: 'driad';
98
133
  /** MMTP packet IDs to forward before data enters the page transport queue. */
99
134
  packetIds?: number[];
100
135
  /** Exact catalog tracks carried by this physical multicast endpoint. */
@@ -1099,6 +1134,9 @@ export class MulticastManager {
1099
1134
  readonly #router: MmtpRouter;
1100
1135
  #hostMfuTimeoutMs: number | null;
1101
1136
  readonly #transport: MulticastTransport<MmtpIngressContext>;
1137
+ /** Live joinRepairEndpoints() releases → the repair owners they registered,
1138
+ * re-applied after configureMultiTrack() clears catalog-derived owners. */
1139
+ readonly #repairReleases = new Map<() => void, MulticastRepairEndpoint["repairOwners"]>();
1102
1140
  #reportedFecDiagnosticsFailure = false;
1103
1141
 
1104
1142
  // ── Stream-global FEC timing reduction ──
@@ -1416,7 +1454,12 @@ export class MulticastManager {
1416
1454
  catalogTrackName,
1417
1455
  );
1418
1456
  this.#configureTrackMapper(packetId, config);
1419
- this.#router.setPacketIdType(packetId, trackType);
1457
+ // A Worker for an already registered track swaps the decoder mid-stream.
1458
+ // Re-registering the track would reset the parser's MPU timing and drop
1459
+ // the rest of the GOP in flight.
1460
+ if (this.#router.trackKindFor(packetId) !== trackType) {
1461
+ this.#router.setPacketIdType(packetId, trackType);
1462
+ }
1420
1463
  }
1421
1464
 
1422
1465
  /**
@@ -1510,6 +1553,18 @@ export class MulticastManager {
1510
1553
  }
1511
1554
  }
1512
1555
 
1556
+ // A data unit must outlive every FEC block that can still complete it: the
1557
+ // release gate waits for them up to terminal retention, and a fragment
1558
+ // recovered after its data unit was evicted is lost.
1559
+ for (const [packetId, c] of this.#trackFecTiming) {
1560
+ if (c.deliveryWindowMs === undefined) continue;
1561
+ mfuTimeoutMs = Math.max(
1562
+ mfuTimeoutMs ?? 0,
1563
+ this.#fec.terminalRetentionMsForPacket(packetId) ?? 0,
1564
+ this.#hostMfuTimeoutMs ?? 0,
1565
+ );
1566
+ }
1567
+
1513
1568
  const failbackWindowMs =
1514
1569
  deliveryWindowMs === undefined
1515
1570
  ? minimumFailbackWindowMs
@@ -1810,6 +1865,8 @@ export class MulticastManager {
1810
1865
  setMfuTimeoutMs(ms: number): void {
1811
1866
  this.#router.setMfuTimeoutMs(ms);
1812
1867
  this.#hostMfuTimeoutMs = this.#router.reassembler.timeoutMs;
1868
+ // A FEC track's data units must still outlive its terminal retention.
1869
+ if (this.#trackFecTiming.size > 0) this.#applyStreamGlobalFecTiming();
1813
1870
  }
1814
1871
 
1815
1872
  setTrackCodec(packetId: number, codec: string) {
@@ -1978,6 +2035,7 @@ export class MulticastManager {
1978
2035
  config.amtRelayPort ??
1979
2036
  config.relayPort ??
1980
2037
  (amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : undefined),
2038
+ amtDiscovery: config.amtDiscovery,
1981
2039
  packetIds: config.packetIds,
1982
2040
  tracks: catalogTracks?.map(({ name, packetId }) => ({ name, packetId })),
1983
2041
  };
@@ -1986,6 +2044,82 @@ export class MulticastManager {
1986
2044
  : this.#transport.join(transportConfig, ingress);
1987
2045
  }
1988
2046
 
2047
+ /**
2048
+ * Join the selected rung's dedicated repair groups beside the media join
2049
+ * (pim #3898): one subscription per endpoint, through `provider` when given
2050
+ * (a `window.multicast`-shaped gateway or a subscribe callback), otherwise a
2051
+ * new MulticastTransport on `window.multicast`. Returns the call that
2052
+ * releases every one of them; dispose() releases them too.
2053
+ *
2054
+ * Packets go straight to the router with the endpoint's ingress, never
2055
+ * through feedPacket(): repair arriving on its own group is not media
2056
+ * liveness, so it must not hold off the media leg's failback watchdog. The
2057
+ * repair roles and owners are registered here; in-band owners stay the
2058
+ * caller's. Joining is best effort: a group that fails to join is logged
2059
+ * and leaves the media join as it was.
2060
+ */
2061
+ joinRepairEndpoints(
2062
+ endpoints: readonly MulticastRepairEndpoint[],
2063
+ provider?: WindowMulticastGateway | MulticastRepairSubscribe,
2064
+ ): () => void {
2065
+ const releases: Array<() => void> = [];
2066
+ let released = false;
2067
+ const safely = (each: () => void) => {
2068
+ try {
2069
+ each();
2070
+ } catch (error) {
2071
+ console.warn("[MulticastManager] repair group release failed", error);
2072
+ }
2073
+ };
2074
+ const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners);
2075
+ this.#applyRepairOwners(repairOwners);
2076
+ for (const endpoint of endpoints) {
2077
+ const ingress: MmtpIngressContext = {
2078
+ tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
2079
+ };
2080
+ const onPacket = (packet: Uint8Array) => {
2081
+ if (!released) this.#router.feedPacket(packet, "multicast", undefined, ingress);
2082
+ };
2083
+ const fail = (error: unknown) =>
2084
+ console.warn(`[MulticastManager] repair group ${endpoint.group}:${endpoint.port} not joined`, error);
2085
+ if (typeof provider === "function") {
2086
+ Promise.resolve()
2087
+ .then(() => provider(endpoint, onPacket))
2088
+ .then((release) => (released ? safely(release) : releases.push(release)), fail);
2089
+ continue;
2090
+ }
2091
+ const transport = new MulticastTransport((packet) => onPacket(packet), { gateway: provider });
2092
+ releases.push(() => transport.dispose());
2093
+ void transport.join({
2094
+ sourceAddress: endpoint.source,
2095
+ groupAddress: endpoint.group,
2096
+ port: endpoint.port,
2097
+ mode: endpoint.mode as MulticastEndpointConfig["mode"],
2098
+ amtRelay: endpoint.amtRelay,
2099
+ amtRelayPort: endpoint.amtRelayPort ?? (endpoint.amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : undefined),
2100
+ packetIds: endpoint.packetIds,
2101
+ tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
2102
+ }).then((joined) => {
2103
+ if (!joined && !released) fail(transport.lastJoinOutcome);
2104
+ });
2105
+ }
2106
+ const release = () => {
2107
+ if (released) return;
2108
+ released = true;
2109
+ this.#repairReleases.delete(release);
2110
+ for (const each of releases.splice(0)) safely(each);
2111
+ };
2112
+ this.#repairReleases.set(release, repairOwners);
2113
+ return release;
2114
+ }
2115
+
2116
+ #applyRepairOwners(owners: MulticastRepairEndpoint["repairOwners"]): void {
2117
+ for (const { packetId, ownerPacketId } of owners) {
2118
+ this.#router.setPacketIdRole(packetId, "repair");
2119
+ this.#router.setRepairPacketIdOwner(packetId, ownerPacketId);
2120
+ }
2121
+ }
2122
+
1989
2123
  // ---------------------------------------------------------------------------
1990
2124
  // In-place rendition switch
1991
2125
  // ---------------------------------------------------------------------------
@@ -2458,11 +2592,9 @@ export class MulticastManager {
2458
2592
  if (!(hasSwitchingSetByGroup.get(groupKey) ?? false)) continue;
2459
2593
 
2460
2594
  const presentRoles = new Set(roles.filter((r) => r !== "single"));
2461
- const required: Array<"base" | "delta" | "repair"> = [
2462
- "base",
2463
- "delta",
2464
- "repair",
2465
- ];
2595
+ // Delta is optional (BLO-49199): base is the self-decodable leg and a
2596
+ // base-only group plays in base-only mode; delta without base cannot.
2597
+ const required: Array<"base" | "repair"> = ["base", "repair"];
2466
2598
  const missing = required.filter((r) => !presentRoles.has(r));
2467
2599
  if (missing.length > 0) {
2468
2600
  throw new Error(
@@ -2517,6 +2649,9 @@ export class MulticastManager {
2517
2649
  this.#switchingSets.clear();
2518
2650
  this.#repairPacketIds.clear();
2519
2651
  this.#router.clearRepairPacketIdOwners();
2652
+ // Dedicated repair groups joined beside the media join outlive a catalog
2653
+ // refresh; their owners are not this catalog's to drop.
2654
+ for (const owners of this.#repairReleases.values()) this.#applyRepairOwners(owners);
2520
2655
  // FEC a previous call configured that this one does not (the source is
2521
2656
  // gone, lost its `fec`, or its FEC is now unavailable) must not stay
2522
2657
  // installed: its symbols would still be read as block coordinates and
@@ -2951,6 +3086,7 @@ export class MulticastManager {
2951
3086
  this.#trackResetObservers.clear();
2952
3087
  this.#repairLifecycleObservers.clear();
2953
3088
  this.#transport.dispose();
3089
+ for (const release of [...this.#repairReleases.keys()]) release();
2954
3090
  this.#router.dispose();
2955
3091
  this.#fec.dispose();
2956
3092
  }
@@ -25,6 +25,8 @@ export interface MulticastTransportConfig {
25
25
  mode?: 'auto' | 'native' | 'tunnel'
26
26
  amtRelay?: string
27
27
  amtRelayPort?: number
28
+ /** `'driad'`: with no relay, the gateway discovers one per RFC 8777. */
29
+ amtDiscovery?: 'driad'
28
30
  packetIds?: number[]
29
31
  tracks?: { name: string; packetId: number }[]
30
32
  }
@@ -330,8 +332,15 @@ export class MulticastTransport<TPacketContext = never> {
330
332
  readonly #unadvertisedPacketIds = new Set<number>()
331
333
  #joinGeneration = 0
332
334
 
333
- constructor(onPacket: (packet: Uint8Array, context?: TPacketContext) => void) {
335
+ // The provider to subscribe through; window.multicast when unset.
336
+ readonly #gateway: WindowMulticastGateway | undefined
337
+
338
+ constructor(
339
+ onPacket: (packet: Uint8Array, context?: TPacketContext) => void,
340
+ options: { gateway?: WindowMulticastGateway } = {},
341
+ ) {
334
342
  this.#onPacket = onPacket
343
+ this.#gateway = options.gateway
335
344
  }
336
345
 
337
346
  static isAvailable(): boolean {
@@ -344,7 +353,8 @@ export class MulticastTransport<TPacketContext = never> {
344
353
  this.#dataPlaneLive = false
345
354
 
346
355
  if (this.#disposed) return this.#declined(generation, 'disposed')
347
- if (!MulticastTransport.isAvailable()) {
356
+ const gateway = this.#gateway ?? getMulticastGlobals().multicast
357
+ if (typeof gateway?.subscribe !== 'function') {
348
358
  console.warn('[MulticastTransport] Multicast API not available')
349
359
  return this.#declined(generation, 'unavailable')
350
360
  }
@@ -365,11 +375,12 @@ export class MulticastTransport<TPacketContext = never> {
365
375
  mode: config.mode,
366
376
  amtRelay: config.amtRelay,
367
377
  amtRelayPort: config.amtRelayPort,
378
+ amtDiscovery: config.amtDiscovery,
368
379
  packetIds: config.packetIds,
369
380
  tracks: config.tracks,
370
381
  })
371
382
  failure = 'provider-rejected'
372
- const subscription = await getMulticastGlobals().multicast!.subscribe!(subscribeConfig)
383
+ const subscription = await gateway.subscribe(subscribeConfig)
373
384
  failure = 'invalid-subscription'
374
385
  console.log(`[MulticastTransport] window.multicast.subscribe returned:`, !!subscription)
375
386
 
@@ -286,8 +286,14 @@ export class SampleCombiner {
286
286
  /**
287
287
  * Add one reassembled data unit. Returns the combined sample once every
288
288
  * constituent data unit has arrived and totals the authored size.
289
+ *
290
+ * `sampleSize` is the authored size the host resolves for the sample as the
291
+ * data unit completes. It stands in only when no size was registered, which
292
+ * happens when the data unit's FI=0/FI=1 reached the reassembler without the
293
+ * host's own FT=2 parse: an FEC-recovered first fragment completed by source
294
+ * fragments, or one decoded before its source copy arrived.
289
295
  */
290
- addMfu(mfu: ReassembledMFU): CombinedSample | null {
296
+ addMfu(mfu: ReassembledMFU, sampleSize?: number): CombinedSample | null {
291
297
  if (mfu.movieFragmentSequenceNumber === undefined || mfu.sampleNumber === undefined) {
292
298
  // Non-timed (Item) MFU: sample combining does not apply.
293
299
  this.#stats.passthroughSamples++
@@ -311,7 +317,7 @@ export class SampleCombiner {
311
317
  }
312
318
 
313
319
  const dataLen = mfu.data.byteLength
314
- const authoredSize = this.#authoredSizes.get(key)
320
+ const authoredSize = this.#authoredSizes.get(key) ?? sampleSize
315
321
 
316
322
  if (offset === 0 && !this.#pending.has(key)) {
317
323
  const passesThrough = authoredSize === undefined
@@ -678,6 +684,13 @@ if (import.meta.vitest) {
678
684
  expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
679
685
  })
680
686
 
687
+ test('a size handed with the data unit completes a sample no head registered', () => {
688
+ const c = combiner({ requireAuthoredSize: true })
689
+ const out = c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5)
690
+ expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5]))
691
+ expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5)).toBeNull()
692
+ })
693
+
681
694
  test('duplicate offset is rejected', () => {
682
695
  const c = combiner()
683
696
  c.registerAuthoredSize(undefined, 1, 9, 17, 10)
@@ -100,7 +100,11 @@ An omitted `fec.interleaveDepthMs` is valid catalog shape, but under
100
100
  `"iso-ssbg1-v1"` it leaves the track without FEC at a receiver (see above).
101
101
  When present, `groupDurationTicks` overrides the integer millisecond field.
102
102
  Switching sets compare `ticks / timescale`, so equal wall-clock durations at
103
- different timescales are valid.
103
+ different timescales are valid. One exception: an intra-only member (group
104
+ duration equal to one frame at its `framerate`, e.g. a forceIOnly base leg) may
105
+ sit beside a GOP member whose group duration is a whole number of its groups,
106
+ because every GOP boundary is then also one of its boundaries. GOP members still
107
+ compare for exact equality (BLO-49202).
104
108
 
105
109
  `multicast-native-ssm-no-network-source.json` is the native-SSM shape: an
106
110
  endpoint's `(protocol, sourceAddress, groupAddress, port)` is complete join