@blockcast/mmt-container 0.4.0-main.bbdfdbf39ded → 0.4.0-main.bd9f80b4a95e

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 (62) hide show
  1. package/dist/browser-runtime.js +230 -33
  2. package/dist/browser-runtime.js.map +2 -2
  3. package/dist/carp-catalog.d.ts +5 -6
  4. package/dist/carp-catalog.d.ts.map +1 -1
  5. package/dist/carp-catalog.js +15 -1
  6. package/dist/carp-catalog.js.map +2 -2
  7. package/dist/catalog-fec-params.js.map +2 -2
  8. package/dist/catalog-network-source.d.ts +4 -5
  9. package/dist/catalog-network-source.d.ts.map +1 -1
  10. package/dist/catalog-network-source.js.map +2 -2
  11. package/dist/cmcd-producer.d.ts +8 -0
  12. package/dist/cmcd-producer.d.ts.map +1 -1
  13. package/dist/cmcd-producer.js +14 -0
  14. package/dist/cmcd-producer.js.map +2 -2
  15. package/dist/fec-manager.d.ts +69 -12
  16. package/dist/fec-manager.d.ts.map +1 -1
  17. package/dist/fec-manager.js +162 -18
  18. package/dist/fec-manager.js.map +2 -2
  19. package/dist/fec-worker-setup.d.ts +8 -0
  20. package/dist/fec-worker-setup.d.ts.map +1 -1
  21. package/dist/fec-worker-setup.js +3 -1
  22. package/dist/fec-worker-setup.js.map +2 -2
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js.map +2 -2
  26. package/dist/iso-block-locator.d.ts +9 -1
  27. package/dist/iso-block-locator.d.ts.map +1 -1
  28. package/dist/iso-block-locator.js +11 -0
  29. package/dist/iso-block-locator.js.map +2 -2
  30. package/dist/mmtp-container-parser.no-modules.js +15 -1
  31. package/dist/mmtp-container-parser.no-modules.js.map +2 -2
  32. package/dist/mmtp-router.d.ts +8 -1
  33. package/dist/mmtp-router.d.ts.map +1 -1
  34. package/dist/mmtp-router.js +20 -6
  35. package/dist/mmtp-router.js.map +2 -2
  36. package/dist/multicast-input.d.ts +3 -2
  37. package/dist/multicast-input.d.ts.map +1 -1
  38. package/dist/multicast-input.js +9 -7
  39. package/dist/multicast-input.js.map +2 -2
  40. package/dist/multicast-manager.d.ts +6 -1
  41. package/dist/multicast-manager.d.ts.map +1 -1
  42. package/dist/multicast-manager.js +189 -24
  43. package/dist/multicast-manager.js.map +2 -2
  44. package/dist/no-modules.js +15 -1
  45. package/dist/no-modules.js.map +2 -2
  46. package/package.json +5 -5
  47. package/schemas/catalog.schema.json +12 -4
  48. package/src/carp-catalog.ts +25 -7
  49. package/src/catalog-network-source.ts +4 -5
  50. package/src/cmcd-producer.ts +17 -0
  51. package/src/fec-manager.ts +232 -19
  52. package/src/fec-worker-setup.ts +10 -0
  53. package/src/index.ts +3 -0
  54. package/src/iso-block-locator.ts +12 -1
  55. package/src/mmtp-router.ts +37 -6
  56. package/src/multicast-input.ts +31 -65
  57. package/src/multicast-manager.ts +9 -0
  58. package/test-vectors/catalog/README.md +9 -3
  59. package/test-vectors/catalog/negative/multicast-amt-driad-with-relay.json +38 -0
  60. package/test-vectors/catalog/positive/mmt01-12-1-init-ref-anchor.json +1 -1
  61. package/test-vectors/catalog/positive/multicast-amt-manual-relay.json +1 -1
  62. package/test-vectors/catalog/section-codes.json +1 -0
