@blockcast/mmt-container 0.4.0-main.d6f2737828fc → 0.4.0

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 (102) hide show
  1. package/README.md +12 -9
  2. package/dist/browser-runtime.js +14219 -13716
  3. package/dist/browser-runtime.js.map +4 -4
  4. package/dist/carp-catalog.d.ts +1 -12
  5. package/dist/carp-catalog.d.ts.map +1 -1
  6. package/dist/carp-catalog.js +14 -6
  7. package/dist/carp-catalog.js.map +4 -4
  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 +101 -42
  11. package/dist/catalog-fec-params.js.map +4 -4
  12. package/dist/catalog-network-source.js +4 -6
  13. package/dist/catalog-network-source.js.map +4 -4
  14. package/dist/cmcd-producer.d.ts.map +1 -1
  15. package/dist/cmcd-producer.js +0 -4
  16. package/dist/cmcd-producer.js.map +2 -2
  17. package/dist/delivery-catalog.d.ts +124 -0
  18. package/dist/delivery-catalog.d.ts.map +1 -0
  19. package/dist/delivery-catalog.js +1867 -0
  20. package/dist/delivery-catalog.js.map +7 -0
  21. package/dist/fec-manager.d.ts +17 -4
  22. package/dist/fec-manager.d.ts.map +1 -1
  23. package/dist/fec-manager.js +41 -20
  24. package/dist/fec-manager.js.map +4 -4
  25. package/dist/fec-state.d.ts +3 -2
  26. package/dist/fec-state.d.ts.map +1 -1
  27. package/dist/fec-state.js +17 -15
  28. package/dist/fec-state.js.map +4 -4
  29. package/dist/fec-worker-setup.d.ts +2 -8
  30. package/dist/fec-worker-setup.d.ts.map +1 -1
  31. package/dist/fec-worker-setup.js +12 -62
  32. package/dist/fec-worker-setup.js.map +4 -4
  33. package/dist/index.d.ts +2 -1
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +10 -0
  36. package/dist/index.js.map +2 -2
  37. package/dist/iso-block-locator.js +4 -6
  38. package/dist/iso-block-locator.js.map +4 -4
  39. package/dist/mfu-reassembler.js +27 -29
  40. package/dist/mfu-reassembler.js.map +4 -4
  41. package/dist/mmtp-container-parser.d.ts +9 -11
  42. package/dist/mmtp-container-parser.d.ts.map +1 -1
  43. package/dist/mmtp-container-parser.js +107 -98
  44. package/dist/mmtp-container-parser.js.map +4 -4
  45. package/dist/mmtp-container-parser.no-modules.js +133 -108
  46. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  47. package/dist/mmtp-decode-pipeline.js +107 -98
  48. package/dist/mmtp-decode-pipeline.js.map +4 -4
  49. package/dist/mmtp-router.d.ts +34 -14
  50. package/dist/mmtp-router.d.ts.map +1 -1
  51. package/dist/mmtp-router.js +143 -113
  52. package/dist/mmtp-router.js.map +4 -4
  53. package/dist/multicast-input.js +4 -6
  54. package/dist/multicast-input.js.map +4 -4
  55. package/dist/multicast-manager.d.ts +39 -3
  56. package/dist/multicast-manager.d.ts.map +1 -1
  57. package/dist/multicast-manager.js +264 -156
  58. package/dist/multicast-manager.js.map +4 -4
  59. package/dist/multicast-transport.js +14 -14
  60. package/dist/multicast-transport.js.map +4 -4
  61. package/dist/multicast-unwrap.js +32 -34
  62. package/dist/multicast-unwrap.js.map +4 -4
  63. package/dist/no-modules.js +130 -107
  64. package/dist/no-modules.js.map +4 -4
  65. package/dist/repair-fetch.d.ts +86 -2
  66. package/dist/repair-fetch.d.ts.map +1 -1
  67. package/dist/repair-fetch.js +86 -17
  68. package/dist/repair-fetch.js.map +4 -4
  69. package/dist/repair-layers.js +4 -6
  70. package/dist/repair-layers.js.map +4 -4
  71. package/dist/signaling.js +5 -7
  72. package/dist/signaling.js.map +4 -4
  73. package/dist/timestamp-codec.js +27 -29
  74. package/dist/timestamp-codec.js.map +4 -4
  75. package/dist/wasm-mfu-reassembler.js +4 -6
  76. package/dist/wasm-mfu-reassembler.js.map +4 -4
  77. package/dist/wasm-mmtp-container-parser.js +107 -98
  78. package/dist/wasm-mmtp-container-parser.js.map +4 -4
  79. package/package.json +5 -6
  80. package/src/carp-catalog.ts +16 -11
  81. package/src/catalog-fec-params.ts +38 -17
  82. package/src/cmcd-producer.ts +0 -6
  83. package/src/delivery-catalog.ts +498 -0
  84. package/src/fec-manager.ts +44 -17
  85. package/src/fec-state.ts +4 -9
  86. package/src/fec-worker-setup.ts +4 -35
  87. package/src/index.ts +27 -0
  88. package/src/mmtp-container-parser.ts +80 -20
  89. package/src/mmtp-router.ts +71 -29
  90. package/src/multicast-manager.ts +93 -26
  91. package/src/repair-fetch.ts +228 -17
  92. package/test-vectors/catalog/README.md +10 -1
  93. package/test-vectors/catalog/negative/multicast-endpoint-relay-address.json +39 -0
  94. package/test-vectors/catalog/negative/raptorq-unaligned-symbol.json +1 -0
  95. package/test-vectors/catalog/positive/multicast-amt-manual-relay.json +38 -0
  96. package/test-vectors/catalog/section-codes.json +33 -0
  97. package/test-vectors/delivery-catalog/README.md +11 -0
  98. package/test-vectors/delivery-catalog/negative/missing-block-profile.json +58 -0
  99. package/test-vectors/delivery-catalog/negative/packet-id-signaling.json +59 -0
  100. package/test-vectors/delivery-catalog/negative/retired-k-padded-block-profile.json +59 -0
  101. package/test-vectors/delivery-catalog/positive/dash.json +56 -0
  102. package/test-vectors/delivery-catalog/positive/mmtp-source-only.json +43 -0
@@ -1,3 +1,6 @@
1
+ import { isoBlockSpanUsable } from '@blockcast/mmt-base';
2
+ /** The optional elapsed-span rule lives in mmt-base beside the other catalog FEC rules. */
3
+ export { isoBlockSpanUsable };
1
4
  /** Smallest positive catalog elapsed span; zero/absence means no elapsed deadline. */
2
5
  export declare const MIN_INTERLEAVE_DEPTH_MS = 1;
3
6
  /** Why FEC is not protecting this session. */
