@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockcast/mmt-container",
3
- "version": "0.4.0-main.bbdfdbf39ded",
3
+ "version": "0.4.0-main.bd9f80b4a95e",
4
4
  "description": "MMTP/LOC container parsing for MMT over MoQ and SSM",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -173,10 +173,10 @@
173
173
  "test:watch": "vitest"
174
174
  },
175
175
  "dependencies": {
176
- "@blockcast/fec-worker": "0.4.0-main.bbdfdbf39ded",
177
- "@blockcast/mmt-base": "0.4.0-main.bbdfdbf39ded",
178
- "@blockcast/mmt-fec": "0.4.0-main.bbdfdbf39ded",
179
- "@blockcast/mmt-manifest-verify": "0.4.0-main.bbdfdbf39ded",
176
+ "@blockcast/fec-worker": "0.4.0-main.bd9f80b4a95e",
177
+ "@blockcast/mmt-base": "0.4.0-main.bd9f80b4a95e",
178
+ "@blockcast/mmt-fec": "0.4.0-main.bd9f80b4a95e",
179
+ "@blockcast/mmt-manifest-verify": "0.4.0-main.bd9f80b4a95e",
180
180
  "@noble/curves": "^1.9.7",
181
181
  "@noble/hashes": "^1.8.0",
182
182
  "ajv": "^8.17.1",
@@ -6,7 +6,7 @@
6
6
  "additionalProperties": false,
7
7
  "required": ["version", "tracks"],
8
8
  "properties": {
9
- "version": { "const": 1 },
9
+ "version": { "enum": [1, "draft-01"], "description": "MSF catalog version: the integer 1, or the \"draft-01\" tag the draft-ramadan-moq-*-01 examples carry." },
10
10
  "streamingFormat": { "const": "mmtp" },
11
11
  "streamingFormatVersion": { "type": "string", "minLength": 1 },
12
12
  "supportsDeltaUpdates": { "type": "boolean" },
@@ -358,15 +358,23 @@
358
358
  "type": "object",
359
359
  "additionalProperties": false,
360
360
  "required": ["type"],
361
- "description": "draft-ramadan-moq-multicast-01 4.2.1. discovery is OPTIONAL: omitted with a hostname relay means dns, omitted with no relay means DRIAD. dns and manual name their relay.",
361
+ "description": "draft-ramadan-moq-multicast-01 4.2.1. discovery is OPTIONAL: omitted with a hostname relay means dns, omitted with no relay means DRIAD. dns and manual name their relay; driad MUST omit it.",
362
362
  "properties": {
363
363
  "type": { "const": "amt" },
364
364
  "discovery": { "enum": ["dns", "driad", "manual"] },
365
365
  "relay": { "type": "string", "minLength": 1 },
366
366
  "port": { "type": "integer", "minimum": 1, "maximum": 65535 }
367
367
  },
368
- "if": { "properties": { "discovery": { "enum": ["dns", "manual"] } }, "required": ["discovery"] },
369
- "then": { "properties": { "relay": true }, "required": ["relay"] }
368
+ "allOf": [
369
+ {
370
+ "if": { "properties": { "discovery": { "enum": ["dns", "manual"] } }, "required": ["discovery"] },
371
+ "then": { "properties": { "relay": true }, "required": ["relay"] }
372
+ },
373
+ {
374
+ "if": { "properties": { "discovery": { "const": "driad" } }, "required": ["discovery"] },
375
+ "then": { "not": { "properties": { "relay": true }, "required": ["relay"] } }
376
+ }
377
+ ]
370
378
  },
371
379
  {
372
380
  "type": "object",
@@ -359,11 +359,10 @@ export type AmtDiscovery = "dns" | "driad" | "manual";
359
359
  * `"manual"` a literal relay, and omitted means `"dns"` when `relay` is a
360
360
  * hostname (DRIAD when `relay` is absent too). `"dns"` and `"manual"` require
361
361
  * `relay`; that relay is the one the player joins. Under `discovery: "driad"` the relay is resolved at
362
- * runtime, so `relay` is OPTIONAL and, when present, only a discovery hint
363
- * (e.g. the `amtFallback.relayDns` name the derived path carries over): readers
364
- * do not join it (`findAmtRelay` in packages/transport
365
- * multicast-catalog-policy.ts and `catalogAmtNetworkSource` in
366
- * catalog-network-source.ts both skip it), so a DRIAD entry never pins a relay.
362
+ * runtime and `relay` MUST be omitted (draft -01 4.2.1); the schema, the
363
+ * runtime validator and `multicastFromConfig` all reject one. The tolerant
364
+ * readers (`findAmtRelay`, `catalogAmtNetworkSource`) still skip a DRIAD
365
+ * entry's relay, so a DRIAD entry never pins a relay.
367
366
  * `port` is OPTIONAL on the wire: the join boundary itself has no default, but
368
367
  * every reader resolves one before that boundary, so a manual relay without a
369
368
  * port joins on RFC 7450's 2268 rather than failing (BLO-38176).
@@ -732,6 +731,7 @@ export type CmsfCatalogErrorCode =
732
731
  | "multicast_track"
733
732
  | "multicast_packet_id"
734
733
  | "multicast_relay_address"
734
+ | "multicast_network_source"
735
735
  | "archive_object"
736
736
  | "archive_origin";
737
737
 
@@ -750,6 +750,18 @@ function catalogError(code: CmsfCatalogErrorCode, path: string, message: string)
750
750
  throw new CmsfCatalogValidationError(code, path, message);
751
751
  }
752
752
 
753
+ // draft-ramadan-moq-multicast-01 4.2.1: DRIAD supplies the relay
754
+ // candidates, so a `discovery: "driad"` entry MUST omit `relay`.
755
+ function validateNetworkSourceRelays(sources: unknown, path: string): void {
756
+ if (!Array.isArray(sources)) return;
757
+ sources.forEach((source, i) => {
758
+ const s = source as Record<string, unknown> | null;
759
+ if (s?.["type"] === "amt" && s["discovery"] === "driad" && s["relay"] !== undefined) {
760
+ catalogError("multicast_network_source", `${path}[${i}].relay`, 'relay must be omitted with discovery "driad"');
761
+ }
762
+ });
763
+ }
764
+
753
765
  /**
754
766
  * Validate the common CMSF shape and the MMTP required-field profile.
755
767
  * `catalogNamespace`, the namespace of the catalog track, sharpens the
@@ -767,7 +779,8 @@ export function validateCmsfMmtpCatalog(
767
779
  // IETF-draft catalogs (cast `ladder_catalog.rs`, moq-server
768
780
  // `catalog-synthesizer.ts`, consumed by the hang player) carry a string
769
781
  // version tag such as "draft-ietf-moq-catalogformat-01" instead of the CMSF
770
- // `version: 1` integer. Nothing keys behavior off the catalog version, so
782
+ // `version: 1` integer, and the draft-ramadan-moq-*-01 examples carry
783
+ // "draft-01". Nothing keys behavior off the catalog version, so
771
784
  // normalize the tag to a number rather than rejecting the whole catalog —
772
785
  // mirrors the relay (dual-stack-relay `bridge/catalog.rs`
773
786
  // `deserialize_optional_u32_lenient`, #825) and moqtail-ts
@@ -777,7 +790,7 @@ export function validateCmsfMmtpCatalog(
777
790
  typeof rawVersion === "string"
778
791
  ? Number.isFinite(Number(rawVersion))
779
792
  ? Number(rawVersion)
780
- : rawVersion.startsWith("draft-ietf-moq-catalogformat")
793
+ : rawVersion.startsWith("draft-ietf-moq-catalogformat") || rawVersion === "draft-01"
781
794
  ? 1
782
795
  : NaN
783
796
  : rawVersion;
@@ -1053,11 +1066,16 @@ export function validateCmsfMmtpCatalog(
1053
1066
 
1054
1067
  const multicast = catalog["multicast"];
1055
1068
  if (typeof multicast === "object" && multicast !== null && !Array.isArray(multicast)) {
1069
+ validateNetworkSourceRelays((multicast as Record<string, unknown>)["networkSource"], "$.multicast.networkSource");
1056
1070
  const endpoints = (multicast as Record<string, unknown>)["endpoints"];
1057
1071
  if (Array.isArray(endpoints)) {
1058
1072
  for (let endpointIndex = 0; endpointIndex < endpoints.length; endpointIndex++) {
1059
1073
  const endpoint = endpoints[endpointIndex];
1060
1074
  if (typeof endpoint !== "object" || endpoint === null || Array.isArray(endpoint)) continue;
1075
+ validateNetworkSourceRelays(
1076
+ (endpoint as Record<string, unknown>)["networkSource"],
1077
+ `$.multicast.endpoints[${endpointIndex}].networkSource`,
1078
+ );
1061
1079
  // The endpoint relay moved to `multicast.networkSource[{type:"amt",relay}]`.
1062
1080
  // Refuse rather than ignore: a dropped relay strands an AMT endpoint
1063
1081
  // with no tunnel and reads as a gateway failure, not a bad catalog.
@@ -53,11 +53,10 @@ function normalizePort(value: unknown): number | undefined {
53
53
  * and a non-blank relay, or `undefined` when the catalog advertises none —
54
54
  * callers fall back to native multicast (or their own explicit relay config).
55
55
  *
56
- * A `discovery: "driad"` entry is skipped even when it names a `relay`: that
57
- * string is the `_amt._udp` DNS name a runtime RFC 8777 lookup resolves, not
58
- * an address to dial, and the emitter derives exactly that shape from
59
- * `amtFallback: {discovery: "driad", relayDns}`. Returning it would turn a
60
- * catalog that asked for DRIAD into a manual join against an unroutable name.
56
+ * A `discovery: "driad"` entry is skipped even when it names a `relay`. Draft
57
+ * -01 4.2.1 forbids that shape and `validateCmsfMmtpCatalog` rejects it, but
58
+ * this reader stays tolerant: returning it would turn a catalog that asked
59
+ * for DRIAD into a manual join against an unroutable name.
61
60
  * `findAmtRelay` in `@blockcast/mmt-transport` applies the same rule — the two
62
61
  * readers of one field must agree on which entries are dialable.
63
62
  *
@@ -15,6 +15,7 @@
15
15
 
16
16
  import type { FecTrackStats } from '@blockcast/fec-worker'
17
17
  import type { ManifestVerificationStats } from '@blockcast/mmt-manifest-verify'
18
+ import type { FecFailClosedReason } from './fec-manager.js'
18
19
 
19
20
  // ---------------------------------------------------------------------------
20
21
  // Types
@@ -153,6 +154,7 @@ export class CmcdProducer {
153
154
  #deltaFailRate: number | null = null
154
155
  #switchMiscount = 0
155
156
  #manifestStats: ManifestVerificationStats | null = null
157
+ #fecFailClosed: FecFailClosedReason | null = null
156
158
 
157
159
  constructor(options: CmcdProducerOptions) {
158
160
  this.#onCmcdParams = options.onCmcdParams
@@ -200,6 +202,16 @@ export class CmcdProducer {
200
202
  this.#switchMiscount += 1
201
203
  }
202
204
 
205
+ /**
206
+ * Record that FEC failed closed at runtime (fec-01 6.3.9). Every later
207
+ * snapshot carries `x-bc-fec-fail-closed` (the reason code) and
208
+ * `x-bc-fec-fail-layer` (the held layer i whose total B_i was undercut), so a
209
+ * stream playing without FEC is told apart from one with no loss.
210
+ */
211
+ updateFecFailClosed(reason: FecFailClosedReason): void {
212
+ this.#fecFailClosed = reason
213
+ }
214
+
203
215
  updateManifestVerification(stats: ManifestVerificationStats): void {
204
216
  this.#manifestStats = stats
205
217
  }
@@ -248,6 +260,11 @@ export class CmcdProducer {
248
260
  params['x-bc-play-mode'] = this.#playMode
249
261
  }
250
262
 
263
+ if (this.#fecFailClosed) {
264
+ params['x-bc-fec-fail-closed'] = this.#fecFailClosed.code
265
+ params['x-bc-fec-fail-layer'] = this.#fecFailClosed.layer
266
+ }
267
+
251
268
  // Delta-fail-rate is only meaningful when a delta track exists.
252
269
  if (
253
270
  this.#playMode !== null &&
@@ -273,6 +273,64 @@ export interface FECManagerConfig {
273
273
  * block `unknown` (fail-closed: protected).
274
274
  */
275
275
  geometry?: BlockClassifierGeometry
276
+ /**
277
+ * fec-01 6.3.9: the source track's base repair layers (catalog
278
+ * `TrackFecParams.repairLayers`). Layer i's held total is
279
+ * B_i = rsIdOffset + repairSymbols. Absent: no anchored check.
280
+ */
281
+ repairLayers?: readonly FecRepairLayer[]
282
+ /** The base layers this receiver holds. Defaults to layer 0 alone. */
283
+ heldLayers?: readonly number[]
284
+ }
285
+
286
+ /** One base repair layer, as `assembleRepairLayers` resolves it. */
287
+ export interface FecRepairLayer {
288
+ layer: number
289
+ repairTrackName: string
290
+ rsIdOffset: number
291
+ repairSymbols: number
292
+ }
293
+
294
+ /**
295
+ * Why a source track's FEC failed closed at runtime (fec-01 6.3.9): a repair
296
+ * packet stated an RSB_length below a held layer's total B_i on that layer's
297
+ * own repair track (`below_own_track_total`), or at or after the anchor, the
298
+ * earliest block in SS_Start serial order whose repair carried >= B_i
299
+ * (`below_anchored_total`). Repair for the track is refused from then on.
300
+ */
301
+ export interface FecFailClosedReason {
302
+ code: 'below_own_track_total' | 'below_anchored_total'
303
+ layer: number
304
+ total: number
305
+ rsbLength: number
306
+ ssStart: number
307
+ anchor?: number
308
+ }
309
+
310
+ /** A {@link FecFailClosedReason} with the stream it closed, as reported to the fail-closed handler. */
311
+ export interface FecFailClosedEvent extends FecFailClosedReason {
312
+ packetId: number
313
+ catalogTrackName: string | undefined
314
+ }
315
+
316
+ interface HeldLayerState {
317
+ layer: number
318
+ repairTrackName: string
319
+ total: number
320
+ /** Earliest (serial order) block start whose repair carried >= total. */
321
+ anchor?: number
322
+ /** Latest (serial order) block start whose repair carried < total. */
323
+ latestBelow?: number
324
+ /** RSB_length that latestBelow's repair carried, for the fail-closed reason. */
325
+ latestBelowRsb?: number
326
+ /** Newest block start seen; anchor and latestBelow are retired behind it. */
327
+ newest?: number
328
+ /**
329
+ * The anchor fell behind the horizon, so no block that can still arrive
330
+ * precedes it: every later packet must carry >= total. Its serial is no
331
+ * longer compared, so SS_Start wrapping past it cannot misorder it.
332
+ */
333
+ settled?: boolean
276
334
  }
277
335
 
278
336
  interface ResolvedFECTrackConfig {
@@ -286,6 +344,8 @@ interface ResolvedFECTrackConfig {
286
344
  trackKind?: TrackKind
287
345
  codec?: string
288
346
  geometry?: BlockClassifierGeometry
347
+ repairLayers?: readonly FecRepairLayer[]
348
+ heldLayers?: readonly number[]
289
349
  }
290
350
 
291
351
  /** Which symbol path completed a short block. */
@@ -483,6 +543,11 @@ export class FECManager {
483
543
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
484
544
  // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
485
545
  #blockRsbLengths = new Map<string, number>()
546
+ /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
547
+ #heldLayerStates = new Map<string, HeldLayerState[]>()
548
+ /** Streams whose FEC failed closed at runtime (fec-01 6.3.9). */
549
+ #fecFailClosed = new Map<string, FecFailClosedReason>()
550
+ #onFecFailClosed: ((event: FecFailClosedEvent) => void) | null = null
486
551
  // Blocks already recovered — prevents late source symbols from restarting timeouts.
487
552
  // WASM removes blocks after recovery; late symbols create empty blocks returning null,
488
553
  // which would falsely start new timeouts without this guard.
@@ -2136,6 +2201,23 @@ export class FECManager {
2136
2201
  ...((config.geometry ?? previous.geometry) === undefined
2137
2202
  ? {}
2138
2203
  : { geometry: config.geometry ?? previous.geometry }),
2204
+ ...((config.repairLayers ?? previous.repairLayers) === undefined
2205
+ ? {}
2206
+ : { repairLayers: config.repairLayers ?? previous.repairLayers }),
2207
+ ...((config.heldLayers ?? previous.heldLayers) === undefined
2208
+ ? {}
2209
+ : { heldLayers: config.heldLayers ?? previous.heldLayers }),
2210
+ }
2211
+ if (
2212
+ // By content: a catalog refresh rebuilds equal arrays, and forgetting
2213
+ // the anchors on one would fail open.
2214
+ JSON.stringify(next.repairLayers) !== JSON.stringify(previous.repairLayers) ||
2215
+ JSON.stringify(next.heldLayers) !== JSON.stringify(previous.heldLayers)
2216
+ ) {
2217
+ // A different layer set is a different set of totals to anchor.
2218
+ for (const key of [...this.#heldLayerStates.keys()]) {
2219
+ if (this.#belongsToPacket(key, packetId)) this.#heldLayerStates.delete(key)
2220
+ }
2139
2221
  }
2140
2222
  if (!hasCatalogTiming) {
2141
2223
  // A missing/zero span has no catalog deadline. Keep an explicitly
@@ -2438,6 +2520,8 @@ export class FECManager {
2438
2520
  resetMap(this.#blockAuthoredLengths)
2439
2521
  resetMap(this.#blockRepairRsIds)
2440
2522
  resetMap(this.#blockRsbLengths)
2523
+ resetMap(this.#heldLayerStates)
2524
+ resetMap(this.#fecFailClosed)
2441
2525
  resetMap(this.#blockPathCounts)
2442
2526
  resetMap(this.#blockAnchorsMs)
2443
2527
  resetMap(this.#blockCatalogTrackNames)
@@ -3946,25 +4030,6 @@ export class FECManager {
3946
4030
  return recovered
3947
4031
  }
3948
4032
 
3949
- /**
3950
- * Feed a repair symbol to the WASM FEC decoder.
3951
- *
3952
- * @returns Recovered block data if repair completed the block, else null.
3953
- * Caller is responsible for routing recovered data and updating
3954
- * block completion state via `markBlockCompleted()`.
3955
- */
3956
- /**
3957
- * Whether a repair symbol of `byteLength` bytes is a valid member of a
3958
- * `packetId` block: every repair symbol is exactly the track's T. A symbol of
3959
- * any other size is counted on `repairSymbolSizeMismatches`, warned (rate
3960
- * limited) and refused. The router calls this before the symbol takes any
3961
- * other part in block state (placement, first-arrival dedup, completed-block
3962
- * accounting), so a malformed repair is counted whatever its arrival order:
3963
- * judged after dedup, one landing on an already-complete block, or behind a
3964
- * valid copy from the other transport, was swallowed as a duplicate and never
3965
- * counted (BLO-48306). A packetId with no configured block profile admits
3966
- * nothing here; its repair is dropped upstream as unreadable.
3967
- */
3968
4033
  /**
3969
4034
  * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
3970
4035
  * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
@@ -3983,6 +4048,18 @@ export class FECManager {
3983
4048
  return ssbLength + rsbLength <= RS_MAX_BLOCK_SYMBOLS
3984
4049
  }
3985
4050
 
4051
+ /**
4052
+ * Whether a repair symbol of `byteLength` bytes is a valid member of a
4053
+ * `packetId` block: every repair symbol is exactly the track's T. A symbol of
4054
+ * any other size is counted on `repairSymbolSizeMismatches`, warned (rate
4055
+ * limited) and refused. The router calls this before the symbol takes any
4056
+ * other part in block state (placement, first-arrival dedup, completed-block
4057
+ * accounting), so a malformed repair is counted whatever its arrival order:
4058
+ * judged after dedup, one landing on an already-complete block, or behind a
4059
+ * valid copy from the other transport, was swallowed as a duplicate and never
4060
+ * counted (BLO-48306). A packetId with no configured block profile admits
4061
+ * nothing here; its repair is dropped upstream as unreadable.
4062
+ */
3986
4063
  admitRepairSymbolSize(
3987
4064
  packetId: number,
3988
4065
  ssStart: number,
@@ -4004,6 +4081,140 @@ export class FECManager {
4004
4081
  return true
4005
4082
  }
4006
4083
 
4084
+ /**
4085
+ * fec-01 6.3.9 receiver check, run on a repair packet after the 4.5 discard
4086
+ * and the size check, before it places a block. For each held layer i with
4087
+ * total B_i = O_i + P_i: the anchor is the earliest block, in SS_Start
4088
+ * serial order, whose repair carried RSB_length >= B_i. The source track
4089
+ * fails closed on (a) a packet on layer i's own repair track (i > 0) below
4090
+ * B_i, or (b) any packet of the instance at or after the anchor below B_i.
4091
+ * Blocks before the anchor (pre-append) stay valid at the previous total. A
4092
+ * packet on a repair track the catalog does not list is discarded and
4093
+ * anchors nothing. `repairTrackName` is the subscribed repair track, never
4094
+ * inferred from RS_ID; without it only (b) runs. Returns false when the
4095
+ * repair must be dropped, including every repair once the track failed.
4096
+ */
4097
+ admitRepairLayerTotal(
4098
+ packetId: number,
4099
+ catalogTrackName: string | undefined,
4100
+ repairTrackName: string | undefined,
4101
+ ssStart: number,
4102
+ rsbLength: number,
4103
+ ): boolean {
4104
+ const streamKey = this.#streamKey(packetId, catalogTrackName)
4105
+ if (this.#fecFailClosed.has(streamKey)) return false
4106
+ const config = this.#trackConfigs.get(packetId)
4107
+ const layers = config?.repairLayers
4108
+ if (layers === undefined || layers.length === 0) return true
4109
+ if (repairTrackName !== undefined && !layers.some((l) => l.repairTrackName === repairTrackName)) {
4110
+ return false
4111
+ }
4112
+ let states = this.#heldLayerStates.get(streamKey)
4113
+ if (states === undefined) {
4114
+ const held = new Set(config!.heldLayers ?? [0])
4115
+ states = layers
4116
+ .filter((l) => held.has(l.layer))
4117
+ .map((l) => ({ layer: l.layer, repairTrackName: l.repairTrackName, total: l.rsIdOffset + l.repairSymbols }))
4118
+ this.#heldLayerStates.set(streamKey, states)
4119
+ }
4120
+ const horizon = this.#layerAnchorHorizon(packetId)
4121
+ // A repair may run ahead of the media, but one more than `horizon` past the
4122
+ // source frontier must not move the held-layer state: advancing `newest` on
4123
+ // it would retire every real anchor and skip this check until traffic caught
4124
+ // up. Such a repair is still judged below the total: it is on its own track,
4125
+ // or after any anchor by definition. With no anchor yet it says nothing.
4126
+ // It is still admitted: in iso the frontier only moves when a repair places
4127
+ // held sources, so dropping it would stall recovery after a long outage.
4128
+ // IsoBlockLocator.placeRepair may still refuse the same repair as `ahead`:
4129
+ // it measures from `newest`, which held sources move, not from this frontier.
4130
+ const frontier = this.#sourceFrontiers.get(streamKey)?.sbn
4131
+ const farAhead =
4132
+ frontier !== undefined && serial32Precedes(frontier, ssStart) && serial32Distance(frontier, ssStart) > horizon
4133
+ for (const state of states) {
4134
+ let code: FecFailClosedReason['code'] | undefined
4135
+ if (farAhead) {
4136
+ if (rsbLength < state.total) {
4137
+ if (state.layer > 0 && repairTrackName === state.repairTrackName) code = 'below_own_track_total'
4138
+ else if (state.anchor !== undefined || state.settled) code = 'below_anchored_total'
4139
+ }
4140
+ } else {
4141
+ // Serials more than `horizon` behind the newest block are retired, so
4142
+ // every serial still compared sits inside one half-window and SS_Start
4143
+ // wrapping on a long-running stream cannot reorder them.
4144
+ if (state.newest === undefined || serial32Precedes(state.newest, ssStart)) state.newest = ssStart
4145
+ const stale = (s: number) => serial32Distance(s, state.newest!) > horizon
4146
+ if (state.latestBelow !== undefined && stale(state.latestBelow)) {
4147
+ delete state.latestBelow
4148
+ delete state.latestBelowRsb
4149
+ }
4150
+ if (state.anchor !== undefined && stale(state.anchor)) state.settled = true
4151
+ if (rsbLength < state.total) {
4152
+ if (state.layer > 0 && repairTrackName === state.repairTrackName) code = 'below_own_track_total'
4153
+ else if (stale(ssStart)) continue // past retention: undecodable, anchors nothing
4154
+ else if (state.settled || (state.anchor !== undefined && !serial32Precedes(ssStart, state.anchor))) code = 'below_anchored_total'
4155
+ else if (state.latestBelow === undefined || serial32Precedes(state.latestBelow, ssStart)) {
4156
+ state.latestBelow = ssStart
4157
+ state.latestBelowRsb = rsbLength
4158
+ }
4159
+ } else if (!state.settled && !stale(ssStart)) {
4160
+ if (state.anchor === undefined || serial32Precedes(ssStart, state.anchor)) state.anchor = ssStart
4161
+ if (state.latestBelow !== undefined && !serial32Precedes(state.latestBelow, state.anchor)) {
4162
+ code = 'below_anchored_total'
4163
+ ssStart = state.latestBelow
4164
+ rsbLength = state.latestBelowRsb!
4165
+ }
4166
+ }
4167
+ }
4168
+ if (code !== undefined) {
4169
+ const reason: FecFailClosedReason = {
4170
+ code, layer: state.layer, total: state.total, rsbLength, ssStart,
4171
+ ...(state.anchor === undefined ? {} : { anchor: state.anchor }),
4172
+ }
4173
+ this.#fecFailClosed.set(streamKey, reason)
4174
+ this.#onFecFailClosed?.({ ...reason, packetId, catalogTrackName })
4175
+ console.warn(
4176
+ `[FECManager] FEC failed closed (fec-01 6.3.9) packetId=${packetId} track=${catalogTrackName ?? '-'}: ${JSON.stringify(reason)}`,
4177
+ )
4178
+ return false
4179
+ }
4180
+ }
4181
+ return true
4182
+ }
4183
+
4184
+ /**
4185
+ * How far (in SS_Start symbols) behind the newest block a 6.3.9 anchor or
4186
+ * below-total block can still matter: the iso locator's retention in blocks
4187
+ * times K, capped at 2^30 so compared serials stay inside one half-window.
4188
+ */
4189
+ #layerAnchorHorizon(packetId: number): number {
4190
+ const cap = 0x40000000
4191
+ let blocks: number | undefined
4192
+ try { blocks = this.isoRetentionBlocksForPacket(packetId) } catch { blocks = undefined }
4193
+ const k = this.#trackConfigs.get(packetId)?.k ?? 0
4194
+ return blocks === undefined || k <= 0 ? cap : Math.min(cap, blocks * k)
4195
+ }
4196
+
4197
+ /**
4198
+ * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), once,
4199
+ * when it does; null stops reporting. The player wiring forwards it to
4200
+ * CmcdProducer.updateFecFailClosed.
4201
+ */
4202
+ setFecFailClosedHandler(handler: ((event: FecFailClosedEvent) => void) | null): void {
4203
+ this.#onFecFailClosed = handler
4204
+ }
4205
+
4206
+ /** The runtime fail-closed reason of a stream's FEC (fec-01 6.3.9), if any. */
4207
+ fecFailClosedReason(packetId: number, catalogTrackName?: string): FecFailClosedReason | undefined {
4208
+ return this.#fecFailClosed.get(this.#streamKey(packetId, catalogTrackName))
4209
+ }
4210
+
4211
+ /**
4212
+ * Feed a repair symbol to the WASM FEC decoder.
4213
+ *
4214
+ * @returns Recovered block data if repair completed the block, else null.
4215
+ * Caller is responsible for routing recovered data and updating
4216
+ * block completion state via `markBlockCompleted()`.
4217
+ */
4007
4218
  feedRepairSymbol(
4008
4219
  packetId: number,
4009
4220
  ssStart: number,
@@ -4561,6 +4772,8 @@ export class FECManager {
4561
4772
  this.#blockAuthoredLengths.clear()
4562
4773
  this.#blockRepairRsIds.clear()
4563
4774
  this.#blockRsbLengths.clear()
4775
+ this.#heldLayerStates.clear()
4776
+ this.#fecFailClosed.clear()
4564
4777
  this.#completedBlocks.clear()
4565
4778
  this.#cleanlyCompletedBlocks.clear()
4566
4779
  this.#repairRequestedBlocks.clear()
@@ -16,6 +16,7 @@
16
16
  import { parseFecBlockProfile, type FecBlockProfile } from '@blockcast/mmt-base'
17
17
  import type { FecWorkerClient, FecTrackConfig } from '@blockcast/fec-worker'
18
18
  import type { MulticastManager } from './multicast-manager.js'
19
+ import type { FecRepairLayer } from './fec-manager.js'
19
20
  import {
20
21
  deriveFecRetentionBlocks,
21
22
  LOCAL_FEC_RETENTION_BLOCKS,
@@ -80,6 +81,13 @@ export interface FecWorkerSetupOptions {
80
81
  mediaUnitDurationMs?: number
81
82
  /** Optional repair track name (MoQ). Forwarded to FecTrackConfig. */
82
83
  repairTrackName?: string
84
+ /**
85
+ * The catalog's base repair layers (`TrackFecParams.repairLayers`) and the
86
+ * layers this receiver holds (default `[0]`), for the fec-01 6.3.9 anchored
87
+ * RSB_length check. Absent layers: no check.
88
+ */
89
+ fecRepairLayers?: readonly FecRepairLayer[]
90
+ heldRepairLayers?: readonly number[]
83
91
  /** Audio sample rate (optional — audio tracks only). */
84
92
  sampleRate?: number
85
93
  /** Codec string (optional; "unknown" is acceptable for first setup). */
@@ -267,6 +275,8 @@ export async function setupFecWorkerForTrack(
267
275
  // or classification.
268
276
  ...(hasCatalogTiming ? { fps: 1000 / opts.mediaUnitDurationMs! } : {}),
269
277
  timeoutMs: deliveryWindowMs,
278
+ ...(opts.fecRepairLayers ? { repairLayers: opts.fecRepairLayers } : {}),
279
+ ...(opts.heldRepairLayers ? { heldLayers: opts.heldRepairLayers } : {}),
270
280
  }, opts.trackName)
271
281
  } catch (e) {
272
282
  // The manager refused the registration (for example the stream still
package/src/index.ts CHANGED
@@ -268,6 +268,9 @@ export {
268
268
  type UndelimitedIsoLoss,
269
269
  type FecBlockResolution,
270
270
  type RepairVia,
271
+ type FecRepairLayer,
272
+ type FecFailClosedReason,
273
+ type FecFailClosedEvent,
271
274
  } from './fec-manager.js'
272
275
 
273
276
  // MMTP Router (packet processing + frame routing)
@@ -59,7 +59,7 @@ export type IsoRepairPlacement<T> =
59
59
  readonly hole?: { readonly block: IsoBlockRange; readonly lostSsId: number }
60
60
  }
61
61
  /** Not a block this stream can use; the repair symbol is dropped. */
62
- | { readonly status: 'conflict' | 'overlap' | 'stale'; readonly reason: string }
62
+ | { readonly status: 'conflict' | 'overlap' | 'stale' | 'ahead'; readonly reason: string }
63
63
 
64
64
  /**
65
65
  * Retention: the locator is never without one. Every call that can grow it
@@ -254,6 +254,14 @@ export class IsoBlockLocator<T> {
254
254
  * known block (a different length, or an overlap with another block or a
255
255
  * span) fails closed: the repair symbol is dropped and no block changes.
256
256
  * A newly stated block retires behind its SS_Start (see the class note).
257
+ * A block so far past `newest` that stating it would retire the position
258
+ * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
259
+ * this is slightly conservative (retirement measures that block from its
260
+ * last SS_ID), costing one dropped repair. Placing it would turn everything
261
+ * between into a repair-less span and leave every real repair behind it
262
+ * `stale`. Sources move `newest` (`hold`, `observe`), so after a real outage
263
+ * the first source back brings the next repair inside the horizon; until one
264
+ * arrives, a stream's repairs alone cannot pass it.
257
265
  */
258
266
  placeRepair(start: number, length: number): IsoRepairPlacement<T> {
259
267
  if (!Number.isSafeInteger(length) || length <= 0 || length > this.#kMax) {
@@ -300,6 +308,9 @@ export class IsoBlockLocator<T> {
300
308
  }
301
309
  }
302
310
  }
311
+ if (this.#newest !== undefined && isoBlocksBehindLowerBound(this.#newest, start, this.#kMax) > this.#retentionBlocks) {
312
+ return { status: 'ahead', reason: `repair block ${start}+${length} is past the retention horizon ahead of ${this.#newest}` }
313
+ }
303
314
  let span: { block: IsoBlockRange; placed: IsoPlacedSource<T>[] } | undefined
304
315
  let hole: { block: IsoBlockRange; lostSsId: number } | undefined
305
316
  if (this.#coverageEnd === undefined) {