@@ -6757,13 +6757,22 @@ var CmsfCatalogValidationError = class extends Error {
6757
6757
  function catalogError(code, path, message) {
6758
6758
  throw new CmsfCatalogValidationError(code, path, message);
6759
6759
  }
6760
+ function validateNetworkSourceRelays(sources, path) {
6761
+ if (!Array.isArray(sources)) return;
6762
+ sources.forEach((source, i) => {
6763
+ const s = source;
6764
+ if (s?.["type"] === "amt" && s["discovery"] === "driad" && s["relay"] !== void 0) {
6765
+ catalogError("multicast_network_source", `${path}[${i}].relay`, 'relay must be omitted with discovery "driad"');
6766
+ }
6767
+ });
6768
+ }
6760
6769
  function validateCmsfMmtpCatalog(value, options = {}) {
6761
6770
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
6762
6771
  catalogError("catalog_object", "$", "catalog must be an object");
6763
6772
  }
6764
6773
  const catalog = value;
6765
6774
  const rawVersion = catalog["version"];
6766
- const normalizedVersion = typeof rawVersion === "string" ? Number.isFinite(Number(rawVersion)) ? Number(rawVersion) : rawVersion.startsWith("draft-ietf-moq-catalogformat") ? 1 : NaN : rawVersion;
6775
+ const normalizedVersion = typeof rawVersion === "string" ? Number.isFinite(Number(rawVersion)) ? Number(rawVersion) : rawVersion.startsWith("draft-ietf-moq-catalogformat") || rawVersion === "draft-01" ? 1 : NaN : rawVersion;
6767
6776
  if (!Number.isInteger(normalizedVersion) || normalizedVersion <= 0) {
6768
6777
  catalogError("catalog_version", "$.version", "version must be a positive integer or a recognized format tag");
6769
6778
  }
@@ -6984,11 +6993,16 @@ function validateCmsfMmtpCatalog(value, options = {}) {
6984
6993
  }
6985
6994
  const multicast = catalog["multicast"];
6986
6995
  if (typeof multicast === "object" && multicast !== null && !Array.isArray(multicast)) {
6996
+ validateNetworkSourceRelays(multicast["networkSource"], "$.multicast.networkSource");
6987
6997
  const endpoints = multicast["endpoints"];
6988
6998
  if (Array.isArray(endpoints)) {
6989
6999
  for (let endpointIndex = 0; endpointIndex < endpoints.length; endpointIndex++) {
6990
7000
  const endpoint = endpoints[endpointIndex];
6991
7001
  if (typeof endpoint !== "object" || endpoint === null || Array.isArray(endpoint)) continue;
7002
+ validateNetworkSourceRelays(
7003
+ endpoint["networkSource"],
7004
+ `$.multicast.endpoints[${endpointIndex}].networkSource`
7005
+ );
6992
7006
  if ("relayAddress" in endpoint) {
6993
7007
  catalogError(
6994
7008
  "multicast_relay_address",
@@ -8824,18 +8838,14 @@ function multicastFromConfig(input) {
8824
8838
  networkSource.forEach(validateNetworkSourceEntry);
8825
8839
  if (networkSource.length > 0) out.networkSource = networkSource;
8826
8840
  const amtRelays = new Set(
8827
- networkSource.flatMap((s) => s.type === "amt" && s.discovery !== "driad" && s.relay?.trim() ? [s.relay.trim()] : []).slice(0, 1)
8841
+ networkSource.flatMap((s) => s.type === "amt" && s.relay?.trim() ? [s.relay.trim()] : []).slice(0, 1)
8828
8842
  );
8829
8843
  input.endpoints.forEach((ep, idx) => {
8830
8844
  const relay = ep.relayAddress?.trim();
8831
8845
  if (!relay || amtRelays.has(relay)) return;
8832
- const demoted = networkSource.some(
8833
- (s) => s.type === "amt" && s.discovery === "driad" && s.relay?.trim() === relay
8834
- );
8835
8846
  const shadowed = networkSource.some(
8836
- (s) => s.type === "amt" && s.discovery !== "driad" && s.relay?.trim() === relay
8847
+ (s) => s.type === "amt" && s.relay?.trim() === relay
8837
8848
  );
8838
- const derived = input.networkSource === void 0;
8839
8849
  const fromAmtFallback = ", derived from amtFallback/MOQCAST_MULTICAST_AMT_*";
8840
8850
  const fromRelay = relayFrom === "amtFallback.relayDns" ? fromAmtFallback : relayFrom === "endpoint.relayAddress" ? ", derived from the endpoint relayAddress values" : "";
8841
8851
  const relayDns = input.amtFallback?.relayDns?.trim();
@@ -8843,7 +8853,7 @@ function multicastFromConfig(input) {
8843
8853
  throw new MulticastInputError(
8844
8854
  "conflicting_amt_relay",
8845
8855
  idx,
8846
- `endpoint[${idx}] relayAddress ${JSON.stringify(relay)} ` + (demoted ? `is carried only by a multicast.networkSource AMT entry with discovery="driad"${derived ? fromAmtFallback : ""}, whose relay is a DRIAD discovery hint that both readers skip, so the catalog names no relay to join; to join it, add a manual entry beside the driad one: [{type:"amt",discovery:"manual",relay:${JSON.stringify(relay)}},{type:"amt",discovery:"driad"}]` : shadowed ? `is carried by a multicast.networkSource AMT entry that is not the first one: both readers join the first AMT entry (${[...amtRelays].join(", ")}) and ignore the rest, so this relay is never joined; keep a single AMT entry, or put this one first` : `is not the relay of any multicast.networkSource AMT entry (${[...amtRelays].join(", ") || "none"})${fromRelay}; ` + (outranked ? `amtFallback.relayDns/MOQCAST_MULTICAST_AMT_RELAY_DNS (${relayDns}) outranks an endpoint relay when networkSource is derived -- drop one, or make them agree` : "networkSource is catalog-level and cannot represent per-endpoint relays"))
8856
+ `endpoint[${idx}] relayAddress ${JSON.stringify(relay)} ` + (shadowed ? `is carried by a multicast.networkSource AMT entry that is not the first one: both readers join the first AMT entry (${[...amtRelays].join(", ")}) and ignore the rest, so this relay is never joined; keep a single AMT entry, or put this one first` : `is not the relay of any multicast.networkSource AMT entry (${[...amtRelays].join(", ") || "none"})${fromRelay}; ` + (outranked ? `amtFallback.relayDns/MOQCAST_MULTICAST_AMT_RELAY_DNS (${relayDns}) outranks an endpoint relay when networkSource is derived -- drop one, or make them agree` : "networkSource is catalog-level and cannot represent per-endpoint relays"))
8847
8857
  );
8848
8858
  });
8849
8859
  input.endpoints.forEach((ep, idx) => {
@@ -8909,6 +8919,12 @@ function validateNetworkSourceEntry(s, i) {
8909
8919
  if ((s.discovery === "dns" || s.discovery === "manual") && s.relay === void 0) {
8910
8920
  throw err("amt_requires_relay", `discovery="${s.discovery}" requires a relay ("driad" resolves it at runtime)`);
8911
8921
  }
8922
+ if (s.discovery === "driad" && s.relay !== void 0) {
8923
+ throw err(
8924
+ "invalid_network_source",
8925
+ `discovery="driad" must omit relay: DRIAD supplies the relay candidates (draft -01 4.2.1); drop the relay (amtFallback.relayDns / endpoint relayAddress on the derived path), or use "dns" or "manual"`
8926
+ );
8927
+ }
8912
8928
  if (s.port !== void 0 && (!Number.isInteger(s.port) || s.port < 1 || s.port > 65535)) {
8913
8929
  throw err("invalid_port", `port must be 1..65535; got ${s.port}`);
8914
8930
  }
@@ -12573,6 +12589,14 @@ var IsoBlockLocator = class _IsoBlockLocator {
12573
12589
  * known block (a different length, or an overlap with another block or a
12574
12590
  * span) fails closed: the repair symbol is dropped and no block changes.
12575
12591
  * A newly stated block retires behind its SS_Start (see the class note).
12592
+ * A block so far past `newest` that stating it would retire the position
12593
+ * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
12594
+ * this is slightly conservative (retirement measures that block from its
12595
+ * last SS_ID), costing one dropped repair. Placing it would turn everything
12596
+ * between into a repair-less span and leave every real repair behind it
12597
+ * `stale`. Sources move `newest` (`hold`, `observe`), so after a real outage
12598
+ * the first source back brings the next repair inside the horizon; until one
12599
+ * arrives, a stream's repairs alone cannot pass it.
12576
12600
  */
12577
12601
  placeRepair(start, length) {
12578
12602
  if (!Number.isSafeInteger(length) || length <= 0 || length > this.#kMax) {
@@ -12615,6 +12639,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
12615
12639
  };
12616
12640
  }
12617
12641
  }
12642
+ if (this.#newest !== void 0 && isoBlocksBehindLowerBound(this.#newest, start, this.#kMax) > this.#retentionBlocks) {
12643
+ return { status: "ahead", reason: `repair block ${start}+${length} is past the retention horizon ahead of ${this.#newest}` };
12644
+ }
12618
12645
  let span;
12619
12646
  let hole;
12620
12647
  if (this.#coverageEnd === void 0) {
@@ -13345,6 +13372,11 @@ var FECManager = class _FECManager {
13345
13372
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
13346
13373
  // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
13347
13374
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
13375
+ /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
13376
+ this.#heldLayerStates = /* @__PURE__ */ new Map();
13377
+ /** Streams whose FEC failed closed at runtime (fec-01 6.3.9). */
13378
+ this.#fecFailClosed = /* @__PURE__ */ new Map();
13379
+ this.#onFecFailClosed = null;
13348
13380
  // Blocks already recovered — prevents late source symbols from restarting timeouts.
13349
13381
  // WASM removes blocks after recovery; late symbols create empty blocks returning null,
13350
13382
  // which would falsely start new timeouts without this guard.
@@ -13599,6 +13631,9 @@ var FECManager = class _FECManager {
13599
13631
  #ssbLengthConflictCount;
13600
13632
  #blockRepairRsIds;
13601
13633
  #blockRsbLengths;
13634
+ #heldLayerStates;
13635
+ #fecFailClosed;
13636
+ #onFecFailClosed;
13602
13637
  #completedBlocks;
13603
13638
  #terminalExpiryMs;
13604
13639
  #terminalQueues;
@@ -14655,8 +14690,19 @@ var FECManager = class _FECManager {
14655
14690
  timeoutMs: config.timeoutMs ?? (timingChanged ? 0 : previous.timeoutMs ?? 0),
14656
14691
  ...(config.trackKind ?? previous.trackKind) === void 0 ? {} : { trackKind: config.trackKind ?? previous.trackKind },
14657
14692
  ...(config.codec ?? previous.codec) === void 0 ? {} : { codec: config.codec ?? previous.codec },
14658
- ...(config.geometry ?? previous.geometry) === void 0 ? {} : { geometry: config.geometry ?? previous.geometry }
14693
+ ...(config.geometry ?? previous.geometry) === void 0 ? {} : { geometry: config.geometry ?? previous.geometry },
14694
+ ...(config.repairLayers ?? previous.repairLayers) === void 0 ? {} : { repairLayers: config.repairLayers ?? previous.repairLayers },
14695
+ ...(config.heldLayers ?? previous.heldLayers) === void 0 ? {} : { heldLayers: config.heldLayers ?? previous.heldLayers }
14659
14696
  };
14697
+ if (
14698
+ // By content: a catalog refresh rebuilds equal arrays, and forgetting
14699
+ // the anchors on one would fail open.
14700
+ JSON.stringify(next.repairLayers) !== JSON.stringify(previous.repairLayers) || JSON.stringify(next.heldLayers) !== JSON.stringify(previous.heldLayers)
14701
+ ) {
14702
+ for (const key of [...this.#heldLayerStates.keys()]) {
14703
+ if (this.#belongsToPacket(key, packetId)) this.#heldLayerStates.delete(key);
14704
+ }
14705
+ }
14660
14706
  if (!hasCatalogTiming) {
14661
14707
  next.timeoutMs = config.timeoutMs !== void 0 && config.timeoutMs > 0 ? config.timeoutMs : previousTrack !== void 0 && previousTrack.interleaveDepthMs === 0 ? previousTrack.timeoutMs : LOCAL_FEC_TIMEOUT_MS;
14662
14708
  } else {
@@ -14891,6 +14937,8 @@ var FECManager = class _FECManager {
14891
14937
  resetMap(this.#blockAuthoredLengths);
14892
14938
  resetMap(this.#blockRepairRsIds);
14893
14939
  resetMap(this.#blockRsbLengths);
14940
+ resetMap(this.#heldLayerStates);
14941
+ resetMap(this.#fecFailClosed);
14894
14942
  resetMap(this.#blockPathCounts);
14895
14943
  resetMap(this.#blockAnchorsMs);
14896
14944
  resetMap(this.#blockCatalogTrackNames);
@@ -16069,12 +16117,17 @@ var FECManager = class _FECManager {
16069
16117
  return recovered;
16070
16118
  }
16071
16119
  /**
16072
- * Feed a repair symbol to the WASM FEC decoder.
16073
- *
16074
- * @returns Recovered block data if repair completed the block, else null.
16075
- * Caller is responsible for routing recovered data and updating
16076
- * block completion state via `markBlockCompleted()`.
16120
+ * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
16121
+ * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
16122
+ * block state unchanged. The router calls this before the repair places a
16123
+ * block or takes any other part in block bookkeeping. A RaptorQ track admits
16124
+ * every header that parsed (its RS_ID < RSB_length check is in the parser).
16077
16125
  */
16126
+ admitRepairBlockLength(packetId, ssbLength, rsbLength, rsId) {
16127
+ if (rsId >= rsbLength) return false;
16128
+ if (this.#trackConfigs.get(packetId)?.algorithm !== "reed-solomon") return true;
16129
+ return ssbLength + rsbLength <= RS_MAX_BLOCK_SYMBOLS;
16130
+ }
16078
16131
  /**
16079
16132
  * Whether a repair symbol of `byteLength` bytes is a valid member of a
16080
16133
  * `packetId` block: every repair symbol is exactly the track's T. A symbol of
@@ -16087,18 +16140,6 @@ var FECManager = class _FECManager {
16087
16140
  * counted (BLO-48306). A packetId with no configured block profile admits
16088
16141
  * nothing here; its repair is dropped upstream as unreadable.
16089
16142
  */
16090
- /**
16091
- * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
16092
- * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
16093
- * block state unchanged. The router calls this before the repair places a
16094
- * block or takes any other part in block bookkeeping. A RaptorQ track admits
16095
- * every header that parsed (its RS_ID < RSB_length check is in the parser).
16096
- */
16097
- admitRepairBlockLength(packetId, ssbLength, rsbLength, rsId) {
16098
- if (rsId >= rsbLength) return false;
16099
- if (this.#trackConfigs.get(packetId)?.algorithm !== "reed-solomon") return true;
16100
- return ssbLength + rsbLength <= RS_MAX_BLOCK_SYMBOLS;
16101
- }
16102
16143
  admitRepairSymbolSize(packetId, ssStart, ssbLength, rsId, byteLength) {
16103
16144
  if (!this.#hasBlockProfile(packetId)) return false;
16104
16145
  const symbolSize = this.#trackConfig(packetId).symbolSize;
@@ -16113,6 +16154,123 @@ var FECManager = class _FECManager {
16113
16154
  }
16114
16155
  return true;
16115
16156
  }
16157
+ /**
16158
+ * fec-01 6.3.9 receiver check, run on a repair packet after the 4.5 discard
16159
+ * and the size check, before it places a block. For each held layer i with
16160
+ * total B_i = O_i + P_i: the anchor is the earliest block, in SS_Start
16161
+ * serial order, whose repair carried RSB_length >= B_i. The source track
16162
+ * fails closed on (a) a packet on layer i's own repair track (i > 0) below
16163
+ * B_i, or (b) any packet of the instance at or after the anchor below B_i.
16164
+ * Blocks before the anchor (pre-append) stay valid at the previous total. A
16165
+ * packet on a repair track the catalog does not list is discarded and
16166
+ * anchors nothing. `repairTrackName` is the subscribed repair track, never
16167
+ * inferred from RS_ID; without it only (b) runs. Returns false when the
16168
+ * repair must be dropped, including every repair once the track failed.
16169
+ */
16170
+ admitRepairLayerTotal(packetId, catalogTrackName, repairTrackName, ssStart, rsbLength) {
16171
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
16172
+ if (this.#fecFailClosed.has(streamKey)) return false;
16173
+ const config = this.#trackConfigs.get(packetId);
16174
+ const layers = config?.repairLayers;
16175
+ if (layers === void 0 || layers.length === 0) return true;
16176
+ if (repairTrackName !== void 0 && !layers.some((l) => l.repairTrackName === repairTrackName)) {
16177
+ return false;
16178
+ }
16179
+ let states = this.#heldLayerStates.get(streamKey);
16180
+ if (states === void 0) {
16181
+ const held = new Set(config.heldLayers ?? [0]);
16182
+ states = layers.filter((l) => held.has(l.layer)).map((l) => ({ layer: l.layer, repairTrackName: l.repairTrackName, total: l.rsIdOffset + l.repairSymbols }));
16183
+ this.#heldLayerStates.set(streamKey, states);
16184
+ }
16185
+ const horizon = this.#layerAnchorHorizon(packetId);
16186
+ const frontier = this.#sourceFrontiers.get(streamKey)?.sbn;
16187
+ const farAhead = frontier !== void 0 && serial32Precedes(frontier, ssStart) && serial32Distance(frontier, ssStart) > horizon;
16188
+ for (const state of states) {
16189
+ let code;
16190
+ if (farAhead) {
16191
+ if (rsbLength < state.total) {
16192
+ if (state.layer > 0 && repairTrackName === state.repairTrackName) code = "below_own_track_total";
16193
+ else if (state.anchor !== void 0 || state.settled) code = "below_anchored_total";
16194
+ }
16195
+ } else {
16196
+ if (state.newest === void 0 || serial32Precedes(state.newest, ssStart)) state.newest = ssStart;
16197
+ const stale = (s) => serial32Distance(s, state.newest) > horizon;
16198
+ if (state.latestBelow !== void 0 && stale(state.latestBelow)) {
16199
+ delete state.latestBelow;
16200
+ delete state.latestBelowRsb;
16201
+ }
16202
+ if (state.anchor !== void 0 && stale(state.anchor)) state.settled = true;
16203
+ if (rsbLength < state.total) {
16204
+ if (state.layer > 0 && repairTrackName === state.repairTrackName) code = "below_own_track_total";
16205
+ else if (stale(ssStart)) continue;
16206
+ else if (state.settled || state.anchor !== void 0 && !serial32Precedes(ssStart, state.anchor)) code = "below_anchored_total";
16207
+ else if (state.latestBelow === void 0 || serial32Precedes(state.latestBelow, ssStart)) {
16208
+ state.latestBelow = ssStart;
16209
+ state.latestBelowRsb = rsbLength;
16210
+ }
16211
+ } else if (!state.settled && !stale(ssStart)) {
16212
+ if (state.anchor === void 0 || serial32Precedes(ssStart, state.anchor)) state.anchor = ssStart;
16213
+ if (state.latestBelow !== void 0 && !serial32Precedes(state.latestBelow, state.anchor)) {
16214
+ code = "below_anchored_total";
16215
+ ssStart = state.latestBelow;
16216
+ rsbLength = state.latestBelowRsb;
16217
+ }
16218
+ }
16219
+ }
16220
+ if (code !== void 0) {
16221
+ const reason = {
16222
+ code,
16223
+ layer: state.layer,
16224
+ total: state.total,
16225
+ rsbLength,
16226
+ ssStart,
16227
+ ...state.anchor === void 0 ? {} : { anchor: state.anchor }
16228
+ };
16229
+ this.#fecFailClosed.set(streamKey, reason);
16230
+ this.#onFecFailClosed?.({ ...reason, packetId, catalogTrackName });
16231
+ console.warn(
16232
+ `[FECManager] FEC failed closed (fec-01 6.3.9) packetId=${packetId} track=${catalogTrackName ?? "-"}: ${JSON.stringify(reason)}`
16233
+ );
16234
+ return false;
16235
+ }
16236
+ }
16237
+ return true;
16238
+ }
16239
+ /**
16240
+ * How far (in SS_Start symbols) behind the newest block a 6.3.9 anchor or
16241
+ * below-total block can still matter: the iso locator's retention in blocks
16242
+ * times K, capped at 2^30 so compared serials stay inside one half-window.
16243
+ */
16244
+ #layerAnchorHorizon(packetId) {
16245
+ const cap = 1073741824;
16246
+ let blocks;
16247
+ try {
16248
+ blocks = this.isoRetentionBlocksForPacket(packetId);
16249
+ } catch {
16250
+ blocks = void 0;
16251
+ }
16252
+ const k = this.#trackConfigs.get(packetId)?.k ?? 0;
16253
+ return blocks === void 0 || k <= 0 ? cap : Math.min(cap, blocks * k);
16254
+ }
16255
+ /**
16256
+ * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), once,
16257
+ * when it does; null stops reporting. The player wiring forwards it to
16258
+ * CmcdProducer.updateFecFailClosed.
16259
+ */
16260
+ setFecFailClosedHandler(handler) {
16261
+ this.#onFecFailClosed = handler;
16262
+ }
16263
+ /** The runtime fail-closed reason of a stream's FEC (fec-01 6.3.9), if any. */
16264
+ fecFailClosedReason(packetId, catalogTrackName) {
16265
+ return this.#fecFailClosed.get(this.#streamKey(packetId, catalogTrackName));
16266
+ }
16267
+ /**
16268
+ * Feed a repair symbol to the WASM FEC decoder.
16269
+ *
16270
+ * @returns Recovered block data if repair completed the block, else null.
16271
+ * Caller is responsible for routing recovered data and updating
16272
+ * block completion state via `markBlockCompleted()`.
16273
+ */
16116
16274
  feedRepairSymbol(packetId, ssStart, ssbLength, rsId, repairData, catalogTrackName) {
16117
16275
  this.#fecStats.repairPackets++;
16118
16276
  this.#statsForPacket(packetId).repairPackets++;
@@ -16504,6 +16662,8 @@ var FECManager = class _FECManager {
16504
16662
  this.#blockAuthoredLengths.clear();
16505
16663
  this.#blockRepairRsIds.clear();
16506
16664
  this.#blockRsbLengths.clear();
16665
+ this.#heldLayerStates.clear();
16666
+ this.#fecFailClosed.clear();
16507
16667
  this.#completedBlocks.clear();
16508
16668
  this.#cleanlyCompletedBlocks.clear();
16509
16669
  this.#repairRequestedBlocks.clear();
@@ -19335,6 +19495,8 @@ var MmtpRouter = class {
19335
19495
  // FEC Payload IDs left unread because their (owner) packetId had no
19336
19496
  // configured fec.blockProfile (see #noteUnreadableFecPayloadId).
19337
19497
  #fecPayloadIdsWithoutProfile = 0;
19498
+ // Repair packets discarded by the fec-01 4.5 block-length rule.
19499
+ #repairBlockLengthDiscards = 0;
19338
19500
  /** The staged in-place stream switch, if any (stageStreamSwitch). */
19339
19501
  #staged = null;
19340
19502
  #disposed = false;
@@ -19575,6 +19737,14 @@ var MmtpRouter = class {
19575
19737
  get fecPayloadIdsWithoutProfile() {
19576
19738
  return this.#fecPayloadIdsWithoutProfile;
19577
19739
  }
19740
+ /**
19741
+ * Repair packets discarded at admission by the fec-01 4.5 rule (RS_ID not
19742
+ * below RSB_length, or a reed-solomon SSB_length + RSB_length above 255),
19743
+ * before they touched any block state.
19744
+ */
19745
+ get repairBlockLengthDiscards() {
19746
+ return this.#repairBlockLengthDiscards;
19747
+ }
19578
19748
  get reassembler() {
19579
19749
  return this.#parser.reassembler;
19580
19750
  }
@@ -19953,13 +20123,13 @@ var MmtpRouter = class {
19953
20123
  * Feed a repair packet from MoQ (reliable QUIC) — parses MMTP repair
19954
20124
  * header and delegates to FECManager for FEC recovery.
19955
20125
  */
19956
- feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName) {
20126
+ feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName) {
19957
20127
  if (this.#disposed) return;
19958
20128
  this.#withDeferredFecPokes(() => {
19959
- this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName);
20129
+ this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName);
19960
20130
  });
19961
20131
  }
19962
- #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName) {
20132
+ #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName) {
19963
20133
  let header;
19964
20134
  try {
19965
20135
  header = parseMMTPHeader(packet);
@@ -19990,7 +20160,7 @@ var MmtpRouter = class {
19990
20160
  this.#noteUnreadableFecPayloadId(ownerPacketId, "repair");
19991
20161
  return;
19992
20162
  }
19993
- this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, "moq");
20163
+ this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, "moq", repairTrackName);
19994
20164
  }
19995
20165
  }
19996
20166
  // ── Packet FEC geometry and block profile ───────────────────────
@@ -20072,14 +20242,17 @@ var MmtpRouter = class {
20072
20242
  * the repair, the order they had on the wire, so a loss-free block completes
20073
20243
  * clean on its repair. A repair contradicting a known block is dropped.
20074
20244
  */
20075
- #handleIsoRepair(ownerPacketId, catalogTrackName, repair, source) {
20245
+ #handleIsoRepair(ownerPacketId, catalogTrackName, repair, source, repairTrackName) {
20076
20246
  const fec = this.#fecManager;
20077
20247
  if (!fec?.placeIsoRepair) {
20078
20248
  throw new Error(
20079
20249
  `[MmtpRouter] packetId=${ownerPacketId} is iso-ssbg1-v1 but its FEC manager cannot place ISO blocks`
20080
20250
  );
20081
20251
  }
20082
- if (fec.admitRepairBlockLength && !fec.admitRepairBlockLength(ownerPacketId, repair.ssbLength, repair.rsbLength, repair.rsId)) return;
20252
+ if (fec.admitRepairBlockLength && !fec.admitRepairBlockLength(ownerPacketId, repair.ssbLength, repair.rsbLength, repair.rsId)) {
20253
+ this.#repairBlockLengthDiscards++;
20254
+ return;
20255
+ }
20083
20256
  if (fec.admitRepairSymbolSize && !fec.admitRepairSymbolSize(
20084
20257
  ownerPacketId,
20085
20258
  repair.ssStart,
@@ -20087,6 +20260,7 @@ var MmtpRouter = class {
20087
20260
  repair.rsId,
20088
20261
  repair.symbolData.byteLength
20089
20262
  )) return;
20263
+ if (fec.admitRepairLayerTotal && !fec.admitRepairLayerTotal(ownerPacketId, catalogTrackName, repairTrackName, repair.ssStart, repair.rsbLength)) return;
20090
20264
  const placement = fec.placeIsoRepair(ownerPacketId, catalogTrackName, repair.ssStart, repair.ssbLength);
20091
20265
  if (placement.status !== "placed") return;
20092
20266
  const blockStart = placement.block.start;
@@ -25060,6 +25234,13 @@ var MulticastManager = class {
25060
25234
  onUndelimitedLoss(cb) {
25061
25235
  this.#fec.setUndelimitedLossHandler(cb);
25062
25236
  }
25237
+ /**
25238
+ * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
25239
+ * to CmcdProducer.updateFecFailClosed.
25240
+ */
25241
+ onFecFailClosed(cb) {
25242
+ this.#fec.setFecFailClosedHandler(cb);
25243
+ }
25063
25244
  /** End a pending hole's range repair: feed what no repair stated as spans. */
25064
25245
  closeIsoHoles(packetId, catalogTrackName, start, length) {
25065
25246
  this.#router.closeIsoHoles(packetId, catalogTrackName, start, length);
@@ -25382,7 +25563,9 @@ async function setupFecWorkerForTrack(opts) {
25382
25563
  // the local cleanup budget, but it must not use a guessed fps for timing
25383
25564
  // or classification.
25384
25565
  ...hasCatalogTiming ? { fps: 1e3 / opts.mediaUnitDurationMs } : {},
25385
- timeoutMs: deliveryWindowMs
25566
+ timeoutMs: deliveryWindowMs,
25567
+ ...opts.fecRepairLayers ? { repairLayers: opts.fecRepairLayers } : {},
25568
+ ...opts.heldRepairLayers ? { heldLayers: opts.heldRepairLayers } : {}
25386
25569
  }, opts.trackName);
25387
25570
  } catch (e) {
25388
25571
  try {
@@ -26933,6 +27116,7 @@ var CmcdProducer = class {
26933
27116
  #deltaFailRate = null;
26934
27117
  #switchMiscount = 0;
26935
27118
  #manifestStats = null;
27119
+ #fecFailClosed = null;
26936
27120
  constructor(options) {
26937
27121
  this.#onCmcdParams = options.onCmcdParams;
26938
27122
  this.#onCmcdPost = options.onCmcdPost;
@@ -26974,6 +27158,15 @@ var CmcdProducer = class {
26974
27158
  incrementSwitchMiscount() {
26975
27159
  this.#switchMiscount += 1;
26976
27160
  }
27161
+ /**
27162
+ * Record that FEC failed closed at runtime (fec-01 6.3.9). Every later
27163
+ * snapshot carries `x-bc-fec-fail-closed` (the reason code) and
27164
+ * `x-bc-fec-fail-layer` (the held layer i whose total B_i was undercut), so a
27165
+ * stream playing without FEC is told apart from one with no loss.
27166
+ */
27167
+ updateFecFailClosed(reason) {
27168
+ this.#fecFailClosed = reason;
27169
+ }
26977
27170
  updateManifestVerification(stats) {
26978
27171
  this.#manifestStats = stats;
26979
27172
  }
@@ -27011,6 +27204,10 @@ var CmcdProducer = class {
27011
27204
  if (this.#playMode !== null) {
27012
27205
  params["x-bc-play-mode"] = this.#playMode;
27013
27206
  }
27207
+ if (this.#fecFailClosed) {
27208
+ params["x-bc-fec-fail-closed"] = this.#fecFailClosed.code;
27209
+ params["x-bc-fec-fail-layer"] = this.#fecFailClosed.layer;
27210
+ }
27014
27211
  if (this.#playMode !== null && this.#playMode !== "single-track" && this.#deltaFailRate !== null) {
27015
27212
  params["x-bc-delta-fail-rate"] = parseFloat(this.#deltaFailRate.toFixed(4));
27016
27213
  }