@@ -91,8 +94,6 @@ export interface FecStateEvidence<S extends object> {
91
94
  * an overlay beyond layer 0.
92
95
  */
93
96
  export declare function catalogDeclaresFec(fec: unknown): boolean;
94
- /** Validate the optional elapsed span without requiring one for in-band FEC. */
95
- export declare function isoBlockSpanUsable(fec: unknown): boolean;
96
97
  /**
97
98
  * Resolve a player's FEC state. First match wins:
98
99
  *
@@ -1 +1 @@
1
- {"version":3,"file":"fec-state.d.ts","sourceRoot":"","sources":["../src/fec-state.ts"],"names":[],"mappings":"AAiBA,sFAAsF;AACtF,eAAO,MAAM,uBAAuB,IAAI,CAAA;AAExC,8CAA8C;AAC9C,MAAM,MAAM,iBAAiB,GAAG,gBAAgB,GAAG,cAAc,GAAG,qBAAqB,CAAA;AAEzF,kDAAkD;AAClD,eAAO,MAAM,oBAAoB,EAAE,SAAS,iBAAiB,EAIlD,CAAA;AAEX,4DAA4D;AAC5D,MAAM,MAAM,kBAAkB,GAAG,MAAM,GAAG,UAAU,GAAG,gBAAgB,CAAA;AAIvE,kFAAkF;AAClF,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAA;IAC1B,QAAQ,CAAC,MAAM,EAAE,iBAAiB,CAAA;CACnC;AAED;;;;;;;;GAQG;AACH,MAAM,MAAM,cAAc,CAAC,CAAC,SAAS,MAAM,IAAI,CAAC,GAAG;IAAE,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAA;CAAE,CAAA;AAE/E,MAAM,MAAM,QAAQ,CAAC,CAAC,SAAS,MAAM,IAAI,cAAc,CAAC,CAAC,CAAC,GAAG,gBAAgB,CAAA;AAE7E,sEAAsE;AACtE,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;AAEhD,uDAAuD;AACvD,MAAM,WAAW,gBAAgB,CAAC,CAAC,SAAS,MAAM;IAChD;;;;;OAKG;IACH,QAAQ,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI,GAAG,SAAS,CAAA;IACpC;;;OAGG;IACH,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAA;IAC5B,gDAAgD;IAChD,QAAQ,CAAC,eAAe,EAAE,kBAAkB,CAAA;IAC5C,gFAAgF;IAChF,QAAQ,CAAC,eAAe,EAAE,OAAO,CAAA;IACjC;;;OAGG;IACH,QAAQ,CAAC,kBAAkB,EAAE,OAAO,CAAA;CACrC;AAkBD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CASxD;AAED,gFAAgF;AAChF,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAKxD;AASD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,eAAe,CAAC,CAAC,SAAS,MAAM,EAAE,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAAG;IAAE,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAA;CAAE,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAA;AACrH,wBAAgB,eAAe,CAAC,CAAC,SAAS,MAAM,EAAE,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,GAAG,aAAa,CAAC,CAAA"}
1
+ {"version":3,"file":"fec-state.d.ts","sourceRoot":"","sources":["../src/fec-state.ts"],"names":[],"mappings":"AAeA,OAAO,EAAqB,kBAAkB,EAAE,MAAM,qBAAqB,CAAA;AAE3E,2FAA2F;AAC3F,OAAO,EAAE,kBAAkB,EAAE,CAAA;AAE7B,sFAAsF;AACtF,eAAO,MAAM,uBAAuB,IAAI,CAAA;AAExC,8CAA8C;AAC9C,MAAM,MAAM,iBAAiB,GAAG,gBAAgB,GAAG,cAAc,GAAG,qBAAqB,CAAA;AAEzF,kDAAkD;AAClD,eAAO,MAAM,oBAAoB,EAAE,SAAS,iBAAiB,EAIlD,CAAA;AAEX,4DAA4D;AAC5D,MAAM,MAAM,kBAAkB,GAAG,MAAM,GAAG,UAAU,GAAG,gBAAgB,CAAA;AAIvE,kFAAkF;AAClF,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAA;IAC1B,QAAQ,CAAC,MAAM,EAAE,iBAAiB,CAAA;CACnC;AAED;;;;;;;;GAQG;AACH,MAAM,MAAM,cAAc,CAAC,CAAC,SAAS,MAAM,IAAI,CAAC,GAAG;IAAE,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAA;CAAE,CAAA;AAE/E,MAAM,MAAM,QAAQ,CAAC,CAAC,SAAS,MAAM,IAAI,cAAc,CAAC,CAAC,CAAC,GAAG,gBAAgB,CAAA;AAE7E,sEAAsE;AACtE,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;AAEhD,uDAAuD;AACvD,MAAM,WAAW,gBAAgB,CAAC,CAAC,SAAS,MAAM;IAChD;;;;;OAKG;IACH,QAAQ,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI,GAAG,SAAS,CAAA;IACpC;;;OAGG;IACH,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAA;IAC5B,gDAAgD;IAChD,QAAQ,CAAC,eAAe,EAAE,kBAAkB,CAAA;IAC5C,gFAAgF;IAChF,QAAQ,CAAC,eAAe,EAAE,OAAO,CAAA;IACjC;;;OAGG;IACH,QAAQ,CAAC,kBAAkB,EAAE,OAAO,CAAA;CACrC;AAkBD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CASxD;AASD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,eAAe,CAAC,CAAC,SAAS,MAAM,EAAE,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAAG;IAAE,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAA;CAAE,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAA;AACrH,wBAAgB,eAAe,CAAC,CAAC,SAAS,MAAM,EAAE,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,GAAG,aAAa,CAAC,CAAA"}
package/dist/fec-state.js CHANGED
@@ -1,13 +1,8 @@
1
- // ../mmt-alta-parse/dist/index.js
1
+ // ../mmt-base/dist/mmtp.js
2
2
  var MPU_HEADER_SIZE = 8;
3
3
  var MPU_LENGTH_FIELD_SIZE = 2;
4
4
  var MPU_HEADER_REMAINDER_SIZE = MPU_HEADER_SIZE - MPU_LENGTH_FIELD_SIZE;
5
5
 
6
- // ../mmt-base/dist/mmtp.js
7
- var MPU_HEADER_SIZE2 = 8;
8
- var MPU_LENGTH_FIELD_SIZE2 = 2;
9
- var MPU_HEADER_REMAINDER_SIZE2 = MPU_HEADER_SIZE2 - MPU_LENGTH_FIELD_SIZE2;
10
-
11
6
  // ../mmt-base/dist/ntp-short.js
12
7
  var NTP_SHORT_BITS = 32;
13
8
  var NTP_SHORT_MODULUS = 2 ** NTP_SHORT_BITS;
@@ -21,6 +16,19 @@ function isFecBlockProfile(value) {
21
16
  return value === "iso-ssbg1-v1";
22
17
  }
23
18
 
19
+ // ../mmt-base/dist/catalog-fec-source.js
20
+ var ALL_ROLES = Object.freeze(["video", "audio"]);
21
+ function recordOf(value) {
22
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
23
+ }
24
+ function isoBlockSpanUsable(fec) {
25
+ const block = recordOf(fec);
26
+ if (block === void 0 || block["blockProfile"] !== "iso-ssbg1-v1")
27
+ return true;
28
+ const ms = block["interleaveDepthMs"];
29
+ return ms === void 0 || typeof ms === "number" && Number.isSafeInteger(ms) && ms >= 0;
30
+ }
31
+
24
32
  // src/fec-state.ts
25
33
  var MIN_INTERLEAVE_DEPTH_MS = 1;
26
34
  var FEC_INACTIVE_REASONS = Object.freeze([
@@ -34,23 +42,17 @@ var INACTIVE = Object.freeze({
34
42
  "reliable-moq": Object.freeze({ state: "inactive", reason: "reliable-moq" }),
35
43
  "no-multicast-bridge": Object.freeze({ state: "inactive", reason: "no-multicast-bridge" })
36
44
  });
37
- function recordOf(value) {
45
+ function recordOf2(value) {
38
46
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
39
47
  }
40
48
  function isPositiveSafeInteger(value) {
41
49
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
42
50
  }
43
51
  function catalogDeclaresFec(fec) {
44
- const block = recordOf(fec);
52
+ const block = recordOf2(fec);
45
53
  if (block === void 0 || block["algorithm"] === "none") return false;
46
54
  return isPositiveSafeInteger(block["sourceSymbols"]) && isPositiveSafeInteger(block["symbolSize"]) && isFecBlockProfile(block["blockProfile"]) && isoBlockSpanUsable(block);
47
55
  }
48
- function isoBlockSpanUsable(fec) {
49
- const block = recordOf(fec);
50
- if (block === void 0 || block["blockProfile"] !== "iso-ssbg1-v1") return true;
51
- const ms = block["interleaveDepthMs"];
52
- return ms === void 0 || typeof ms === "number" && Number.isSafeInteger(ms) && ms >= 0;
53
- }
54
56
  function requireBoolean(value, field) {
55
57
  if (typeof value !== "boolean") {
56
58
  throw new TypeError(`resolveFecState: ${field} must be a boolean, got ${typeof value}`);
@@ -65,7 +67,7 @@ function resolveFecState(evidence) {
65
67
  if (typeof transportPolicy !== "string" || !TRANSPORT_POLICIES.has(transportPolicy)) {
66
68
  throw new TypeError(`resolveFecState: unsupported transportPolicy ${JSON.stringify(transportPolicy)}`);
67
69
  }
68
- if (stats !== null && stats !== void 0 && recordOf(stats) === void 0) {
70
+ if (stats !== null && stats !== void 0 && recordOf2(stats) === void 0) {
69
71
  throw new TypeError("resolveFecState: stats must be a plain object, null or undefined");
70
72
  }
71
73
  if (!catalogFec) return INACTIVE["no-catalog-fec"];
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../mmt-alta-parse/src/index.ts", "../../mmt-base/src/mmtp.ts", "../../mmt-base/src/ntp-short.ts", "../../mmt-base/src/fec-block-profile.ts", "../src/fec-state.ts"],
4
- "sourcesContent": ["/**\n * Zero-dependency helper for extracting the detached ALTA authenticator trailer\n * from an MMTP source packet.\n *\n * Lives in its own leaf package so both `@blockcast/mmt-container` (wire-path\n * parsing) and `@blockcast/fec-worker` (FEC-recovered-source parsing) can share\n * one implementation without creating a package cycle between them.\n *\n * Spec: ISO/IEC 23008-1:2023 + draft-ramadan-moq-mmt \u00A712 (detached trailer, Path 2).\n */\n\n// --- Private MMTP/MPU/MFU constants (ISO/IEC 23008-1 \u00A79.2.2\u20139.2.3) ---\n// Duplicated here as immutable spec values so this package stays a leaf with\n// zero `@blockcast/*` dependencies. Re-deriving from `mmt-container` would\n// reintroduce the package cycle this split exists to avoid.\n\nconst MMTP_HEADER_SIZE = 12\nconst MPU_HEADER_SIZE = 8\nconst MPU_LENGTH_FIELD_SIZE = 2\nconst MPU_HEADER_REMAINDER_SIZE = MPU_HEADER_SIZE - MPU_LENGTH_FIELD_SIZE\nconst TIMED_MFU_DU_HEADER_SIZE = 14\nconst NONTIMED_MFU_DU_HEADER_SIZE = 4\nconst PACKET_TYPE_MPU = 0x00\n\n// --- Public ALTA trailer constants ---\n\n/**\n * MMTP header-extension ext_type assigned to the detached ALTA authenticator\n * trailer (Path 2 / 08-07). Carried in an `[ext_type][ext_length][auth]`\n * block appended after the MPU's declared payload bytes, before the 4-byte\n * Source FEC Payload ID. MMTP X-bit stays 0 \u2014 non-ALTA MMTP receivers treat\n * the trailer as bytes past `payload_length` and skip it (per ISO 23008-1\n * \u00A79.2.2 \"may be discarded without impacting correct processing\").\n */\nexport const MMTP_EXT_TYPE_ALTA_AUTH = 0xf0a1\n\n/** Fixed size of the trailer's `[ext_type][ext_length]` prefix (2 + 2 BE). */\nexport const MMTP_EXT_TRAILER_HEADER_SIZE = 4\n\n/** Result of extracting the detached ALTA authenticator from an MMTP packet. */\nexport interface AltaTrailer {\n /** Authenticator bytes (no ext_type/ext_length prefix, no trailing padding). */\n auth: Uint8Array\n /**\n * Wire-packet byte offset where the signed payload ends, i.e. where the\n * trailer begins. Caller uses this to produce\n * `payload = wirePacket.subarray(0, signedEnd)` for verify_detached.\n */\n signedEnd: number\n}\n\n/**\n * Extract the detached ALTA authenticator trailer from an MMTP source packet.\n *\n * Wire layout:\n * `[MMTP hdr][length(2)][remaining MPU hdr(6)][DU?][media][TRAILER][SS_ID?]`\n * `payload_length = 6 + DU bytes + media bytes`\n *\n * Returns `null` when:\n * - the packet is too small / malformed,\n * - `payload_length` cannot contain the remaining six MPU-header bytes,\n * - the declared payload overruns the packet,\n * - no bytes remain between `payload_length` and the SS_ID,\n * - the trailer's `ext_type` isn't {@link MMTP_EXT_TYPE_ALTA_AUTH},\n * - the declared `ext_length` would extend past the SS_ID boundary.\n *\n * Non-MPU packets (repair, signaling) always return `null`.\n *\n * @param options.skipFecId When true, do NOT reserve 4 trailing bytes for the\n * Source FEC Payload ID. Use on FEC-recovered symbols where the PID has\n * already been stripped upstream.\n */\nexport function extractAltaTrailer(\n mmtpPacket: Uint8Array,\n options?: { skipFecId?: boolean },\n): AltaTrailer | null {\n if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) return null\n // ISO/IEC 23008-1:2023 Figure 8 places V=0 packet_type in the low six bits.\n const packetType = mmtpPacket[1]! & 0x3f\n if (packetType !== PACKET_TYPE_MPU) return null\n\n const fecType = (mmtpPacket[0]! >> 3) & 0x03\n let headerLength = MMTP_HEADER_SIZE\n if (fecType < 2 && (mmtpPacket[0]! & 0x20) !== 0) headerLength += 4\n if (fecType < 2 && (mmtpPacket[0]! & 0x02) !== 0) {\n if (headerLength + 4 > mmtpPacket.length) return null\n const extensionLength = new DataView(\n mmtpPacket.buffer,\n mmtpPacket.byteOffset + headerLength + 2,\n 2,\n ).getUint16(0, false)\n headerLength += 4 + extensionLength\n }\n if (headerLength + MPU_HEADER_SIZE > mmtpPacket.length) return null\n\n const payload = mmtpPacket.subarray(headerLength)\n\n // Inline a minimal MPU-header read \u2014 only the fields extractAltaTrailer needs.\n // payloadLength: 16 BE at bytes 0-1.\n // Byte 2 packs FT(4) | T(1) | FI(2) | A(1).\n const payloadLength = (payload[0]! << 8) | payload[1]!\n const flagsByte = payload[2]!\n const fragmentType = (flagsByte >> 4) & 0x0f\n const timed = ((flagsByte >> 3) & 0x01) === 1\n const fragmentationIndicator = (flagsByte >> 1) & 0x03\n\n // Only MFU packets (FT=2) carry the detached trailer.\n if (fragmentType !== 2) return null\n\n // FI=0/1 structurally carries a DU header; FI=2/3 does not. Require at\n // least one media byte after that deterministic layout so the bytes at the\n // declared boundary cannot impersonate ALTA for a header-only fragment.\n const dataUnitHeaderSize = fragmentationIndicator <= 1\n ? (timed ? TIMED_MFU_DU_HEADER_SIZE : NONTIMED_MFU_DU_HEADER_SIZE)\n : 0\n if (payloadLength <= MPU_HEADER_REMAINDER_SIZE + dataUnitHeaderSize) return null\n\n if (fecType > 1) return null\n const hasFecId = !options?.skipFecId && fecType === 1\n const payloadEnd = hasFecId ? payload.length - 4 : payload.length\n const declaredEnd = MPU_LENGTH_FIELD_SIZE + payloadLength\n if (declaredEnd > payloadEnd) return null\n\n if (declaredEnd + MMTP_EXT_TRAILER_HEADER_SIZE > payloadEnd) return null\n const extType = (payload[declaredEnd]! << 8) | payload[declaredEnd + 1]!\n if (extType !== MMTP_EXT_TYPE_ALTA_AUTH) return null\n const extLen = (payload[declaredEnd + 2]! << 8) | payload[declaredEnd + 3]!\n\n const authStart = declaredEnd + MMTP_EXT_TRAILER_HEADER_SIZE\n if (authStart + extLen !== payloadEnd) return null\n\n return {\n auth: payload.subarray(authStart, payloadEnd),\n signedEnd: headerLength + declaredEnd,\n }\n}\n", "import {\n MMTP_EXT_TYPE_ALTA_AUTH as _LEAF_MMTP_EXT_TYPE_ALTA_AUTH,\n MMTP_EXT_TRAILER_HEADER_SIZE as _LEAF_MMTP_EXT_TRAILER_HEADER_SIZE,\n extractAltaTrailer as _leafExtractAltaTrailer,\n type AltaTrailer as _LeafAltaTrailer,\n} from '@blockcast/mmt-alta-parse'\n\n/**\n * @mmt/container - MMTP Parser\n *\n * MMTP (MMT Protocol) packet parser based on ISO/IEC 23008-1:2023 Section 9.2\n *\n * MMTP header format (12 bytes):\n * - Byte 0: V(2) | C(1) | FEC_type(2) | r(1) | X(1) | R(1)\n * - Byte 1: reserved(2) | packet_type(6)\n * - Bytes 2-3: packet_id (big-endian)\n * - Bytes 4-7: timestamp (big-endian, 32-bit)\n * - Bytes 8-11: sequence_number (big-endian)\n *\n * FEC_type values:\n * - 0: No FEC / source packet\n * - 1: FEC mode 0 (source with FEC payload ID)\n * - 2: FEC repair packet mode 0\n * - 3: FEC repair packet mode 1\n *\n * @packageDocumentation\n */\n\nexport interface MMTPHeader {\n version: number\n /** Packet type: 0x00=MPU, 0x02=Signaling, 0x03=Repair */\n packetType: number\n packetId: number\n timestamp: bigint\n sequenceNumber: number\n payloadLength: number\n fecType: number\n /** C flag: header carries a 32-bit packet_counter. */\n packetCounterFlag: boolean\n packetCounter?: number\n /** X flag: header carries an extension header and value. */\n extensionFlag: boolean\n extension?: { type: number; data: Uint8Array }\n /** Byte offset at which the MMTP payload begins. */\n headerLength: number\n /** Random Access Point flag - indicates keyframe (ISO 23008-1, byte 0 bit 0) */\n rapFlag: boolean\n}\n\nexport interface MPUHeader {\n mpuSequenceNumber: number\n fragmentationIndicator: number // FI: 0=complete, 1=first, 2=middle, 3=last\n /** 8-bit MPU fragment_counter from byte 3. */\n fragmentCounter: number\n /** T flag: 1=timed media (14-byte MFU DU header), 0=non-timed (4-byte header) */\n timedFlag: number\n /** A flag: aggregated MPU payload. This strict profile requires A=0. */\n aggregationFlag: boolean\n /** MPU payload_length (bytes 0-1): bytes after the length field, including\n * the remaining six MPU-header bytes and all data-unit bytes. */\n payloadLength: number\n}\n\nexport interface MFUDuHeader {\n movieFragmentSequenceNumber: number\n sampleNumber: number\n offset: number\n priority: number\n dependencyCounter: number\n}\n\nexport interface MMTPPacket {\n header: MMTPHeader\n payload: Uint8Array\n}\n\nexport const MMTP_HEADER_SIZE = 12\nexport const MPU_HEADER_SIZE = 8\nexport const MFU_DU_HEADER_SIZE_TIMED = 14 // T=1: timed media (video/audio samples)\nexport const MFU_DU_HEADER_SIZE_NONTIMED = 4 // T=0: non-timed media (item_id only)\n\nconst MPU_LENGTH_FIELD_SIZE = 2\nconst MPU_HEADER_REMAINDER_SIZE = MPU_HEADER_SIZE - MPU_LENGTH_FIELD_SIZE\nconst SOURCE_FEC_PAYLOAD_ID_SIZE = 4\n\n// MMTP Packet Types (ISO/IEC 23008-1:2023 Section 9.2.2)\nexport const PACKET_TYPE_MPU = 0x00\nexport const PACKET_TYPE_SIGNALING = 0x02\nexport const PACKET_TYPE_REPAIR = 0x03\n\n// AL-FEC Signaling Message ID (ISO/IEC 23008-1:2023 Amendment 1:2025)\nexport const ALFEC_MESSAGE_ID = 0x0203\n\n/**\n * MMTP `packet_id` of the signaling flow, which carries PACKET_TYPE_SIGNALING\n * packets such as the AL-FEC message (ALFEC_MESSAGE_ID). The FFmpeg `moq_mmt`\n * muxer sends that message on this packet_id into the same multicast group as\n * the media, and moqcast-draft (PR #44) makes advertising it for a track a\n * MUST NOT. A track's packet_id is therefore 1..MMTP_PACKET_ID_MAX.\n */\nexport const MMTP_SIGNALING_PACKET_ID = 0\n\n/** Largest value of the 16-bit MMTP `packet_id` header field. */\nexport const MMTP_PACKET_ID_MAX = 0xffff\n\n// FEC Code IDs\nexport const FEC_CODE_XOR = 1\nexport const FEC_CODE_RAPTORQ = 2\n\n/**\n * Parse MMTP header from buffer\n */\nexport function parseMMTPHeader(buffer: Uint8Array): MMTPHeader {\n if (buffer.length < MMTP_HEADER_SIZE) {\n throw new Error(`MMTP packet too small: ${buffer.length} bytes`)\n }\n\n const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength)\n\n const version = (buffer[0]! >> 6) & 0x03\n if (version !== 0) {\n throw new Error(`Unsupported MMTP version: ${version}`)\n }\n\n // Extract FEC type from byte 0, bits 3-4\n const fecType = (buffer[0]! >> 3) & 0x03\n const packetCounterFlag = (buffer[0]! & 0x20) !== 0\n const extensionFlag = (buffer[0]! & 0x02) !== 0\n\n // Extract RAP flag from byte 0, bit 0 (R bit - Random Access Point)\n const rapFlag = (buffer[0]! & 0x01) === 1\n\n // ISO/IEC 23008-1:2023 Figure 8 (V=0) places reserved(2) before\n // packet_type(6), so packet_type occupies the low six bits of byte 1.\n const packetType = buffer[1]! & 0x3F\n\n let offset = 2\n\n // Packet ID (2 bytes, big-endian)\n const packetId = view.getUint16(offset, false)\n offset += 2\n\n // Timestamp (4 bytes, big-endian)\n const timestamp = BigInt(view.getUint32(offset, false))\n offset += 4\n\n // Sequence number (4 bytes, big-endian)\n const sequenceNumber = view.getUint32(offset, false)\n offset += 4\n\n let packetCounter: number | undefined\n if (packetCounterFlag) {\n if (offset + 4 > buffer.length) throw new Error('MMTP packet truncated in packet_counter')\n packetCounter = view.getUint32(offset, false)\n offset += 4\n }\n\n let extension: { type: number; data: Uint8Array } | undefined\n if (extensionFlag) {\n if (offset + 4 > buffer.length) throw new Error('MMTP packet truncated in header extension')\n const type = view.getUint16(offset, false)\n const length = view.getUint16(offset + 2, false)\n offset += 4\n if (offset + length > buffer.length) throw new Error('MMTP packet truncated in header extension value')\n extension = { type, data: buffer.subarray(offset, offset + length) }\n offset += length\n }\n\n return {\n version,\n packetType,\n packetId,\n timestamp,\n sequenceNumber,\n payloadLength: buffer.length - offset,\n fecType,\n packetCounterFlag,\n packetCounter,\n extensionFlag,\n extension,\n headerLength: offset,\n rapFlag,\n }\n}\n\n/**\n * The MMTP `packet_id` of `buffer`, or null exactly when parseMMTPHeader would\n * throw for it (short buffer, V != 0, truncated packet_counter or header\n * extension).\n *\n * This is the per-packet filter a receiver runs before any other work, so it\n * builds no header object, DataView or BigInt timestamp (BLO-36599). Use\n * parseMMTPHeader when any other header field is needed.\n */\nexport function readMMTPPacketId(buffer: Uint8Array): number | null {\n if (buffer.length < MMTP_HEADER_SIZE) return null\n const flags = buffer[0]!\n if (((flags >> 6) & 0x03) !== 0) return null\n let offset = MMTP_HEADER_SIZE\n if ((flags & 0x20) !== 0) {\n if (offset + 4 > buffer.length) return null\n offset += 4\n }\n if ((flags & 0x02) !== 0) {\n if (offset + 4 > buffer.length) return null\n const length = (buffer[offset + 2]! << 8) | buffer[offset + 3]!\n if (offset + 4 + length > buffer.length) return null\n }\n return (buffer[2]! << 8) | buffer[3]!\n}\n\n/**\n * Unwrap MMTP packet to extract payload\n */\nexport function unwrapMMTP(buffer: Uint8Array): MMTPPacket {\n const header = parseMMTPHeader(buffer)\n const payload = buffer.subarray(header.headerLength)\n\n return { header, payload }\n}\n\n/**\n * Parse MPU header from payload\n * ISO/IEC 23008-1:2023 Section 9.2.3.3\n *\n * MPU Header format (8 bytes) as written by FFmpeg/libmmt:\n * - Bytes 0-1: payload_length (16 bits, big-endian)\n * - Byte 2: FT(4) | T(1) | FI(2) | A(1)\n * - Byte 3: fragment_counter (8 bits)\n * - Bytes 4-7: MPU_sequence_number (32 bits, big-endian)\n */\nexport function parseMPUHeader(payload: Uint8Array): MPUHeader {\n if (payload.length < MPU_HEADER_SIZE) {\n throw new Error(`Payload too small for MPU header: ${payload.length} bytes`)\n }\n\n const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength)\n\n // Bytes 0-1: payload_length (16 bits, big-endian)\n const payloadLength = view.getUint16(0, false)\n\n // Byte 2: FT(4) | T(1) | FI(2) | A(1)\n const flagsByte = payload[2]!\n const timedFlag = (flagsByte >> 3) & 0x01\n const fragmentationIndicator = (flagsByte >> 1) & 0x03\n const aggregationFlag = (flagsByte & 0x01) !== 0\n\n // Byte 3: fragment_counter (8 bits). The high bit is part of the counter in\n // the current libmmt/FFmpeg writer ABI.\n const fragmentCounter = payload[3]!\n\n // Bytes 4-7: MPU_sequence_number (32 bits, big-endian)\n const mpuSequenceNumber = view.getUint32(4, false)\n\n return {\n mpuSequenceNumber,\n fragmentationIndicator,\n fragmentCounter,\n timedFlag,\n aggregationFlag,\n payloadLength,\n }\n}\n\nexport function parseTimedMfuDuHeader(payload: Uint8Array, offset: number): MFUDuHeader | null {\n if (offset < 0 || offset + MFU_DU_HEADER_SIZE_TIMED > payload.length) return null\n const view = new DataView(payload.buffer, payload.byteOffset + offset, MFU_DU_HEADER_SIZE_TIMED)\n return {\n movieFragmentSequenceNumber: view.getUint32(0, false),\n sampleNumber: view.getUint32(4, false),\n offset: view.getUint32(8, false),\n priority: payload[offset + 12]!,\n dependencyCounter: payload[offset + 13]!,\n }\n}\n\n/**\n * Why `extractMFUPayload` refused a packet.\n *\n * These identifiers are part of the public contract: callers surface them in\n * diagnostics, so renaming one is a breaking change.\n */\nexport type MFURejectionGate =\n | 'packet-shorter-than-mmtp-plus-mpu-header'\n | 'mmtp-header-unparseable'\n | 'not-an-mpu-packet'\n | 'payload-shorter-than-mpu-header'\n | 'aggregation-flag-set'\n | 'mpu-payload-length-below-header-remainder'\n | 'mpu-declared-end-exceeds-payload'\n | 'mfu-offset-at-or-past-declared-end'\n | 'source-fec-payload-id-width-mismatch'\n | 'declared-trailers-unresolved'\n\nexport interface MFURejection {\n gate: MFURejectionGate\n /** Human-readable detail, including the byte arithmetic that decided it. */\n detail: string\n}\n\ninterface MfuPayloadLayout {\n hasMfuDuHeader: boolean\n mfuOffset: number\n dataEnd: number\n}\n\nfunction resolveMfuPayloadLayout(\n mpu: MPUHeader,\n fragmentType: number,\n payload: Uint8Array,\n): { layout: MfuPayloadLayout } | { rejection: MFURejection } {\n if (mpu.payloadLength < MPU_HEADER_REMAINDER_SIZE) {\n return {\n rejection: {\n gate: 'mpu-payload-length-below-header-remainder',\n detail: `payload_length=${mpu.payloadLength} < ${MPU_HEADER_REMAINDER_SIZE}`,\n },\n }\n }\n\n // ISO/IEC 23008-1 defines payload_length from immediately after its own\n // two-byte field. It therefore includes the remaining six MPU-header bytes.\n const declaredEnd = MPU_LENGTH_FIELD_SIZE + mpu.payloadLength\n if (declaredEnd > payload.length) {\n return {\n rejection: {\n gate: 'mpu-declared-end-exceeds-payload',\n detail:\n `payload_length=${mpu.payloadLength} implies end=${declaredEnd}, ` +\n `payload is ${payload.length} bytes`,\n },\n }\n }\n\n const hasHeader = fragmentType === 2 && mpu.fragmentationIndicator <= 1\n const mfuHeaderSize = mpu.timedFlag ? MFU_DU_HEADER_SIZE_TIMED : MFU_DU_HEADER_SIZE_NONTIMED\n const mfuOffset = MPU_HEADER_SIZE + (hasHeader ? mfuHeaderSize : 0)\n if (mfuOffset >= declaredEnd) {\n return {\n rejection: {\n gate: 'mfu-offset-at-or-past-declared-end',\n detail: `mfuOffset=${mfuOffset} >= declaredEnd=${declaredEnd}`,\n },\n }\n }\n\n return {\n layout: {\n hasMfuDuHeader: hasHeader,\n mfuOffset,\n dataEnd: declaredEnd,\n },\n }\n}\n\nfunction isEmptyOrExactAltaTrailer(payload: Uint8Array, start: number, end: number): boolean {\n if (start === end) return true\n if (start < 0 || end > payload.length || start + _LEAF_MMTP_EXT_TRAILER_HEADER_SIZE > end) {\n return false\n }\n\n const view = new DataView(\n payload.buffer,\n payload.byteOffset + start,\n end - start,\n )\n if (view.getUint16(0, false) !== _LEAF_MMTP_EXT_TYPE_ALTA_AUTH) return false\n\n const authLength = view.getUint16(2, false)\n return start + _LEAF_MMTP_EXT_TRAILER_HEADER_SIZE + authLength === end\n}\n\ninterface DeclaredTrailerLayout {\n hasFecId: boolean\n}\n\nfunction resolveDeclaredTrailers(\n payload: Uint8Array,\n declaredEnd: number,\n fecType: number,\n options?: { skipFecId?: boolean },\n): DeclaredTrailerLayout | null {\n if (declaredEnd > payload.length) return null\n\n if (options?.skipFecId) {\n return isEmptyOrExactAltaTrailer(payload, declaredEnd, payload.length)\n ? { hasFecId: false }\n : null\n }\n\n if (fecType === 1) {\n const fecStart = payload.length - SOURCE_FEC_PAYLOAD_ID_SIZE\n if (fecStart < declaredEnd || !isEmptyOrExactAltaTrailer(payload, declaredEnd, fecStart)) {\n return null\n }\n return { hasFecId: true }\n }\n if (fecType !== 0) return null\n\n if (isEmptyOrExactAltaTrailer(payload, declaredEnd, payload.length)) {\n return { hasFecId: false }\n }\n\n return null\n}\n\n/**\n * Extract NAL unit payload from MMTP packet\n */\nexport function extractNALUnit(mmtpPacket: Uint8Array): Uint8Array {\n const extraction = extractMFUPayload(mmtpPacket)\n if (!extraction) throw new Error('Malformed MMTP MPU payload')\n return extraction.data\n}\n\n/** Result of extracting MFU payload from an MMTP packet */\nexport interface MFUExtraction {\n /** MMTP header fields */\n header: MMTPHeader\n /** MPU header fields */\n mpu: MPUHeader\n /** Fragment type (FT field, 4 bits): 0=metadata, 2=MFU data */\n fragmentType: number\n /** MFU payload data (video/audio bytes, headers stripped, FEC ID excluded) */\n data: Uint8Array\n /** Parsed timed MFU DU header when present, otherwise null */\n mfuDuHeader: MFUDuHeader | null\n /** Non-timed MFU Item_ID when the 4-byte DU header is present. */\n itemId: number | null\n /** Source FEC Payload ID if present (`FEC_type == 1`), or null */\n fecPayloadId: { ssId: number } | null\n}\n\n/**\n * Extract MFU payload from a raw MMTP packet.\n *\n * Handles all the byte arithmetic for:\n * - MMTP header (12 bytes)\n * - MPU sub-header (8 bytes, payloadLength field)\n * - MFU DU header (14 bytes timed / 4 bytes non-timed, only for FI \u2264 1)\n * - Source FEC Payload ID (4 bytes at end, only when `FEC_type == 1`)\n *\n * `payloadLength` is the ISO length-after-field value: six remaining MPU-header\n * bytes, then the MFU DU header when present, then media. ALTA and Source FEC\n * trailers are outside that declared span and must consume the exact suffix.\n *\n * @param mmtpPacket Raw MMTP packet (from multicast or MoQ)\n * @param options.skipFecId When true, do NOT subtract the 4-byte Source FEC Payload ID\n * from the payload boundary, even if fecType >= 1 in the MMTP header. Use this for\n * FEC-recovered symbols where the FEC PID was already stripped before WASM decoding\n * but the fecType bits in byte 0 still reflect the original packet (FEC Type=1 per\n * draft-ramadan-moq-mmt-00 \u00A73.1).\n * @returns Extracted MFU data + metadata, or null if packet is too small\n */\ninterface MfuPlan {\n header: MMTPHeader\n payload: Uint8Array\n mpu: MPUHeader\n fragmentType: number\n layout: MfuPayloadLayout\n trailerLayout: DeclaredTrailerLayout\n}\n\n/**\n * Single source of truth for whether a packet yields an MFU payload.\n *\n * `extractMFUPayload` and `explainMFURejection` both delegate here, so the\n * reason reported to operators can never drift from the decision the parser\n * actually made.\n */\nfunction planMfuExtraction(\n mmtpPacket: Uint8Array,\n options?: { skipFecId?: boolean },\n parsedHeader?: MMTPHeader,\n): { plan: MfuPlan } | { rejection: MFURejection } {\n if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) {\n return {\n rejection: {\n gate: 'packet-shorter-than-mmtp-plus-mpu-header',\n detail: `${mmtpPacket.length} bytes < ${MMTP_HEADER_SIZE + MPU_HEADER_SIZE}`,\n },\n }\n }\n\n let header: MMTPHeader\n if (parsedHeader) {\n header = parsedHeader\n } else {\n try {\n header = parseMMTPHeader(mmtpPacket)\n } catch (error) {\n return {\n rejection: {\n gate: 'mmtp-header-unparseable',\n detail: error instanceof Error ? error.message : String(error),\n },\n }\n }\n }\n if (header.packetType !== PACKET_TYPE_MPU) {\n return {\n rejection: {\n gate: 'not-an-mpu-packet',\n detail: `packetType=0x${header.packetType.toString(16).padStart(2, '0')}`,\n },\n }\n }\n\n const payload = mmtpPacket.subarray(header.headerLength)\n if (payload.length < MPU_HEADER_SIZE) {\n return {\n rejection: {\n gate: 'payload-shorter-than-mpu-header',\n detail: `${payload.length} bytes < ${MPU_HEADER_SIZE}`,\n },\n }\n }\n\n const mpu = parseMPUHeader(payload)\n if (mpu.aggregationFlag) {\n return {\n rejection: { gate: 'aggregation-flag-set', detail: 'strict profile requires A=0' },\n }\n }\n\n // Fragment type from byte 2 upper nibble (not returned by parseMPUHeader)\n const fragmentType = (payload[2]! >> 4) & 0x0f\n\n const layoutResult = resolveMfuPayloadLayout(mpu, fragmentType, payload)\n if ('rejection' in layoutResult) return layoutResult\n const { layout } = layoutResult\n\n const trailerLayout = resolveDeclaredTrailers(\n payload,\n layout.dataEnd,\n header.fecType,\n options,\n )\n if (!trailerLayout) {\n // The most common cause is a producer whose Source FEC Payload ID width\n // disagrees with ISO/IEC 23008-1 \u00A7C.5.2. Name that explicitly rather than\n // leaving operators to infer it from a generic trailer error.\n if (!options?.skipFecId && header.fecType === 1) {\n const observed = payload.length - layout.dataEnd\n if (observed !== SOURCE_FEC_PAYLOAD_ID_SIZE) {\n return {\n rejection: {\n gate: 'source-fec-payload-id-width-mismatch',\n detail:\n `producer wrote a ${observed}-byte Source FEC Payload ID, ` +\n `ISO/IEC 23008-1 \u00A7C.5.2 requires ${SOURCE_FEC_PAYLOAD_ID_SIZE} ` +\n `(payload=${payload.length}, declaredEnd=${layout.dataEnd})`,\n },\n }\n }\n }\n return {\n rejection: {\n gate: 'declared-trailers-unresolved',\n detail:\n `trailer bytes [${layout.dataEnd}, ${payload.length}) are neither empty ` +\n `nor an exact ALTA trailer (fecType=${header.fecType})`,\n },\n }\n }\n\n return { plan: { header, payload, mpu, fragmentType, layout, trailerLayout } }\n}\n\n/**\n * Report why `extractMFUPayload` would refuse this packet, or null if it would\n * accept it.\n *\n * `extractMFUPayload` returns bare `null` on ten distinct conditions, which\n * makes a producer/consumer framing disagreement indistinguishable from a\n * publisher that never started \u2014 both render as silence. Use this wherever\n * that distinction matters: diagnostics, contract tests, and operator-facing\n * logs.\n */\nexport function explainMFURejection(\n mmtpPacket: Uint8Array,\n options?: { skipFecId?: boolean },\n): MFURejection | null {\n const result = planMfuExtraction(mmtpPacket, options)\n return 'rejection' in result ? result.rejection : null\n}\n\nexport function extractMFUPayload(\n mmtpPacket: Uint8Array,\n options?: { skipFecId?: boolean },\n): MFUExtraction | null {\n return extractPlannedMfu(mmtpPacket, planMfuExtraction(mmtpPacket, options))\n}\n\n/**\n * extractMFUPayload for a caller that already holds this packet's parsed MMTP\n * header, so the header is not parsed a second time (BLO-36599).\n *\n * `header` must be `parseMMTPHeader(mmtpPacket)` of this same packet; the\n * result is then identical to `extractMFUPayload(mmtpPacket, options)`.\n */\nexport function extractMFUPayloadWithHeader(\n mmtpPacket: Uint8Array,\n header: MMTPHeader,\n options?: { skipFecId?: boolean },\n): MFUExtraction | null {\n return extractPlannedMfu(mmtpPacket, planMfuExtraction(mmtpPacket, options, header))\n}\n\nfunction extractPlannedMfu(\n mmtpPacket: Uint8Array,\n result: { plan: MfuPlan } | { rejection: MFURejection },\n): MFUExtraction | null {\n if ('rejection' in result) return null\n const { header, payload, mpu, fragmentType, layout, trailerLayout } = result.plan\n\n const mfuDuHeaderPresent = layout.hasMfuDuHeader\n const mfuOffset = layout.mfuOffset\n const dataEnd = layout.dataEnd\n\n const mfuDuHeader =\n mfuDuHeaderPresent && mpu.timedFlag === 1\n ? parseTimedMfuDuHeader(payload, MPU_HEADER_SIZE)\n : null\n const itemId =\n mfuDuHeaderPresent && mpu.timedFlag === 0\n ? new DataView(payload.buffer, payload.byteOffset + MPU_HEADER_SIZE, 4).getUint32(0, false)\n : null\n\n const data = payload.subarray(mfuOffset, dataEnd)\n\n const fecPayloadId = trailerLayout.hasFecId\n ? {\n ssId: new DataView(\n mmtpPacket.buffer,\n mmtpPacket.byteOffset + mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE,\n SOURCE_FEC_PAYLOAD_ID_SIZE,\n ).getUint32(0, false),\n }\n : null\n\n return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId }\n}\n\n/**\n * Extract timestamp from MMTP packet\n */\nexport function extractTimestamp(mmtpPacket: Uint8Array): bigint {\n const { header } = unwrapMMTP(mmtpPacket)\n return header.timestamp\n}\n\n/**\n * Check if MMTP packet is an FEC repair packet\n * FEC_type 2 and 3 are repair packets\n */\nexport function isFecRepairPacket(mmtpPacket: Uint8Array): boolean {\n if (mmtpPacket.length < 1) return false\n const fecType = (mmtpPacket[0]! >> 3) & 0x03\n return fecType >= 2\n}\n\n/**\n * Extract Source FEC Payload ID (SS_ID) from the last 4 bytes of an MMTP\n * source packet per ISO/IEC 23008-1:2023 Section C.5.2 Figure C.10.\n *\n * SS_ID is a flat 32-bit monotonic counter (incremented by 1 per packet\n * for ssbg_mode0 and ssbg_mode1). Block membership and ESI use the\n * configured K; repair SS_Start identifies the first SS_ID of the block and\n * SSB_length records the authored source-symbol count:\n * SBN = floor(SS_ID / K), ESI = SS_ID % K\n * SS_Start = SBN * K (first SS_ID of the block)\n *\n * This matches FFmpeg moqenc_mmt.c, the drafts (draft-ramadan-moq-fec \u00A76.2),\n * and ATSC A/331 \u00A78.1.2.5 which defers to ISO 23008-1 Annex C.\n */\nexport function extractFecPayloadId(mmtpPacket: Uint8Array): { ssId: number } | null {\n const header = parseHeaderForSourceFecId(mmtpPacket)\n return header ? sourceFecPayloadIdOf(mmtpPacket, header) : null\n}\n\n/**\n * Return true when FEC_type=1 and the exact suffix after the ISO-declared MPU\n * payload contains a four-byte Source FEC Payload ID.\n */\nexport function hasSourceFecPayloadId(mmtpPacket: Uint8Array): boolean {\n const header = parseHeaderForSourceFecId(mmtpPacket)\n return header !== null && sourceFecPayloadIdOf(mmtpPacket, header) !== null\n}\n\nfunction parseHeaderForSourceFecId(mmtpPacket: Uint8Array): MMTPHeader | null {\n if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) return null\n try {\n return parseMMTPHeader(mmtpPacket)\n } catch {\n return null\n }\n}\n\n/**\n * The Source FEC Payload ID of a packet whose MMTP header the caller already\n * parsed, or null when the packet carries none: present only when FEC_type=1\n * and the exact suffix after the ISO-declared MPU payload holds the four-byte\n * ID (ISO/IEC 23008-1 \u00A7C.5.2). Same answer as extractFecPayloadId, without a\n * second header parse (BLO-36599).\n *\n * `header` must be `parseMMTPHeader(mmtpPacket)` of this same packet.\n */\nexport function sourceFecPayloadIdOf(\n mmtpPacket: Uint8Array,\n header: MMTPHeader,\n): { ssId: number } | null {\n if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) return null\n if (header.packetType !== PACKET_TYPE_MPU) return null\n\n const payload = mmtpPacket.subarray(header.headerLength)\n if (payload.length < MPU_HEADER_SIZE) return null\n const payloadLength = (payload[0]! << 8) | payload[1]!\n if (payloadLength < MPU_HEADER_REMAINDER_SIZE) return null\n const declaredEnd = MPU_LENGTH_FIELD_SIZE + payloadLength\n if (!resolveDeclaredTrailers(payload, declaredEnd, header.fecType)?.hasFecId) return null\n\n // Flat 4-byte SS_ID: encoder writes block_id * K + symbol_id\n const off = mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE\n return {\n ssId:\n ((mmtpPacket[off]! << 24) |\n (mmtpPacket[off + 1]! << 16) |\n (mmtpPacket[off + 2]! << 8) |\n mmtpPacket[off + 3]!) >>>\n 0,\n }\n}\n\n/**\n * MMTP header-extension ext_type assigned to the detached ALTA authenticator\n * trailer (Path 2 / 08-07). Carried in an `[ext_type][ext_length][auth]`\n * block appended after the MPU's declared payload bytes, before the 4-byte\n * Source FEC Payload ID. MMTP X-bit stays 0 \u2014 non-ALTA MMTP receivers treat\n * the trailer as bytes past `payload_length` and skip it (per ISO 23008-1\n * \u00A79.2.2 \"may be discarded without impacting correct processing\").\n */\n// Re-export the ALTA trailer helper from the zero-dep leaf package. The leaf\n// owns the implementation so container and FEC consumers share one parser\n// without creating a package cycle.\nexport const MMTP_EXT_TYPE_ALTA_AUTH = _LEAF_MMTP_EXT_TYPE_ALTA_AUTH\nexport const MMTP_EXT_TRAILER_HEADER_SIZE = _LEAF_MMTP_EXT_TRAILER_HEADER_SIZE\nexport type AltaTrailer = _LeafAltaTrailer\nexport const extractAltaTrailer = _leafExtractAltaTrailer\n\n/** Size of Repair FEC Payload ID per ISO/IEC 23008-1 Section C.5.3 */\nexport const REPAIR_FEC_PID_SIZE = 13\n\n/**\n * Parse the 13-byte Repair FEC Payload ID after the complete dynamic MMTP header.\n * `parsedHeader`, when given, must be `parseMMTPHeader(mmtpPacket)` of this\n * same packet; it spares the second header parse (BLO-36599).\n */\nfunction readRepairFecPayloadIdFields(mmtpPacket: Uint8Array, parsedHeader?: MMTPHeader): {\n packetId: number; ssStart: number; rsbLength: number; rsId: number; ssbLength: number; dataOffset: number\n} | null {\n let header: MMTPHeader\n if (parsedHeader) {\n header = parsedHeader\n } else {\n try {\n header = parseMMTPHeader(mmtpPacket)\n } catch {\n return null\n }\n }\n if (header.packetType !== PACKET_TYPE_REPAIR || header.fecType !== 2) return null\n\n const off = header.headerLength\n if (mmtpPacket.length < off + REPAIR_FEC_PID_SIZE) return null\n const ssStart =\n ((mmtpPacket[off]! << 24) |\n (mmtpPacket[off + 1]! << 16) |\n (mmtpPacket[off + 2]! << 8) |\n mmtpPacket[off + 3]!) >>>\n 0 // 32 bits\n const rsbLength = (mmtpPacket[off + 4]! << 16) | (mmtpPacket[off + 5]! << 8) | mmtpPacket[off + 6]! // 24 bits\n const rsId = (mmtpPacket[off + 7]! << 16) | (mmtpPacket[off + 8]! << 8) | mmtpPacket[off + 9]! // 24 bits\n const ssbLength = (mmtpPacket[off + 10]! << 16) | (mmtpPacket[off + 11]! << 8) | mmtpPacket[off + 12]! // 24 bits\n return {\n packetId: header.packetId,\n ssStart,\n rsbLength,\n rsId,\n ssbLength,\n dataOffset: off + REPAIR_FEC_PID_SIZE,\n }\n}\n\n/**\n * Extract Repair FEC Payload ID from a raw-multicast MMTP repair packet.\n * Per ISO/IEC 23008-1:2023 Section C.5.3 (ssbg_mode0, one-stage, no FFSRP_TS):\n * [MMTP header][SS_Start:4][RSB_length:3][RS_ID:3][SSB_length:3][repair data]\n * OTI is delivered via AL-FEC signaling message (Table C.3), not per-packet.\n *\n * Byte 1 is reserved(2)|packet_type(6) for V=0, so repair type 0x03 is 0x03.\n * Pre-migration high-bits bytes (0x0c) are rejected \u2014 no compatibility decode.\n */\nexport function extractRepairFecPayloadId(mmtpPacket: Uint8Array): {\n ssStart: number; rsbLength: number; rsId: number; ssbLength: number\n} | null {\n const fields = readRepairFecPayloadIdFields(mmtpPacket)\n if (!fields) return null\n return {\n ssStart: fields.ssStart,\n rsbLength: fields.rsbLength,\n rsId: fields.rsId,\n ssbLength: fields.ssbLength,\n }\n}\n\n/** Parsed MoQ repair frame per ISO/IEC 23008-1 Section C.4.3 + C.5.3 */\nexport interface MoqRepairFrame {\n /** MMTP packetId (1=video, 2=audio) \u2014 for routing to correct FEC decoder */\n packetId: number\n /** SS_Start (32 bits): SS_ID of first source symbol in block */\n ssStart: number\n /** RSB_length (24 bits): number of repair symbols (P) */\n rsbLength: number\n /** RS_ID (24 bits): repair symbol index (0-based) */\n rsId: number\n /** SSB_length (24 bits): authored source-symbol count (1..=configured K) */\n ssbLength: number\n /** Repair symbol data after the dynamic MMTP header and 13-byte FEC payload ID. */\n symbolData: Uint8Array\n}\n\n/**\n * Parse a MoQ repair frame (ISO/IEC 23008-1 Annex C format).\n *\n * Wire format per ISO 23008-1 \u00A7C.4.3 + \u00A7C.5.3:\n * MMTP Header: fixed 12 bytes plus C/X optional fields\n * then SS_Start (4 bytes) \u2192 block identifier\n * then RSB_length (3 bytes) \u2192 P\n * then RS_ID (3 bytes) \u2192 ESI = K + RS_ID\n * then SSB_length (3 bytes) \u2192 authored source-symbol count (1..=K)\n * then Repair Symbol Data (T bytes)\n *\n * @param frame - Raw MoQ repair frame bytes\n * @returns Parsed frame or null if invalid\n */\nexport function parseMoqRepairFrame(frame: Uint8Array): MoqRepairFrame | null {\n return moqRepairFrameFrom(frame, readRepairFecPayloadIdFields(frame))\n}\n\n/**\n * parseMoqRepairFrame for a caller that already holds this frame's parsed MMTP\n * header, so the header is not parsed a second time (BLO-36599). The router's\n * multicast repair branch uses it: one repair packet in every K + P otherwise\n * paid two header parses.\n *\n * `header` must be `parseMMTPHeader(frame)` of this same frame; the result is\n * then identical to `parseMoqRepairFrame(frame)`.\n */\nexport function parseMoqRepairFrameWithHeader(\n frame: Uint8Array,\n header: MMTPHeader,\n): MoqRepairFrame | null {\n return moqRepairFrameFrom(frame, readRepairFecPayloadIdFields(frame, header))\n}\n\nfunction moqRepairFrameFrom(\n frame: Uint8Array,\n repairId: ReturnType<typeof readRepairFecPayloadIdFields>,\n): MoqRepairFrame | null {\n if (!repairId) return null\n\n const symbolData = frame.subarray(repairId.dataOffset)\n if (\n repairId.rsbLength === 0 ||\n repairId.ssbLength === 0 ||\n repairId.rsId >= repairId.rsbLength ||\n symbolData.length === 0\n ) return null\n\n return {\n packetId: repairId.packetId,\n ssStart: repairId.ssStart,\n rsbLength: repairId.rsbLength,\n rsId: repairId.rsId,\n ssbLength: repairId.ssbLength,\n symbolData,\n }\n}\n\n// The signalling-message parsers (9.3.4.2 payload header, AL-FEC message,\n// PA/MPT) live in ./signalling.ts.\n", "/**\n * NTP short format (RFC 5905 \u00A76): an unsigned 32-bit, 16.16 fixed-point count\n * of seconds. The MMTP header `timestamp` field (ISO/IEC 23008-1 \u00A79.2.2)\n * carries each packet's UTC sending instant in this format, so the value wraps\n * to 0 every 2^16 s (~18.2 h).\n *\n * Plain numeric order on these values breaks at every wrap: a retained\n * `Math.max` stays at the pre-wrap value and every later instant compares as\n * older. Order send times only with {@link compareNtpShort}, which applies\n * RFC 1982 serial-number arithmetic over the field's width.\n */\n\n/** Width in bits of the MMTP `timestamp` field (NTP short). */\nexport const NTP_SHORT_BITS = 32\n\n/** Number of distinct NTP-short values; the field wraps to 0 here. */\nexport const NTP_SHORT_MODULUS = 2 ** NTP_SHORT_BITS\n\n/**\n * RFC 1982 \u00A73.2's `2^(SERIAL_BITS - 1)`. Two values whose forward distance is\n * below this are ordered; exactly this far apart they are not ordered at all.\n * Two instants must be less than this far apart (2^15 s, ~9.1 h of send time)\n * for the comparison to give their true order.\n */\nexport const NTP_SHORT_HALF_RANGE = 2 ** (NTP_SHORT_BITS - 1)\n\n/**\n * Serial order of one NTP-short value relative to another.\n *\n * `'unordered'` is RFC 1982's undefined case: the values are exactly\n * {@link NTP_SHORT_HALF_RANGE} apart, so neither precedes the other. It is\n * never folded into `'before'` or `'after'`; each caller decides what an\n * unorderable pair means for it.\n */\nexport type NtpShortOrder = 'before' | 'equal' | 'after' | 'unordered'\n\n/** True when `value` is an NTP-short value: an integer in [0, NTP_SHORT_MODULUS). */\nexport function isNtpShort(value: number): boolean {\n return Number.isInteger(value) && value >= 0 && value < NTP_SHORT_MODULUS\n}\n\n/**\n * RFC 1982 serial comparison of NTP-short `a` against `b`: `'after'` when `a`\n * is the later instant, `'before'` when it is the earlier one.\n *\n * The answer is the true order only while the two instants are less than\n * {@link NTP_SHORT_HALF_RANGE} apart. Past that a 32-bit field cannot tell\n * later from earlier, and the result names whichever direction is nearer.\n * This is not a total order (it is not transitive across the whole space), so\n * it must never be used to sort.\n *\n * @throws {RangeError} if either operand is not an NTP-short value\n */\nexport function compareNtpShort(a: number, b: number): NtpShortOrder {\n if (!isNtpShort(a) || !isNtpShort(b)) {\n throw new RangeError(\n `NTP-short values must be integers in [0, 2^${NTP_SHORT_BITS}), got ${String(a)} and ${String(b)}`,\n )\n }\n if (a === b) return 'equal'\n // Forward distance from b to a, reduced into [1, NTP_SHORT_MODULUS). Both\n // operands are below 2^32, so every step is exact in a double.\n const forward = (a - b + NTP_SHORT_MODULUS) % NTP_SHORT_MODULUS\n if (forward < NTP_SHORT_HALF_RANGE) return 'after'\n if (forward > NTP_SHORT_HALF_RANGE) return 'before'\n return 'unordered'\n}\n", "/**\n * FEC block profile (BLO-35597, ISO/IEC 23008-1 Annex C).\n *\n * Every catalog `fec` object that declares an FEC instance names its block\n * profile in `fec.blockProfile`. A receiver applies all of a profile's rules\n * or none of them, so the token is the one explicit per-stream discriminator:\n * it is never defaulted and never inferred from the wire.\n *\n * draft-ramadan-moq-fec \u00A75.1 defines exactly one value, and it is the only\n * profile this library implements:\n *\n * - `iso-ssbg1-v1`: ssbg_mode1 (C.3.3): a source symbol is\n * `u16 length || protected packet || zero padding` to T; a block is a\n * K' = SSB_length RaptorQ block (C.5.3) and repair ESI = SSB_length + RS_ID;\n * SS_ID increments by one per FEC source packet and wraps at 2^32 (C.5.2),\n * so a block is located by membership in `[SS_Start, SS_Start + SSB_length)`\n * under RFC 1982 serial arithmetic; the MoQ repair group id is the 62-bit\n * wrap-epoch-extended SS_Start. The AL-FEC coding byte for this profile is\n * 0x14 (one-stage, ssbg_mode1, fec_payload_id_mode 0, Amd 1:2025 Table C.3).\n *\n * A track whose `blockProfile` is absent or names any other token (the\n * retired Blockcast-private `k-padded-v1` included) has no FEC: a receiver\n * consumes its source without FEC and joins none of its repair tracks\n * (draft-ramadan-moq-fec \u00A75.1). `parseFecBlockProfile` throws for such a\n * token; the per-track catalog resolver turns the same rule into a typed\n * per-track \"FEC unavailable\" outcome instead of failing the session.\n */\nimport { serial32Add, serial32Distance, serial32Precedes } from './serial-number.js'\n\n/** The block profile a catalog `fec.blockProfile` may name: the one this library implements. */\nexport type FecBlockProfile = 'iso-ssbg1-v1'\n\n/** Every accepted `fec.blockProfile` token. */\nexport const FEC_BLOCK_PROFILES: readonly FecBlockProfile[] = Object.freeze([\n 'iso-ssbg1-v1',\n])\n\n/** True for a block-profile token this library implements. */\nexport function isFecBlockProfile(value: unknown): value is FecBlockProfile {\n return value === 'iso-ssbg1-v1'\n}\n\n/**\n * Read a required `fec.blockProfile`. Throws on an absent token and on any\n * token other than `iso-ssbg1-v1`: there is no default and nothing is\n * inferred from the wire (draft-ramadan-moq-fec \u00A75.1).\n *\n * @param where the catalog path of the field, for the error message.\n */\nexport function parseFecBlockProfile(value: unknown, where: string): FecBlockProfile {\n if (isFecBlockProfile(value)) return value\n if (value === undefined) {\n throw new Error(`${where} is required: name the FEC block profile (\"iso-ssbg1-v1\")`)\n }\n throw new Error(`${where} must be \"iso-ssbg1-v1\" (got ${JSON.stringify(value)})`)\n}\n\n/** ISO/IEC 23008-1 C.3.3 ssbg_mode1: the two-octet packet length field. */\nexport const SSBG1_LENGTH_FIELD_BYTES = 2\n\n/** The largest protected packet an ssbg_mode1 symbol of size T can carry. */\nexport function ssbg1MaxPacketLength(symbolSize: number): number {\n return symbolSize - SSBG1_LENGTH_FIELD_BYTES\n}\n\n/** Whether a protected packet of `packetLength` bytes fits one T-byte ssbg_mode1 symbol. */\nexport function ssbg1FitsSymbol(packetLength: number, symbolSize: number): boolean {\n return (\n Number.isSafeInteger(packetLength) &&\n packetLength >= 0 &&\n packetLength <= ssbg1MaxPacketLength(symbolSize) &&\n packetLength <= 0xffff\n )\n}\n\n/**\n * Build one ssbg_mode1 source symbol (C.3.3): the protected packet's length\n * in two octets, network byte order, then the packet, then zero octets up to\n * T. The protected packet is the MMTP packet before its Source FEC Payload ID\n * is appended (C.4.2).\n *\n * @throws when `length + 2 > T`: the packet cannot be protected under this\n * profile, and silently truncating it would corrupt every repair symbol.\n */\nexport function buildSsbg1SourceSymbol(packet: Uint8Array, symbolSize: number): Uint8Array {\n if (!Number.isSafeInteger(symbolSize) || symbolSize <= SSBG1_LENGTH_FIELD_BYTES) {\n throw new Error(`ssbg_mode1 symbol size must exceed ${SSBG1_LENGTH_FIELD_BYTES} (got ${symbolSize})`)\n }\n if (!ssbg1FitsSymbol(packet.byteLength, symbolSize)) {\n throw new Error(\n `ssbg_mode1 source symbol needs ${packet.byteLength} + ${SSBG1_LENGTH_FIELD_BYTES} bytes but T is ${symbolSize}`,\n )\n }\n const symbol = new Uint8Array(symbolSize)\n symbol[0] = (packet.byteLength >>> 8) & 0xff\n symbol[1] = packet.byteLength & 0xff\n symbol.set(packet, SSBG1_LENGTH_FIELD_BYTES)\n return symbol\n}\n\n/**\n * Recover the protected packet from one ssbg_mode1 source symbol: the bytes\n * the length field names. Returns null, never a guess, when the length field\n * points past the symbol or any padding octet is non-zero (C.3.3 padding is\n * all 00h), since either means the recovered symbol is not what was sent.\n */\nexport function trimSsbg1SourceSymbol(symbol: Uint8Array): Uint8Array | null {\n if (symbol.byteLength < SSBG1_LENGTH_FIELD_BYTES) return null\n const length = (symbol[0]! << 8) | symbol[1]!\n const end = SSBG1_LENGTH_FIELD_BYTES + length\n if (end > symbol.byteLength) return null\n for (let i = end; i < symbol.byteLength; i++) {\n if (symbol[i] !== 0) return null\n }\n return symbol.subarray(SSBG1_LENGTH_FIELD_BYTES, end)\n}\n\n/** The SS_ID after the last source symbol of `[ssStart, ssStart + ssbLength)`. */\nexport function isoBlockEnd(ssStart: number, ssbLength: number): number {\n return serial32Add(ssStart, ssbLength)\n}\n\n/**\n * Range membership (C.5.2, C.5.3): whether `ssId` is one of the\n * `ssbLength` consecutive SS_IDs starting at `ssStart`, modulo 2^32.\n */\nexport function isoBlockContains(ssStart: number, ssbLength: number, ssId: number): boolean {\n return serial32Distance(ssStart, ssId) < ssbLength\n}\n\n/**\n * A lower bound on how many blocks the block starting at `a` lies behind the\n * one starting at `b` (0 when `a` does not precede `b`). An iso-ssbg1-v1\n * block holds at most `kMax` source symbols (the catalog `sourceSymbols`, the\n * AL-FEC maximum_k_for_repair_flow), so `n * kMax` SS_IDs always span at least\n * `n` blocks. Every interleave horizon in the receiver (decoder retention,\n * worker retirement, ordered-relay settlement) uses this one bound, so the\n * manager's horizon can never fall inside the decoder's.\n */\nexport function isoBlocksBehindLowerBound(a: number, b: number, kMax: number): number {\n if (!Number.isSafeInteger(kMax) || kMax <= 0) {\n throw new Error(`iso-ssbg1-v1 block horizon needs a positive maximum K (got ${kMax})`)\n }\n return serial32Precedes(a, b) ? Math.floor(serial32Distance(a, b) / kMax) : 0\n}\n", "// Typed FEC state shared by every player (hang/moq-lib, moqtail, Shaka MSF).\n//\n// A player's FEC counters are `null` in three unrelated situations: the\n// session is on reliable MoQ, where FEC has nothing to protect (FEC protects\n// only lossy multicast/AMT datagrams); no multicast bridge exists, so no lossy\n// leg can be joined; or the catalog declares no FEC for the tracks the player\n// selected. `null` also meant \"nothing decoded yet\" and \"the pipeline broke\",\n// so an idle session and a broken one looked identical.\n//\n// `resolveFecState` names which case holds. Each reason is read from a fact the\n// player already owns -- its catalog, its transport policy, its bridge probe\n// and its physical subscription -- and never from counters, console text,\n// timers or elapsed time. The rules live here so the three players cannot\n// disagree about precedence.\n\nimport { isFecBlockProfile } from '@blockcast/mmt-base'\n\n/** Smallest positive catalog elapsed span; zero/absence means no elapsed deadline. */\nexport const MIN_INTERLEAVE_DEPTH_MS = 1\n\n/** Why FEC is not protecting this session. */\nexport type FecInactiveReason = 'no-catalog-fec' | 'reliable-moq' | 'no-multicast-bridge'\n\n/** Every inactive reason, in resolution order. */\nexport const FEC_INACTIVE_REASONS: readonly FecInactiveReason[] = Object.freeze([\n 'no-catalog-fec',\n 'reliable-moq',\n 'no-multicast-bridge',\n] as const)\n\n/** The transport policy vocabulary every player accepts. */\nexport type FecTransportPolicy = 'auto' | 'moq-only' | 'multicast-only'\n\nconst TRANSPORT_POLICIES: ReadonlySet<string> = new Set<FecTransportPolicy>(['auto', 'moq-only', 'multicast-only'])\n\n/** FEC is not protecting this session; `reason` says why. Carries no counters. */\nexport interface FecInactiveState {\n readonly state: 'inactive'\n readonly reason: FecInactiveReason\n}\n\n/**\n * FEC is the protection in force for this session's delivery path.\n *\n * Flat on purpose: the player's existing counters stay at the paths every\n * consumer already reads (`fec.blocksRecovered`, `fec.tracks`, `fec.blocks`),\n * with `state` added beside them. A consumer that ignores `state` reads an\n * active report exactly as before and an inactive one as \"no counters\", which\n * is what `null` meant to it.\n */\nexport type FecActiveState<S extends object> = S & { readonly state: 'active' }\n\nexport type FecState<S extends object> = FecActiveState<S> | FecInactiveState\n\n/** An active state whose decoder has not reported any counter yet. */\nexport type NoFecCounters = Record<never, never>\n\n/** The authoritative facts `resolveFecState` reads. */\nexport interface FecStateEvidence<S extends object> {\n /**\n * The counters the player reports today, or null/undefined when it has none.\n * Payload only: it never decides the state, because moqtail and Shaka report\n * a zeroed snapshot as soon as a MulticastManager exists, which is before any\n * bridge or subscription does.\n */\n readonly stats: S | null | undefined\n /**\n * Whether the catalog declares FEC (see `catalogDeclaresFec`) for at least\n * one media track the player selected.\n */\n readonly catalogFec: boolean\n /** The player's configured transport policy. */\n readonly transportPolicy: FecTransportPolicy\n /** Whether a multicast bridge (`window.multicast`) is available to the page. */\n readonly bridgeAvailable: boolean\n /**\n * Whether a physical multicast/AMT subscription is live: the bridge accepted\n * it and it has not been closed. A requested leg is not a joined one.\n */\n readonly multicastLegJoined: boolean\n}\n\nconst INACTIVE: Readonly<Record<FecInactiveReason, FecInactiveState>> = Object.freeze({\n 'no-catalog-fec': Object.freeze({ state: 'inactive', reason: 'no-catalog-fec' }),\n 'reliable-moq': Object.freeze({ state: 'inactive', reason: 'reliable-moq' }),\n 'no-multicast-bridge': Object.freeze({ state: 'inactive', reason: 'no-multicast-bridge' }),\n})\n\nfunction recordOf(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\nfunction isPositiveSafeInteger(value: unknown): boolean {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0\n}\n\n/**\n * Whether one catalog `fec` block (a hang rendition's `fec` or an MSF/CMSF\n * track's `fec`) declares an FEC instance a receiver can configure: source\n * symbols per block (K) and a symbol size (T) are both positive integers, the\n * algorithm is not `none`, `blockProfile` names the implemented profile\n * `iso-ssbg1-v1` (BLO-35597), and the block carries that profile's usable\n * span field (`isoBlockSpanUsable`); zero/absence still permits in-band FEC. Total: it never throws, and answers false for\n * any other value.\n *\n * `resolveCatalogTrackFec` reads this predicate, so the players' parameters and\n * this state never disagree. Of the blocks this rejects, it returns no FEC\n * geometry only for `algorithm: \"none\"`. One with any other algorithm is a\n * malformed catalog (`FecCatalogConfig` marks both fields REQUIRED; the MSF\n * schema and `validateCmsfMmtpCatalog` enforce them on `tracks[]`, but the\n * hang dialect's `renditions` schema is permissive, so this is where a hang\n * block fails closed), and `resolveCatalogTrackFec` throws a `RepairContractError` for\n * it (`track_fec` unless another repair-contract violation fires first),\n * whether or not the source has repair layers, rather than silently dropping\n * the track's repair subscription.\n *\n * The block profile is part of this predicate because the profile selects the\n * block math and is never defaulted: draft-ramadan-moq-fec \u00A75.1 defines one,\n * `iso-ssbg1-v1`, and a receiver MUST NOT apply FEC under any other token. The\n * retired `k-padded-v1` is simply not a known profile. `resolveCatalogTrackFec`\n * and `MulticastManager.configureMultiTrack` resolve such a track to no FEC\n * with a typed `TrackFecUnavailable` reason (`catalogFecUnavailable`: code\n * `track_fec_block_profile_unimplemented` for an unimplemented token,\n * `track_fec_block_profile` for an absent one), scoped to that track, so their\n * parameters and this state still agree. The CMSF conformance validator\n * (`validateCmsfMmtpCatalog`) rejects the catalog with the same code. An\n * `iso-ssbg1-v1` instance with an invalid span is likewise unavailable for its\n * track alone. Zero or absence supplies no elapsed deadline and uses bounded\n * receiver-local state while decoding in-band FEC.\n *\n * The repair-contract resolvers (`resolveRepairLayers`) gate a `depends` target\n * on `algorithm` alone and never read a source's `symbolSize`. They check its\n * `sourceSymbols` for the RaptorQ K bound, and require a positive integer\n * `sourceSymbols` and `repairSymbols` only when the source has repair layers or\n * an overlay beyond layer 0.\n */\nexport function catalogDeclaresFec(fec: unknown): boolean {\n const block = recordOf(fec)\n if (block === undefined || block['algorithm'] === 'none') return false\n return (\n isPositiveSafeInteger(block['sourceSymbols']) &&\n isPositiveSafeInteger(block['symbolSize']) &&\n isFecBlockProfile(block['blockProfile']) &&\n isoBlockSpanUsable(block)\n )\n}\n\n/** Validate the optional elapsed span without requiring one for in-band FEC. */\nexport function isoBlockSpanUsable(fec: unknown): boolean {\n const block = recordOf(fec)\n if (block === undefined || block['blockProfile'] !== 'iso-ssbg1-v1') return true\n const ms = block['interleaveDepthMs']\n return ms === undefined || (typeof ms === 'number' && Number.isSafeInteger(ms) && ms >= 0)\n}\n\nfunction requireBoolean(value: unknown, field: string): boolean {\n if (typeof value !== 'boolean') {\n throw new TypeError(`resolveFecState: ${field} must be a boolean, got ${typeof value}`)\n }\n return value\n}\n\n/**\n * Resolve a player's FEC state. First match wins:\n *\n * 1. The catalog declares no FEC for a selected track: `no-catalog-fec`. FEC\n * geometry comes only from the catalog, so there is nothing to configure on\n * any path.\n * 2. The policy is `moq-only`: `reliable-moq`. Media travels only over QUIC,\n * which is reliable, so FEC has no loss to repair, bridge or not.\n * 3. No multicast bridge: `no-multicast-bridge`. No lossy leg can exist, and on\n * `auto` this is the reason the session is on reliable MoQ.\n * 4. The policy is `multicast-only`, or a lossy subscription is live: active.\n * `multicast-only` commits the session to the lossy leg, so FEC is in force\n * before the join completes; whether the join succeeded is the physical\n * attestation's question, not this one. The counters may be absent until\n * the decoder reports.\n * 5. Otherwise (`auto`, a bridge, no live subscription): `reliable-moq`.\n *\n * Throws on malformed evidence rather than picking a reason for it.\n */\nexport function resolveFecState<S extends object>(evidence: FecStateEvidence<S> & { readonly stats: S }): FecState<S>\nexport function resolveFecState<S extends object>(evidence: FecStateEvidence<S>): FecState<S | NoFecCounters>\nexport function resolveFecState<S extends object>(evidence: FecStateEvidence<S>): FecState<S | NoFecCounters> {\n const catalogFec = requireBoolean(evidence.catalogFec, 'catalogFec')\n const bridgeAvailable = requireBoolean(evidence.bridgeAvailable, 'bridgeAvailable')\n const multicastLegJoined = requireBoolean(evidence.multicastLegJoined, 'multicastLegJoined')\n const { transportPolicy, stats } = evidence\n if (typeof transportPolicy !== 'string' || !TRANSPORT_POLICIES.has(transportPolicy)) {\n throw new TypeError(`resolveFecState: unsupported transportPolicy ${JSON.stringify(transportPolicy)}`)\n }\n if (stats !== null && stats !== undefined && recordOf(stats) === undefined) {\n throw new TypeError('resolveFecState: stats must be a plain object, null or undefined')\n }\n\n if (!catalogFec) return INACTIVE['no-catalog-fec']\n if (transportPolicy === 'moq-only') return INACTIVE['reliable-moq']\n if (!bridgeAvailable) return INACTIVE['no-multicast-bridge']\n if (transportPolicy === 'multicast-only' || multicastLegJoined) {\n // The discriminant is written last so a stats field of the same name can\n // never masquerade as a state.\n return { ...(stats ?? {}), state: 'active' } as FecActiveState<S | NoFecCounters>\n }\n return INACTIVE['reliable-moq']\n}\n"],
5
- "mappings": ";AAiBA,IAAM,kBAAkB;AACxB,IAAM,wBAAwB;AAC9B,IAAM,4BAA4B,kBAAkB;;;AC0D7C,IAAMA,mBAAkB;AAI/B,IAAMC,yBAAwB;AAC9B,IAAMC,6BAA4BC,mBAAkBF;;;ACrE7C,IAAM,iBAAiB;AAGvB,IAAM,oBAAoB,KAAK;AAQ/B,IAAM,uBAAuB,MAAM,iBAAiB;;;ACSpD,IAAM,qBAAiD,OAAO,OAAO;EAC1E;CACD;AAGK,SAAU,kBAAkB,OAAc;AAC9C,SAAO,UAAU;AACnB;;;ACtBO,IAAM,0BAA0B;AAMhC,IAAM,uBAAqD,OAAO,OAAO;AAAA,EAC9E;AAAA,EACA;AAAA,EACA;AACF,CAAU;AAKV,IAAM,qBAA0C,oBAAI,IAAwB,CAAC,QAAQ,YAAY,gBAAgB,CAAC;AAiDlH,IAAM,WAAkE,OAAO,OAAO;AAAA,EACpF,kBAAkB,OAAO,OAAO,EAAE,OAAO,YAAY,QAAQ,iBAAiB,CAAC;AAAA,EAC/E,gBAAgB,OAAO,OAAO,EAAE,OAAO,YAAY,QAAQ,eAAe,CAAC;AAAA,EAC3E,uBAAuB,OAAO,OAAO,EAAE,OAAO,YAAY,QAAQ,sBAAsB,CAAC;AAC3F,CAAC;AAED,SAAS,SAAS,OAAqD;AACrE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,IACrE,QACD;AACN;AAEA,SAAS,sBAAsB,OAAyB;AACtD,SAAO,OAAO,UAAU,YAAY,OAAO,cAAc,KAAK,KAAK,QAAQ;AAC7E;AA0CO,SAAS,mBAAmB,KAAuB;AACxD,QAAM,QAAQ,SAAS,GAAG;AAC1B,MAAI,UAAU,UAAa,MAAM,WAAW,MAAM,OAAQ,QAAO;AACjE,SACE,sBAAsB,MAAM,eAAe,CAAC,KAC5C,sBAAsB,MAAM,YAAY,CAAC,KACzC,kBAAkB,MAAM,cAAc,CAAC,KACvC,mBAAmB,KAAK;AAE5B;AAGO,SAAS,mBAAmB,KAAuB;AACxD,QAAM,QAAQ,SAAS,GAAG;AAC1B,MAAI,UAAU,UAAa,MAAM,cAAc,MAAM,eAAgB,QAAO;AAC5E,QAAM,KAAK,MAAM,mBAAmB;AACpC,SAAO,OAAO,UAAc,OAAO,OAAO,YAAY,OAAO,cAAc,EAAE,KAAK,MAAM;AAC1F;AAEA,SAAS,eAAe,OAAgB,OAAwB;AAC9D,MAAI,OAAO,UAAU,WAAW;AAC9B,UAAM,IAAI,UAAU,oBAAoB,KAAK,2BAA2B,OAAO,KAAK,EAAE;AAAA,EACxF;AACA,SAAO;AACT;AAuBO,SAAS,gBAAkC,UAA4D;AAC5G,QAAM,aAAa,eAAe,SAAS,YAAY,YAAY;AACnE,QAAM,kBAAkB,eAAe,SAAS,iBAAiB,iBAAiB;AAClF,QAAM,qBAAqB,eAAe,SAAS,oBAAoB,oBAAoB;AAC3F,QAAM,EAAE,iBAAiB,MAAM,IAAI;AACnC,MAAI,OAAO,oBAAoB,YAAY,CAAC,mBAAmB,IAAI,eAAe,GAAG;AACnF,UAAM,IAAI,UAAU,gDAAgD,KAAK,UAAU,eAAe,CAAC,EAAE;AAAA,EACvG;AACA,MAAI,UAAU,QAAQ,UAAU,UAAa,SAAS,KAAK,MAAM,QAAW;AAC1E,UAAM,IAAI,UAAU,kEAAkE;AAAA,EACxF;AAEA,MAAI,CAAC,WAAY,QAAO,SAAS,gBAAgB;AACjD,MAAI,oBAAoB,WAAY,QAAO,SAAS,cAAc;AAClE,MAAI,CAAC,gBAAiB,QAAO,SAAS,qBAAqB;AAC3D,MAAI,oBAAoB,oBAAoB,oBAAoB;AAG9D,WAAO,EAAE,GAAI,SAAS,CAAC,GAAI,OAAO,SAAS;AAAA,EAC7C;AACA,SAAO,SAAS,cAAc;AAChC;",
6
- "names": ["MPU_HEADER_SIZE", "MPU_LENGTH_FIELD_SIZE", "MPU_HEADER_REMAINDER_SIZE", "MPU_HEADER_SIZE"]
3
+ "sources": ["../../mmt-base/src/mmtp.ts", "../../mmt-base/src/ntp-short.ts", "../../mmt-base/src/fec-block-profile.ts", "../../mmt-base/src/catalog-fec-source.ts", "../src/fec-state.ts"],
4
+ "sourcesContent": ["/**\n * @mmt/container - MMTP Parser\n *\n * MMTP (MMT Protocol) packet parser based on ISO/IEC 23008-1:2023 Section 9.2\n *\n * MMTP header format (12 bytes):\n * - Byte 0: V(2) | C(1) | FEC_type(2) | r(1) | X(1) | R(1)\n * - Byte 1: reserved(2) | packet_type(6)\n * - Bytes 2-3: packet_id (big-endian)\n * - Bytes 4-7: timestamp (big-endian, 32-bit)\n * - Bytes 8-11: sequence_number (big-endian)\n *\n * FEC_type values:\n * - 0: No FEC / source packet\n * - 1: FEC mode 0 (source with FEC payload ID)\n * - 2: FEC repair packet mode 0\n * - 3: FEC repair packet mode 1\n *\n * @packageDocumentation\n */\n\nexport interface MMTPHeader {\n version: number\n /** Packet type: 0x00=MPU, 0x02=Signaling, 0x03=Repair */\n packetType: number\n packetId: number\n timestamp: bigint\n sequenceNumber: number\n payloadLength: number\n fecType: number\n /** C flag: header carries a 32-bit packet_counter. */\n packetCounterFlag: boolean\n packetCounter?: number\n /** X flag: header carries an extension header and value. */\n extensionFlag: boolean\n extension?: { type: number; data: Uint8Array }\n /** Byte offset at which the MMTP payload begins. */\n headerLength: number\n /** Random Access Point flag - indicates keyframe (ISO 23008-1, byte 0 bit 0) */\n rapFlag: boolean\n}\n\nexport interface MPUHeader {\n mpuSequenceNumber: number\n fragmentationIndicator: number // FI: 0=complete, 1=first, 2=middle, 3=last\n /** 8-bit MPU fragment_counter from byte 3. */\n fragmentCounter: number\n /** T flag: 1=timed media (14-byte MFU DU header), 0=non-timed (4-byte header) */\n timedFlag: number\n /** A flag: aggregated MPU payload. This strict profile requires A=0. */\n aggregationFlag: boolean\n /** MPU payload_length (bytes 0-1): bytes after the length field, including\n * the remaining six MPU-header bytes and all data-unit bytes. */\n payloadLength: number\n}\n\nexport interface MFUDuHeader {\n movieFragmentSequenceNumber: number\n sampleNumber: number\n offset: number\n priority: number\n dependencyCounter: number\n}\n\nexport interface MMTPPacket {\n header: MMTPHeader\n payload: Uint8Array\n}\n\nexport const MMTP_HEADER_SIZE = 12\nexport const MPU_HEADER_SIZE = 8\nexport const MFU_DU_HEADER_SIZE_TIMED = 14 // T=1: timed media (video/audio samples)\nexport const MFU_DU_HEADER_SIZE_NONTIMED = 4 // T=0: non-timed media (item_id only)\n\nconst MPU_LENGTH_FIELD_SIZE = 2\nconst MPU_HEADER_REMAINDER_SIZE = MPU_HEADER_SIZE - MPU_LENGTH_FIELD_SIZE\nconst SOURCE_FEC_PAYLOAD_ID_SIZE = 4\n\n// MMTP Packet Types (ISO/IEC 23008-1:2023 Section 9.2.2)\nexport const PACKET_TYPE_MPU = 0x00\nexport const PACKET_TYPE_SIGNALING = 0x02\nexport const PACKET_TYPE_REPAIR = 0x03\n\n// AL-FEC Signaling Message ID (ISO/IEC 23008-1:2023 Amendment 1:2025)\nexport const ALFEC_MESSAGE_ID = 0x0203\n\n/**\n * MMTP `packet_id` of the signaling flow, which carries PACKET_TYPE_SIGNALING\n * packets such as the AL-FEC message (ALFEC_MESSAGE_ID). The FFmpeg `moq_mmt`\n * muxer sends that message on this packet_id into the same multicast group as\n * the media, and moqcast-draft (PR #44) makes advertising it for a track a\n * MUST NOT. A track's packet_id is therefore 1..MMTP_PACKET_ID_MAX.\n */\nexport const MMTP_SIGNALING_PACKET_ID = 0\n\n/** Largest value of the 16-bit MMTP `packet_id` header field. */\nexport const MMTP_PACKET_ID_MAX = 0xffff\n\n// FEC Code IDs\nexport const FEC_CODE_XOR = 1\nexport const FEC_CODE_RAPTORQ = 2\n\n/**\n * Parse MMTP header from buffer\n */\nexport function parseMMTPHeader(buffer: Uint8Array): MMTPHeader {\n if (buffer.length < MMTP_HEADER_SIZE) {\n throw new Error(`MMTP packet too small: ${buffer.length} bytes`)\n }\n\n const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength)\n\n const version = (buffer[0]! >> 6) & 0x03\n if (version !== 0) {\n throw new Error(`Unsupported MMTP version: ${version}`)\n }\n\n // Extract FEC type from byte 0, bits 3-4\n const fecType = (buffer[0]! >> 3) & 0x03\n const packetCounterFlag = (buffer[0]! & 0x20) !== 0\n const extensionFlag = (buffer[0]! & 0x02) !== 0\n\n // Extract RAP flag from byte 0, bit 0 (R bit - Random Access Point)\n const rapFlag = (buffer[0]! & 0x01) === 1\n\n // ISO/IEC 23008-1:2023 Figure 8 (V=0) places reserved(2) before\n // packet_type(6), so packet_type occupies the low six bits of byte 1.\n const packetType = buffer[1]! & 0x3F\n\n let offset = 2\n\n // Packet ID (2 bytes, big-endian)\n const packetId = view.getUint16(offset, false)\n offset += 2\n\n // Timestamp (4 bytes, big-endian)\n const timestamp = BigInt(view.getUint32(offset, false))\n offset += 4\n\n // Sequence number (4 bytes, big-endian)\n const sequenceNumber = view.getUint32(offset, false)\n offset += 4\n\n let packetCounter: number | undefined\n if (packetCounterFlag) {\n if (offset + 4 > buffer.length) throw new Error('MMTP packet truncated in packet_counter')\n packetCounter = view.getUint32(offset, false)\n offset += 4\n }\n\n let extension: { type: number; data: Uint8Array } | undefined\n if (extensionFlag) {\n if (offset + 4 > buffer.length) throw new Error('MMTP packet truncated in header extension')\n const type = view.getUint16(offset, false)\n const length = view.getUint16(offset + 2, false)\n offset += 4\n if (offset + length > buffer.length) throw new Error('MMTP packet truncated in header extension value')\n extension = { type, data: buffer.subarray(offset, offset + length) }\n offset += length\n }\n\n return {\n version,\n packetType,\n packetId,\n timestamp,\n sequenceNumber,\n payloadLength: buffer.length - offset,\n fecType,\n packetCounterFlag,\n packetCounter,\n extensionFlag,\n extension,\n headerLength: offset,\n rapFlag,\n }\n}\n\n/**\n * The MMTP `packet_id` of `buffer`, or null exactly when parseMMTPHeader would\n * throw for it (short buffer, V != 0, truncated packet_counter or header\n * extension).\n *\n * This is the per-packet filter a receiver runs before any other work, so it\n * builds no header object, DataView or BigInt timestamp (BLO-36599). Use\n * parseMMTPHeader when any other header field is needed.\n */\nexport function readMMTPPacketId(buffer: Uint8Array): number | null {\n if (buffer.length < MMTP_HEADER_SIZE) return null\n const flags = buffer[0]!\n if (((flags >> 6) & 0x03) !== 0) return null\n let offset = MMTP_HEADER_SIZE\n if ((flags & 0x20) !== 0) {\n if (offset + 4 > buffer.length) return null\n offset += 4\n }\n if ((flags & 0x02) !== 0) {\n if (offset + 4 > buffer.length) return null\n const length = (buffer[offset + 2]! << 8) | buffer[offset + 3]!\n if (offset + 4 + length > buffer.length) return null\n }\n return (buffer[2]! << 8) | buffer[3]!\n}\n\n/**\n * Unwrap MMTP packet to extract payload\n */\nexport function unwrapMMTP(buffer: Uint8Array): MMTPPacket {\n const header = parseMMTPHeader(buffer)\n const payload = buffer.subarray(header.headerLength)\n\n return { header, payload }\n}\n\n/**\n * Parse MPU header from payload\n * ISO/IEC 23008-1:2023 Section 9.2.3.3\n *\n * MPU Header format (8 bytes) as written by FFmpeg/libmmt:\n * - Bytes 0-1: payload_length (16 bits, big-endian)\n * - Byte 2: FT(4) | T(1) | FI(2) | A(1)\n * - Byte 3: fragment_counter (8 bits)\n * - Bytes 4-7: MPU_sequence_number (32 bits, big-endian)\n */\nexport function parseMPUHeader(payload: Uint8Array): MPUHeader {\n if (payload.length < MPU_HEADER_SIZE) {\n throw new Error(`Payload too small for MPU header: ${payload.length} bytes`)\n }\n\n const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength)\n\n // Bytes 0-1: payload_length (16 bits, big-endian)\n const payloadLength = view.getUint16(0, false)\n\n // Byte 2: FT(4) | T(1) | FI(2) | A(1)\n const flagsByte = payload[2]!\n const timedFlag = (flagsByte >> 3) & 0x01\n const fragmentationIndicator = (flagsByte >> 1) & 0x03\n const aggregationFlag = (flagsByte & 0x01) !== 0\n\n // Byte 3: fragment_counter (8 bits). The high bit is part of the counter in\n // the current libmmt/FFmpeg writer ABI.\n const fragmentCounter = payload[3]!\n\n // Bytes 4-7: MPU_sequence_number (32 bits, big-endian)\n const mpuSequenceNumber = view.getUint32(4, false)\n\n return {\n mpuSequenceNumber,\n fragmentationIndicator,\n fragmentCounter,\n timedFlag,\n aggregationFlag,\n payloadLength,\n }\n}\n\nexport function parseTimedMfuDuHeader(payload: Uint8Array, offset: number): MFUDuHeader | null {\n if (offset < 0 || offset + MFU_DU_HEADER_SIZE_TIMED > payload.length) return null\n const view = new DataView(payload.buffer, payload.byteOffset + offset, MFU_DU_HEADER_SIZE_TIMED)\n return {\n movieFragmentSequenceNumber: view.getUint32(0, false),\n sampleNumber: view.getUint32(4, false),\n offset: view.getUint32(8, false),\n priority: payload[offset + 12]!,\n dependencyCounter: payload[offset + 13]!,\n }\n}\n\n/**\n * Why `extractMFUPayload` refused a packet.\n *\n * These identifiers are part of the public contract: callers surface them in\n * diagnostics, so renaming one is a breaking change.\n */\nexport type MFURejectionGate =\n | 'packet-shorter-than-mmtp-plus-mpu-header'\n | 'mmtp-header-unparseable'\n | 'not-an-mpu-packet'\n | 'payload-shorter-than-mpu-header'\n | 'aggregation-flag-set'\n | 'mpu-payload-length-below-header-remainder'\n | 'mpu-declared-end-exceeds-payload'\n | 'mfu-offset-at-or-past-declared-end'\n | 'source-fec-payload-id-width-mismatch'\n | 'declared-trailers-unresolved'\n\nexport interface MFURejection {\n gate: MFURejectionGate\n /** Human-readable detail, including the byte arithmetic that decided it. */\n detail: string\n}\n\ninterface MfuPayloadLayout {\n hasMfuDuHeader: boolean\n mfuOffset: number\n dataEnd: number\n}\n\nfunction resolveMfuPayloadLayout(\n mpu: MPUHeader,\n fragmentType: number,\n payload: Uint8Array,\n): { layout: MfuPayloadLayout } | { rejection: MFURejection } {\n if (mpu.payloadLength < MPU_HEADER_REMAINDER_SIZE) {\n return {\n rejection: {\n gate: 'mpu-payload-length-below-header-remainder',\n detail: `payload_length=${mpu.payloadLength} < ${MPU_HEADER_REMAINDER_SIZE}`,\n },\n }\n }\n\n // ISO/IEC 23008-1 defines payload_length from immediately after its own\n // two-byte field. It therefore includes the remaining six MPU-header bytes.\n const declaredEnd = MPU_LENGTH_FIELD_SIZE + mpu.payloadLength\n if (declaredEnd > payload.length) {\n return {\n rejection: {\n gate: 'mpu-declared-end-exceeds-payload',\n detail:\n `payload_length=${mpu.payloadLength} implies end=${declaredEnd}, ` +\n `payload is ${payload.length} bytes`,\n },\n }\n }\n\n const hasHeader = fragmentType === 2 && mpu.fragmentationIndicator <= 1\n const mfuHeaderSize = mpu.timedFlag ? MFU_DU_HEADER_SIZE_TIMED : MFU_DU_HEADER_SIZE_NONTIMED\n const mfuOffset = MPU_HEADER_SIZE + (hasHeader ? mfuHeaderSize : 0)\n if (mfuOffset >= declaredEnd) {\n return {\n rejection: {\n gate: 'mfu-offset-at-or-past-declared-end',\n detail: `mfuOffset=${mfuOffset} >= declaredEnd=${declaredEnd}`,\n },\n }\n }\n\n return {\n layout: {\n hasMfuDuHeader: hasHeader,\n mfuOffset,\n dataEnd: declaredEnd,\n },\n }\n}\n\n// Legacy detached per-packet authenticator suffix `[0xf0a1][len][auth]`. Its\n// producer was removed (BLO-16483) and nothing verifies it any more; provenance\n// is the signed per-group manifest. Receivers still skip an exact suffix so a\n// stale producer degrades to unauthenticated playback instead of dropped\n// packets. ponytail: hard-cut to reject once no deployed producer can emit it.\nconst LEGACY_TRAILER_EXT_TYPE = 0xf0a1\nconst LEGACY_TRAILER_HEADER_SIZE = 4\n\nfunction isEmptyOrExactLegacyTrailer(payload: Uint8Array, start: number, end: number): boolean {\n if (start === end) return true\n if (start < 0 || end > payload.length || start + LEGACY_TRAILER_HEADER_SIZE > end) {\n return false\n }\n\n const view = new DataView(\n payload.buffer,\n payload.byteOffset + start,\n end - start,\n )\n if (view.getUint16(0, false) !== LEGACY_TRAILER_EXT_TYPE) return false\n\n const authLength = view.getUint16(2, false)\n return start + LEGACY_TRAILER_HEADER_SIZE + authLength === end\n}\n\ninterface DeclaredTrailerLayout {\n hasFecId: boolean\n}\n\nfunction resolveDeclaredTrailers(\n payload: Uint8Array,\n declaredEnd: number,\n fecType: number,\n options?: { skipFecId?: boolean },\n): DeclaredTrailerLayout | null {\n if (declaredEnd > payload.length) return null\n\n if (options?.skipFecId) {\n return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)\n ? { hasFecId: false }\n : null\n }\n\n if (fecType === 1) {\n const fecStart = payload.length - SOURCE_FEC_PAYLOAD_ID_SIZE\n if (fecStart < declaredEnd || !isEmptyOrExactLegacyTrailer(payload, declaredEnd, fecStart)) {\n return null\n }\n return { hasFecId: true }\n }\n if (fecType !== 0) return null\n\n if (isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)) {\n return { hasFecId: false }\n }\n\n return null\n}\n\n/**\n * Extract NAL unit payload from MMTP packet\n */\nexport function extractNALUnit(mmtpPacket: Uint8Array): Uint8Array {\n const extraction = extractMFUPayload(mmtpPacket)\n if (!extraction) throw new Error('Malformed MMTP MPU payload')\n return extraction.data\n}\n\n/** Result of extracting MFU payload from an MMTP packet */\nexport interface MFUExtraction {\n /** MMTP header fields */\n header: MMTPHeader\n /** MPU header fields */\n mpu: MPUHeader\n /** Fragment type (FT field, 4 bits): 0=metadata, 2=MFU data */\n fragmentType: number\n /** MFU payload data (video/audio bytes, headers stripped, FEC ID excluded) */\n data: Uint8Array\n /** Parsed timed MFU DU header when present, otherwise null */\n mfuDuHeader: MFUDuHeader | null\n /** Non-timed MFU Item_ID when the 4-byte DU header is present. */\n itemId: number | null\n /** Source FEC Payload ID if present (`FEC_type == 1`), or null */\n fecPayloadId: { ssId: number } | null\n}\n\n/**\n * Extract MFU payload from a raw MMTP packet.\n *\n * Handles all the byte arithmetic for:\n * - MMTP header (12 bytes)\n * - MPU sub-header (8 bytes, payloadLength field)\n * - MFU DU header (14 bytes timed / 4 bytes non-timed, only for FI \u2264 1)\n * - Source FEC Payload ID (4 bytes at end, only when `FEC_type == 1`)\n *\n * `payloadLength` is the ISO length-after-field value: six remaining MPU-header\n * bytes, then the MFU DU header when present, then media. The legacy\n * authenticator suffix and the Source FEC trailer are outside that declared span and must consume the exact suffix.\n *\n * @param mmtpPacket Raw MMTP packet (from multicast or MoQ)\n * @param options.skipFecId When true, do NOT subtract the 4-byte Source FEC Payload ID\n * from the payload boundary, even if fecType >= 1 in the MMTP header. Use this for\n * FEC-recovered symbols where the FEC PID was already stripped before WASM decoding\n * but the fecType bits in byte 0 still reflect the original packet (FEC Type=1 per\n * draft-ramadan-moq-mmt-00 \u00A73.1).\n * @returns Extracted MFU data + metadata, or null if packet is too small\n */\ninterface MfuPlan {\n header: MMTPHeader\n payload: Uint8Array\n mpu: MPUHeader\n fragmentType: number\n layout: MfuPayloadLayout\n trailerLayout: DeclaredTrailerLayout\n}\n\n/**\n * Single source of truth for whether a packet yields an MFU payload.\n *\n * `extractMFUPayload` and `explainMFURejection` both delegate here, so the\n * reason reported to operators can never drift from the decision the parser\n * actually made.\n */\nfunction planMfuExtraction(\n mmtpPacket: Uint8Array,\n options?: { skipFecId?: boolean },\n parsedHeader?: MMTPHeader,\n): { plan: MfuPlan } | { rejection: MFURejection } {\n if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) {\n return {\n rejection: {\n gate: 'packet-shorter-than-mmtp-plus-mpu-header',\n detail: `${mmtpPacket.length} bytes < ${MMTP_HEADER_SIZE + MPU_HEADER_SIZE}`,\n },\n }\n }\n\n let header: MMTPHeader\n if (parsedHeader) {\n header = parsedHeader\n } else {\n try {\n header = parseMMTPHeader(mmtpPacket)\n } catch (error) {\n return {\n rejection: {\n gate: 'mmtp-header-unparseable',\n detail: error instanceof Error ? error.message : String(error),\n },\n }\n }\n }\n if (header.packetType !== PACKET_TYPE_MPU) {\n return {\n rejection: {\n gate: 'not-an-mpu-packet',\n detail: `packetType=0x${header.packetType.toString(16).padStart(2, '0')}`,\n },\n }\n }\n\n const payload = mmtpPacket.subarray(header.headerLength)\n if (payload.length < MPU_HEADER_SIZE) {\n return {\n rejection: {\n gate: 'payload-shorter-than-mpu-header',\n detail: `${payload.length} bytes < ${MPU_HEADER_SIZE}`,\n },\n }\n }\n\n const mpu = parseMPUHeader(payload)\n if (mpu.aggregationFlag) {\n return {\n rejection: { gate: 'aggregation-flag-set', detail: 'strict profile requires A=0' },\n }\n }\n\n // Fragment type from byte 2 upper nibble (not returned by parseMPUHeader)\n const fragmentType = (payload[2]! >> 4) & 0x0f\n\n const layoutResult = resolveMfuPayloadLayout(mpu, fragmentType, payload)\n if ('rejection' in layoutResult) return layoutResult\n const { layout } = layoutResult\n\n const trailerLayout = resolveDeclaredTrailers(\n payload,\n layout.dataEnd,\n header.fecType,\n options,\n )\n if (!trailerLayout) {\n // The most common cause is a producer whose Source FEC Payload ID width\n // disagrees with ISO/IEC 23008-1 \u00A7C.5.2. Name that explicitly rather than\n // leaving operators to infer it from a generic trailer error.\n if (!options?.skipFecId && header.fecType === 1) {\n const observed = payload.length - layout.dataEnd\n if (observed !== SOURCE_FEC_PAYLOAD_ID_SIZE) {\n return {\n rejection: {\n gate: 'source-fec-payload-id-width-mismatch',\n detail:\n `producer wrote a ${observed}-byte Source FEC Payload ID, ` +\n `ISO/IEC 23008-1 \u00A7C.5.2 requires ${SOURCE_FEC_PAYLOAD_ID_SIZE} ` +\n `(payload=${payload.length}, declaredEnd=${layout.dataEnd})`,\n },\n }\n }\n }\n return {\n rejection: {\n gate: 'declared-trailers-unresolved',\n detail:\n `trailer bytes [${layout.dataEnd}, ${payload.length}) are neither empty ` +\n `nor an exact legacy authenticator trailer (fecType=${header.fecType})`,\n },\n }\n }\n\n return { plan: { header, payload, mpu, fragmentType, layout, trailerLayout } }\n}\n\n/**\n * Report why `extractMFUPayload` would refuse this packet, or null if it would\n * accept it.\n *\n * `extractMFUPayload` returns bare `null` on ten distinct conditions, which\n * makes a producer/consumer framing disagreement indistinguishable from a\n * publisher that never started \u2014 both render as silence. Use this wherever\n * that distinction matters: diagnostics, contract tests, and operator-facing\n * logs.\n */\nexport function explainMFURejection(\n mmtpPacket: Uint8Array,\n options?: { skipFecId?: boolean },\n): MFURejection | null {\n const result = planMfuExtraction(mmtpPacket, options)\n return 'rejection' in result ? result.rejection : null\n}\n\nexport function extractMFUPayload(\n mmtpPacket: Uint8Array,\n options?: { skipFecId?: boolean },\n): MFUExtraction | null {\n return extractPlannedMfu(mmtpPacket, planMfuExtraction(mmtpPacket, options))\n}\n\n/**\n * extractMFUPayload for a caller that already holds this packet's parsed MMTP\n * header, so the header is not parsed a second time (BLO-36599).\n *\n * `header` must be `parseMMTPHeader(mmtpPacket)` of this same packet; the\n * result is then identical to `extractMFUPayload(mmtpPacket, options)`.\n */\nexport function extractMFUPayloadWithHeader(\n mmtpPacket: Uint8Array,\n header: MMTPHeader,\n options?: { skipFecId?: boolean },\n): MFUExtraction | null {\n return extractPlannedMfu(mmtpPacket, planMfuExtraction(mmtpPacket, options, header))\n}\n\nfunction extractPlannedMfu(\n mmtpPacket: Uint8Array,\n result: { plan: MfuPlan } | { rejection: MFURejection },\n): MFUExtraction | null {\n if ('rejection' in result) return null\n const { header, payload, mpu, fragmentType, layout, trailerLayout } = result.plan\n\n const mfuDuHeaderPresent = layout.hasMfuDuHeader\n const mfuOffset = layout.mfuOffset\n const dataEnd = layout.dataEnd\n\n const mfuDuHeader =\n mfuDuHeaderPresent && mpu.timedFlag === 1\n ? parseTimedMfuDuHeader(payload, MPU_HEADER_SIZE)\n : null\n const itemId =\n mfuDuHeaderPresent && mpu.timedFlag === 0\n ? new DataView(payload.buffer, payload.byteOffset + MPU_HEADER_SIZE, 4).getUint32(0, false)\n : null\n\n const data = payload.subarray(mfuOffset, dataEnd)\n\n const fecPayloadId = trailerLayout.hasFecId\n ? {\n ssId: new DataView(\n mmtpPacket.buffer,\n mmtpPacket.byteOffset + mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE,\n SOURCE_FEC_PAYLOAD_ID_SIZE,\n ).getUint32(0, false),\n }\n : null\n\n return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId }\n}\n\n/**\n * Extract timestamp from MMTP packet\n */\nexport function extractTimestamp(mmtpPacket: Uint8Array): bigint {\n const { header } = unwrapMMTP(mmtpPacket)\n return header.timestamp\n}\n\n/**\n * Check if MMTP packet is an FEC repair packet\n * FEC_type 2 and 3 are repair packets\n */\nexport function isFecRepairPacket(mmtpPacket: Uint8Array): boolean {\n if (mmtpPacket.length < 1) return false\n const fecType = (mmtpPacket[0]! >> 3) & 0x03\n return fecType >= 2\n}\n\n/**\n * Extract Source FEC Payload ID (SS_ID) from the last 4 bytes of an MMTP\n * source packet per ISO/IEC 23008-1:2023 Section C.5.2 Figure C.10.\n *\n * SS_ID is a flat 32-bit monotonic counter (incremented by 1 per packet\n * for ssbg_mode0 and ssbg_mode1). Block membership and ESI use the\n * configured K; repair SS_Start identifies the first SS_ID of the block and\n * SSB_length records the authored source-symbol count:\n * SBN = floor(SS_ID / K), ESI = SS_ID % K\n * SS_Start = SBN * K (first SS_ID of the block)\n *\n * This matches FFmpeg moqenc_mmt.c, the drafts (draft-ramadan-moq-fec \u00A76.2),\n * and ATSC A/331 \u00A78.1.2.5 which defers to ISO 23008-1 Annex C.\n */\nexport function extractFecPayloadId(mmtpPacket: Uint8Array): { ssId: number } | null {\n const header = parseHeaderForSourceFecId(mmtpPacket)\n return header ? sourceFecPayloadIdOf(mmtpPacket, header) : null\n}\n\n/**\n * Return true when FEC_type=1 and the exact suffix after the ISO-declared MPU\n * payload contains a four-byte Source FEC Payload ID.\n */\nexport function hasSourceFecPayloadId(mmtpPacket: Uint8Array): boolean {\n const header = parseHeaderForSourceFecId(mmtpPacket)\n return header !== null && sourceFecPayloadIdOf(mmtpPacket, header) !== null\n}\n\nfunction parseHeaderForSourceFecId(mmtpPacket: Uint8Array): MMTPHeader | null {\n if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) return null\n try {\n return parseMMTPHeader(mmtpPacket)\n } catch {\n return null\n }\n}\n\n/**\n * The Source FEC Payload ID of a packet whose MMTP header the caller already\n * parsed, or null when the packet carries none: present only when FEC_type=1\n * and the exact suffix after the ISO-declared MPU payload holds the four-byte\n * ID (ISO/IEC 23008-1 \u00A7C.5.2). Same answer as extractFecPayloadId, without a\n * second header parse (BLO-36599).\n *\n * `header` must be `parseMMTPHeader(mmtpPacket)` of this same packet.\n */\nexport function sourceFecPayloadIdOf(\n mmtpPacket: Uint8Array,\n header: MMTPHeader,\n): { ssId: number } | null {\n if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) return null\n if (header.packetType !== PACKET_TYPE_MPU) return null\n\n const payload = mmtpPacket.subarray(header.headerLength)\n if (payload.length < MPU_HEADER_SIZE) return null\n const payloadLength = (payload[0]! << 8) | payload[1]!\n if (payloadLength < MPU_HEADER_REMAINDER_SIZE) return null\n const declaredEnd = MPU_LENGTH_FIELD_SIZE + payloadLength\n if (!resolveDeclaredTrailers(payload, declaredEnd, header.fecType)?.hasFecId) return null\n\n // Flat 4-byte SS_ID: encoder writes block_id * K + symbol_id\n const off = mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE\n return {\n ssId:\n ((mmtpPacket[off]! << 24) |\n (mmtpPacket[off + 1]! << 16) |\n (mmtpPacket[off + 2]! << 8) |\n mmtpPacket[off + 3]!) >>>\n 0,\n }\n}\n\n/** Size of Repair FEC Payload ID per ISO/IEC 23008-1 Section C.5.3 */\nexport const REPAIR_FEC_PID_SIZE = 13\n\n/**\n * Parse the 13-byte Repair FEC Payload ID after the complete dynamic MMTP header.\n * `parsedHeader`, when given, must be `parseMMTPHeader(mmtpPacket)` of this\n * same packet; it spares the second header parse (BLO-36599).\n */\nfunction readRepairFecPayloadIdFields(mmtpPacket: Uint8Array, parsedHeader?: MMTPHeader): {\n packetId: number; ssStart: number; rsbLength: number; rsId: number; ssbLength: number; dataOffset: number\n} | null {\n let header: MMTPHeader\n if (parsedHeader) {\n header = parsedHeader\n } else {\n try {\n header = parseMMTPHeader(mmtpPacket)\n } catch {\n return null\n }\n }\n if (header.packetType !== PACKET_TYPE_REPAIR || header.fecType !== 2) return null\n\n const off = header.headerLength\n if (mmtpPacket.length < off + REPAIR_FEC_PID_SIZE) return null\n const ssStart =\n ((mmtpPacket[off]! << 24) |\n (mmtpPacket[off + 1]! << 16) |\n (mmtpPacket[off + 2]! << 8) |\n mmtpPacket[off + 3]!) >>>\n 0 // 32 bits\n const rsbLength = (mmtpPacket[off + 4]! << 16) | (mmtpPacket[off + 5]! << 8) | mmtpPacket[off + 6]! // 24 bits\n const rsId = (mmtpPacket[off + 7]! << 16) | (mmtpPacket[off + 8]! << 8) | mmtpPacket[off + 9]! // 24 bits\n const ssbLength = (mmtpPacket[off + 10]! << 16) | (mmtpPacket[off + 11]! << 8) | mmtpPacket[off + 12]! // 24 bits\n return {\n packetId: header.packetId,\n ssStart,\n rsbLength,\n rsId,\n ssbLength,\n dataOffset: off + REPAIR_FEC_PID_SIZE,\n }\n}\n\n/**\n * Extract Repair FEC Payload ID from a raw-multicast MMTP repair packet.\n * Per ISO/IEC 23008-1:2023 Section C.5.3 (ssbg_mode0, one-stage, no FFSRP_TS):\n * [MMTP header][SS_Start:4][RSB_length:3][RS_ID:3][SSB_length:3][repair data]\n * OTI is delivered via AL-FEC signaling message (Table C.3), not per-packet.\n *\n * Byte 1 is reserved(2)|packet_type(6) for V=0, so repair type 0x03 is 0x03.\n * Pre-migration high-bits bytes (0x0c) are rejected \u2014 no compatibility decode.\n */\nexport function extractRepairFecPayloadId(mmtpPacket: Uint8Array): {\n ssStart: number; rsbLength: number; rsId: number; ssbLength: number\n} | null {\n const fields = readRepairFecPayloadIdFields(mmtpPacket)\n if (!fields) return null\n return {\n ssStart: fields.ssStart,\n rsbLength: fields.rsbLength,\n rsId: fields.rsId,\n ssbLength: fields.ssbLength,\n }\n}\n\n/** Parsed MoQ repair frame per ISO/IEC 23008-1 Section C.4.3 + C.5.3 */\nexport interface MoqRepairFrame {\n /** MMTP packetId (1=video, 2=audio) \u2014 for routing to correct FEC decoder */\n packetId: number\n /** SS_Start (32 bits): SS_ID of first source symbol in block */\n ssStart: number\n /** RSB_length (24 bits): number of repair symbols (P) */\n rsbLength: number\n /** RS_ID (24 bits): repair symbol index (0-based) */\n rsId: number\n /** SSB_length (24 bits): authored source-symbol count (1..=configured K) */\n ssbLength: number\n /** Repair symbol data after the dynamic MMTP header and 13-byte FEC payload ID. */\n symbolData: Uint8Array\n}\n\n/**\n * Parse a MoQ repair frame (ISO/IEC 23008-1 Annex C format).\n *\n * Wire format per ISO 23008-1 \u00A7C.4.3 + \u00A7C.5.3:\n * MMTP Header: fixed 12 bytes plus C/X optional fields\n * then SS_Start (4 bytes) \u2192 block identifier\n * then RSB_length (3 bytes) \u2192 P\n * then RS_ID (3 bytes) \u2192 ESI = K + RS_ID\n * then SSB_length (3 bytes) \u2192 authored source-symbol count (1..=K)\n * then Repair Symbol Data (T bytes)\n *\n * @param frame - Raw MoQ repair frame bytes\n * @returns Parsed frame or null if invalid\n */\nexport function parseMoqRepairFrame(frame: Uint8Array): MoqRepairFrame | null {\n return moqRepairFrameFrom(frame, readRepairFecPayloadIdFields(frame))\n}\n\n/**\n * parseMoqRepairFrame for a caller that already holds this frame's parsed MMTP\n * header, so the header is not parsed a second time (BLO-36599). The router's\n * multicast repair branch uses it: one repair packet in every K + P otherwise\n * paid two header parses.\n *\n * `header` must be `parseMMTPHeader(frame)` of this same frame; the result is\n * then identical to `parseMoqRepairFrame(frame)`.\n */\nexport function parseMoqRepairFrameWithHeader(\n frame: Uint8Array,\n header: MMTPHeader,\n): MoqRepairFrame | null {\n return moqRepairFrameFrom(frame, readRepairFecPayloadIdFields(frame, header))\n}\n\nfunction moqRepairFrameFrom(\n frame: Uint8Array,\n repairId: ReturnType<typeof readRepairFecPayloadIdFields>,\n): MoqRepairFrame | null {\n if (!repairId) return null\n\n const symbolData = frame.subarray(repairId.dataOffset)\n if (\n repairId.rsbLength === 0 ||\n repairId.ssbLength === 0 ||\n repairId.rsId >= repairId.rsbLength ||\n symbolData.length === 0\n ) return null\n\n return {\n packetId: repairId.packetId,\n ssStart: repairId.ssStart,\n rsbLength: repairId.rsbLength,\n rsId: repairId.rsId,\n ssbLength: repairId.ssbLength,\n symbolData,\n }\n}\n\n// The signalling-message parsers (9.3.4.2 payload header, AL-FEC message,\n// PA/MPT) live in ./signalling.ts.\n", "/**\n * NTP short format (RFC 5905 \u00A76): an unsigned 32-bit, 16.16 fixed-point count\n * of seconds. The MMTP header `timestamp` field (ISO/IEC 23008-1 \u00A79.2.2)\n * carries each packet's UTC sending instant in this format, so the value wraps\n * to 0 every 2^16 s (~18.2 h).\n *\n * Plain numeric order on these values breaks at every wrap: a retained\n * `Math.max` stays at the pre-wrap value and every later instant compares as\n * older. Order send times only with {@link compareNtpShort}, which applies\n * RFC 1982 serial-number arithmetic over the field's width.\n */\n\n/** Width in bits of the MMTP `timestamp` field (NTP short). */\nexport const NTP_SHORT_BITS = 32\n\n/** Number of distinct NTP-short values; the field wraps to 0 here. */\nexport const NTP_SHORT_MODULUS = 2 ** NTP_SHORT_BITS\n\n/**\n * RFC 1982 \u00A73.2's `2^(SERIAL_BITS - 1)`. Two values whose forward distance is\n * below this are ordered; exactly this far apart they are not ordered at all.\n * Two instants must be less than this far apart (2^15 s, ~9.1 h of send time)\n * for the comparison to give their true order.\n */\nexport const NTP_SHORT_HALF_RANGE = 2 ** (NTP_SHORT_BITS - 1)\n\n/**\n * Serial order of one NTP-short value relative to another.\n *\n * `'unordered'` is RFC 1982's undefined case: the values are exactly\n * {@link NTP_SHORT_HALF_RANGE} apart, so neither precedes the other. It is\n * never folded into `'before'` or `'after'`; each caller decides what an\n * unorderable pair means for it.\n */\nexport type NtpShortOrder = 'before' | 'equal' | 'after' | 'unordered'\n\n/** True when `value` is an NTP-short value: an integer in [0, NTP_SHORT_MODULUS). */\nexport function isNtpShort(value: number): boolean {\n return Number.isInteger(value) && value >= 0 && value < NTP_SHORT_MODULUS\n}\n\n/**\n * RFC 1982 serial comparison of NTP-short `a` against `b`: `'after'` when `a`\n * is the later instant, `'before'` when it is the earlier one.\n *\n * The answer is the true order only while the two instants are less than\n * {@link NTP_SHORT_HALF_RANGE} apart. Past that a 32-bit field cannot tell\n * later from earlier, and the result names whichever direction is nearer.\n * This is not a total order (it is not transitive across the whole space), so\n * it must never be used to sort.\n *\n * @throws {RangeError} if either operand is not an NTP-short value\n */\nexport function compareNtpShort(a: number, b: number): NtpShortOrder {\n if (!isNtpShort(a) || !isNtpShort(b)) {\n throw new RangeError(\n `NTP-short values must be integers in [0, 2^${NTP_SHORT_BITS}), got ${String(a)} and ${String(b)}`,\n )\n }\n if (a === b) return 'equal'\n // Forward distance from b to a, reduced into [1, NTP_SHORT_MODULUS). Both\n // operands are below 2^32, so every step is exact in a double.\n const forward = (a - b + NTP_SHORT_MODULUS) % NTP_SHORT_MODULUS\n if (forward < NTP_SHORT_HALF_RANGE) return 'after'\n if (forward > NTP_SHORT_HALF_RANGE) return 'before'\n return 'unordered'\n}\n", "/**\n * FEC block profile (BLO-35597, ISO/IEC 23008-1 Annex C).\n *\n * Every catalog `fec` object that declares an FEC instance names its block\n * profile in `fec.blockProfile`. A receiver applies all of a profile's rules\n * or none of them, so the token is the one explicit per-stream discriminator:\n * it is never defaulted and never inferred from the wire.\n *\n * draft-ramadan-moq-fec \u00A75.1 defines exactly one value, and it is the only\n * profile this library implements:\n *\n * - `iso-ssbg1-v1`: ssbg_mode1 (C.3.3): a source symbol is\n * `u16 length || protected packet || zero padding` to T; a block is a\n * K' = SSB_length RaptorQ block (C.5.3) and repair ESI = SSB_length + RS_ID;\n * SS_ID increments by one per FEC source packet and wraps at 2^32 (C.5.2),\n * so a block is located by membership in `[SS_Start, SS_Start + SSB_length)`\n * under RFC 1982 serial arithmetic; the MoQ repair group id is the 62-bit\n * wrap-epoch-extended SS_Start. The AL-FEC coding byte for this profile is\n * 0x14 (one-stage, ssbg_mode1, fec_payload_id_mode 0, Amd 1:2025 Table C.3).\n *\n * A track whose `blockProfile` is absent or names any other token (the\n * retired Blockcast-private `k-padded-v1` included) has no FEC: a receiver\n * consumes its source without FEC and joins none of its repair tracks\n * (draft-ramadan-moq-fec \u00A75.1). `parseFecBlockProfile` throws for such a\n * token; the per-track catalog resolver turns the same rule into a typed\n * per-track \"FEC unavailable\" outcome instead of failing the session.\n */\nimport { serial32Add, serial32Distance, serial32Precedes } from './serial-number.js'\n\n/** The block profile a catalog `fec.blockProfile` may name: the one this library implements. */\nexport type FecBlockProfile = 'iso-ssbg1-v1'\n\n/** Every accepted `fec.blockProfile` token. */\nexport const FEC_BLOCK_PROFILES: readonly FecBlockProfile[] = Object.freeze([\n 'iso-ssbg1-v1',\n])\n\n/** True for a block-profile token this library implements. */\nexport function isFecBlockProfile(value: unknown): value is FecBlockProfile {\n return value === 'iso-ssbg1-v1'\n}\n\n/**\n * Read a required `fec.blockProfile`. Throws on an absent token and on any\n * token other than `iso-ssbg1-v1`: there is no default and nothing is\n * inferred from the wire (draft-ramadan-moq-fec \u00A75.1).\n *\n * @param where the catalog path of the field, for the error message.\n */\nexport function parseFecBlockProfile(value: unknown, where: string): FecBlockProfile {\n if (isFecBlockProfile(value)) return value\n if (value === undefined) {\n throw new Error(`${where} is required: name the FEC block profile (\"iso-ssbg1-v1\")`)\n }\n throw new Error(`${where} must be \"iso-ssbg1-v1\" (got ${JSON.stringify(value)})`)\n}\n\n/** ISO/IEC 23008-1 C.3.3 ssbg_mode1: the two-octet packet length field. */\nexport const SSBG1_LENGTH_FIELD_BYTES = 2\n\n/** The largest protected packet an ssbg_mode1 symbol of size T can carry. */\nexport function ssbg1MaxPacketLength(symbolSize: number): number {\n return symbolSize - SSBG1_LENGTH_FIELD_BYTES\n}\n\n/** Whether a protected packet of `packetLength` bytes fits one T-byte ssbg_mode1 symbol. */\nexport function ssbg1FitsSymbol(packetLength: number, symbolSize: number): boolean {\n return (\n Number.isSafeInteger(packetLength) &&\n packetLength >= 0 &&\n packetLength <= ssbg1MaxPacketLength(symbolSize) &&\n packetLength <= 0xffff\n )\n}\n\n/**\n * Build one ssbg_mode1 source symbol (C.3.3): the protected packet's length\n * in two octets, network byte order, then the packet, then zero octets up to\n * T. The protected packet is the MMTP packet before its Source FEC Payload ID\n * is appended (C.4.2).\n *\n * @throws when `length + 2 > T`: the packet cannot be protected under this\n * profile, and silently truncating it would corrupt every repair symbol.\n */\nexport function buildSsbg1SourceSymbol(packet: Uint8Array, symbolSize: number): Uint8Array {\n if (!Number.isSafeInteger(symbolSize) || symbolSize <= SSBG1_LENGTH_FIELD_BYTES) {\n throw new Error(`ssbg_mode1 symbol size must exceed ${SSBG1_LENGTH_FIELD_BYTES} (got ${symbolSize})`)\n }\n if (!ssbg1FitsSymbol(packet.byteLength, symbolSize)) {\n throw new Error(\n `ssbg_mode1 source symbol needs ${packet.byteLength} + ${SSBG1_LENGTH_FIELD_BYTES} bytes but T is ${symbolSize}`,\n )\n }\n const symbol = new Uint8Array(symbolSize)\n symbol[0] = (packet.byteLength >>> 8) & 0xff\n symbol[1] = packet.byteLength & 0xff\n symbol.set(packet, SSBG1_LENGTH_FIELD_BYTES)\n return symbol\n}\n\n/**\n * Recover the protected packet from one ssbg_mode1 source symbol: the bytes\n * the length field names. Returns null, never a guess, when the length field\n * points past the symbol or any padding octet is non-zero (C.3.3 padding is\n * all 00h), since either means the recovered symbol is not what was sent.\n */\nexport function trimSsbg1SourceSymbol(symbol: Uint8Array): Uint8Array | null {\n if (symbol.byteLength < SSBG1_LENGTH_FIELD_BYTES) return null\n const length = (symbol[0]! << 8) | symbol[1]!\n const end = SSBG1_LENGTH_FIELD_BYTES + length\n if (end > symbol.byteLength) return null\n for (let i = end; i < symbol.byteLength; i++) {\n if (symbol[i] !== 0) return null\n }\n return symbol.subarray(SSBG1_LENGTH_FIELD_BYTES, end)\n}\n\n/** The SS_ID after the last source symbol of `[ssStart, ssStart + ssbLength)`. */\nexport function isoBlockEnd(ssStart: number, ssbLength: number): number {\n return serial32Add(ssStart, ssbLength)\n}\n\n/**\n * Range membership (C.5.2, C.5.3): whether `ssId` is one of the\n * `ssbLength` consecutive SS_IDs starting at `ssStart`, modulo 2^32.\n */\nexport function isoBlockContains(ssStart: number, ssbLength: number, ssId: number): boolean {\n return serial32Distance(ssStart, ssId) < ssbLength\n}\n\n/**\n * A lower bound on how many blocks the block starting at `a` lies behind the\n * one starting at `b` (0 when `a` does not precede `b`). An iso-ssbg1-v1\n * block holds at most `kMax` source symbols (the catalog `sourceSymbols`, the\n * AL-FEC maximum_k_for_repair_flow), so `n * kMax` SS_IDs always span at least\n * `n` blocks. Every interleave horizon in the receiver (decoder retention,\n * worker retirement, ordered-relay settlement) uses this one bound, so the\n * manager's horizon can never fall inside the decoder's.\n */\nexport function isoBlocksBehindLowerBound(a: number, b: number, kMax: number): number {\n if (!Number.isSafeInteger(kMax) || kMax <= 0) {\n throw new Error(`iso-ssbg1-v1 block horizon needs a positive maximum K (got ${kMax})`)\n }\n return serial32Precedes(a, b) ? Math.floor(serial32Distance(a, b) / kMax) : 0\n}\n", "/**\n * Catalog FEC source rules shared by every catalog reader (BLO-40851).\n *\n * These are the dialect-level reads the container resolvers\n * (`resolveRepairLayers`, `catalogFecUnavailable`), the transport endpoint\n * selection (`selectEndpointPacketIds`) and a player's repair inventory all\n * need to agree on. They live here, in the leaf package every one of those\n * depends on, so there is one copy of each rule instead of copies pinned\n * against each other by tests.\n *\n * - `locateCatalogFecSource`: which catalog entry declares a source's `fec`\n * block. hang `video`/`audio` rendition blocks are authoritative over an MSF\n * `tracks[]` entry of the same name.\n * - `catalogFecAvailable`: draft-ramadan-moq-fec \u00A75.1, whether a block's FEC\n * is usable at all (implemented `blockProfile`, usable span).\n * - `catalogFecDeclaresUnconfigurableInstance`: a declared FEC instance whose\n * geometry a decoder cannot configure, which is a malformed catalog rather\n * than \"no FEC\".\n *\n * Every function is total: it never throws, whatever the input.\n */\nimport { isFecBlockProfile } from './fec-block-profile.js'\n\n/** The catalog media roles that carry hang renditions. */\nexport type CatalogFecRole = 'video' | 'audio'\n\n/** One media source's `fec` block, as `locateCatalogFecSource` found it. */\nexport type CatalogFecSource =\n | {\n readonly dialect: 'hang'\n readonly role: CatalogFecRole\n /** The rendition object. */\n readonly entry: Record<string, unknown>\n /** The rendition's `fec` value, unvalidated (may be undefined). */\n readonly fec: unknown\n /** JSON path of that `fec` block. */\n readonly fecPath: string\n }\n | {\n readonly dialect: 'msf'\n /** Index of the entry in `tracks[]`. */\n readonly index: number\n /** The `tracks[]` entry (an empty object when the entry is not an object). */\n readonly entry: Record<string, unknown>\n /** The entry's `fec` value, unvalidated (may be undefined). */\n readonly fec: unknown\n /** JSON path of that `fec` block. */\n readonly fecPath: string\n }\n\nconst ALL_ROLES: readonly CatalogFecRole[] = Object.freeze(['video', 'audio'])\n\nfunction recordOf(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\n/**\n * Locate the catalog entry that declares one media source's `fec` block, in\n * either catalog dialect.\n *\n * A hang `video`/`audio` rendition named `source` wins, in `roles` order, over\n * a `tracks[]` entry of the same name: when a catalog carries rendition blocks\n * beside a `tracks[]` switching-set index (the unified ABR ladder catalog),\n * the rendition blocks are authoritative, exactly as they are for hang's own\n * catalog decode. The precedence is keyed on the rendition EXISTING as an\n * object, not on it carrying `fec`: a rendition without `fec` locates with\n * `fec: undefined` and never falls through to `tracks[]`.\n *\n * Otherwise the first `tracks[]` entry named `source` locates. Returns\n * undefined when neither dialect names it, or when `catalog` is not an object.\n *\n * @param roles the hang roles to search, in order (both by default). A typed\n * track reference passes its own role only.\n */\nexport function locateCatalogFecSource(\n catalog: unknown,\n source: string,\n roles: readonly CatalogFecRole[] = ALL_ROLES,\n): CatalogFecSource | undefined {\n const root = recordOf(catalog)\n if (root === undefined) return undefined\n for (const role of roles) {\n const renditions = recordOf(recordOf(root[role])?.['renditions'])\n if (renditions === undefined || !Object.hasOwn(renditions, source)) continue\n const entry = recordOf(renditions[source])\n if (entry === undefined) continue\n return Object.freeze({\n dialect: 'hang' as const,\n role,\n entry,\n fec: entry['fec'],\n fecPath: `$.${role}.renditions[${JSON.stringify(source)}].fec`,\n })\n }\n const tracks = root['tracks']\n if (!Array.isArray(tracks)) return undefined\n const index = tracks.findIndex((track) => recordOf(track)?.['name'] === source)\n if (index < 0) return undefined\n const entry = recordOf(tracks[index]) ?? {}\n return Object.freeze({\n dialect: 'msf' as const,\n index,\n entry,\n fec: entry['fec'],\n fecPath: `$.tracks[${index}].fec`,\n })\n}\n\n/**\n * Whether an `iso-ssbg1-v1` block's optional `interleaveDepthMs` span is\n * usable: absent, or a non-negative safe integer. Zero or absence supplies no\n * elapsed deadline and still permits in-band FEC. True for every block that\n * names another profile (the span is not read) and for a non-object.\n */\nexport function isoBlockSpanUsable(fec: unknown): boolean {\n const block = recordOf(fec)\n if (block === undefined || block['blockProfile'] !== 'iso-ssbg1-v1') return true\n const ms = block['interleaveDepthMs']\n return ms === undefined || (typeof ms === 'number' && Number.isSafeInteger(ms) && ms >= 0)\n}\n\n/**\n * Whether one catalog `fec` block leaves its FEC available\n * (draft-ramadan-moq-fec \u00A75.1): the decision the container's\n * `catalogFecUnavailable` explains with a typed reason.\n *\n * False when the block declares an FEC instance (any `algorithm` but `\"none\"`)\n * and names no implemented `blockProfile` (the retired `k-padded-v1`\n * included), or carries an `iso-ssbg1-v1` span it cannot use; and when a block\n * declaring no FEC instance carries a profile token that is not implemented.\n * True for a non-object and for every other block. It reads only the profile\n * and the span: malformed geometry (`sourceSymbols`, `symbolSize`) is\n * `catalogFecDeclaresUnconfigurableInstance`'s.\n *\n * A receiver applies no FEC to a source whose block is unavailable and joins\n * none of its repair tracks, without failing the session.\n */\nexport function catalogFecAvailable(fec: unknown): boolean {\n const block = recordOf(fec)\n if (block === undefined) return true\n const declaresFecInstance = block['algorithm'] !== 'none'\n const profile = block['blockProfile']\n const profileOk = isFecBlockProfile(profile) || (profile === undefined && !declaresFecInstance)\n return profileOk && (!declaresFecInstance || isoBlockSpanUsable(block))\n}\n\nfunction isPositiveSafeInteger(value: unknown): boolean {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0\n}\n\n/**\n * Whether a source's `fec` block declares an FEC instance (any `algorithm`\n * but `\"none\"`) whose `sourceSymbols` or `symbolSize` is not a positive\n * integer. Geometry a decoder cannot configure is a malformed catalog, not\n * \"no FEC\": the container's per-track resolver throws `track_fec` for exactly\n * this block, whatever its profile or span.\n */\nexport function catalogFecDeclaresUnconfigurableInstance(fec: unknown): boolean {\n const block = recordOf(fec)\n if (block === undefined || block['algorithm'] === 'none') return false\n return !(isPositiveSafeInteger(block['sourceSymbols']) && isPositiveSafeInteger(block['symbolSize']))\n}\n", "// Typed FEC state shared by every player (hang/moq-lib, moqtail, Shaka MSF).\n//\n// A player's FEC counters are `null` in three unrelated situations: the\n// session is on reliable MoQ, where FEC has nothing to protect (FEC protects\n// only lossy multicast/AMT datagrams); no multicast bridge exists, so no lossy\n// leg can be joined; or the catalog declares no FEC for the tracks the player\n// selected. `null` also meant \"nothing decoded yet\" and \"the pipeline broke\",\n// so an idle session and a broken one looked identical.\n//\n// `resolveFecState` names which case holds. Each reason is read from a fact the\n// player already owns -- its catalog, its transport policy, its bridge probe\n// and its physical subscription -- and never from counters, console text,\n// timers or elapsed time. The rules live here so the three players cannot\n// disagree about precedence.\n\nimport { isFecBlockProfile, isoBlockSpanUsable } from '@blockcast/mmt-base'\n\n/** The optional elapsed-span rule lives in mmt-base beside the other catalog FEC rules. */\nexport { isoBlockSpanUsable }\n\n/** Smallest positive catalog elapsed span; zero/absence means no elapsed deadline. */\nexport const MIN_INTERLEAVE_DEPTH_MS = 1\n\n/** Why FEC is not protecting this session. */\nexport type FecInactiveReason = 'no-catalog-fec' | 'reliable-moq' | 'no-multicast-bridge'\n\n/** Every inactive reason, in resolution order. */\nexport const FEC_INACTIVE_REASONS: readonly FecInactiveReason[] = Object.freeze([\n 'no-catalog-fec',\n 'reliable-moq',\n 'no-multicast-bridge',\n] as const)\n\n/** The transport policy vocabulary every player accepts. */\nexport type FecTransportPolicy = 'auto' | 'moq-only' | 'multicast-only'\n\nconst TRANSPORT_POLICIES: ReadonlySet<string> = new Set<FecTransportPolicy>(['auto', 'moq-only', 'multicast-only'])\n\n/** FEC is not protecting this session; `reason` says why. Carries no counters. */\nexport interface FecInactiveState {\n readonly state: 'inactive'\n readonly reason: FecInactiveReason\n}\n\n/**\n * FEC is the protection in force for this session's delivery path.\n *\n * Flat on purpose: the player's existing counters stay at the paths every\n * consumer already reads (`fec.blocksRecovered`, `fec.tracks`, `fec.blocks`),\n * with `state` added beside them. A consumer that ignores `state` reads an\n * active report exactly as before and an inactive one as \"no counters\", which\n * is what `null` meant to it.\n */\nexport type FecActiveState<S extends object> = S & { readonly state: 'active' }\n\nexport type FecState<S extends object> = FecActiveState<S> | FecInactiveState\n\n/** An active state whose decoder has not reported any counter yet. */\nexport type NoFecCounters = Record<never, never>\n\n/** The authoritative facts `resolveFecState` reads. */\nexport interface FecStateEvidence<S extends object> {\n /**\n * The counters the player reports today, or null/undefined when it has none.\n * Payload only: it never decides the state, because moqtail and Shaka report\n * a zeroed snapshot as soon as a MulticastManager exists, which is before any\n * bridge or subscription does.\n */\n readonly stats: S | null | undefined\n /**\n * Whether the catalog declares FEC (see `catalogDeclaresFec`) for at least\n * one media track the player selected.\n */\n readonly catalogFec: boolean\n /** The player's configured transport policy. */\n readonly transportPolicy: FecTransportPolicy\n /** Whether a multicast bridge (`window.multicast`) is available to the page. */\n readonly bridgeAvailable: boolean\n /**\n * Whether a physical multicast/AMT subscription is live: the bridge accepted\n * it and it has not been closed. A requested leg is not a joined one.\n */\n readonly multicastLegJoined: boolean\n}\n\nconst INACTIVE: Readonly<Record<FecInactiveReason, FecInactiveState>> = Object.freeze({\n 'no-catalog-fec': Object.freeze({ state: 'inactive', reason: 'no-catalog-fec' }),\n 'reliable-moq': Object.freeze({ state: 'inactive', reason: 'reliable-moq' }),\n 'no-multicast-bridge': Object.freeze({ state: 'inactive', reason: 'no-multicast-bridge' }),\n})\n\nfunction recordOf(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\nfunction isPositiveSafeInteger(value: unknown): boolean {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0\n}\n\n/**\n * Whether one catalog `fec` block (a hang rendition's `fec` or an MSF/CMSF\n * track's `fec`) declares an FEC instance a receiver can configure: source\n * symbols per block (K) and a symbol size (T) are both positive integers, the\n * algorithm is not `none`, `blockProfile` names the implemented profile\n * `iso-ssbg1-v1` (BLO-35597), and the block carries that profile's usable\n * span field (`isoBlockSpanUsable`); zero/absence still permits in-band FEC. Total: it never throws, and answers false for\n * any other value.\n *\n * `resolveCatalogTrackFec` reads this predicate, so the players' parameters and\n * this state never disagree. Of the blocks this rejects, it returns no FEC\n * geometry only for `algorithm: \"none\"`. One with any other algorithm is a\n * malformed catalog (`FecCatalogConfig` marks both fields REQUIRED; the MSF\n * schema and `validateCmsfMmtpCatalog` enforce them on `tracks[]`, but the\n * hang dialect's `renditions` schema is permissive, so this is where a hang\n * block fails closed), and `resolveCatalogTrackFec` throws a `RepairContractError` for\n * it (`track_fec` unless another repair-contract violation fires first),\n * whether or not the source has repair layers, rather than silently dropping\n * the track's repair subscription.\n *\n * The block profile is part of this predicate because the profile selects the\n * block math and is never defaulted: draft-ramadan-moq-fec \u00A75.1 defines one,\n * `iso-ssbg1-v1`, and a receiver MUST NOT apply FEC under any other token. The\n * retired `k-padded-v1` is simply not a known profile. `resolveCatalogTrackFec`\n * and `MulticastManager.configureMultiTrack` resolve such a track to no FEC\n * with a typed `TrackFecUnavailable` reason (`catalogFecUnavailable`: code\n * `track_fec_block_profile_unimplemented` for an unimplemented token,\n * `track_fec_block_profile` for an absent one), scoped to that track, so their\n * parameters and this state still agree. The CMSF conformance validator\n * (`validateCmsfMmtpCatalog`) rejects the catalog with the same code. An\n * `iso-ssbg1-v1` instance with an invalid span is likewise unavailable for its\n * track alone. Zero or absence supplies no elapsed deadline and uses bounded\n * receiver-local state while decoding in-band FEC.\n *\n * The repair-contract resolvers (`resolveRepairLayers`) gate a `depends` target\n * on `algorithm` alone and never read a source's `symbolSize`. They check its\n * `sourceSymbols` for the RaptorQ K bound, and require a positive integer\n * `sourceSymbols` and `repairSymbols` only when the source has repair layers or\n * an overlay beyond layer 0.\n */\nexport function catalogDeclaresFec(fec: unknown): boolean {\n const block = recordOf(fec)\n if (block === undefined || block['algorithm'] === 'none') return false\n return (\n isPositiveSafeInteger(block['sourceSymbols']) &&\n isPositiveSafeInteger(block['symbolSize']) &&\n isFecBlockProfile(block['blockProfile']) &&\n isoBlockSpanUsable(block)\n )\n}\n\nfunction requireBoolean(value: unknown, field: string): boolean {\n if (typeof value !== 'boolean') {\n throw new TypeError(`resolveFecState: ${field} must be a boolean, got ${typeof value}`)\n }\n return value\n}\n\n/**\n * Resolve a player's FEC state. First match wins:\n *\n * 1. The catalog declares no FEC for a selected track: `no-catalog-fec`. FEC\n * geometry comes only from the catalog, so there is nothing to configure on\n * any path.\n * 2. The policy is `moq-only`: `reliable-moq`. Media travels only over QUIC,\n * which is reliable, so FEC has no loss to repair, bridge or not.\n * 3. No multicast bridge: `no-multicast-bridge`. No lossy leg can exist, and on\n * `auto` this is the reason the session is on reliable MoQ.\n * 4. The policy is `multicast-only`, or a lossy subscription is live: active.\n * `multicast-only` commits the session to the lossy leg, so FEC is in force\n * before the join completes; whether the join succeeded is the physical\n * attestation's question, not this one. The counters may be absent until\n * the decoder reports.\n * 5. Otherwise (`auto`, a bridge, no live subscription): `reliable-moq`.\n *\n * Throws on malformed evidence rather than picking a reason for it.\n */\nexport function resolveFecState<S extends object>(evidence: FecStateEvidence<S> & { readonly stats: S }): FecState<S>\nexport function resolveFecState<S extends object>(evidence: FecStateEvidence<S>): FecState<S | NoFecCounters>\nexport function resolveFecState<S extends object>(evidence: FecStateEvidence<S>): FecState<S | NoFecCounters> {\n const catalogFec = requireBoolean(evidence.catalogFec, 'catalogFec')\n const bridgeAvailable = requireBoolean(evidence.bridgeAvailable, 'bridgeAvailable')\n const multicastLegJoined = requireBoolean(evidence.multicastLegJoined, 'multicastLegJoined')\n const { transportPolicy, stats } = evidence\n if (typeof transportPolicy !== 'string' || !TRANSPORT_POLICIES.has(transportPolicy)) {\n throw new TypeError(`resolveFecState: unsupported transportPolicy ${JSON.stringify(transportPolicy)}`)\n }\n if (stats !== null && stats !== undefined && recordOf(stats) === undefined) {\n throw new TypeError('resolveFecState: stats must be a plain object, null or undefined')\n }\n\n if (!catalogFec) return INACTIVE['no-catalog-fec']\n if (transportPolicy === 'moq-only') return INACTIVE['reliable-moq']\n if (!bridgeAvailable) return INACTIVE['no-multicast-bridge']\n if (transportPolicy === 'multicast-only' || multicastLegJoined) {\n // The discriminant is written last so a stats field of the same name can\n // never masquerade as a state.\n return { ...(stats ?? {}), state: 'active' } as FecActiveState<S | NoFecCounters>\n }\n return INACTIVE['reliable-moq']\n}\n"],
5
+ "mappings": ";AAsEO,IAAM,kBAAkB;AAI/B,IAAM,wBAAwB;AAC9B,IAAM,4BAA4B,kBAAkB;;;AC9D7C,IAAM,iBAAiB;AAGvB,IAAM,oBAAoB,KAAK;AAQ/B,IAAM,uBAAuB,MAAM,iBAAiB;;;ACSpD,IAAM,qBAAiD,OAAO,OAAO;EAC1E;CACD;AAGK,SAAU,kBAAkB,OAAc;AAC9C,SAAO,UAAU;AACnB;;;ACUA,IAAM,YAAuC,OAAO,OAAO,CAAC,SAAS,OAAO,CAAC;AAE7E,SAAS,SAAS,OAAc;AAC9B,SAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IACrE,QACD;AACN;AA4DM,SAAU,mBAAmB,KAAY;AAC7C,QAAM,QAAQ,SAAS,GAAG;AAC1B,MAAI,UAAU,UAAa,MAAM,cAAc,MAAM;AAAgB,WAAO;AAC5E,QAAM,KAAK,MAAM,mBAAmB;AACpC,SAAO,OAAO,UAAc,OAAO,OAAO,YAAY,OAAO,cAAc,EAAE,KAAK,MAAM;AAC1F;;;ACpGO,IAAM,0BAA0B;AAMhC,IAAM,uBAAqD,OAAO,OAAO;AAAA,EAC9E;AAAA,EACA;AAAA,EACA;AACF,CAAU;AAKV,IAAM,qBAA0C,oBAAI,IAAwB,CAAC,QAAQ,YAAY,gBAAgB,CAAC;AAiDlH,IAAM,WAAkE,OAAO,OAAO;AAAA,EACpF,kBAAkB,OAAO,OAAO,EAAE,OAAO,YAAY,QAAQ,iBAAiB,CAAC;AAAA,EAC/E,gBAAgB,OAAO,OAAO,EAAE,OAAO,YAAY,QAAQ,eAAe,CAAC;AAAA,EAC3E,uBAAuB,OAAO,OAAO,EAAE,OAAO,YAAY,QAAQ,sBAAsB,CAAC;AAC3F,CAAC;AAED,SAASA,UAAS,OAAqD;AACrE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,IACrE,QACD;AACN;AAEA,SAAS,sBAAsB,OAAyB;AACtD,SAAO,OAAO,UAAU,YAAY,OAAO,cAAc,KAAK,KAAK,QAAQ;AAC7E;AA0CO,SAAS,mBAAmB,KAAuB;AACxD,QAAM,QAAQA,UAAS,GAAG;AAC1B,MAAI,UAAU,UAAa,MAAM,WAAW,MAAM,OAAQ,QAAO;AACjE,SACE,sBAAsB,MAAM,eAAe,CAAC,KAC5C,sBAAsB,MAAM,YAAY,CAAC,KACzC,kBAAkB,MAAM,cAAc,CAAC,KACvC,mBAAmB,KAAK;AAE5B;AAEA,SAAS,eAAe,OAAgB,OAAwB;AAC9D,MAAI,OAAO,UAAU,WAAW;AAC9B,UAAM,IAAI,UAAU,oBAAoB,KAAK,2BAA2B,OAAO,KAAK,EAAE;AAAA,EACxF;AACA,SAAO;AACT;AAuBO,SAAS,gBAAkC,UAA4D;AAC5G,QAAM,aAAa,eAAe,SAAS,YAAY,YAAY;AACnE,QAAM,kBAAkB,eAAe,SAAS,iBAAiB,iBAAiB;AAClF,QAAM,qBAAqB,eAAe,SAAS,oBAAoB,oBAAoB;AAC3F,QAAM,EAAE,iBAAiB,MAAM,IAAI;AACnC,MAAI,OAAO,oBAAoB,YAAY,CAAC,mBAAmB,IAAI,eAAe,GAAG;AACnF,UAAM,IAAI,UAAU,gDAAgD,KAAK,UAAU,eAAe,CAAC,EAAE;AAAA,EACvG;AACA,MAAI,UAAU,QAAQ,UAAU,UAAaA,UAAS,KAAK,MAAM,QAAW;AAC1E,UAAM,IAAI,UAAU,kEAAkE;AAAA,EACxF;AAEA,MAAI,CAAC,WAAY,QAAO,SAAS,gBAAgB;AACjD,MAAI,oBAAoB,WAAY,QAAO,SAAS,cAAc;AAClE,MAAI,CAAC,gBAAiB,QAAO,SAAS,qBAAqB;AAC3D,MAAI,oBAAoB,oBAAoB,oBAAoB;AAG9D,WAAO,EAAE,GAAI,SAAS,CAAC,GAAI,OAAO,SAAS;AAAA,EAC7C;AACA,SAAO,SAAS,cAAc;AAChC;",
6
+ "names": ["recordOf"]
7
7
  }
