@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
@@ -171,26 +171,30 @@ function isEmptyOrExactLegacyTrailer(payload, start, end) {
171
171
  const authLength = view2.getUint16(2, false);
172
172
  return start + LEGACY_TRAILER_HEADER_SIZE + authLength === end;
173
173
  }
174
- function resolveDeclaredTrailers(payload, declaredEnd, fecType, options) {
174
+ function resolveDeclaredTrailers(payload, declaredEnd, fecType, options, rapFlag = false) {
175
175
  if (declaredEnd > payload.length)
176
176
  return null;
177
177
  if (options?.skipFecId) {
178
- return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false } : null;
178
+ return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false, hasOverlayFecId: false } : null;
179
179
  }
180
+ const overlay = options?.overlayDeclared === true && rapFlag;
180
181
  if (fecType === 1) {
181
- const fecStart = payload.length - SOURCE_FEC_PAYLOAD_ID_SIZE;
182
+ const fecStart = payload.length - sourceFecTrailerSize(overlay);
182
183
  if (fecStart < declaredEnd || !isEmptyOrExactLegacyTrailer(payload, declaredEnd, fecStart)) {
183
184
  return null;
184
185
  }
185
- return { hasFecId: true };
186
+ return { hasFecId: true, hasOverlayFecId: overlay };
186
187
  }
187
- if (fecType !== 0)
188
+ if (fecType !== 0 || overlay)
188
189
  return null;
189
190
  if (isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)) {
190
- return { hasFecId: false };
191
+ return { hasFecId: false, hasOverlayFecId: false };
191
192
  }
192
193
  return null;
193
194
  }
195
+ function sourceFecTrailerSize(overlay) {
196
+ return overlay ? 2 * SOURCE_FEC_PAYLOAD_ID_SIZE : SOURCE_FEC_PAYLOAD_ID_SIZE;
197
+ }
194
198
  function planMfuExtraction(mmtpPacket, options, parsedHeader) {
195
199
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) {
196
200
  return {
@@ -243,15 +247,16 @@ function planMfuExtraction(mmtpPacket, options, parsedHeader) {
243
247
  if ("rejection" in layoutResult)
244
248
  return layoutResult;
245
249
  const { layout } = layoutResult;
246
- const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options);
250
+ const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options, header.rapFlag);
247
251
  if (!trailerLayout) {
248
252
  if (!options?.skipFecId && header.fecType === 1) {
249
253
  const observed = payload.length - layout.dataEnd;
250
- if (observed !== SOURCE_FEC_PAYLOAD_ID_SIZE) {
254
+ const expected = sourceFecTrailerSize(options?.overlayDeclared === true && header.rapFlag);
255
+ if (observed !== expected) {
251
256
  return {
252
257
  rejection: {
253
258
  gate: "source-fec-payload-id-width-mismatch",
254
- detail: `producer wrote a ${observed}-byte Source FEC Payload ID, ISO/IEC 23008-1 \xA7C.5.2 requires ${SOURCE_FEC_PAYLOAD_ID_SIZE} (payload=${payload.length}, declaredEnd=${layout.dataEnd})`
259
+ detail: `producer wrote a ${observed}-byte Source FEC Payload ID, ISO/IEC 23008-1 \xA7C.5.2 requires ${expected} (payload=${payload.length}, declaredEnd=${layout.dataEnd})`
255
260
  }
256
261
  };
257
262
  }
@@ -278,10 +283,13 @@ function extractPlannedMfu(mmtpPacket, result) {
278
283
  const mfuDuHeader = mfuDuHeaderPresent && mpu.timedFlag === 1 ? parseTimedMfuDuHeader(payload, MPU_HEADER_SIZE) : null;
279
284
  const itemId = mfuDuHeaderPresent && mpu.timedFlag === 0 ? new DataView(payload.buffer, payload.byteOffset + MPU_HEADER_SIZE, 4).getUint32(0, false) : null;
280
285
  const data = payload.subarray(mfuOffset, dataEnd);
281
- const fecPayloadId = trailerLayout.hasFecId ? {
282
- ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE, SOURCE_FEC_PAYLOAD_ID_SIZE).getUint32(0, false)
283
- } : null;
284
- return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId };
286
+ const trailerStart = mmtpPacket.length - sourceFecTrailerSize(trailerLayout.hasOverlayFecId);
287
+ const ssIdAt = (offset) => ({
288
+ ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + offset, 4).getUint32(0, false)
289
+ });
290
+ const fecPayloadId = trailerLayout.hasFecId ? ssIdAt(trailerStart) : null;
291
+ const overlayFecPayloadId = trailerLayout.hasOverlayFecId ? ssIdAt(trailerStart + SOURCE_FEC_PAYLOAD_ID_SIZE) : null;
292
+ return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId, overlayFecPayloadId };
285
293
  }
286
294
  function sourceFecPayloadIdOf(mmtpPacket, header) {
287
295
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE)
@@ -417,6 +425,28 @@ function isoBlocksBehindLowerBound(a, b, kMax) {
417
425
  return serial32Precedes(a, b) ? Math.floor(serial32Distance(a, b) / kMax) : 0;
418
426
  }
419
427
 
428
+ // ../mmt-base/dist/catalog-fec-source.js
429
+ var ALL_ROLES = Object.freeze(["video", "audio"]);
430
+ function recordOf(value) {
431
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
432
+ }
433
+ function isoBlockSpanUsable(fec) {
434
+ const block = recordOf(fec);
435
+ if (block === void 0 || block["blockProfile"] !== "iso-ssbg1-v1")
436
+ return true;
437
+ const ms = block["interleaveDepthMs"];
438
+ return ms === void 0 || typeof ms === "number" && Number.isSafeInteger(ms) && ms >= 0;
439
+ }
440
+ function catalogFecAvailable(fec) {
441
+ const block = recordOf(fec);
442
+ if (block === void 0)
443
+ return true;
444
+ const declaresFecInstance = block["algorithm"] !== "none";
445
+ const profile = block["blockProfile"];
446
+ const profileOk = isFecBlockProfile(profile) || profile === void 0 && !declaresFecInstance;
447
+ return profileOk && (!declaresFecInstance || isoBlockSpanUsable(block));
448
+ }
449
+
420
450
  // src/track-session.ts
421
451
  import { fecBlockBudgetMs } from "@blockcast/mmt-fec";
422
452
  function computeFecDeliveryWindowMs(config) {
@@ -774,15 +804,6 @@ var INACTIVE = Object.freeze({
774
804
  "reliable-moq": Object.freeze({ state: "inactive", reason: "reliable-moq" }),
775
805
  "no-multicast-bridge": Object.freeze({ state: "inactive", reason: "no-multicast-bridge" })
776
806
  });
777
- function recordOf(value) {
778
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
779
- }
780
- function isoBlockSpanUsable(fec) {
781
- const block = recordOf(fec);
782
- if (block === void 0 || block["blockProfile"] !== "iso-ssbg1-v1") return true;
783
- const ms = block["interleaveDepthMs"];
784
- return ms === void 0 || typeof ms === "number" && Number.isSafeInteger(ms) && ms >= 0;
785
- }
786
807
 
787
808
  // src/block-policy.ts
788
809
  import { deriveFecInterleaveDepth } from "@blockcast/mmt-fec";
@@ -1478,9 +1499,13 @@ var FECManager = class _FECManager {
1478
1499
  // per stream. Not only throws: the ordinary out-of-range case is detected by
1479
1500
  // arithmetic and never throws at all.
1480
1501
  this.#orderedHorizonWarnedFor = /* @__PURE__ */ new Set();
1481
- // Newest block start (SS_Start) seen per stream and when: the frontier for
1482
- // source-discontinuity detection and isoSpanResolution.
1502
+ // Newest block start (SS_Start) any symbol carried per stream and when: the
1503
+ // frontier isoSpanResolution reads.
1483
1504
  this.#highestSbn = /* @__PURE__ */ new Map();
1505
+ // The same from source symbols alone: the frontier a source is judged
1506
+ // against for a discontinuity. Repairs ride their own group, which can run
1507
+ // blocks ahead of the media they protect.
1508
+ this.#sourceFrontiers = /* @__PURE__ */ new Map();
1484
1509
  // iso-ssbg1-v1 block location per stream (streamKey). A source belongs to a
1485
1510
  // block only once a repair symbol stated the block's (SS_Start, SSB_length).
1486
1511
  this.#isoLocators = /* @__PURE__ */ new Map();
@@ -1498,8 +1523,8 @@ var FECManager = class _FECManager {
1498
1523
  // rate-limited like the other per-symbol warns here. Cumulative.
1499
1524
  this.#isoDecoderUnplacedRetireFailed = 0;
1500
1525
  // The latest source symbol per stream that carried its MMTP
1501
- // packet_sequence_number: the anchor that bounds how many blocks the
1502
- // producer can have started before a later source symbol.
1526
+ // packet_sequence_number, by its own SS_ID: the anchor that bounds how far
1527
+ // the producer's SS_IDs can have moved before or after another source symbol.
1503
1528
  this.#sourceAnchors = /* @__PURE__ */ new Map();
1504
1529
  // Catalog/reset epoch per packetId. Gap decisions carry it for fencing.
1505
1530
  this.#packetEpochs = /* @__PURE__ */ new Map();
@@ -1637,6 +1662,7 @@ var FECManager = class _FECManager {
1637
1662
  #materializedBlocks;
1638
1663
  #orderedHorizonWarnedFor;
1639
1664
  #highestSbn;
1665
+ #sourceFrontiers;
1640
1666
  #isoLocators;
1641
1667
  #isoRepairRefusedCount;
1642
1668
  #isoSourceOversizeCount;
@@ -2227,8 +2253,8 @@ var FECManager = class _FECManager {
2227
2253
  // Deliberately one block tighter than deriveFecRetentionBlocks over the same
2228
2254
  // inputs (that function's `+ 1`). Different question: the retention horizon
2229
2255
  // asks how long the decoder still ACCEPTS symbols for a block, this asks how
2230
- // many blocks a stream can live behind (or ahead of) its frontier before a
2231
- // source symbol there is a discontinuity rather than loss (see #noteSbnSeen).
2256
+ // many blocks a stream can jump ahead of its frontier before a source symbol
2257
+ // there is a discontinuity rather than loss (see #noteSbnSeen).
2232
2258
  // The extra block of retention is slack for a block still being fed; a block
2233
2259
  // nothing has been heard from does not get it. Not the units defect — but it
2234
2260
  // is the next place the two can drift, so change both or neither.
@@ -2238,55 +2264,72 @@ var FECManager = class _FECManager {
2238
2264
  }
2239
2265
  /**
2240
2266
  * Record that a symbol for block `sbn` (the block's SS_Start) arrived and
2241
- * advance the stream's frontier, the newest block start seen.
2267
+ * advance the stream's frontiers, the newest block start seen.
2242
2268
  *
2243
- * A SOURCE symbol whose block goes back further than one live window, or
2244
- * jumps further than the stream could have produced since its last symbol,
2245
- * is a source discontinuity, not loss. A repair symbol can only advance the
2269
+ * A SOURCE symbol is judged against the newest source block alone: repairs
2270
+ * ride their own group, which can run blocks ahead of the media. One whose
2271
+ * block goes back further than the blocks this manager retains, or that
2272
+ * cannot have been sent before the source it lies behind, or that jumps
2273
+ * further than the stream could have produced since its last symbol, is a
2274
+ * source discontinuity, not loss. A repair symbol can only advance the
2246
2275
  * frontier: a D-28 fetch legitimately answers for an old block, so it never
2247
2276
  * signals a discontinuity.
2248
2277
  *
2249
2278
  * The producer closes a block at its Dth media-unit boundary OR when K
2250
2279
  * source symbols filled it, so one interleave span can start several blocks
2251
- * (every large keyframe does). What bounds a forward jump is therefore
2252
- * packet evidence, not a block rate: SS_ID advances by one per FEC source
2253
- * packet (ISO/IEC 23008-1 C.5.2) and the MMTP packet_sequence_number by one
2254
- * per packet of the packet_id, so with both source symbols'
2255
- * packet_sequence_number a block start can move at most the packets sent
2256
- * between them plus the anchor's own offset into its block (< K). Without
2257
- * it, only the D-close rate is known.
2280
+ * (every large keyframe does). What bounds a jump is therefore packet
2281
+ * evidence, not a block rate: SS_ID advances by one per FEC source packet
2282
+ * (ISO/IEC 23008-1 C.5.2) and the MMTP packet_sequence_number by one per
2283
+ * packet of the packet_id, so with both source symbols'
2284
+ * packet_sequence_number their SS_IDs (`ssId`, not their block starts,
2285
+ * which a repair-less span can put far behind) can move at most the packets
2286
+ * sent between them, in either direction, plus K of slack for sources lost
2287
+ * before a hop that renumbers packets. Without it, only the D-close rate is
2288
+ * known.
2258
2289
  *
2259
2290
  * Vanished blocks are not enumerated here: their starts are unknown until a
2260
2291
  * repair states them. The SS_IDs between two stated blocks become one
2261
2292
  * repair-less span when the later block's repair arrives (placeIsoRepair).
2262
2293
  */
2263
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber) {
2294
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
2264
2295
  const streamKey = this.#streamKey(packetId, catalogTrackName);
2265
2296
  const now = performance.now();
2266
- const previous = this.#highestSbn.get(streamKey);
2297
+ const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
2267
2298
  const anchor = this.#sourceAnchors.get(streamKey);
2268
2299
  const psn = symbol === "source" && packetSequenceNumber !== void 0 && Number.isSafeInteger(packetSequenceNumber) && packetSequenceNumber >= 0 && packetSequenceNumber <= 4294967295 ? packetSequenceNumber : void 0;
2269
2300
  const anchorHere = () => {
2270
- if (psn !== void 0 && (anchor === void 0 || !this.#blockPrecedes(sbn, anchor.sbn))) {
2271
- this.#sourceAnchors.set(streamKey, { sbn, psn, atMs: now });
2301
+ if (psn !== void 0 && (anchor === void 0 || !serial32Precedes(ssId, anchor.ssId))) {
2302
+ this.#sourceAnchors.set(streamKey, { ssId, psn, atMs: now });
2303
+ }
2304
+ };
2305
+ const advance = () => {
2306
+ const highest = this.#highestSbn.get(streamKey);
2307
+ if (highest === void 0 || this.#blockPrecedes(highest.sbn, sbn)) {
2308
+ this.#highestSbn.set(streamKey, { sbn, atMs: now });
2272
2309
  }
2310
+ if (symbol === "source") this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
2311
+ anchorHere();
2273
2312
  };
2274
2313
  const discontinuity = () => {
2275
2314
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity();
2276
2315
  this.#highestSbn.set(streamKey, { sbn, atMs: now });
2316
+ this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
2277
2317
  if (psn === void 0) this.#sourceAnchors.delete(streamKey);
2278
- else this.#sourceAnchors.set(streamKey, { sbn, psn, atMs: now });
2318
+ else this.#sourceAnchors.set(streamKey, { ssId, psn, atMs: now });
2279
2319
  this.onSourceDiscontinuity?.(packetId, catalogTrackName);
2280
2320
  };
2281
2321
  if (previous === void 0) {
2282
- this.#highestSbn.set(streamKey, { sbn, atMs: now });
2283
- anchorHere();
2322
+ advance();
2284
2323
  return;
2285
2324
  }
2286
2325
  const config = this.#trackConfig(packetId);
2287
2326
  const window2 = this.#liveWindowBlocks(config);
2327
+ const sentInOrder = (from, to) => {
2328
+ const sent = to.psn - from.psn >>> 0;
2329
+ return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
2330
+ };
2288
2331
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
2289
- if (symbol === "source" && window2 !== null && this.#blocksBehind(sbn, previous.sbn, packetId) > window2) {
2332
+ if (symbol === "source" && window2 !== null && this.#blockPrecedes(sbn, previous.sbn) && (this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId) || psn !== void 0 && anchor !== void 0 && serial32Precedes(ssId, anchor.ssId) && psn !== anchor.psn && !sentInOrder({ ssId, psn }, anchor))) {
2290
2333
  discontinuity();
2291
2334
  return;
2292
2335
  }
@@ -2296,9 +2339,8 @@ var FECManager = class _FECManager {
2296
2339
  const missing = this.#blocksBehind(previous.sbn, sbn, packetId) - 1;
2297
2340
  let plausible = true;
2298
2341
  if (window2 !== null) {
2299
- if (psn !== void 0 && anchor !== void 0 && this.#blockPrecedes(anchor.sbn, sbn) && psn !== anchor.psn) {
2300
- const sent = psn - anchor.psn >>> 0;
2301
- plausible = sent <= 2147483647 && serial32Distance(anchor.sbn, sbn) <= sent + config.k;
2342
+ if (psn !== void 0 && anchor !== void 0 && serial32Precedes(anchor.ssId, ssId) && psn !== anchor.psn) {
2343
+ plausible = sentInOrder(anchor, { ssId, psn });
2302
2344
  } else {
2303
2345
  plausible = missing <= window2 + Math.ceil((now - previous.atMs) / config.interleaveDepthMs);
2304
2346
  }
@@ -2308,8 +2350,7 @@ var FECManager = class _FECManager {
2308
2350
  discontinuity();
2309
2351
  return;
2310
2352
  }
2311
- this.#highestSbn.set(streamKey, { sbn, atMs: now });
2312
- anchorHere();
2353
+ advance();
2313
2354
  }
2314
2355
  /*
2315
2356
  * Block order for one stream (BLO-35597 iso:5). A block is keyed by its
@@ -2893,6 +2934,7 @@ var FECManager = class _FECManager {
2893
2934
  resetSet(this.#materializedBlocks);
2894
2935
  resetMap(this.#resolvedBlockClasses);
2895
2936
  resetMap(this.#highestSbn);
2937
+ resetMap(this.#sourceFrontiers);
2896
2938
  resetMap(this.#isoLocators);
2897
2939
  resetMap(this.#sourceAnchors);
2898
2940
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName));
@@ -2998,6 +3040,7 @@ var FECManager = class _FECManager {
2998
3040
  dropMap(this.#orderedPendingBlocks);
2999
3041
  dropMap(this.#resolvedBlockClasses);
3000
3042
  dropMap(this.#highestSbn);
3043
+ dropMap(this.#sourceFrontiers);
3001
3044
  dropMap(this.#isoLocators);
3002
3045
  dropMap(this.#sourceAnchors);
3003
3046
  dropMap(this.#classifiers);
@@ -3090,7 +3133,13 @@ var FECManager = class _FECManager {
3090
3133
  if (isSourceSymbol && esi === 0) {
3091
3134
  this.#startupPartialBlocks.delete(blockKey);
3092
3135
  this.#startupAlignedPackets.add(streamKey);
3093
- } else if (isStartupPartial && !isReadyMulticastRepair || !this.#startupAlignedPackets.has(streamKey) && !isReadyMulticastRepair) {
3136
+ } else if (
3137
+ // A ready multicast repair opens a block the join has not seen yet, never
3138
+ // a join partial: its sources were refused, so its repairs alone open a
3139
+ // block that cannot decode and fails at its deadline, once per packet ID
3140
+ // per join (BLO-48308).
3141
+ isStartupPartial || !this.#startupAlignedPackets.has(streamKey) && !isReadyMulticastRepair
3142
+ ) {
3094
3143
  this.#markStartupPartial(blockKey);
3095
3144
  return false;
3096
3145
  }
@@ -3415,6 +3464,10 @@ var FECManager = class _FECManager {
3415
3464
  }
3416
3465
  return blocks;
3417
3466
  }
3467
+ /** The iso-ssbg1-v1 locator horizon of a configured packetId, in blocks (#isoRetentionBlocks). */
3468
+ isoRetentionBlocksForPacket(packetId) {
3469
+ return this.#hasBlockProfile(packetId) ? this.#isoRetentionBlocks(packetId) : void 0;
3470
+ }
3418
3471
  /** Whether an iso-ssbg1-v1 protected packet fits one ssbg_mode1 symbol (len + 2 <= T). */
3419
3472
  isoSourceFits(packetId, packetLength) {
3420
3473
  const symbolSize = this.#trackConfigs.get(packetId)?.symbolSize;
@@ -3996,20 +4049,37 @@ var FECManager = class _FECManager {
3996
4049
  * Caller is responsible for routing recovered data and updating
3997
4050
  * block completion state via `markBlockCompleted()`.
3998
4051
  */
3999
- feedRepairSymbol(packetId, ssStart, ssbLength, rsId, repairData, catalogTrackName) {
4000
- this.#fecStats.repairPackets++;
4001
- this.#statsForPacket(packetId).repairPackets++;
4002
- if (!this.#hasBlockProfile(packetId)) return null;
4052
+ /**
4053
+ * Whether a repair symbol of `byteLength` bytes is a valid member of a
4054
+ * `packetId` block: every repair symbol is exactly the track's T. A symbol of
4055
+ * any other size is counted on `repairSymbolSizeMismatches`, warned (rate
4056
+ * limited) and refused. The router calls this before the symbol takes any
4057
+ * other part in block state (placement, first-arrival dedup, completed-block
4058
+ * accounting), so a malformed repair is counted whatever its arrival order:
4059
+ * judged after dedup, one landing on an already-complete block, or behind a
4060
+ * valid copy from the other transport, was swallowed as a duplicate and never
4061
+ * counted (BLO-48306). A packetId with no configured block profile admits
4062
+ * nothing here; its repair is dropped upstream as unreadable.
4063
+ */
4064
+ admitRepairSymbolSize(packetId, ssStart, ssbLength, rsId, byteLength) {
4065
+ if (!this.#hasBlockProfile(packetId)) return false;
4003
4066
  const symbolSize = this.#trackConfig(packetId).symbolSize;
4004
- if (symbolSize > 0 && repairData.byteLength !== symbolSize) {
4067
+ if (symbolSize > 0 && byteLength !== symbolSize) {
4005
4068
  this.#repairSymbolSizeMismatchCount++;
4006
4069
  if (this.#repairSymbolSizeMismatchCount <= 5 || this.#repairSymbolSizeMismatchCount % 100 === 0) {
4007
4070
  console.warn(
4008
- `[FECManager] Dropping repair symbol with invalid size: got ${repairData.byteLength}B, expected ${symbolSize}B (packetId=${packetId}, ssStart=${ssStart}, ssbLength=${ssbLength}, rsId=${rsId})`
4071
+ `[FECManager] Dropping repair symbol with invalid size: got ${byteLength}B, expected ${symbolSize}B (packetId=${packetId}, ssStart=${ssStart}, ssbLength=${ssbLength}, rsId=${rsId})`
4009
4072
  );
4010
4073
  }
4011
- return null;
4074
+ return false;
4012
4075
  }
4076
+ return true;
4077
+ }
4078
+ feedRepairSymbol(packetId, ssStart, ssbLength, rsId, repairData, catalogTrackName) {
4079
+ this.#fecStats.repairPackets++;
4080
+ this.#statsForPacket(packetId).repairPackets++;
4081
+ if (!this.#hasBlockProfile(packetId)) return null;
4082
+ if (!this.admitRepairSymbolSize(packetId, ssStart, ssbLength, rsId, repairData.byteLength)) return null;
4013
4083
  const fecData = repairData;
4014
4084
  const k = this.#trackConfig(packetId).k;
4015
4085
  const block = this.#isoLocatorFor(packetId, catalogTrackName).blockAt(ssStart);
@@ -4162,7 +4232,14 @@ var FECManager = class _FECManager {
4162
4232
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
4163
4233
  const k = trackConfig.k;
4164
4234
  if (this.#completedBlocks.has(key)) return;
4165
- this.#noteSbnSeen(sbn, packetId, catalogTrackName, "source", evidence.packetSequenceNumber);
4235
+ this.#noteSbnSeen(
4236
+ sbn,
4237
+ packetId,
4238
+ catalogTrackName,
4239
+ "source",
4240
+ evidence.packetSequenceNumber,
4241
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
4242
+ );
4166
4243
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
4167
4244
  if (Number.isInteger(esi) && esi >= authoredLength) {
4168
4245
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -4413,6 +4490,7 @@ var FECManager = class _FECManager {
4413
4490
  this.#repairedBlocks.clear();
4414
4491
  this.#materializedBlocks.clear();
4415
4492
  this.#highestSbn.clear();
4493
+ this.#sourceFrontiers.clear();
4416
4494
  this.#isoLocators.clear();
4417
4495
  this.#sourceAnchors.clear();
4418
4496
  this.#trackConfigs.clear();
@@ -9312,8 +9390,14 @@ var SampleCombiner = class {
9312
9390
  /**
9313
9391
  * Add one reassembled data unit. Returns the combined sample once every
9314
9392
  * constituent data unit has arrived and totals the authored size.
9393
+ *
9394
+ * `sampleSize` is the authored size the host resolves for the sample as the
9395
+ * data unit completes. It stands in only when no size was registered, which
9396
+ * happens when the data unit's FI=0/FI=1 reached the reassembler without the
9397
+ * host's own FT=2 parse: an FEC-recovered first fragment completed by source
9398
+ * fragments, or one decoded before its source copy arrived.
9315
9399
  */
9316
- addMfu(mfu) {
9400
+ addMfu(mfu, sampleSize) {
9317
9401
  if (mfu.movieFragmentSequenceNumber === void 0 || mfu.sampleNumber === void 0) {
9318
9402
  this.#stats.passthroughSamples++;
9319
9403
  return fromPassthrough(mfu);
@@ -9329,7 +9413,7 @@ var SampleCombiner = class {
9329
9413
  return null;
9330
9414
  }
9331
9415
  const dataLen = mfu.data.byteLength;
9332
- const authoredSize = this.#authoredSizes.get(key);
9416
+ const authoredSize = this.#authoredSizes.get(key) ?? sampleSize;
9333
9417
  if (offset === 0 && !this.#pending.has(key)) {
9334
9418
  const passesThrough = authoredSize === void 0 ? !this.#requireAuthoredSize : dataLen === authoredSize;
9335
9419
  if (passesThrough) {
@@ -9623,6 +9707,12 @@ if (void 0) {
9623
9707
  const out = c.addMfu(mfu(1, 9, 17, 5, [6, 7, 8, 9, 10], 1001n, false));
9624
9708
  expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
9625
9709
  });
9710
+ test("a size handed with the data unit completes a sample no head registered", () => {
9711
+ const c = combiner({ requireAuthoredSize: true });
9712
+ const out = c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5);
9713
+ expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5]));
9714
+ expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5)).toBeNull();
9715
+ });
9626
9716
  test("duplicate offset is rejected", () => {
9627
9717
  const c = combiner();
9628
9718
  c.registerAuthoredSize(void 0, 1, 9, 17, 10);
@@ -10867,6 +10957,7 @@ function isFmp4Box(data) {
10867
10957
  const type = String.fromCharCode(data[4], data[5], data[6], data[7]);
10868
10958
  return FMPU_BOX_TYPES.has(type);
10869
10959
  }
10960
+ var MAX_AWAITING_TIMING_HEADS = 8;
10870
10961
  var MmtpContainerParser = class _MmtpContainerParser {
10871
10962
  constructor(config) {
10872
10963
  this.#tracks = /* @__PURE__ */ new Map();
@@ -10925,6 +11016,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
10925
11016
  * reordering into the parser. */
10926
11017
  this.#reliableMoqStartupGate = /* @__PURE__ */ new Map();
10927
11018
  this.#disposed = false;
11019
+ this.#replayingAwaitingTiming = false;
10928
11020
  this.#fedObjects = 0;
10929
11021
  this.#reassemblerFragmentsFed = 0;
10930
11022
  this.#reassemblerDataUnitsReturned = 0;
@@ -11017,6 +11109,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
11017
11109
  #reorderStats;
11018
11110
  #reliableMoqStartupGate;
11019
11111
  #disposed;
11112
+ #replayingAwaitingTiming;
11020
11113
  #fedObjects;
11021
11114
  #reassemblerFragmentsFed;
11022
11115
  #reassemblerDataUnitsReturned;
@@ -11266,7 +11359,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
11266
11359
  * a single failure bucket. Returns null so call sites stay `return this.#drop(...)`.
11267
11360
  */
11268
11361
  #drop(reason) {
11269
- this.#countOutcome(`drop:${reason}`);
11362
+ if (this.#replayingAwaitingTiming) this.#countDeferredOutcome(reason);
11363
+ else this.#countOutcome(`drop:${reason}`);
11270
11364
  return null;
11271
11365
  }
11272
11366
  get reorderDiagnostics() {
@@ -11289,6 +11383,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
11289
11383
  for (const combiner of this.#sampleCombiners.values()) {
11290
11384
  combiner.cleanupTimeouts(timeoutMs);
11291
11385
  }
11386
+ const now = Date.now();
11387
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
11388
+ while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
11389
+ awaitingTiming.shift();
11390
+ }
11391
+ }
11292
11392
  }
11293
11393
  /**
11294
11394
  * Phase 1 of two-phase parsing. Returns structured header info for FEC feeding.
@@ -11369,7 +11469,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
11369
11469
  byteLength: packet.byteLength
11370
11470
  };
11371
11471
  }
11372
- if (info.fecPayloadId !== null && this.#sourceSymbolCb) {
11472
+ if (info.fecPayloadId !== null && this.#sourceSymbolCb && !this.#replayingAwaitingTiming) {
11373
11473
  const rawSymbol = packet.subarray(0, packet.length - 4);
11374
11474
  try {
11375
11475
  this.#sourceSymbolCb(info.packetId, info.fecPayloadId.ssId, rawSymbol);
@@ -11417,6 +11517,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
11417
11517
  }
11418
11518
  return this.#drop("fragment-timing-refused");
11419
11519
  }
11520
+ this.#replayAwaitingTiming(streamKey, resolver2);
11420
11521
  return {
11421
11522
  kind: "fragment",
11422
11523
  packet: info,
@@ -11440,7 +11541,18 @@ var MmtpContainerParser = class _MmtpContainerParser {
11440
11541
  mfuDuHeader.movieFragmentSequenceNumber,
11441
11542
  mfuDuHeader.sampleNumber
11442
11543
  );
11443
- if (!headTiming) return this.#drop("mfu-sample-timing-missing");
11544
+ if (!headTiming) {
11545
+ this.#awaitTiming(streamKey, {
11546
+ packet,
11547
+ options,
11548
+ parsed,
11549
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
11550
+ movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
11551
+ sampleNumber: mfuDuHeader.sampleNumber,
11552
+ arrivedAt: Date.now()
11553
+ });
11554
+ return this.#drop("mfu-sample-timing-missing");
11555
+ }
11444
11556
  const offset = mfuDuHeader.offset;
11445
11557
  if (!Number.isSafeInteger(offset) || offset < 0 || offset >= headTiming.size)
11446
11558
  return this.#drop("mfu-offset-out-of-range");
@@ -11516,16 +11628,17 @@ var MmtpContainerParser = class _MmtpContainerParser {
11516
11628
  const sampleNumber = assembled.sampleNumber;
11517
11629
  if (movieFragmentSequenceNumber === void 0 || sampleNumber === void 0)
11518
11630
  return this.#drop("assembled-identity-missing");
11519
- if (!resolver.sampleTiming(
11631
+ const assembledTiming = resolver.sampleTiming(
11520
11632
  assembled.mpuSequenceNumber,
11521
11633
  movieFragmentSequenceNumber,
11522
11634
  sampleNumber
11523
- )) return this.#drop("assembled-timing-missing");
11635
+ );
11636
+ if (!assembledTiming) return this.#drop("assembled-timing-missing");
11524
11637
  if (assembled.mpuSequenceNumber !== mpu.mpuSequenceNumber)
11525
11638
  return this.#drop("assembled-mpu-mismatch");
11526
11639
  let combined;
11527
11640
  try {
11528
- combined = this.#sampleCombinerFor(streamKey).addMfu(assembled);
11641
+ combined = this.#sampleCombinerFor(streamKey).addMfu(assembled, assembledTiming.size);
11529
11642
  } catch (error) {
11530
11643
  if (!(error instanceof SampleCombineError)) throw error;
11531
11644
  console.warn(
@@ -11834,9 +11947,37 @@ var MmtpContainerParser = class _MmtpContainerParser {
11834
11947
  if (existing) return existing.resolver;
11835
11948
  if (!create) return null;
11836
11949
  const resolver = new IsoBmffTimingResolver(this.#maxPendingTimingSamples);
11837
- this.#timingStreams.set(streamKey, { packetId, resolver });
11950
+ this.#timingStreams.set(streamKey, { packetId, resolver, awaitingTiming: [] });
11838
11951
  return resolver;
11839
11952
  }
11953
+ #awaitTiming(streamKey, head) {
11954
+ const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
11955
+ if (!awaitingTiming) return;
11956
+ awaitingTiming.push(head);
11957
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
11958
+ }
11959
+ /**
11960
+ * Feed again the heads whose timing the FT=1 just admitted declares. That
11961
+ * FT=1 can be an FEC recovery landing after its sample's FI=1, and neither
11962
+ * FEC path routes a source symbol that already arrived a second time.
11963
+ */
11964
+ #replayAwaitingTiming(streamKey, resolver) {
11965
+ const state = this.#timingStreams.get(streamKey);
11966
+ if (!state || state.awaitingTiming.length === 0) return;
11967
+ const ready = state.awaitingTiming.filter((head) => resolver.sampleTiming(
11968
+ head.mpuSequenceNumber,
11969
+ head.movieFragmentSequenceNumber,
11970
+ head.sampleNumber
11971
+ ));
11972
+ if (ready.length === 0) return;
11973
+ state.awaitingTiming = state.awaitingTiming.filter((head) => !ready.includes(head));
11974
+ this.#replayingAwaitingTiming = true;
11975
+ try {
11976
+ for (const head of ready) this.#feed(head.packet, head.options, head.parsed);
11977
+ } finally {
11978
+ this.#replayingAwaitingTiming = false;
11979
+ }
11980
+ }
11840
11981
  #dropTimingStream(streamKey) {
11841
11982
  const state = this.#timingStreams.get(streamKey);
11842
11983
  if (!state) return;
@@ -12440,6 +12581,12 @@ var MmtpRouter = class {
12440
12581
  // MSE recovery routes through CmafBlockAssembler and can reorder by block; the
12441
12582
  // direct callback path has to preserve decode order before frames leave libmmt.
12442
12583
  #latestVideoSeqByStream = /* @__PURE__ */ new Map();
12584
+ /**
12585
+ * Per stream, SS_ID - packet_sequence_number (mod 2^32) of its latest
12586
+ * first-arrival FEC source packet. A recovered source symbol's wire
12587
+ * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
12588
+ */
12589
+ #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
12443
12590
  #lastDirectSourceVideoTsByStream = /* @__PURE__ */ new Map();
12444
12591
  #lastDirectEmittedVideoTsByStream = /* @__PURE__ */ new Map();
12445
12592
  #pendingDirectRecoveredVideoByStream = /* @__PURE__ */ new Map();
@@ -12514,6 +12661,7 @@ var MmtpRouter = class {
12514
12661
  */
12515
12662
  #onPublisherRestart;
12516
12663
  #publisherRestarts = 0;
12664
+ #restampedRecoveredSeqs = 0;
12517
12665
  /** Inits delivered with no onTrackInit handler for their packetId (MOQT-01). */
12518
12666
  #unmappedInitDeliveries = 0;
12519
12667
  // FEC Payload IDs left unread because their (owner) packetId had no
@@ -12734,6 +12882,14 @@ var MmtpRouter = class {
12734
12882
  get publisherRestartCount() {
12735
12883
  return this.#publisherRestarts;
12736
12884
  }
12885
+ /**
12886
+ * FEC-recovered source symbols whose reconstructed header named a
12887
+ * packet_sequence_number other than the wire sequence their SS_ID maps to:
12888
+ * a hop re-stamped the sequence after the sender protected the packet.
12889
+ */
12890
+ get restampedRecoveredSequenceCount() {
12891
+ return this.#restampedRecoveredSeqs;
12892
+ }
12737
12893
  /**
12738
12894
  * Packets whose Source or Repair FEC Payload ID was left unread because
12739
12895
  * their (owner) packetId had no configured `fec.blockProfile`: FEC not
@@ -13249,6 +13405,13 @@ var MmtpRouter = class {
13249
13405
  `[MmtpRouter] packetId=${ownerPacketId} is iso-ssbg1-v1 but its FEC manager cannot place ISO blocks`
13250
13406
  );
13251
13407
  }
13408
+ if (fec.admitRepairSymbolSize && !fec.admitRepairSymbolSize(
13409
+ ownerPacketId,
13410
+ repair.ssStart,
13411
+ repair.ssbLength,
13412
+ repair.rsId,
13413
+ repair.symbolData.byteLength
13414
+ )) return;
13252
13415
  const placement = fec.placeIsoRepair(ownerPacketId, catalogTrackName, repair.ssStart, repair.ssbLength);
13253
13416
  if (placement.status !== "placed") return;
13254
13417
  const blockStart = placement.block.start;
@@ -13378,6 +13541,7 @@ var MmtpRouter = class {
13378
13541
  this.#trackSynced.delete(streamKey);
13379
13542
  this.#droppedPreSyncVideo.delete(streamKey);
13380
13543
  this.#latestVideoSeqByStream.delete(streamKey);
13544
+ this.#ssIdSeqOffsetByStream.delete(streamKey);
13381
13545
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
13382
13546
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
13383
13547
  this.#pendingDirectRecoveredVideoByStream.delete(streamKey);
@@ -14148,6 +14312,12 @@ var MmtpRouter = class {
14148
14312
  } else if (fecUnreadable && info.fecPayloadId) {
14149
14313
  parseSourceSymbol = !duplicates.parsedSymbols.has(info.fecPayloadId.ssId);
14150
14314
  }
14315
+ if (fecPayloadId && !overlapCopy) {
14316
+ this.#ssIdSeqOffsetByStream.set(
14317
+ this.#mediaStreamKey(info.packetId, catalogTrackName),
14318
+ fecPayloadId.ssId - info.sequenceNumber >>> 0
14319
+ );
14320
+ }
14151
14321
  if (!this.#fecManager || !info.fecPayloadId || parseSourceSymbol) {
14152
14322
  if (this.#fecManager && info.fecPayloadId) {
14153
14323
  duplicates.parsedSymbols.add(info.fecPayloadId.ssId);
@@ -14724,6 +14894,20 @@ var MmtpRouter = class {
14724
14894
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName) {
14725
14895
  if (ownerPacketId == null) return;
14726
14896
  if (this.#classifyPacketId(ownerPacketId) === null) return;
14897
+ const ssIdSeqOffset = this.#ssIdSeqOffsetByStream.get(
14898
+ this.#mediaStreamKey(ownerPacketId, catalogTrackName)
14899
+ );
14900
+ if (ssIdSeqOffset !== void 0) {
14901
+ result = {
14902
+ ...result,
14903
+ symbols: result.symbols.map((sym) => {
14904
+ const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
14905
+ if (wire === sym.packetSequenceNumber) return sym;
14906
+ this.#restampedRecoveredSeqs++;
14907
+ return { ...sym, packetSequenceNumber: wire };
14908
+ })
14909
+ };
14910
+ }
14727
14911
  this.#stream(ownerPacketId, catalogTrackName).duplicates.advance(blockId);
14728
14912
  const deliveryProvenance = this.#fecManager?.blockDeliveryProvenance?.(
14729
14913
  blockId,
@@ -15217,178 +15401,6 @@ var MoqFecAlgorithm;
15217
15401
  MoqFecAlgorithm2[MoqFecAlgorithm2["RaptorQ"] = 2] = "RaptorQ";
15218
15402
  })(MoqFecAlgorithm || (MoqFecAlgorithm = {}));
15219
15403
 
15220
- // node_modules/@blockcast/mmt-base/dist/mmtp.js
15221
- var MPU_HEADER_SIZE2 = 8;
15222
- var MPU_LENGTH_FIELD_SIZE2 = 2;
15223
- var MPU_HEADER_REMAINDER_SIZE2 = MPU_HEADER_SIZE2 - MPU_LENGTH_FIELD_SIZE2;
15224
- var MMTP_SIGNALING_PACKET_ID2 = 0;
15225
- var MMTP_PACKET_ID_MAX2 = 65535;
15226
-
15227
- // node_modules/@blockcast/mmt-base/dist/net-constants.js
15228
- var DEFAULT_AMT_RELAY_PORT2 = 2268;
15229
-
15230
- // node_modules/@blockcast/mmt-base/dist/ntp-short.js
15231
- var NTP_SHORT_BITS2 = 32;
15232
- var NTP_SHORT_MODULUS2 = 2 ** NTP_SHORT_BITS2;
15233
- var NTP_SHORT_HALF_RANGE2 = 2 ** (NTP_SHORT_BITS2 - 1);
15234
- function isNtpShort(value) {
15235
- return Number.isInteger(value) && value >= 0 && value < NTP_SHORT_MODULUS2;
15236
- }
15237
- function compareNtpShort(a, b) {
15238
- if (!isNtpShort(a) || !isNtpShort(b)) {
15239
- throw new RangeError(`NTP-short values must be integers in [0, 2^${NTP_SHORT_BITS2}), got ${String(a)} and ${String(b)}`);
15240
- }
15241
- if (a === b)
15242
- return "equal";
15243
- const forward = (a - b + NTP_SHORT_MODULUS2) % NTP_SHORT_MODULUS2;
15244
- if (forward < NTP_SHORT_HALF_RANGE2)
15245
- return "after";
15246
- if (forward > NTP_SHORT_HALF_RANGE2)
15247
- return "before";
15248
- return "unordered";
15249
- }
15250
-
15251
- // node_modules/@blockcast/mmt-base/dist/fec-block-profile.js
15252
- var FEC_BLOCK_PROFILES2 = Object.freeze([
15253
- "iso-ssbg1-v1"
15254
- ]);
15255
-
15256
- // node_modules/@blockcast/mmt-transport/dist/driad-discovery.js
15257
- var DRIADDiscovery = class {
15258
- cache = /* @__PURE__ */ new Map();
15259
- cacheExpiry = 3e5;
15260
- // 5 minutes
15261
- /**
15262
- * Discover AMT relays for a multicast source address (RFC 8777)
15263
- *
15264
- * @param source - The multicast source IP address (NOT the group!)
15265
- * @returns Array of discovered AMT relays that can tunnel traffic from this source
15266
- */
15267
- async discoverRelays(source) {
15268
- const cached = this.cache.get(source);
15269
- if (cached) {
15270
- return cached;
15271
- }
15272
- try {
15273
- const reversedSource = source.split(".").reverse().join(".");
15274
- const queryDomain = `${reversedSource}.amt.in-addr.arpa`;
15275
- console.log(`[DRIAD] Discovering relays for source ${source} via ${queryDomain}`);
15276
- const relays = await this.queryDRIADProxy(source);
15277
- if (relays.length > 0) {
15278
- this.cache.set(source, relays);
15279
- setTimeout(() => this.cache.delete(source), this.cacheExpiry);
15280
- }
15281
- return relays;
15282
- } catch (error) {
15283
- console.warn(`[DRIAD] Discovery failed for source ${source}:`, error);
15284
- return [];
15285
- }
15286
- }
15287
- /**
15288
- * Query DRIAD proxy service (browser-compatible)
15289
- */
15290
- async queryDRIADProxy(source) {
15291
- const proxyEndpoints = [
15292
- "https://driad.amt.net/api/v1/relays",
15293
- "https://multicast-gateway.cloudflare.com/driad"
15294
- ];
15295
- for (const endpoint of proxyEndpoints) {
15296
- try {
15297
- const response = await fetch(`${endpoint}?source=${encodeURIComponent(source)}`, {
15298
- method: "GET",
15299
- headers: { Accept: "application/json" },
15300
- signal: AbortSignal.timeout(5e3)
15301
- });
15302
- if (response.ok) {
15303
- const data = await response.json();
15304
- return data.relays || [];
15305
- }
15306
- } catch {
15307
- }
15308
- }
15309
- const dohRelay = await this.queryDNSOverHTTPS(source);
15310
- if (dohRelay) {
15311
- return [dohRelay];
15312
- }
15313
- return [];
15314
- }
15315
- /**
15316
- * Query DNS-over-HTTPS for DRIAD relay based on source address (RFC 8777)
15317
- */
15318
- async queryDNSOverHTTPS(source) {
15319
- try {
15320
- const reversedSource = source.split(".").reverse().join(".");
15321
- const queryName = `${reversedSource}.amt.in-addr.arpa`;
15322
- const dohUrl = `https://cloudflare-dns.com/dns-query?name=${queryName}&type=A`;
15323
- const response = await fetch(dohUrl, {
15324
- headers: { Accept: "application/dns-json" },
15325
- signal: AbortSignal.timeout(3e3)
15326
- });
15327
- if (!response.ok) {
15328
- return null;
15329
- }
15330
- const result = await response.json();
15331
- if (result.Answer && result.Answer.length > 0) {
15332
- return {
15333
- host: result.Answer[0].data,
15334
- port: DEFAULT_AMT_RELAY_PORT2,
15335
- priority: 10,
15336
- weight: 100,
15337
- asn: 0
15338
- };
15339
- }
15340
- return null;
15341
- } catch (error) {
15342
- console.warn("[DRIAD] DNS-over-HTTPS query failed:", error);
15343
- return null;
15344
- }
15345
- }
15346
- /**
15347
- * Select best relay based on RTT measurements
15348
- */
15349
- async selectBestRelay(relays) {
15350
- if (relays.length === 0)
15351
- return null;
15352
- const measured = await Promise.all(relays.map(async (relay) => {
15353
- const rtt = await this.measureRTT(relay.host, relay.port);
15354
- return { ...relay, rtt };
15355
- }));
15356
- measured.sort((a, b) => {
15357
- if (a.priority !== b.priority)
15358
- return a.priority - b.priority;
15359
- return (a.rtt || Infinity) - (b.rtt || Infinity);
15360
- });
15361
- console.log(`[DRIAD] Selected relay: ${measured[0].host} (RTT: ${measured[0].rtt}ms)`);
15362
- return measured[0];
15363
- }
15364
- async measureRTT(host, _port) {
15365
- const start = performance.now();
15366
- try {
15367
- await fetch(`https://${host}/health`, {
15368
- method: "HEAD",
15369
- signal: AbortSignal.timeout(2e3),
15370
- mode: "no-cors"
15371
- });
15372
- return performance.now() - start;
15373
- } catch {
15374
- return Infinity;
15375
- }
15376
- }
15377
- /**
15378
- * Clear the relay cache
15379
- */
15380
- clearCache() {
15381
- this.cache.clear();
15382
- }
15383
- /**
15384
- * Get cached relays for a source address
15385
- */
15386
- getCached(source) {
15387
- return this.cache.get(source);
15388
- }
15389
- };
15390
- var driadDiscovery = new DRIADDiscovery();
15391
-
15392
15404
  // node_modules/@blockcast/mmt-transport/dist/multicast-tier.js
15393
15405
  function endpointKey(endpoint) {
15394
15406
  return `${endpoint.sourceAddress ?? ""}|${endpoint.groupAddress}|${endpoint.port}`;
@@ -15596,6 +15608,45 @@ var AdaptiveBitrateController = class {
15596
15608
  }
15597
15609
  };
15598
15610
 
15611
+ // node_modules/@blockcast/mmt-base/dist/mmtp.js
15612
+ var MPU_HEADER_SIZE2 = 8;
15613
+ var MPU_LENGTH_FIELD_SIZE2 = 2;
15614
+ var MPU_HEADER_REMAINDER_SIZE2 = MPU_HEADER_SIZE2 - MPU_LENGTH_FIELD_SIZE2;
15615
+ var MMTP_SIGNALING_PACKET_ID2 = 0;
15616
+ var MMTP_PACKET_ID_MAX2 = 65535;
15617
+
15618
+ // node_modules/@blockcast/mmt-base/dist/net-constants.js
15619
+ var DEFAULT_AMT_RELAY_PORT2 = 2268;
15620
+
15621
+ // node_modules/@blockcast/mmt-base/dist/ntp-short.js
15622
+ var NTP_SHORT_BITS2 = 32;
15623
+ var NTP_SHORT_MODULUS2 = 2 ** NTP_SHORT_BITS2;
15624
+ var NTP_SHORT_HALF_RANGE2 = 2 ** (NTP_SHORT_BITS2 - 1);
15625
+ function isNtpShort(value) {
15626
+ return Number.isInteger(value) && value >= 0 && value < NTP_SHORT_MODULUS2;
15627
+ }
15628
+ function compareNtpShort(a, b) {
15629
+ if (!isNtpShort(a) || !isNtpShort(b)) {
15630
+ throw new RangeError(`NTP-short values must be integers in [0, 2^${NTP_SHORT_BITS2}), got ${String(a)} and ${String(b)}`);
15631
+ }
15632
+ if (a === b)
15633
+ return "equal";
15634
+ const forward = (a - b + NTP_SHORT_MODULUS2) % NTP_SHORT_MODULUS2;
15635
+ if (forward < NTP_SHORT_HALF_RANGE2)
15636
+ return "after";
15637
+ if (forward > NTP_SHORT_HALF_RANGE2)
15638
+ return "before";
15639
+ return "unordered";
15640
+ }
15641
+
15642
+ // node_modules/@blockcast/mmt-base/dist/fec-block-profile.js
15643
+ var FEC_BLOCK_PROFILES2 = Object.freeze([
15644
+ "iso-ssbg1-v1"
15645
+ ]);
15646
+
15647
+ // node_modules/@blockcast/mmt-base/dist/catalog-fec-source.js
15648
+ var ALL_ROLES2 = Object.freeze(["video", "audio"]);
15649
+
15599
15650
  // node_modules/@blockcast/mmt-transport/dist/multicast-orchestrator.js
15600
15651
  var DEFAULT_DWELL_MS = 3e3;
15601
15652
  var DEFAULT_JOIN_DEADLINE_MS = 5e3;
@@ -15834,7 +15885,8 @@ function toWindowMulticastSubscribeConfig(input) {
15834
15885
  ...input.packetIds?.length ? { packetIds: [...input.packetIds] } : {}
15835
15886
  };
15836
15887
  const relay = input.amtRelay?.trim();
15837
- const wantsAmt = input.mode === "tunnel" || input.mode !== "native" && relay !== void 0 && relay !== "";
15888
+ const driad = !relay && input.amtDiscovery === "driad";
15889
+ const wantsAmt = input.mode === "tunnel" || input.mode !== "native" && (relay !== void 0 && relay !== "" || driad);
15838
15890
  if (!wantsAmt) {
15839
15891
  const native = {
15840
15892
  ...base,
@@ -15844,6 +15896,20 @@ function toWindowMulticastSubscribeConfig(input) {
15844
15896
  return native;
15845
15897
  }
15846
15898
  const relayPort = input.amtRelayPort;
15899
+ if (driad) {
15900
+ if (!base.source)
15901
+ throw new TypeError("AMT DRIAD discovery requires a source address");
15902
+ if (relayPort !== void 0 && !isPositivePort(relayPort)) {
15903
+ throw new TypeError("AMT DRIAD discovery requires a valid relay port when one is given");
15904
+ }
15905
+ return {
15906
+ ...base,
15907
+ source: base.source,
15908
+ origin: "amt",
15909
+ discovery: "driad",
15910
+ ...relayPort !== void 0 ? { relayPort } : {}
15911
+ };
15912
+ }
15847
15913
  if (!relay || relayPort === void 0 || !isPositivePort(relayPort)) {
15848
15914
  throw new TypeError("AMT requires a resolved relay and a valid relay port");
15849
15915
  }
@@ -15887,7 +15953,8 @@ function normalizeMulticastEndpoint(endpoint) {
15887
15953
  port: endpoint.port,
15888
15954
  ...endpoint.mode ? { mode: endpoint.mode } : {},
15889
15955
  ...amtRelay ? { amtRelay } : {},
15890
- ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
15956
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {},
15957
+ ...endpoint.amtDiscovery === "driad" ? { amtDiscovery: "driad" } : {}
15891
15958
  };
15892
15959
  }
15893
15960
  function multicastEndpointKey(endpoint) {
@@ -15900,7 +15967,9 @@ function multicastEndpointKey(endpoint) {
15900
15967
  normalized.port,
15901
15968
  normalized.mode ?? "auto",
15902
15969
  normalized.amtRelay ?? "",
15903
- normalized.amtRelayPort ?? ""
15970
+ normalized.amtRelayPort ?? "",
15971
+ // A DRIAD join is a different gateway subscription from a native one.
15972
+ ...normalized.amtDiscovery ? [normalized.amtDiscovery] : []
15904
15973
  ]);
15905
15974
  }
15906
15975
  function isMulticastTrackPacketId(value) {
@@ -15940,7 +16009,8 @@ var MulticastSubscriptionPool = class {
15940
16009
  port: config.port,
15941
16010
  mode: config.mode,
15942
16011
  amtRelay: config.amtRelay,
15943
- amtRelayPort: config.amtRelayPort
16012
+ amtRelayPort: config.amtRelayPort,
16013
+ amtDiscovery: config.amtDiscovery
15944
16014
  });
15945
16015
  if (!endpoint)
15946
16016
  throw new Error("Invalid multicast endpoint");
@@ -16006,7 +16076,8 @@ var MulticastSubscriptionPool = class {
16006
16076
  port: endpoint.port,
16007
16077
  ...endpoint.mode ? { mode: endpoint.mode } : {},
16008
16078
  ...endpoint.amtRelay ? { amtRelay: endpoint.amtRelay } : {},
16009
- ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
16079
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {},
16080
+ ...endpoint.amtDiscovery ? { amtDiscovery: endpoint.amtDiscovery } : {}
16010
16081
  }));
16011
16082
  const consumers = /* @__PURE__ */ new Map();
16012
16083
  let entry;
@@ -16086,7 +16157,6 @@ var TransportManager = class {
16086
16157
  };
16087
16158
  capabilities = null;
16088
16159
  subscription = null;
16089
- driad = new DRIADDiscovery();
16090
16160
  /** Built by `connect()` from the caller's ladder; there is no built-in one. */
16091
16161
  abr = null;
16092
16162
  multicastOrchestrator = null;
@@ -16136,8 +16206,8 @@ var TransportManager = class {
16136
16206
  nativeIGMP: hasGatewayBytes,
16137
16207
  directSockets: typeof win?.UDPSocket !== "undefined",
16138
16208
  amt: false,
16139
- driad: true,
16140
- // DRIAD uses HTTP proxy, always available
16209
+ driad: hasGatewayBytes,
16210
+ // the gateway runs RFC 8777 discovery
16141
16211
  fecDecode: false
16142
16212
  };
16143
16213
  console.log("[Transport] Capabilities:", this.capabilities);
@@ -16148,7 +16218,7 @@ var TransportManager = class {
16148
16218
  *
16149
16219
  * Promotion hierarchy:
16150
16220
  * 1. window.multicast gateway bytes
16151
- * 2. AMT proxy (specified or discovered via DRIAD)
16221
+ * 2. AMT: a configured relay via the AMT proxy, else gateway DRIAD discovery
16152
16222
  * 3. MOQ WebTransport (final fallback)
16153
16223
  *
16154
16224
  * The ABR ladder (`abrLadder`) and initial rendition (`initialQuality`)
@@ -16242,7 +16312,7 @@ var TransportManager = class {
16242
16312
  /**
16243
16313
  * Connect via the lowercase window.multicast bytes gateway.
16244
16314
  */
16245
- async connectWindowMulticast(config, generation) {
16315
+ async connectWindowMulticast(config, generation, mode = "multicast") {
16246
16316
  try {
16247
16317
  const gateway = this.getWindowMulticastGateway();
16248
16318
  if (typeof gateway?.subscribe !== "function")
@@ -16277,7 +16347,7 @@ var TransportManager = class {
16277
16347
  }
16278
16348
  };
16279
16349
  this.state = {
16280
- mode: "multicast",
16350
+ mode,
16281
16351
  connected: true,
16282
16352
  group: config.group,
16283
16353
  source: config.source,
@@ -16295,29 +16365,19 @@ var TransportManager = class {
16295
16365
  }
16296
16366
  }
16297
16367
  /**
16298
- * Connect via AMT proxy (with optional DRIAD discovery)
16368
+ * Connect via AMT: a configured relay goes through the AMT proxy; with no
16369
+ * relay, the window.multicast gateway discovers one per RFC 8777 (DRIAD).
16299
16370
  */
16300
16371
  async connectAmt(config, generation) {
16301
16372
  try {
16302
- let amtRelay = config.amtRelay;
16303
- if (!amtRelay && config.driadEnabled !== false && config.source) {
16304
- console.log(`[Transport] Discovering AMT relay via DRIAD for source ${config.source}...`);
16305
- const relays = await this.driad.discoverRelays(config.source);
16306
- if (generation !== this.connectionGeneration)
16307
- return false;
16308
- const bestRelay = await this.driad.selectBestRelay(relays);
16309
- if (generation !== this.connectionGeneration)
16310
- return false;
16311
- if (bestRelay) {
16312
- amtRelay = bestRelay.host;
16313
- this.state.amtRelay = amtRelay;
16314
- }
16315
- }
16316
- if (!amtRelay) {
16373
+ if (config.amtRelay)
16374
+ return await this.connectAmtProxy(config, config.amtRelay, generation);
16375
+ if (config.driadEnabled === false || !config.source || config.mode === "native") {
16317
16376
  console.warn("[Transport] No AMT relay available (DRIAD requires source address for SSM)");
16318
16377
  return false;
16319
16378
  }
16320
- return await this.connectAmtProxy(config, amtRelay, generation);
16379
+ console.log(`[Transport] Asking the gateway for a DRIAD relay for source ${config.source}...`);
16380
+ return await this.connectWindowMulticast({ ...config, amtDiscovery: "driad" }, generation, "amt");
16321
16381
  } catch (error) {
16322
16382
  console.warn("[Transport] AMT connection failed:", error);
16323
16383
  return false;
@@ -16548,7 +16608,6 @@ var AMTGatewayManager = class {
16548
16608
  subscriptions = /* @__PURE__ */ new Map();
16549
16609
  messageHandler;
16550
16610
  pendingPackets = /* @__PURE__ */ new Map();
16551
- driad = new DRIADDiscovery();
16552
16611
  constructor() {
16553
16612
  this.messageHandler = (event) => {
16554
16613
  const data = event.data;
@@ -16579,26 +16638,12 @@ var AMTGatewayManager = class {
16579
16638
  return keyStr;
16580
16639
  }
16581
16640
  try {
16582
- let relayAddress;
16583
- let discoveryMethod;
16641
+ const relayAddress = config.relayAddress;
16584
16642
  const relayPort = config.relayPort || DEFAULT_AMT_RELAY_PORT2;
16585
- if (config.relayAddress) {
16586
- relayAddress = config.relayAddress;
16587
- discoveryMethod = "manual";
16588
- console.log(`[AMT] Using configured relay ${relayAddress}:${relayPort}`);
16589
- } else if (key.source) {
16590
- console.log(`[AMT] No relay configured, discovering via DRIAD for source ${key.source}...`);
16591
- const relays = await this.driad.discoverRelays(key.source);
16592
- const bestRelay = await this.driad.selectBestRelay(relays);
16593
- if (!bestRelay) {
16594
- throw new Error(`AMT relay discovery failed for source ${key.source}. Please specify a relay address in the subscription configuration.`);
16595
- }
16596
- relayAddress = bestRelay.host;
16597
- discoveryMethod = "driad";
16598
- console.log(`[AMT] Discovered relay via DRIAD: ${relayAddress}:${relayPort}`);
16599
- } else {
16600
- throw new Error(`AMT relay discovery requires a source address for SSM (RFC 8777). Please specify either a relay address or source address.`);
16643
+ if (!relayAddress) {
16644
+ throw new Error(`AMT relay address required: this manager does no relay discovery. For RFC 8777 DRIAD discovery, join through window.multicast with amtDiscovery: "driad".`);
16601
16645
  }
16646
+ console.log(`[AMT] Using configured relay ${relayAddress}:${relayPort}`);
16602
16647
  const subscriptionId = keyStr;
16603
16648
  this.pendingPackets.set(subscriptionId, []);
16604
16649
  const subscription = {
@@ -16609,7 +16654,7 @@ var AMTGatewayManager = class {
16609
16654
  relay: {
16610
16655
  address: relayAddress,
16611
16656
  port: relayPort,
16612
- discoveryMethod,
16657
+ discoveryMethod: "manual",
16613
16658
  discoveredAt: Date.now()
16614
16659
  }
16615
16660
  };
@@ -16765,7 +16810,7 @@ function sameIds(a, b) {
16765
16810
  for (const id of a) if (!b.has(id)) return false;
16766
16811
  return true;
16767
16812
  }
16768
- var MulticastTransport = class _MulticastTransport {
16813
+ var MulticastTransport = class {
16769
16814
  #onPacket;
16770
16815
  #subscription = null;
16771
16816
  #packetListener = null;
@@ -16837,8 +16882,11 @@ var MulticastTransport = class _MulticastTransport {
16837
16882
  // droppedPacketIds.
16838
16883
  #unadvertisedPacketIds = /* @__PURE__ */ new Set();
16839
16884
  #joinGeneration = 0;
16840
- constructor(onPacket) {
16885
+ // The provider to subscribe through; window.multicast when unset.
16886
+ #gateway;
16887
+ constructor(onPacket, options = {}) {
16841
16888
  this.#onPacket = onPacket;
16889
+ this.#gateway = options.gateway;
16842
16890
  }
16843
16891
  static isAvailable() {
16844
16892
  return hasMulticastGateway();
@@ -16848,7 +16896,8 @@ var MulticastTransport = class _MulticastTransport {
16848
16896
  this.#releaseSubscription();
16849
16897
  this.#dataPlaneLive = false;
16850
16898
  if (this.#disposed) return this.#declined(generation, "disposed");
16851
- if (!_MulticastTransport.isAvailable()) {
16899
+ const gateway = this.#gateway ?? getMulticastGlobals().multicast;
16900
+ if (typeof gateway?.subscribe !== "function") {
16852
16901
  console.warn("[MulticastTransport] Multicast API not available");
16853
16902
  return this.#declined(generation, "unavailable");
16854
16903
  }
@@ -16865,11 +16914,12 @@ var MulticastTransport = class _MulticastTransport {
16865
16914
  mode: config.mode,
16866
16915
  amtRelay: config.amtRelay,
16867
16916
  amtRelayPort: config.amtRelayPort,
16917
+ amtDiscovery: config.amtDiscovery,
16868
16918
  packetIds: config.packetIds,
16869
16919
  tracks: config.tracks
16870
16920
  });
16871
16921
  failure = "provider-rejected";
16872
- const subscription = await getMulticastGlobals().multicast.subscribe(subscribeConfig);
16922
+ const subscription = await gateway.subscribe(subscribeConfig);
16873
16923
  failure = "invalid-subscription";
16874
16924
  console.log(`[MulticastTransport] window.multicast.subscribe returned:`, !!subscription);
16875
16925
  if (this.#disposed || generation !== this.#joinGeneration) {
@@ -17573,10 +17623,14 @@ function isoSpanUnavailable(fec, path, declaresFecInstance) {
17573
17623
  });
17574
17624
  }
17575
17625
  function catalogFecUnavailable(fec, fecPath) {
17626
+ if (catalogFecAvailable(fec)) return void 0;
17576
17627
  const block = recordOf2(fec);
17577
- if (block === void 0) return void 0;
17578
17628
  const declaresFecInstance = block["algorithm"] !== "none";
17579
- return blockProfileUnavailable(block["blockProfile"], `${fecPath}.blockProfile`, declaresFecInstance) ?? isoSpanUnavailable(block, `${fecPath}.interleaveDepthMs`, declaresFecInstance);
17629
+ const reason = blockProfileUnavailable(block["blockProfile"], `${fecPath}.blockProfile`, declaresFecInstance) ?? isoSpanUnavailable(block, `${fecPath}.interleaveDepthMs`, declaresFecInstance);
17630
+ if (reason === void 0) {
17631
+ throw new Error(`catalogFecUnavailable: ${fecPath} is unavailable but no reason applies (rule drift)`);
17632
+ }
17633
+ return reason;
17580
17634
  }
17581
17635
 
17582
17636
  // src/multicast-manager.ts
@@ -17911,6 +17965,9 @@ var MulticastManager = class {
17911
17965
  #router;
17912
17966
  #hostMfuTimeoutMs;
17913
17967
  #transport;
17968
+ /** Live joinRepairEndpoints() releases → the repair owners they registered,
17969
+ * re-applied after configureMultiTrack() clears catalog-derived owners. */
17970
+ #repairReleases = /* @__PURE__ */ new Map();
17914
17971
  #reportedFecDiagnosticsFailure = false;
17915
17972
  // ── Stream-global FEC timing reduction ──
17916
17973
  //
@@ -18174,7 +18231,9 @@ var MulticastManager = class {
18174
18231
  catalogTrackName
18175
18232
  );
18176
18233
  this.#configureTrackMapper(packetId, config);
18177
- this.#router.setPacketIdType(packetId, trackType);
18234
+ if (this.#router.trackKindFor(packetId) !== trackType) {
18235
+ this.#router.setPacketIdType(packetId, trackType);
18236
+ }
18178
18237
  }
18179
18238
  /**
18180
18239
  * Stop routing a stream's symbols to its Worker decoder. Returns false when
@@ -18255,6 +18314,14 @@ var MulticastManager = class {
18255
18314
  );
18256
18315
  }
18257
18316
  }
18317
+ for (const [packetId, c] of this.#trackFecTiming) {
18318
+ if (c.deliveryWindowMs === void 0) continue;
18319
+ mfuTimeoutMs = Math.max(
18320
+ mfuTimeoutMs ?? 0,
18321
+ this.#fec.terminalRetentionMsForPacket(packetId) ?? 0,
18322
+ this.#hostMfuTimeoutMs ?? 0
18323
+ );
18324
+ }
18258
18325
  const failbackWindowMs = deliveryWindowMs === void 0 ? minimumFailbackWindowMs : Math.max(deliveryWindowMs, minimumFailbackWindowMs ?? 0);
18259
18326
  this.#transport.setFailbackWindowMs(failbackWindowMs ?? null);
18260
18327
  this.#router.setMfuTimeoutMs(mfuTimeoutMs ?? this.#hostMfuTimeoutMs);
@@ -18438,6 +18505,7 @@ var MulticastManager = class {
18438
18505
  setMfuTimeoutMs(ms) {
18439
18506
  this.#router.setMfuTimeoutMs(ms);
18440
18507
  this.#hostMfuTimeoutMs = this.#router.reassembler.timeoutMs;
18508
+ if (this.#trackFecTiming.size > 0) this.#applyStreamGlobalFecTiming();
18441
18509
  }
18442
18510
  setTrackCodec(packetId, codec) {
18443
18511
  this.#router.setTrackCodec(packetId, codec);
@@ -18558,11 +18626,80 @@ var MulticastManager = class {
18558
18626
  // through whatever the relay looks like, since dropping it would be the
18559
18627
  // worse behaviour.
18560
18628
  amtRelayPort: config.amtRelayPort ?? config.relayPort ?? (amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : void 0),
18629
+ amtDiscovery: config.amtDiscovery,
18561
18630
  packetIds: config.packetIds,
18562
18631
  tracks: catalogTracks?.map(({ name, packetId }) => ({ name, packetId }))
18563
18632
  };
18564
18633
  return ingress === void 0 ? this.#transport.join(transportConfig) : this.#transport.join(transportConfig, ingress);
18565
18634
  }
18635
+ /**
18636
+ * Join the selected rung's dedicated repair groups beside the media join
18637
+ * (pim #3898): one subscription per endpoint, through `provider` when given
18638
+ * (a `window.multicast`-shaped gateway or a subscribe callback), otherwise a
18639
+ * new MulticastTransport on `window.multicast`. Returns the call that
18640
+ * releases every one of them; dispose() releases them too.
18641
+ *
18642
+ * Packets go straight to the router with the endpoint's ingress, never
18643
+ * through feedPacket(): repair arriving on its own group is not media
18644
+ * liveness, so it must not hold off the media leg's failback watchdog. The
18645
+ * repair roles and owners are registered here; in-band owners stay the
18646
+ * caller's. Joining is best effort: a group that fails to join is logged
18647
+ * and leaves the media join as it was.
18648
+ */
18649
+ joinRepairEndpoints(endpoints, provider) {
18650
+ const releases = [];
18651
+ let released = false;
18652
+ const safely = (each) => {
18653
+ try {
18654
+ each();
18655
+ } catch (error) {
18656
+ console.warn("[MulticastManager] repair group release failed", error);
18657
+ }
18658
+ };
18659
+ const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners);
18660
+ this.#applyRepairOwners(repairOwners);
18661
+ for (const endpoint of endpoints) {
18662
+ const ingress = {
18663
+ tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId })))
18664
+ };
18665
+ const onPacket = (packet) => {
18666
+ if (!released) this.#router.feedPacket(packet, "multicast", void 0, ingress);
18667
+ };
18668
+ const fail = (error) => console.warn(`[MulticastManager] repair group ${endpoint.group}:${endpoint.port} not joined`, error);
18669
+ if (typeof provider === "function") {
18670
+ Promise.resolve().then(() => provider(endpoint, onPacket)).then((release2) => released ? safely(release2) : releases.push(release2), fail);
18671
+ continue;
18672
+ }
18673
+ const transport = new MulticastTransport((packet) => onPacket(packet), { gateway: provider });
18674
+ releases.push(() => transport.dispose());
18675
+ void transport.join({
18676
+ sourceAddress: endpoint.source,
18677
+ groupAddress: endpoint.group,
18678
+ port: endpoint.port,
18679
+ mode: endpoint.mode,
18680
+ amtRelay: endpoint.amtRelay,
18681
+ amtRelayPort: endpoint.amtRelayPort ?? (endpoint.amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : void 0),
18682
+ packetIds: endpoint.packetIds,
18683
+ tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId }))
18684
+ }).then((joined) => {
18685
+ if (!joined && !released) fail(transport.lastJoinOutcome);
18686
+ });
18687
+ }
18688
+ const release = () => {
18689
+ if (released) return;
18690
+ released = true;
18691
+ this.#repairReleases.delete(release);
18692
+ for (const each of releases.splice(0)) safely(each);
18693
+ };
18694
+ this.#repairReleases.set(release, repairOwners);
18695
+ return release;
18696
+ }
18697
+ #applyRepairOwners(owners) {
18698
+ for (const { packetId, ownerPacketId } of owners) {
18699
+ this.#router.setPacketIdRole(packetId, "repair");
18700
+ this.#router.setRepairPacketIdOwner(packetId, ownerPacketId);
18701
+ }
18702
+ }
18566
18703
  // ---------------------------------------------------------------------------
18567
18704
  // In-place rendition switch
18568
18705
  // ---------------------------------------------------------------------------
@@ -18924,11 +19061,7 @@ var MulticastManager = class {
18924
19061
  for (const [groupKey, roles] of resolvedRolesByGroup) {
18925
19062
  if (!(hasSwitchingSetByGroup.get(groupKey) ?? false)) continue;
18926
19063
  const presentRoles = new Set(roles.filter((r) => r !== "single"));
18927
- const required = [
18928
- "base",
18929
- "delta",
18930
- "repair"
18931
- ];
19064
+ const required = ["base", "repair"];
18932
19065
  const missing = required.filter((r) => !presentRoles.has(r));
18933
19066
  if (missing.length > 0) {
18934
19067
  throw new Error(
@@ -18975,6 +19108,7 @@ var MulticastManager = class {
18975
19108
  this.#switchingSets.clear();
18976
19109
  this.#repairPacketIds.clear();
18977
19110
  this.#router.clearRepairPacketIdOwners();
19111
+ for (const owners of this.#repairReleases.values()) this.#applyRepairOwners(owners);
18978
19112
  const fecPacketIds = new Set([...fecDecoders.keys()].map((i) => catalog.tracks[i].packetId));
18979
19113
  for (const [packetId, catalogTrackName] of this.#multiTrackFecTracks) {
18980
19114
  if (fecPacketIds.has(packetId)) continue;
@@ -19306,6 +19440,7 @@ var MulticastManager = class {
19306
19440
  this.#trackResetObservers.clear();
19307
19441
  this.#repairLifecycleObservers.clear();
19308
19442
  this.#transport.dispose();
19443
+ for (const release of [...this.#repairReleases.keys()]) release();
19309
19444
  this.#router.dispose();
19310
19445
  this.#fec.dispose();
19311
19446
  }