@@ -4,7 +4,7 @@
4
4
  * Wires a FecWorkerClient into a MulticastManager for a specific track.
5
5
  * Both moq-lib (`hang-mmt-fec/js/watch/src/element.ts`) and moqtail
6
6
  * (`moqtail-private/apps/client-js/src/lib/player.ts`) call this from their
7
- * SessionManager `fec-setup` handler so the Worker+ALTA setup lives in one
7
+ * SessionManager `fec-setup` handler so the Worker setup lives in one
8
8
  * place instead of being duplicated across ~80 lines per player.
9
9
  *
10
10
  * Callers are responsible for holding the returned `dispose()` and calling it
@@ -21,8 +21,6 @@ export interface FecWorkerAssetUrls {
21
21
  fecWorker: string;
22
22
  /** URL to the RaptorQ WASM module (compiled via compileStreaming). */
23
23
  rqWasm: string;
24
- /** URL to the ALTA WASM module. Fetched only when an ALTA key is provided. */
25
- altaWasm: string;
26
24
  }
27
25
  export interface FecWorkerSetupOptions {
28
26
  /** MulticastManager that should receive the configured Worker. */
@@ -46,7 +44,7 @@ export interface FecWorkerSetupOptions {
46
44
  * block distance from below; it never strides SS_IDs into blocks.
47
45
  */
48
46
  fecK: number;
49
- /** Symbol size in bytes (T) — the ALTA-adjusted value if ALTA is signed. */
47
+ /** Symbol size in bytes (T). */
50
48
  fecSymbolSize: number;
51
49
  /** Repair symbols per block (P). */
52
50
  fecRepairCount: number;
@@ -76,8 +74,6 @@ export interface FecWorkerSetupOptions {
76
74
  codec?: string;
77
75
  /** Video framerate (optional metadata forwarded to the worker). */
78
76
  framerate?: number;
79
- /** Base64 SPKI public key (optional). Accepts padded/unpadded, std or url-safe alphabet. */
80
- altaPublicKeySpki?: string;
81
77
  /** Absolute or origin-relative asset URLs. */
82
78
  assetUrls: FecWorkerAssetUrls;
83
79
  /** Optional FecWorkerClient factory — main use is test injection. */
@@ -86,8 +82,6 @@ export interface FecWorkerSetupOptions {
86
82
  export interface FecWorkerSetupResult {
87
83
  /** The configured client (already registered with MulticastManager). */
88
84
  client: FecWorkerClient;
89
- /** True when the ALTA public key decoded and the ALTA WASM compiled. */
90
- altaEnabled: boolean;
91
85
  /** Removes the Worker from MulticastManager routing, then releases it. */
92
86
  dispose: () => void;
93
87
  }
@@ -1 +1 @@
1
- {"version":3,"file":"fec-worker-setup.d.ts","sourceRoot":"","sources":["../src/fec-worker-setup.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAwB,KAAK,eAAe,EAAE,MAAM,qBAAqB,CAAA;AAChF,OAAO,KAAK,EAAE,eAAe,EAAkB,MAAM,uBAAuB,CAAA;AAC5E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAQ9D,0EAA0E;AAC1E,MAAM,WAAW,kBAAkB;IACjC,gEAAgE;IAChE,SAAS,EAAE,MAAM,CAAA;IACjB,sEAAsE;IACtE,MAAM,EAAE,MAAM,CAAA;IACd,8EAA8E;IAC9E,QAAQ,EAAE,MAAM,CAAA;CACjB;AAED,MAAM,WAAW,qBAAqB;IACpC,kEAAkE;IAClE,gBAAgB,EAAE,gBAAgB,CAAA;IAClC,wDAAwD;IACxD,QAAQ,EAAE,MAAM,CAAA;IAChB,+CAA+C;IAC/C,SAAS,EAAE,MAAM,CAAA;IACjB,yDAAyD;IACzD,SAAS,EAAE,OAAO,GAAG,OAAO,CAAA;IAC5B;;;;;OAKG;IACH,eAAe,EAAE,eAAe,CAAA;IAChC;;;;OAIG;IACH,IAAI,EAAE,MAAM,CAAA;IACZ,4EAA4E;IAC5E,aAAa,EAAE,MAAM,CAAA;IACrB,oCAAoC;IACpC,cAAc,EAAE,MAAM,CAAA;IACtB;;;;;;OAMG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,2EAA2E;IAC3E,eAAe,EAAE,MAAM,CAAA;IACvB,uDAAuD;IACvD,qBAAqB,CAAC,EAAE,MAAM,CAAA;IAC9B;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAA;IAC5B,qEAAqE;IACrE,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,wDAAwD;IACxD,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,wEAAwE;IACxE,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,mEAAmE;IACnE,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,4FAA4F;IAC5F,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,8CAA8C;IAC9C,SAAS,EAAE,kBAAkB,CAAA;IAC7B,qEAAqE;IACrE,aAAa,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,KAAK,eAAe,CAAA;CACpD;AAED,MAAM,WAAW,oBAAoB;IACnC,wEAAwE;IACxE,MAAM,EAAE,eAAe,CAAA;IACvB,wEAAwE;IACxE,WAAW,EAAE,OAAO,CAAA;IACpB,0EAA0E;IAC1E,OAAO,EAAE,MAAM,IAAI,CAAA;CACpB;AAED;;;;;;;;GAQG;AACH,wBAAsB,sBAAsB,CAC1C,IAAI,EAAE,qBAAqB,GAC1B,OAAO,CAAC,oBAAoB,CAAC,CAyN/B"}
1
+ {"version":3,"file":"fec-worker-setup.d.ts","sourceRoot":"","sources":["../src/fec-worker-setup.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAwB,KAAK,eAAe,EAAE,MAAM,qBAAqB,CAAA;AAChF,OAAO,KAAK,EAAE,eAAe,EAAkB,MAAM,uBAAuB,CAAA;AAC5E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAQ9D,0EAA0E;AAC1E,MAAM,WAAW,kBAAkB;IACjC,gEAAgE;IAChE,SAAS,EAAE,MAAM,CAAA;IACjB,sEAAsE;IACtE,MAAM,EAAE,MAAM,CAAA;CACf;AAED,MAAM,WAAW,qBAAqB;IACpC,kEAAkE;IAClE,gBAAgB,EAAE,gBAAgB,CAAA;IAClC,wDAAwD;IACxD,QAAQ,EAAE,MAAM,CAAA;IAChB,+CAA+C;IAC/C,SAAS,EAAE,MAAM,CAAA;IACjB,yDAAyD;IACzD,SAAS,EAAE,OAAO,GAAG,OAAO,CAAA;IAC5B;;;;;OAKG;IACH,eAAe,EAAE,eAAe,CAAA;IAChC;;;;OAIG;IACH,IAAI,EAAE,MAAM,CAAA;IACZ,gCAAgC;IAChC,aAAa,EAAE,MAAM,CAAA;IACrB,oCAAoC;IACpC,cAAc,EAAE,MAAM,CAAA;IACtB;;;;;;OAMG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,2EAA2E;IAC3E,eAAe,EAAE,MAAM,CAAA;IACvB,uDAAuD;IACvD,qBAAqB,CAAC,EAAE,MAAM,CAAA;IAC9B;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAA;IAC5B,qEAAqE;IACrE,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,wDAAwD;IACxD,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,wEAAwE;IACxE,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,mEAAmE;IACnE,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,8CAA8C;IAC9C,SAAS,EAAE,kBAAkB,CAAA;IAC7B,qEAAqE;IACrE,aAAa,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,KAAK,eAAe,CAAA;CACpD;AAED,MAAM,WAAW,oBAAoB;IACnC,wEAAwE;IACxE,MAAM,EAAE,eAAe,CAAA;IACvB,0EAA0E;IAC1E,OAAO,EAAE,MAAM,IAAI,CAAA;CACpB;AAED;;;;;;;;GAQG;AACH,wBAAsB,sBAAsB,CAC1C,IAAI,EAAE,qBAAqB,GAC1B,OAAO,CAAC,oBAAoB,CAAC,CAgM/B"}
@@ -90,51 +90,27 @@ var init_fec_worker_client = __esm({
90
90
  * `interleaveMs: 0` is a valid no-span catalog value; in that mode the
91
91
  * caller supplies a positive receiver-local `deliveryWindowMs`.
92
92
  * wasmModule is transferred (not neutered — WebAssembly.Module is shareable).
93
- * altaPublicKey is PKCS#8 SPKI DER bytes (self-describing — algorithm detected from OID).
94
- * Transferred (detached from sender).
95
- * altaWasmModule is structured-cloneable (NOT transferable — do not add to transfer list).
96
93
  */
97
- configure(config, wasmModule, altaPublicKey, altaWasmModule) {
94
+ configure(config, wasmModule) {
98
95
  if (this.#disposed)
99
96
  throw new Error("[FecWorkerClient] disposed");
100
97
  this.#flushSymbols();
101
98
  const cmd = {
102
99
  type: "configure",
103
100
  config,
104
- wasmModule,
105
- altaPublicKey,
106
- altaWasmModule
101
+ wasmModule
107
102
  };
108
- const transferList = [];
109
- if (altaPublicKey)
110
- transferList.push(altaPublicKey);
111
- this.#worker.postMessage(cmd, transferList);
103
+ this.#worker.postMessage(cmd);
112
104
  }
113
105
  /**
114
106
  * Feed a source symbol to the Worker. data ArrayBuffer is transferred (zero-copy).
115
107
  * Caller must not access data after this call — it is transferred with the
116
108
  * task's symbol batch, before any later command of this client.
117
- *
118
- * Optional `alta` carries the detached ALTA authenticator bytes and the
119
- * byte offset in `data` where the signed payload ends. The auth buffer is
120
- * transferred zero-copy alongside `data`. Use {@link getMmtpAltaTrailer}
121
- * upstream (mmtp-router) to extract it from the wire packet.
122
109
  */
123
- feedSource(ssId, data, ts, alta) {
110
+ feedSource(ssId, data, ts) {
124
111
  if (this.#disposed)
125
112
  throw new Error("[FecWorkerClient] feedSource on a disposed client");
126
- if (alta) {
127
- this.#queueSymbol({
128
- type: "feedSource",
129
- ssId,
130
- data,
131
- ts,
132
- altaAuth: alta.auth,
133
- altaPayloadEnd: alta.payloadEnd
134
- }, data, alta.auth);
135
- } else {
136
- this.#queueSymbol({ type: "feedSource", ssId, data, ts }, data);
137
- }
113
+ this.#queueSymbol({ type: "feedSource", ssId, data, ts }, data);
138
114
  }
139
115
  /**
140
116
  * Feed a repair symbol to the Worker. data ArrayBuffer is transferred (zero-copy).
@@ -150,15 +126,13 @@ var init_fec_worker_client = __esm({
150
126
  throw new Error("[FecWorkerClient] feedRepair on a disposed client");
151
127
  this.#queueSymbol({ type: "feedRepair", ssStart, ssbLength, rsId, data, ts }, data);
152
128
  }
153
- #queueSymbol(symbol, data, auth) {
129
+ #queueSymbol(symbol, data) {
154
130
  if (!this.#batchSymbols) {
155
- this.#worker.postMessage(symbol, auth ? [data, auth] : [data]);
131
+ this.#worker.postMessage(symbol, [data]);
156
132
  return;
157
133
  }
158
134
  this.#pendingSymbols.push(symbol);
159
135
  this.#pendingTransfer.push(data);
160
- if (auth)
161
- this.#pendingTransfer.push(auth);
162
136
  if (this.#flushQueued)
163
137
  return;
164
138
  this.#flushQueued = true;
@@ -502,16 +476,11 @@ var init_dist = __esm({
502
476
  }
503
477
  });
504
478
 
505
- // ../mmt-alta-parse/dist/index.js
479
+ // ../mmt-base/dist/mmtp.js
506
480
  var MPU_HEADER_SIZE = 8;
507
481
  var MPU_LENGTH_FIELD_SIZE = 2;
508
482
  var MPU_HEADER_REMAINDER_SIZE = MPU_HEADER_SIZE - MPU_LENGTH_FIELD_SIZE;
509
483
 
510
- // ../mmt-base/dist/mmtp.js
511
- var MPU_HEADER_SIZE2 = 8;
512
- var MPU_LENGTH_FIELD_SIZE2 = 2;
513
- var MPU_HEADER_REMAINDER_SIZE2 = MPU_HEADER_SIZE2 - MPU_LENGTH_FIELD_SIZE2;
514
-
515
484
  // ../mmt-base/dist/ntp-short.js
516
485
  var NTP_SHORT_BITS = 32;
517
486
  var NTP_SHORT_MODULUS = 2 ** NTP_SHORT_BITS;
@@ -533,6 +502,9 @@ function parseFecBlockProfile(value, where) {
533
502
  throw new Error(`${where} must be "iso-ssbg1-v1" (got ${JSON.stringify(value)})`);
534
503
  }
535
504
 
505
+ // ../mmt-base/dist/catalog-fec-source.js
506
+ var ALL_ROLES = Object.freeze(["video", "audio"]);
507
+
536
508
  // src/fec-worker-setup.ts
537
509
  import {
538
510
  deriveFecRetentionBlocks,
@@ -625,26 +597,6 @@ async function setupFecWorkerForTrack(opts) {
625
597
  const FecWorkerCtor = await Promise.resolve().then(() => (init_dist(), dist_exports));
626
598
  const client = opts.clientFactory ? opts.clientFactory(workerUrl) : new FecWorkerCtor.FecWorkerClient(workerUrl);
627
599
  const rqWasm = await WebAssembly.compileStreaming(fetch(opts.assetUrls.rqWasm));
628
- let altaKeyBuffer;
629
- let altaWasmModule;
630
- if (opts.altaPublicKeySpki) {
631
- const b64 = opts.altaPublicKeySpki.replace(/-/g, "+").replace(/_/g, "/");
632
- const padded = b64.padEnd(Math.ceil(b64.length / 4) * 4, "=");
633
- try {
634
- const keyBytes = Uint8Array.from(atob(padded), (c) => c.charCodeAt(0));
635
- if (keyBytes.length >= 32 && keyBytes.length <= 256) {
636
- altaKeyBuffer = keyBytes.buffer;
637
- altaWasmModule = await WebAssembly.compileStreaming(fetch(opts.assetUrls.altaWasm));
638
- } else {
639
- console.warn(
640
- `[fec-worker-setup] ALTA SPKI wrong length for "${opts.trackName}": ${keyBytes.length} (expected 32..256) \u2014 ALTA disabled`
641
- );
642
- }
643
- } catch (e) {
644
- console.warn(`[fec-worker-setup] ALTA key decode / WASM compile failed for "${opts.trackName}":`, e);
645
- }
646
- }
647
- const altaEnabled = !!(altaKeyBuffer && altaWasmModule);
648
600
  const fecTrackConfig = {
649
601
  codec: opts.codec ?? "unknown",
650
602
  trackName: opts.trackName,
@@ -663,10 +615,9 @@ async function setupFecWorkerForTrack(opts) {
663
615
  deliveryWindowMs,
664
616
  fecMode: "subframe",
665
617
  repairTrack: opts.repairTrackName,
666
- altaEnabled,
667
618
  relayBlockSigEnabled: false
668
619
  };
669
- client.configure(fecTrackConfig, rqWasm, altaKeyBuffer, altaWasmModule);
620
+ client.configure(fecTrackConfig, rqWasm);
670
621
  try {
671
622
  opts.multicastManager.setFecWorker(opts.packetId, client, opts.trackType, {
672
623
  blockProfile,
@@ -689,7 +640,6 @@ async function setupFecWorkerForTrack(opts) {
689
640
  let disposed = false;
690
641
  return {
691
642
  client,
692
- altaEnabled,
693
643
  dispose: () => {
694
644
  if (disposed) return;
695
645
  disposed = true;