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

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 (191) hide show
  1. package/README.md +31 -17
  2. package/dist/align.d.ts +24 -18
  3. package/dist/align.d.ts.map +1 -1
  4. package/dist/align.js +23 -4
  5. package/dist/align.js.map +2 -2
  6. package/dist/browser-runtime.js +1192 -375
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +67 -31
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +291 -199
  11. package/dist/carp-catalog.js.map +3 -3
  12. package/dist/catalog-fec-params.d.ts +12 -4
  13. package/dist/catalog-fec-params.d.ts.map +1 -1
  14. package/dist/catalog-fec-params.js +40 -17
  15. package/dist/catalog-fec-params.js.map +3 -3
  16. package/dist/catalog-network-source.d.ts +24 -2
  17. package/dist/catalog-network-source.d.ts.map +1 -1
  18. package/dist/catalog-network-source.js +21 -1
  19. package/dist/catalog-network-source.js.map +2 -2
  20. package/dist/catalog-validator.d.ts +4 -3
  21. package/dist/catalog-validator.d.ts.map +1 -1
  22. package/dist/catalog-validator.js +0 -29
  23. package/dist/catalog-validator.js.map +3 -3
  24. package/dist/delivery-catalog.js +18 -12
  25. package/dist/delivery-catalog.js.map +4 -4
  26. package/dist/fec-manager.d.ts +49 -1
  27. package/dist/fec-manager.d.ts.map +1 -1
  28. package/dist/fec-manager.js +176 -23
  29. package/dist/fec-manager.js.map +3 -3
  30. package/dist/fec-state.d.ts +2 -1
  31. package/dist/fec-state.d.ts.map +1 -1
  32. package/dist/fec-state.js +18 -3
  33. package/dist/fec-state.js.map +3 -3
  34. package/dist/fec-worker-setup.d.ts +2 -0
  35. package/dist/fec-worker-setup.d.ts.map +1 -1
  36. package/dist/fec-worker-setup.js +2 -1
  37. package/dist/fec-worker-setup.js.map +2 -2
  38. package/dist/index.d.ts +5 -5
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +8 -8
  41. package/dist/index.js.map +2 -2
  42. package/dist/iso-block-locator.d.ts +29 -0
  43. package/dist/iso-block-locator.d.ts.map +1 -1
  44. package/dist/iso-block-locator.js +97 -17
  45. package/dist/iso-block-locator.js.map +3 -3
  46. package/dist/manifest-auth-plan.d.ts +26 -25
  47. package/dist/manifest-auth-plan.d.ts.map +1 -1
  48. package/dist/manifest-auth-plan.js +331 -1171
  49. package/dist/manifest-auth-plan.js.map +4 -4
  50. package/dist/mfu-reassembler.js.map +2 -2
  51. package/dist/mmtp-container-parser.js.map +2 -2
  52. package/dist/mmtp-container-parser.no-modules.js +1014 -289
  53. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  54. package/dist/mmtp-decode-pipeline.js.map +2 -2
  55. package/dist/mmtp-fec-session.d.ts +159 -0
  56. package/dist/mmtp-fec-session.d.ts.map +1 -0
  57. package/dist/mmtp-fec-session.js +531 -0
  58. package/dist/mmtp-fec-session.js.map +7 -0
  59. package/dist/mmtp-router.d.ts +17 -1
  60. package/dist/mmtp-router.d.ts.map +1 -1
  61. package/dist/mmtp-router.js +29 -0
  62. package/dist/mmtp-router.js.map +2 -2
  63. package/dist/multicast-auth-catalog.d.ts +86 -92
  64. package/dist/multicast-auth-catalog.d.ts.map +1 -1
  65. package/dist/multicast-auth-catalog.js +347 -132
  66. package/dist/multicast-auth-catalog.js.map +4 -4
  67. package/dist/multicast-input.d.ts +28 -6
  68. package/dist/multicast-input.d.ts.map +1 -1
  69. package/dist/multicast-input.js +290 -28
  70. package/dist/multicast-input.js.map +3 -3
  71. package/dist/multicast-manager.d.ts +40 -5
  72. package/dist/multicast-manager.d.ts.map +1 -1
  73. package/dist/multicast-manager.js +293 -54
  74. package/dist/multicast-manager.js.map +4 -4
  75. package/dist/multicast-transport.d.ts +6 -0
  76. package/dist/multicast-transport.d.ts.map +1 -1
  77. package/dist/multicast-transport.js +18 -11
  78. package/dist/multicast-transport.js.map +4 -4
  79. package/dist/multicast-unwrap.js.map +2 -2
  80. package/dist/no-modules.d.ts +4 -1
  81. package/dist/no-modules.d.ts.map +1 -1
  82. package/dist/no-modules.js +964 -274
  83. package/dist/no-modules.js.map +4 -4
  84. package/dist/phase14-catalog-override.d.ts +1 -1
  85. package/dist/phase14-catalog-override.d.ts.map +1 -1
  86. package/dist/phase14-catalog-override.js +2 -2
  87. package/dist/phase14-catalog-override.js.map +2 -2
  88. package/dist/repair-fetch.d.ts +81 -6
  89. package/dist/repair-fetch.d.ts.map +1 -1
  90. package/dist/repair-fetch.js +156 -31
  91. package/dist/repair-fetch.js.map +3 -3
  92. package/dist/repair-layers.d.ts +2 -0
  93. package/dist/repair-layers.d.ts.map +1 -1
  94. package/dist/repair-layers.js +19 -2
  95. package/dist/repair-layers.js.map +2 -2
  96. package/dist/signaling.d.ts +2 -2
  97. package/dist/signaling.d.ts.map +1 -1
  98. package/dist/signaling.js +3 -3
  99. package/dist/signaling.js.map +2 -2
  100. package/dist/source-auth.js +2710 -7
  101. package/dist/source-auth.js.map +4 -4
  102. package/dist/switching-set-alignment.d.ts +1 -1
  103. package/dist/switching-set-alignment.js.map +1 -1
  104. package/dist/timestamp-codec.js.map +2 -2
  105. package/dist/wasm-mfu-reassembler.js.map +1 -1
  106. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  107. package/package.json +6 -9
  108. package/schemas/catalog.schema.json +124 -37
  109. package/src/align.ts +52 -21
  110. package/src/carp-catalog.ts +131 -52
  111. package/src/catalog-fec-params.ts +28 -3
  112. package/src/catalog-network-source.ts +45 -2
  113. package/src/catalog-validator.ts +4 -11
  114. package/src/fec-manager.ts +128 -14
  115. package/src/fec-state.ts +11 -4
  116. package/src/fec-worker-setup.ts +4 -1
  117. package/src/index.ts +24 -10
  118. package/src/iso-block-locator.ts +97 -6
  119. package/src/manifest-auth-plan.ts +39 -91
  120. package/src/mmtp-fec-session.ts +533 -0
  121. package/src/mmtp-router.ts +57 -0
  122. package/src/multicast-auth-catalog.ts +131 -238
  123. package/src/multicast-input.ts +119 -61
  124. package/src/multicast-manager.ts +115 -14
  125. package/src/multicast-transport.ts +3 -0
  126. package/src/no-modules.ts +7 -1
  127. package/src/phase14-catalog-override.ts +3 -3
  128. package/src/repair-fetch.ts +283 -39
  129. package/src/repair-layers.ts +22 -2
  130. package/src/signaling.ts +2 -2
  131. package/src/switching-set-alignment.ts +1 -1
  132. package/test-vectors/align.json +108 -32
  133. package/test-vectors/bc-provenance-v2.json +1526 -0
  134. package/test-vectors/catalog/README.md +60 -3
  135. package/test-vectors/catalog/negative/fec-block-profile-missing.json +1 -1
  136. package/test-vectors/catalog/negative/fec-block-profile-retired.json +1 -1
  137. package/test-vectors/catalog/negative/fec-block-profile-unknown.json +1 -1
  138. package/test-vectors/catalog/negative/fec-iso-symbol-size-below-floor.json +28 -0
  139. package/test-vectors/catalog/negative/fec-reed-solomon-iso-symbol-size-13.json +28 -0
  140. package/test-vectors/catalog/negative/fec-reed-solomon-k-plus-p-over-255.json +39 -0
  141. package/test-vectors/catalog/negative/fec-reed-solomon-overlay-over-255.json +40 -0
  142. package/test-vectors/catalog/negative/fec-repair-overlay-source-symbols-zero.json +43 -0
  143. package/test-vectors/catalog/negative/fec-repair-symbols-zero.json +28 -0
  144. package/test-vectors/catalog/negative/fec-source-symbols-zero.json +28 -0
  145. package/test-vectors/catalog/negative/fec-symbol-size-zero.json +28 -0
  146. package/test-vectors/catalog/negative/init-data-inline-without-data.json +22 -0
  147. package/test-vectors/catalog/negative/mmtp-mode-mpu.json +15 -0
  148. package/test-vectors/catalog/negative/multicast-amt-dns-without-relay.json +37 -0
  149. package/test-vectors/catalog/negative/multicast-auth-asm-missing-sender-address.json +77 -0
  150. package/test-vectors/catalog/negative/multicast-auth-duplicate-first-epoch.json +56 -0
  151. package/test-vectors/catalog/negative/multicast-auth-duplicate-kid.json +56 -0
  152. package/test-vectors/catalog/negative/multicast-auth-endpoint-auth-without-object-auth.json +38 -0
  153. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-auth.json +49 -0
  154. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-bandwidth.json +55 -0
  155. package/test-vectors/catalog/negative/multicast-auth-manifest-port-equals-port.json +56 -0
  156. package/test-vectors/catalog/negative/multicast-auth-manifest-timer-out-of-range.json +56 -0
  157. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-above-max.json +56 -0
  158. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-below-min.json +56 -0
  159. package/test-vectors/catalog/negative/multicast-auth-root-dotted-key.json +55 -0
  160. package/test-vectors/catalog/negative/multicast-auth-sender-address-on-ssm.json +57 -0
  161. package/test-vectors/catalog/negative/multicast-auth-version-1.json +56 -0
  162. package/test-vectors/catalog/negative/multicast-auth-version-3.json +56 -0
  163. package/test-vectors/catalog/negative/multicast-auth-version-missing.json +55 -0
  164. package/test-vectors/catalog/negative/multicast-endpoint-foreign-namespace-track.json +44 -0
  165. package/test-vectors/catalog/negative/multicast-endpoint-protocol-amt.json +38 -0
  166. package/test-vectors/catalog/negative/multicast-endpoint-protocol-atsc3.json +38 -0
  167. package/test-vectors/catalog/negative/presentation-anchor-unsafe.json +16 -0
  168. package/test-vectors/catalog/positive/fec-algorithm-unimplemented.json +29 -0
  169. package/test-vectors/catalog/positive/fec-iso-ssbg1.json +1 -1
  170. package/test-vectors/catalog/positive/fec-multicast.json +1 -1
  171. package/test-vectors/catalog/positive/fec-reed-solomon-layered.json +50 -0
  172. package/test-vectors/catalog/positive/mmt01-12-1-init-ref-anchor.json +29 -0
  173. package/test-vectors/catalog/positive/multicast-amt-discovery-omitted.json +37 -0
  174. package/test-vectors/catalog/positive/multicast-amt-dns-relay.json +38 -0
  175. package/test-vectors/catalog/positive/multicast-amt-manual-relay.json +2 -2
  176. package/test-vectors/catalog/{negative/multicast-endpoint-missing-protocol-and-source.json → positive/multicast-asm-unprotected.json} +10 -5
  177. package/test-vectors/catalog/positive/multicast-auth-asm-sender.json +78 -0
  178. package/test-vectors/catalog/positive/multicast-auth-rotation.json +39 -38
  179. package/test-vectors/catalog/positive/multicast-draft01-4-1-example.json +81 -0
  180. package/test-vectors/catalog/positive/multicast-draft01-7-2-6-example.json +70 -0
  181. package/test-vectors/catalog/positive/presentation-anchor-negative.json +27 -0
  182. package/test-vectors/catalog/section-codes.json +30 -1
  183. package/test-vectors/catalog-multicast-auth-v1.json +38 -20
  184. package/test-vectors/catalog-validation.json +6 -5
  185. package/test-vectors/catalog-validator-public-api.mjs +14 -9
  186. package/test-vectors/generate-bc-provenance-v2.mjs +252 -0
  187. package/dist/fec-codec.d.ts +0 -32
  188. package/dist/fec-codec.d.ts.map +0 -1
  189. package/dist/fec-codec.js +0 -47
  190. package/dist/fec-codec.js.map +0 -7
  191. package/src/fec-codec.ts +0 -61
@@ -1007,19 +1007,275 @@ function catalogFecAvailable(fec) {
1007
1007
  const block = recordOf(fec);
1008
1008
  if (block === void 0)
1009
1009
  return true;
1010
+ if (fecAlgorithmUnimplemented(block["algorithm"]))
1011
+ return false;
1010
1012
  const declaresFecInstance = block["algorithm"] !== "none";
1011
1013
  const profile = block["blockProfile"];
1012
1014
  const profileOk = isFecBlockProfile(profile) || profile === void 0 && !declaresFecInstance;
1013
1015
  return profileOk && (!declaresFecInstance || isoBlockSpanUsable(block));
1014
1016
  }
1017
+ function fecAlgorithmUnimplemented(algorithm) {
1018
+ return typeof algorithm === "string" && algorithm !== "none" && algorithm !== "raptorq" && algorithm !== "reed-solomon";
1019
+ }
1015
1020
  function isPositiveSafeInteger(value) {
1016
1021
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
1017
1022
  }
1023
+ var ISO_SSBG1_MIN_SYMBOL_SIZE = 14;
1018
1024
  function catalogFecDeclaresUnconfigurableInstance(fec) {
1019
1025
  const block = recordOf(fec);
1020
- if (block === void 0 || block["algorithm"] === "none")
1026
+ if (block === void 0 || block["algorithm"] === "none" || fecAlgorithmUnimplemented(block["algorithm"]))
1021
1027
  return false;
1022
- return !(isPositiveSafeInteger(block["sourceSymbols"]) && isPositiveSafeInteger(block["symbolSize"]));
1028
+ if (!(isPositiveSafeInteger(block["sourceSymbols"]) && isPositiveSafeInteger(block["symbolSize"])))
1029
+ return true;
1030
+ return block["blockProfile"] === "iso-ssbg1-v1" && block["symbolSize"] < ISO_SSBG1_MIN_SYMBOL_SIZE;
1031
+ }
1032
+
1033
+ // ../mmt-base/dist/multicast-catalog.js
1034
+ var ED25519_PUBLIC_KEY_BASE64URL = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;
1035
+ var UINT32_MAX = 4294967295;
1036
+ var AUTH_MEMBERS = /* @__PURE__ */ new Set(["scheme", "version", "sig", "keys", "minEpoch"]);
1037
+ var KEY_MEMBERS = /* @__PURE__ */ new Set(["kid", "publicKey", "firstEpoch"]);
1038
+ var ENDPOINT_AUTH_MEMBERS = /* @__PURE__ */ new Set([
1039
+ "manifestPort",
1040
+ "streamId",
1041
+ "senderAddress",
1042
+ "maxAuthDelayMs",
1043
+ "manifestTimerMs",
1044
+ "manifestTrack"
1045
+ ]);
1046
+ function isObject(value) {
1047
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1048
+ }
1049
+ function isNonEmptyString(value) {
1050
+ return typeof value === "string" && value.trim().length > 0;
1051
+ }
1052
+ function isIntegerIn(value, min, max) {
1053
+ return Number.isSafeInteger(value) && value >= min && value <= max;
1054
+ }
1055
+ function multicastEndpointSource(endpoint) {
1056
+ if (!isObject(endpoint))
1057
+ return void 0;
1058
+ const sourceAddress = endpoint["sourceAddress"];
1059
+ if (sourceAddress !== void 0 && !isNonEmptyString(sourceAddress))
1060
+ return void 0;
1061
+ const mode = sourceAddress === void 0 ? "asm" : "ssm";
1062
+ const protocol = endpoint["protocol"];
1063
+ if (protocol !== void 0 && protocol !== mode)
1064
+ return void 0;
1065
+ const auth = endpoint["auth"];
1066
+ const senderAddress = isObject(auth) ? auth["senderAddress"] : void 0;
1067
+ if (mode === "ssm")
1068
+ return senderAddress === void 0 ? { mode, source: sourceAddress } : void 0;
1069
+ if (auth === void 0)
1070
+ return { mode };
1071
+ return isNonEmptyString(senderAddress) ? { mode, source: senderAddress } : void 0;
1072
+ }
1073
+ function authIssues(auth) {
1074
+ const base = "$.multicast.auth";
1075
+ const issue = (path, message) => [
1076
+ { code: "multicast_auth", path: `${base}${path}`, message }
1077
+ ];
1078
+ if (!isObject(auth))
1079
+ return issue("", "auth must be an object");
1080
+ const unknown = Object.keys(auth).filter((key) => !AUTH_MEMBERS.has(key));
1081
+ if (unknown.length > 0) {
1082
+ return issue("", `auth has unknown member(s) ${unknown.join(", ")}; draft -01 7.2.6 defines scheme, version, sig, keys and minEpoch`);
1083
+ }
1084
+ if (auth["scheme"] !== "bc-provenance")
1085
+ return issue(".scheme", 'scheme must be "bc-provenance"');
1086
+ if (auth["version"] !== 2)
1087
+ return issue(".version", "version must be 2 (bc-provenance version 2, draft -01 7.2)");
1088
+ if (auth["sig"] !== "ed25519")
1089
+ return issue(".sig", 'sig must be "ed25519"');
1090
+ const keys = auth["keys"];
1091
+ if (!Array.isArray(keys) || keys.length < 1 || keys.length > 4) {
1092
+ return issue(".keys", "keys must be an array of one to four {kid, publicKey, firstEpoch} objects");
1093
+ }
1094
+ const kids = /* @__PURE__ */ new Set();
1095
+ const firstEpochs = /* @__PURE__ */ new Set();
1096
+ for (let index = 0; index < keys.length; index++) {
1097
+ const key = keys[index];
1098
+ const at = `.keys[${index}]`;
1099
+ if (!isObject(key) || Object.keys(key).some((member) => !KEY_MEMBERS.has(member))) {
1100
+ return issue(at, "a key is exactly {kid, publicKey, firstEpoch}");
1101
+ }
1102
+ if (!isIntegerIn(key["kid"], 0, UINT32_MAX))
1103
+ return issue(`${at}.kid`, "kid must be an unsigned 32-bit integer");
1104
+ if (typeof key["publicKey"] !== "string" || !ED25519_PUBLIC_KEY_BASE64URL.test(key["publicKey"])) {
1105
+ return issue(`${at}.publicKey`, "publicKey must be a 32-octet Ed25519 key in canonical unpadded base64url");
1106
+ }
1107
+ if (!isIntegerIn(key["firstEpoch"], 0, UINT32_MAX)) {
1108
+ return issue(`${at}.firstEpoch`, "firstEpoch must be an unsigned 32-bit integer");
1109
+ }
1110
+ if (kids.has(key["kid"]))
1111
+ return issue(`${at}.kid`, `kid ${key["kid"]} is repeated; the catalog holds no key set`);
1112
+ if (firstEpochs.has(key["firstEpoch"])) {
1113
+ return issue(`${at}.firstEpoch`, `firstEpoch ${key["firstEpoch"]} is repeated; the catalog holds no key set`);
1114
+ }
1115
+ kids.add(key["kid"]);
1116
+ firstEpochs.add(key["firstEpoch"]);
1117
+ }
1118
+ if (!isIntegerIn(auth["minEpoch"], 0, UINT32_MAX)) {
1119
+ return issue(".minEpoch", "minEpoch must be an unsigned 32-bit integer");
1120
+ }
1121
+ return [];
1122
+ }
1123
+ function endpointAuthIssue(endpoint, mode, at) {
1124
+ const auth = endpoint["auth"];
1125
+ if (!isObject(auth))
1126
+ return { path: `${at}.auth`, message: "auth must be an object" };
1127
+ const unknown = Object.keys(auth).filter((key) => !ENDPOINT_AUTH_MEMBERS.has(key));
1128
+ if (unknown.length > 0)
1129
+ return { path: `${at}.auth`, message: `auth has unknown member(s) ${unknown.join(", ")}` };
1130
+ if (!isIntegerIn(auth["manifestPort"], 1, 65535)) {
1131
+ return { path: `${at}.auth.manifestPort`, message: "manifestPort must be an integer from 1 to 65535" };
1132
+ }
1133
+ if (!isIntegerIn(auth["streamId"], 0, UINT32_MAX)) {
1134
+ return { path: `${at}.auth.streamId`, message: "streamId must be an unsigned 32-bit integer" };
1135
+ }
1136
+ if (mode === "ssm" && auth["senderAddress"] !== void 0) {
1137
+ return { path: `${at}.auth.senderAddress`, message: "senderAddress must not appear on an SSM endpoint; S is sourceAddress" };
1138
+ }
1139
+ if (mode === "asm" && !isNonEmptyString(auth["senderAddress"])) {
1140
+ return { path: `${at}.auth.senderAddress`, message: "a protected ASM endpoint requires senderAddress" };
1141
+ }
1142
+ if (auth["maxAuthDelayMs"] !== void 0 && !isIntegerIn(auth["maxAuthDelayMs"], 50, 1e3)) {
1143
+ return { path: `${at}.auth.maxAuthDelayMs`, message: "maxAuthDelayMs must be an integer from 50 to 1000" };
1144
+ }
1145
+ if (auth["manifestTimerMs"] !== void 0 && !isIntegerIn(auth["manifestTimerMs"], 1, Number.MAX_SAFE_INTEGER)) {
1146
+ return { path: `${at}.auth.manifestTimerMs`, message: "manifestTimerMs must be an integer of at least 1" };
1147
+ }
1148
+ if (auth["manifestTrack"] !== void 0 && !isNonEmptyString(auth["manifestTrack"])) {
1149
+ return { path: `${at}.auth.manifestTrack`, message: "manifestTrack must be a non-empty string" };
1150
+ }
1151
+ if (!isIntegerIn(endpoint["bandwidth"], 1, Number.MAX_SAFE_INTEGER)) {
1152
+ return { path: `${at}.bandwidth`, message: "a protected endpoint requires bandwidth, which bounds the receiver's hold queues" };
1153
+ }
1154
+ return void 0;
1155
+ }
1156
+ var CATALOG_NAMESPACE = /* @__PURE__ */ Symbol.for("@blockcast/mmt-base/catalogNamespace");
1157
+ function multicastCatalogIssues(catalog, options = {}) {
1158
+ if (!isObject(catalog))
1159
+ return [];
1160
+ const issues = [];
1161
+ if ("multicast.auth" in catalog) {
1162
+ issues.push({
1163
+ code: "multicast_auth",
1164
+ path: '$["multicast.auth"]',
1165
+ message: 'the root "multicast.auth" key is retired; declare auth as multicast.auth (draft -01 7.2.6)'
1166
+ });
1167
+ }
1168
+ const multicast = catalog["multicast"];
1169
+ if (!isObject(multicast))
1170
+ return issues;
1171
+ const protectedCatalog = multicast["auth"] !== void 0;
1172
+ if (protectedCatalog)
1173
+ issues.push(...authIssues(multicast["auth"]));
1174
+ const endpoints = multicast["endpoints"];
1175
+ if (!Array.isArray(endpoints))
1176
+ return issues;
1177
+ const tracks = Array.isArray(catalog["tracks"]) ? catalog["tracks"] : [];
1178
+ const namespaceOf = /* @__PURE__ */ new Map();
1179
+ for (const track of tracks) {
1180
+ if (isObject(track) && typeof track["name"] === "string")
1181
+ namespaceOf.set(track["name"], track["namespace"]);
1182
+ }
1183
+ const tagged = catalog[CATALOG_NAMESPACE];
1184
+ let referenceNamespace = options.catalogNamespace ?? (typeof tagged === "string" ? tagged : void 0);
1185
+ const sources = [];
1186
+ for (let index = 0; index < endpoints.length; index++) {
1187
+ const endpoint = endpoints[index];
1188
+ const at = `$.multicast.endpoints[${index}]`;
1189
+ const fail = (code, path, message) => {
1190
+ issues.push({ code, path, message, endpointIndex: index });
1191
+ };
1192
+ sources.push(void 0);
1193
+ if (!isObject(endpoint)) {
1194
+ fail("multicast_endpoint", at, "endpoint must be an object");
1195
+ continue;
1196
+ }
1197
+ const protocol = endpoint["protocol"];
1198
+ if (protocol !== void 0 && protocol !== "ssm" && protocol !== "asm") {
1199
+ fail("multicast_endpoint", `${at}.protocol`, `protocol must be "ssm" or "asm"; a bearer such as ${JSON.stringify(protocol)} is a networkSource entry (draft -01 4.2)`);
1200
+ continue;
1201
+ }
1202
+ const hasAuth = endpoint["auth"] !== void 0;
1203
+ if (protectedCatalog !== hasAuth) {
1204
+ fail("multicast_endpoint_auth", `${at}.auth`, protectedCatalog ? "every endpoint requires auth when multicast carries auth; a receiver ignores this endpoint" : "auth names no key without multicast.auth; a receiver ignores this endpoint");
1205
+ continue;
1206
+ }
1207
+ const sourceAddress = endpoint["sourceAddress"];
1208
+ if (sourceAddress !== void 0 && !isNonEmptyString(sourceAddress)) {
1209
+ fail("multicast_endpoint", `${at}.sourceAddress`, "sourceAddress must be a non-empty string");
1210
+ continue;
1211
+ }
1212
+ const mode = sourceAddress === void 0 ? "asm" : "ssm";
1213
+ if (protocol !== void 0 && protocol !== mode) {
1214
+ fail("multicast_endpoint", `${at}.protocol`, `protocol ${JSON.stringify(protocol)} disagrees with sourceAddress, which selects ${mode}`);
1215
+ continue;
1216
+ }
1217
+ if (!isIntegerIn(endpoint["port"], 1, 65535)) {
1218
+ fail("multicast_endpoint", `${at}.port`, "port must be an integer from 1 to 65535");
1219
+ continue;
1220
+ }
1221
+ if (hasAuth) {
1222
+ const authIssue = endpointAuthIssue(endpoint, mode, at);
1223
+ if (authIssue) {
1224
+ fail("multicast_endpoint_auth", authIssue.path, authIssue.message);
1225
+ continue;
1226
+ }
1227
+ }
1228
+ sources[index] = multicastEndpointSource(endpoint);
1229
+ const refs = Array.isArray(endpoint["tracks"]) ? endpoint["tracks"] : [];
1230
+ for (let refIndex = 0; refIndex < refs.length; refIndex++) {
1231
+ const ref = refs[refIndex];
1232
+ const name = isObject(ref) ? ref["name"] : ref;
1233
+ if (typeof name !== "string")
1234
+ continue;
1235
+ const namespace = namespaceOf.get(name);
1236
+ if (typeof namespace !== "string")
1237
+ continue;
1238
+ referenceNamespace ??= namespace;
1239
+ if (namespace !== referenceNamespace) {
1240
+ fail("multicast_track", `${at}.tracks[${refIndex}].name`, `track ${JSON.stringify(name)} declares namespace ${JSON.stringify(namespace)}, not the catalog track's ${JSON.stringify(referenceNamespace)}`);
1241
+ }
1242
+ }
1243
+ }
1244
+ const tupleOf = (index) => {
1245
+ const endpoint = endpoints[index];
1246
+ const auth = endpoint["auth"];
1247
+ return {
1248
+ sg: JSON.stringify([sources[index].source ?? null, endpoint["groupAddress"]]),
1249
+ port: endpoint["port"],
1250
+ manifestPort: isObject(auth) ? auth["manifestPort"] : void 0
1251
+ };
1252
+ };
1253
+ for (let index = 0; index < endpoints.length; index++) {
1254
+ if (!sources[index])
1255
+ continue;
1256
+ const own = tupleOf(index);
1257
+ const at = `$.multicast.endpoints[${index}]`;
1258
+ if (own.manifestPort !== void 0 && own.manifestPort === own.port) {
1259
+ issues.push({ code: "multicast_endpoint_auth", path: `${at}.auth.manifestPort`, message: "manifestPort must differ from the endpoint's own port", endpointIndex: index });
1260
+ continue;
1261
+ }
1262
+ for (let other = 0; other < endpoints.length; other++) {
1263
+ if (other === index || !sources[other])
1264
+ continue;
1265
+ const peer = tupleOf(other);
1266
+ if (peer.sg !== own.sg)
1267
+ continue;
1268
+ if (peer.port === own.port) {
1269
+ issues.push({ code: "multicast_endpoint", path: `${at}.port`, message: `(S, G, port) is shared with endpoint ${other}; one endpoint object per multicast tuple`, endpointIndex: index });
1270
+ break;
1271
+ }
1272
+ if (own.manifestPort !== void 0 && (own.manifestPort === peer.port || own.manifestPort === peer.manifestPort)) {
1273
+ issues.push({ code: "multicast_endpoint_auth", path: `${at}.auth.manifestPort`, message: `manifestPort is a port or manifestPort of endpoint ${other} on the same (S, G)`, endpointIndex: index });
1274
+ break;
1275
+ }
1276
+ }
1277
+ }
1278
+ return issues;
1023
1279
  }
1024
1280
 
1025
1281
  // src/mfu-reassembler.ts
@@ -6023,197 +6279,6 @@ if (void 0) {
6023
6279
  });
6024
6280
  }
6025
6281
 
6026
- // src/multicast-auth-catalog.ts
6027
- var RAW_ED25519_KEY_LENGTH = 32;
6028
- var SOURCE_AUTH_SCOPE_LENGTH = 32;
6029
- var BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
6030
- function encodeBase64Url(bytes) {
6031
- let output = "";
6032
- for (let i = 0; i < bytes.length; i += 3) {
6033
- const b0 = bytes[i];
6034
- const b1 = bytes[i + 1];
6035
- const b2 = bytes[i + 2];
6036
- output += BASE64URL_ALPHABET[b0 >> 2];
6037
- output += BASE64URL_ALPHABET[(b0 & 3) << 4 | (b1 === void 0 ? 0 : b1 >> 4)];
6038
- if (b1 === void 0) break;
6039
- output += BASE64URL_ALPHABET[(b1 & 15) << 2 | (b2 === void 0 ? 0 : b2 >> 6)];
6040
- if (b2 === void 0) break;
6041
- output += BASE64URL_ALPHABET[b2 & 63];
6042
- }
6043
- return output;
6044
- }
6045
- var BASE64URL_DECODE_TABLE = (() => {
6046
- const table = new Int8Array(128).fill(-1);
6047
- for (let i = 0; i < BASE64URL_ALPHABET.length; i++) {
6048
- table[BASE64URL_ALPHABET.charCodeAt(i)] = i;
6049
- }
6050
- return table;
6051
- })();
6052
- function decodeBase64Url(text) {
6053
- if (text.length % 4 === 1) {
6054
- throw new Error(`[multicast-auth-catalog] invalid unpadded base64url length for "${text}"`);
6055
- }
6056
- const bytes = [];
6057
- let buffer = 0;
6058
- let bits = 0;
6059
- for (let i = 0; i < text.length; i++) {
6060
- const code = text.charCodeAt(i);
6061
- const value = code < 128 ? BASE64URL_DECODE_TABLE[code] : -1;
6062
- if (value === void 0 || value < 0) {
6063
- throw new Error(`[multicast-auth-catalog] invalid base64url character in "${text}"`);
6064
- }
6065
- buffer = buffer << 6 | value;
6066
- bits += 6;
6067
- if (bits >= 8) {
6068
- bits -= 8;
6069
- bytes.push(buffer >> bits & 255);
6070
- }
6071
- }
6072
- const decoded = Uint8Array.from(bytes);
6073
- if (encodeBase64Url(decoded) !== text) {
6074
- throw new Error(`[multicast-auth-catalog] non-canonical base64url encoding "${text}"`);
6075
- }
6076
- return decoded;
6077
- }
6078
- function decodeAuthScope(authScope) {
6079
- const bytes = decodeBase64Url(authScope);
6080
- if (bytes.byteLength !== SOURCE_AUTH_SCOPE_LENGTH) {
6081
- throw new Error(
6082
- `[multicast-auth-catalog] authScope must decode to ${SOURCE_AUTH_SCOPE_LENGTH} raw bytes, got ${bytes.byteLength}`
6083
- );
6084
- }
6085
- return bytes;
6086
- }
6087
- function decodeEd25519PublicKey(publicKey) {
6088
- const bytes = decodeBase64Url(publicKey);
6089
- if (bytes.byteLength !== RAW_ED25519_KEY_LENGTH) {
6090
- throw new Error(
6091
- `[multicast-auth-catalog] public key must decode to ${RAW_ED25519_KEY_LENGTH} raw bytes, got ${bytes.byteLength}`
6092
- );
6093
- }
6094
- return bytes;
6095
- }
6096
- function isNonEmptyString(value) {
6097
- return typeof value === "string" && value.length > 0;
6098
- }
6099
- function isValidAuthScopeField(value) {
6100
- if (!isNonEmptyString(value)) return false;
6101
- try {
6102
- decodeAuthScope(value);
6103
- return true;
6104
- } catch {
6105
- return false;
6106
- }
6107
- }
6108
- function isValidPublicKeyField(value) {
6109
- if (!isNonEmptyString(value)) return false;
6110
- try {
6111
- decodeEd25519PublicKey(value);
6112
- return true;
6113
- } catch {
6114
- return false;
6115
- }
6116
- }
6117
- function hasOnlyKeys(object2, allowed) {
6118
- const allowedKeys = new Set(allowed);
6119
- return Object.keys(object2).every((key) => allowedKeys.has(key));
6120
- }
6121
- function isMulticastAuthTrackConfig(obj) {
6122
- if (typeof obj !== "object" || obj === null) return false;
6123
- const o = obj;
6124
- return hasOnlyKeys(o, ["mediaTrack", "manifestTrack", "authScope", "sourceSymbolFormat"]) && isNonEmptyString(o["mediaTrack"]) && isNonEmptyString(o["manifestTrack"]) && o["mediaTrack"] !== o["manifestTrack"] && isValidAuthScopeField(o["authScope"]) && isNonEmptyString(o["sourceSymbolFormat"]);
6125
- }
6126
- var VALID_COMPACTION = /* @__PURE__ */ new Set(["merkle", "none"]);
6127
- var VALID_ENFORCEMENT = /* @__PURE__ */ new Set(["shadow", "enforce"]);
6128
- function hasUniqueMulticastAuthTrackBindings(tracks) {
6129
- const bindings = tracks.flatMap((track) => {
6130
- if (typeof track !== "object" || track === null) return [];
6131
- const value = track;
6132
- if (typeof value["mediaTrack"] !== "string" || typeof value["sourceSymbolFormat"] !== "string") {
6133
- return [];
6134
- }
6135
- return [JSON.stringify([value["mediaTrack"], value["sourceSymbolFormat"]])];
6136
- });
6137
- return new Set(bindings).size === bindings.length;
6138
- }
6139
- function isMulticastAuthConfig(obj) {
6140
- if (typeof obj !== "object" || obj === null) return false;
6141
- const o = obj;
6142
- if (o["scheme"] !== "bc-provenance") return false;
6143
- if (o["hash"] !== "blake3") return false;
6144
- if (o["sig"] !== "ed25519") return false;
6145
- if (!hasOnlyKeys(o, ["scheme", "hash", "sig", "publicKey", "keyId", "previousKey", "compaction", "enforcement", "tracks"])) return false;
6146
- if (!isValidPublicKeyField(o["publicKey"])) return false;
6147
- if (!isNonEmptyString(o["keyId"])) return false;
6148
- if (o["previousKey"] !== void 0 && !isValidPublicKeyField(o["previousKey"])) return false;
6149
- if (o["previousKey"] === o["publicKey"]) return false;
6150
- if (typeof o["compaction"] !== "string" || !VALID_COMPACTION.has(o["compaction"])) return false;
6151
- if (o["enforcement"] !== void 0) {
6152
- if (typeof o["enforcement"] !== "string" || !VALID_ENFORCEMENT.has(o["enforcement"])) return false;
6153
- }
6154
- if (!Array.isArray(o["tracks"]) || o["tracks"].length === 0) return false;
6155
- const tracks = o["tracks"];
6156
- if (!tracks.every((t) => isMulticastAuthTrackConfig(t))) return false;
6157
- const typedTracks = tracks;
6158
- const scopes = typedTracks.map((t) => t.authScope);
6159
- if (new Set(scopes).size !== scopes.length) return false;
6160
- if (!hasUniqueMulticastAuthTrackBindings(typedTracks)) return false;
6161
- const manifestTracks = typedTracks.map((t) => t.manifestTrack);
6162
- if (new Set(manifestTracks).size !== manifestTracks.length) return false;
6163
- return true;
6164
- }
6165
- function resolveMulticastAuthMode(playerMode, auth) {
6166
- if (playerMode !== void 0) return playerMode;
6167
- if (auth === void 0) return "off";
6168
- return auth.enforcement ?? "shadow";
6169
- }
6170
- function resolveMulticastAuthCatalog(catalog, playerMode) {
6171
- if (typeof catalog !== "object" || catalog === null || Array.isArray(catalog)) {
6172
- throw new Error("[multicast-auth-catalog] catalog must be an object");
6173
- }
6174
- const root = catalog;
6175
- const rawAuth = root["multicast.auth"];
6176
- if (rawAuth === void 0) {
6177
- if (playerMode === "enforce") {
6178
- throw new Error("[multicast-auth-catalog] player enforce mode requires multicast.auth");
6179
- }
6180
- return void 0;
6181
- }
6182
- if (!isMulticastAuthConfig(rawAuth)) {
6183
- throw new Error("[multicast-auth-catalog] invalid multicast.auth v2 block");
6184
- }
6185
- const rawTracks = root["tracks"];
6186
- if (!Array.isArray(rawTracks)) {
6187
- throw new Error("[multicast-auth-catalog] catalog tracks must be an array");
6188
- }
6189
- const catalogTrackNames = new Set(
6190
- rawTracks.flatMap(
6191
- (track) => typeof track === "object" && track !== null && typeof track["name"] === "string" ? [track["name"]] : []
6192
- )
6193
- );
6194
- for (const track of rawAuth.tracks) {
6195
- if (!catalogTrackNames.has(track.mediaTrack)) {
6196
- throw new Error(`[multicast-auth-catalog] unknown mediaTrack "${track.mediaTrack}"`);
6197
- }
6198
- if (!catalogTrackNames.has(track.manifestTrack)) {
6199
- throw new Error(`[multicast-auth-catalog] unknown manifestTrack "${track.manifestTrack}"`);
6200
- }
6201
- }
6202
- return {
6203
- keyId: rawAuth.keyId,
6204
- acceptedPublicKeys: [
6205
- decodeEd25519PublicKey(rawAuth.publicKey),
6206
- ...rawAuth.previousKey === void 0 ? [] : [decodeEd25519PublicKey(rawAuth.previousKey)]
6207
- ],
6208
- mode: resolveMulticastAuthMode(playerMode, rawAuth),
6209
- compaction: rawAuth.compaction,
6210
- tracks: rawAuth.tracks.map((track) => ({
6211
- ...track,
6212
- authScope: decodeAuthScope(track.authScope)
6213
- }))
6214
- };
6215
- }
6216
-
6217
6282
  // src/repair-layers.ts
6218
6283
  var REPAIR_PRIORITY_MIN = 192;
6219
6284
  var REPAIR_PRIORITY_MAX = 255;
@@ -6221,6 +6286,7 @@ var DEFAULT_REPAIR_PRIORITY = 240;
6221
6286
  var MAX_RAPTORQ_SOURCE_SYMBOLS = 56403;
6222
6287
  var MAX_REPAIR_SYMBOLS = 16777215;
6223
6288
  var MAX_ENCODING_SYMBOL_ID = 16777215;
6289
+ var MAX_REED_SOLOMON_BLOCK_SYMBOLS = 255;
6224
6290
  var RepairContractError = class extends Error {
6225
6291
  constructor(code, path, message) {
6226
6292
  super(`[repair-layers:${code}] ${path}: ${message}`);
@@ -6403,11 +6469,12 @@ function assembleRepairLayers(source, descriptors, fail = throwRepairContractErr
6403
6469
  if (layered && !positiveInteger(source.sourceSymbols)) {
6404
6470
  fail("track_fec", `${source.path}.sourceSymbols`, "layered or overlay repair needs a positive integer sourceSymbols on the source");
6405
6471
  }
6406
- if (layered && source.algorithm !== "raptorq") {
6472
+ const reedSolomon = source.algorithm === "reed-solomon";
6473
+ if (layered && source.algorithm !== "raptorq" && !reedSolomon) {
6407
6474
  fail(
6408
6475
  "track_fec",
6409
6476
  `${source.path}.algorithm`,
6410
- "repair layers and overlays are defined only for raptorq: a block code fixes its codeword length, so symbols of a larger P are not symbols of the code a receiver holding fewer layers decodes"
6477
+ "repair layers and overlays are defined only for raptorq and reed-solomon (draft-ramadan-moq-fec-01 6.3.4 rule 7)"
6411
6478
  );
6412
6479
  }
6413
6480
  let layerZeroPriority = DEFAULT_REPAIR_PRIORITY;
@@ -6466,6 +6533,13 @@ function assembleRepairLayers(source, descriptors, fail = throwRepairContractErr
6466
6533
  `overlay sourceSymbols + repairSymbols - 1 exceeds the 24-bit ESI space (${MAX_ENCODING_SYMBOL_ID})`
6467
6534
  );
6468
6535
  }
6536
+ if (reedSolomon && sourceSymbols + repairSymbols > MAX_REED_SOLOMON_BLOCK_SYMBOLS) {
6537
+ fail(
6538
+ "track_fec_bounds",
6539
+ `${d.path}.repairSymbols`,
6540
+ `reed-solomon overlay sourceSymbols + repairSymbols exceeds ${MAX_REED_SOLOMON_BLOCK_SYMBOLS} (draft-ramadan-moq-fec-01 6.3.4 rule 12)`
6541
+ );
6542
+ }
6469
6543
  overlays.push({ repairTrackName: d.name, scope: "keyframe", sourceSymbols, repairSymbols, priority: d.priority });
6470
6544
  }
6471
6545
  let offset = layerZeroSymbols;
@@ -6510,6 +6584,13 @@ function assembleRepairLayers(source, descriptors, fail = throwRepairContractErr
6510
6584
  `sourceSymbols + total base repair symbols - 1 exceeds the 24-bit ESI space (${MAX_ENCODING_SYMBOL_ID})`
6511
6585
  );
6512
6586
  }
6587
+ if (reedSolomon && k + totalBaseRepairSymbols > MAX_REED_SOLOMON_BLOCK_SYMBOLS) {
6588
+ fail(
6589
+ "track_fec_bounds",
6590
+ `${source.path}.sourceSymbols`,
6591
+ `reed-solomon sourceSymbols + total base repair symbols exceeds ${MAX_REED_SOLOMON_BLOCK_SYMBOLS} (draft-ramadan-moq-fec-01 6.3.4 rule 12)`
6592
+ );
6593
+ }
6513
6594
  return { sourceTrackName: source.name, baseLayers, overlays, totalBaseRepairSymbols };
6514
6595
  }
6515
6596
 
@@ -6557,7 +6638,7 @@ function isFecCatalogGeometry(obj) {
6557
6638
  const o = obj;
6558
6639
  const algorithm = o["algorithm"];
6559
6640
  const symbolSize = o["symbolSize"];
6560
- return typeof algorithm === "string" && (algorithm === "none" || algorithm === "raptorq" || algorithm === "reed-solomon") && typeof o["sourceSymbols"] === "number" && o["sourceSymbols"] >= 1 && typeof o["repairSymbols"] === "number" && o["repairSymbols"] >= 1 && typeof symbolSize === "number" && symbolSize >= 1 && (algorithm !== "raptorq" || symbolSize % 8 === 0) && typeof o["repairTrack"] === "string" && o["repairTrack"].length > 0;
6641
+ return typeof algorithm === "string" && algorithm.length > 0 && typeof o["sourceSymbols"] === "number" && o["sourceSymbols"] >= 1 && typeof o["repairSymbols"] === "number" && o["repairSymbols"] >= 1 && typeof symbolSize === "number" && symbolSize >= 1 && (algorithm !== "raptorq" || symbolSize % 8 === 0) && typeof o["repairTrack"] === "string" && o["repairTrack"].length > 0;
6561
6642
  }
6562
6643
  function isFecCatalogConfig(obj) {
6563
6644
  if (!isFecCatalogGeometry(obj)) return false;
@@ -6572,8 +6653,7 @@ function isMulticastTrackObject(obj) {
6572
6653
  function isMulticastEndpoint(obj) {
6573
6654
  if (typeof obj !== "object" || obj === null) return false;
6574
6655
  const o = obj;
6575
- const protocol = o["protocol"] ?? (typeof o["sourceAddress"] === "string" && o["sourceAddress"].length > 0 ? "ssm" : void 0);
6576
- return typeof protocol === "string" && (protocol === "ssm" || protocol === "asm" || protocol === "amt" || protocol === "atsc3") && typeof o["groupAddress"] === "string" && o["groupAddress"].length > 0 && typeof o["port"] === "number" && o["port"] > 0 && o["port"] <= 65535 && Array.isArray(o["tracks"]) && o["tracks"].every((t) => typeof t === "string" || isMulticastTrackObject(t));
6656
+ return multicastEndpointSource(o) !== void 0 && typeof o["groupAddress"] === "string" && o["groupAddress"].length > 0 && typeof o["port"] === "number" && o["port"] > 0 && o["port"] <= 65535 && Array.isArray(o["tracks"]) && o["tracks"].every((t) => typeof t === "string" || isMulticastTrackObject(t));
6577
6657
  }
6578
6658
  function isMulticastCatalogConfig(obj) {
6579
6659
  if (typeof obj !== "object" || obj === null) return false;
@@ -6677,7 +6757,7 @@ var CmsfCatalogValidationError = class extends Error {
6677
6757
  function catalogError(code, path, message) {
6678
6758
  throw new CmsfCatalogValidationError(code, path, message);
6679
6759
  }
6680
- function validateCmsfMmtpCatalog(value) {
6760
+ function validateCmsfMmtpCatalog(value, options = {}) {
6681
6761
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
6682
6762
  catalogError("catalog_object", "$", "catalog must be an object");
6683
6763
  }
@@ -6698,6 +6778,22 @@ function validateCmsfMmtpCatalog(value) {
6698
6778
  "commonTrackFields is retired; every track carries its own fields"
6699
6779
  );
6700
6780
  }
6781
+ const initDataList = catalog["initDataList"];
6782
+ if (initDataList !== void 0) {
6783
+ if (!Array.isArray(initDataList)) {
6784
+ catalogError("catalog_init_data_list", "$.initDataList", "initDataList must be an array");
6785
+ }
6786
+ initDataList.forEach((entry, i) => {
6787
+ const e = entry;
6788
+ const entryPath = `$.initDataList[${i}]`;
6789
+ if (typeof e !== "object" || e === null || Array.isArray(e) || typeof e["id"] !== "string" || e["id"].length === 0 || typeof e["type"] !== "string" || e["type"].length === 0) {
6790
+ catalogError("catalog_init_data_list", entryPath, "entry needs a non-empty string id and type");
6791
+ }
6792
+ if (e["type"] === "inline" && (typeof e["data"] !== "string" || e["data"].length === 0)) {
6793
+ catalogError("catalog_init_data_list", `${entryPath}.data`, 'an "inline" entry needs non-empty data');
6794
+ }
6795
+ });
6796
+ }
6701
6797
  const tracks = catalog["tracks"];
6702
6798
  const trackRecords = [];
6703
6799
  const positiveInteger3 = (input) => Number.isSafeInteger(input) && input > 0;
@@ -6749,6 +6845,14 @@ function validateCmsfMmtpCatalog(value) {
6749
6845
  if (keyframeIntervalMs !== void 0 && !positiveNumber2(keyframeIntervalMs) || keyframeIntervalTicks !== void 0 && !positiveInteger3(keyframeIntervalTicks)) {
6750
6846
  catalogError("track_keyframe_interval", path, "keyframe interval fields must be positive numbers");
6751
6847
  }
6848
+ const anchor = track["presentationAnchorTicks"];
6849
+ if (anchor !== void 0 && !Number.isSafeInteger(anchor)) {
6850
+ catalogError("track_presentation_anchor", `${path}.presentationAnchorTicks`, "must be a safe integer");
6851
+ }
6852
+ const initRef = track["initRef"];
6853
+ if (initRef !== void 0 && (typeof initRef !== "string" || initRef.length === 0)) {
6854
+ catalogError("track_init_ref", `${path}.initRef`, "must be a non-empty string");
6855
+ }
6752
6856
  if (packaging === "fec-repair") {
6753
6857
  rejectRepairTrackGeometry(path, track, catalogError);
6754
6858
  validateRepairTrackFields(describeRepairTrack(name, path, track), catalogError);
@@ -6756,9 +6860,8 @@ function validateCmsfMmtpCatalog(value) {
6756
6860
  rejectRepairFieldsOnMediaTrack(path, track, catalogError);
6757
6861
  }
6758
6862
  if (packaging === "mmtp") {
6759
- const mmtpMode = track["mmtpMode"];
6760
- if (mmtpMode !== "mpu" && mmtpMode !== "mfu") {
6761
- catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mpu or mfu");
6863
+ if (track["mmtpMode"] !== "mfu") {
6864
+ catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mfu");
6762
6865
  }
6763
6866
  if (!positiveInteger3(timescale)) {
6764
6867
  catalogError("track_timescale", `${path}.timescale`, "must be a positive integer");
@@ -6781,8 +6884,8 @@ function validateCmsfMmtpCatalog(value) {
6781
6884
  }
6782
6885
  const config = fec;
6783
6886
  const algorithm = config["algorithm"];
6784
- if (algorithm !== "none" && algorithm !== "raptorq" && algorithm !== "reed-solomon") {
6785
- catalogError("track_fec", `${path}.fec.algorithm`, "algorithm is not supported");
6887
+ if (typeof algorithm !== "string" || algorithm.length === 0) {
6888
+ catalogError("track_fec", `${path}.fec.algorithm`, "must be a non-empty string");
6786
6889
  }
6787
6890
  if ("interleaveDepth" in config || "interleaveMs" in config) {
6788
6891
  catalogError("track_fec", `${path}.fec`, "interleaveDepthMs is the only supported interleave field");
@@ -6811,6 +6914,9 @@ function validateCmsfMmtpCatalog(value) {
6811
6914
  }
6812
6915
  }
6813
6916
  readFecBlockProfile(config["blockProfile"], `${path}.fec.blockProfile`, algorithm !== "none", catalogError);
6917
+ if (algorithm !== "none" && config["symbolSize"] < ISO_SSBG1_MIN_SYMBOL_SIZE) {
6918
+ catalogError("track_fec", `${path}.fec.symbolSize`, "iso-ssbg1-v1 symbolSize must be at least 14");
6919
+ }
6814
6920
  }
6815
6921
  }
6816
6922
  const repairDescriptors = trackRecords.flatMap(
@@ -6922,15 +7028,8 @@ function validateCmsfMmtpCatalog(value) {
6922
7028
  }
6923
7029
  }
6924
7030
  }
6925
- try {
6926
- resolveMulticastAuthCatalog(catalog);
6927
- } catch (error) {
6928
- catalogError(
6929
- "multicast_auth",
6930
- "$.multicast.auth",
6931
- error instanceof Error ? error.message : "invalid multicast.auth v2 block"
6932
- );
6933
- }
7031
+ const [multicastIssue] = multicastCatalogIssues(catalog, options);
7032
+ if (multicastIssue) catalogError(multicastIssue.code, multicastIssue.path, multicastIssue.message);
6934
7033
  validateArchive(catalog);
6935
7034
  return catalog;
6936
7035
  }
@@ -6956,7 +7055,7 @@ function resolveGroupDurationTicks(timing, timescale) {
6956
7055
  const product = timing.groupDurationMs * timescale;
6957
7056
  if (product % 1e3 !== 0) {
6958
7057
  throw new Error(
6959
- `[carp-catalog] resolveGroupDurationTicks: groupDurationMs=${timing.groupDurationMs} at timescale=${timescale} produces non-integer ticks (${product / 1e3}); publisher must use groupDurationTicks override (mmt-00 \xA74.4.4)`
7058
+ `[carp-catalog] resolveGroupDurationTicks: groupDurationMs=${timing.groupDurationMs} at timescale=${timescale} produces non-integer ticks (${product / 1e3}); publisher must use groupDurationTicks override (mmt-01 \xA74.4.2)`
6960
7059
  );
6961
7060
  }
6962
7061
  return product / 1e3;
@@ -6977,14 +7076,6 @@ function validateSwitchingSetTiming(tracks) {
6977
7076
  return { ok: false, expectedTicks, mismatches };
6978
7077
  }
6979
7078
 
6980
- // node_modules/@blockcast/mmt-transport/dist/types.js
6981
- var MoqFecAlgorithm;
6982
- (function(MoqFecAlgorithm2) {
6983
- MoqFecAlgorithm2[MoqFecAlgorithm2["None"] = 0] = "None";
6984
- MoqFecAlgorithm2[MoqFecAlgorithm2["Xor"] = 1] = "Xor";
6985
- MoqFecAlgorithm2[MoqFecAlgorithm2["RaptorQ"] = 2] = "RaptorQ";
6986
- })(MoqFecAlgorithm || (MoqFecAlgorithm = {}));
6987
-
6988
7079
  // node_modules/@blockcast/mmt-transport/dist/multicast-tier.js
6989
7080
  function endpointKey(endpoint) {
6990
7081
  return `${endpoint.sourceAddress ?? ""}|${endpoint.groupAddress}|${endpoint.port}`;
@@ -7115,8 +7206,8 @@ var AdaptiveBitrateController = class {
7115
7206
  /**
7116
7207
  * Update FEC statistics for ABR decisions
7117
7208
  *
7118
- * Per draft-ramadan-moq-fec-00, ABR should use the effective loss rate
7119
- * (after FEC recovery) rather than raw transport loss rate.
7209
+ * ABR uses the effective loss rate (after FEC recovery) rather than the
7210
+ * raw transport loss rate.
7120
7211
  *
7121
7212
  * @param stats - FEC statistics from the FEC decoder
7122
7213
  */
@@ -7468,6 +7559,20 @@ function toWindowMulticastSubscribeConfig(input) {
7468
7559
  consume: "bytes",
7469
7560
  ...input.packetIds?.length ? { packetIds: [...input.packetIds] } : {}
7470
7561
  };
7562
+ if (input.atsc3) {
7563
+ const { frequency, plpId, serviceId } = input.atsc3;
7564
+ if (!Number.isInteger(frequency) || frequency < 1) {
7565
+ throw new TypeError(`ATSC3 tuning requires a positive integer frequency in kHz, got ${String(frequency)}`);
7566
+ }
7567
+ return {
7568
+ ...base,
7569
+ origin: "tuner",
7570
+ standard: "atsc3",
7571
+ frequency,
7572
+ ...plpId !== void 0 ? { plpId } : {},
7573
+ ...serviceId !== void 0 ? { serviceId } : {}
7574
+ };
7575
+ }
7471
7576
  const relay = input.amtRelay?.trim();
7472
7577
  const driad = !relay && input.amtDiscovery === "driad";
7473
7578
  const wantsAmt = input.mode === "tunnel" || input.mode !== "native" && (relay !== void 0 && relay !== "" || driad);
@@ -8713,8 +8818,7 @@ function multicastFromConfig(input) {
8713
8818
  );
8714
8819
  }
8715
8820
  }
8716
- const seenTuples = /* @__PURE__ */ new Set();
8717
- const endpoints = input.endpoints.map((ep, idx) => validateEndpoint2(ep, idx, seenTuples));
8821
+ const endpoints = input.endpoints.map((ep, idx) => validateEndpoint2(ep, idx));
8718
8822
  const out = { endpoints };
8719
8823
  const { entries: networkSource, relayFrom } = resolveNetworkSource(input);
8720
8824
  networkSource.forEach(validateNetworkSourceEntry);
@@ -8748,9 +8852,20 @@ function multicastFromConfig(input) {
8748
8852
  throw new MulticastInputError(
8749
8853
  ep.protocol === "amt" ? "amt_requires_relay" : "atsc3_requires_tuning",
8750
8854
  idx,
8751
- `endpoint[${idx}] protocol=${ep.protocol} requires a multicast.networkSource entry of type "${ep.protocol}"` + (ep.protocol === "atsc3" ? " carrying frequency, plpId, serviceId and slsUri \u2014 an ATSC3 endpoint is not tunable without them" : "")
8855
+ `endpoint[${idx}] protocol=${ep.protocol} requires a multicast.networkSource entry of type "${ep.protocol}"` + (ep.protocol === "atsc3" ? " carrying at least its frequency (kHz) \u2014 an ATSC3 endpoint is not tunable without it" : "")
8752
8856
  );
8753
8857
  });
8858
+ input.endpoints.forEach((ep, idx) => {
8859
+ if (ep.protocol !== "amt" && ep.protocol !== "atsc3") return;
8860
+ endpoints[idx].networkSource = networkSource.filter((s) => s.type === ep.protocol).map((s) => ({ ...s }));
8861
+ });
8862
+ if (input.auth !== void 0) out.auth = input.auth;
8863
+ const [issue] = multicastCatalogIssues({ multicast: out });
8864
+ if (issue) {
8865
+ const kind = issue.code === "multicast_auth" ? "invalid_multicast_auth" : issue.code === "multicast_endpoint_auth" ? "invalid_endpoint_auth" : issue.path.endsWith(".port") ? "duplicate_endpoint_tuple" : "protocol_source_mismatch";
8866
+ const where = issue.endpointIndex === void 0 ? "" : `endpoint[${issue.endpointIndex}] `;
8867
+ throw new MulticastInputError(kind, issue.endpointIndex ?? null, `${where}${issue.path.replace("$.multicast.", "")}: ${issue.message}`);
8868
+ }
8754
8869
  if (input.enabled !== void 0) out.enabled = input.enabled;
8755
8870
  if (input.version !== void 0) out.version = input.version;
8756
8871
  if (input.validUntil !== void 0) out.validUntil = input.validUntil;
@@ -8762,10 +8877,10 @@ function resolveNetworkSource(input) {
8762
8877
  }
8763
8878
  const relayDns = input.amtFallback?.relayDns?.trim();
8764
8879
  const relay = relayDns || input.endpoints.map((ep) => ep.relayAddress?.trim()).find((r) => !!r);
8765
- const discovery = input.amtFallback?.discovery ?? (relay ? "manual" : void 0);
8766
- if (discovery === void 0) return { entries: [], relayFrom: null };
8880
+ const discovery = input.amtFallback?.discovery;
8881
+ if (discovery === void 0 && !relay) return { entries: [], relayFrom: null };
8767
8882
  return {
8768
- entries: [{ type: "amt", discovery, ...relay ? { relay } : {} }],
8883
+ entries: [{ type: "amt", ...discovery ? { discovery } : {}, ...relay ? { relay } : {} }],
8769
8884
  relayFrom: !relay ? null : relayDns ? "amtFallback.relayDns" : "endpoint.relayAddress"
8770
8885
  };
8771
8886
  }
@@ -8778,8 +8893,11 @@ function validateNetworkSourceEntry(s, i) {
8778
8893
  const extra = Object.keys(s).filter((k) => !keys.has(k) && s[k] !== void 0);
8779
8894
  if (extra.length > 0) throw err("invalid_network_source", `has keys the schema rejects: ${extra.join(", ")}`);
8780
8895
  if (s.type === "amt") {
8781
- if (s.discovery !== "driad" && s.discovery !== "manual") {
8782
- throw err("invalid_amt_discovery", `discovery must be "driad" or "manual"; got ${JSON.stringify(s.discovery)}`);
8896
+ if (s.discovery !== void 0 && s.discovery !== "dns" && s.discovery !== "driad" && s.discovery !== "manual") {
8897
+ throw err(
8898
+ "invalid_amt_discovery",
8899
+ `discovery must be "dns", "driad" or "manual" when present; got ${JSON.stringify(s.discovery)}`
8900
+ );
8783
8901
  }
8784
8902
  if (s.relay !== void 0) {
8785
8903
  const relay = typeof s.relay === "string" ? s.relay.trim() : "";
@@ -8788,8 +8906,8 @@ function validateNetworkSourceEntry(s, i) {
8788
8906
  }
8789
8907
  s.relay = relay;
8790
8908
  }
8791
- if (s.discovery === "manual" && s.relay === void 0) {
8792
- throw err("amt_requires_relay", `discovery="manual" requires a relay ("driad" resolves it at runtime)`);
8909
+ if ((s.discovery === "dns" || s.discovery === "manual") && s.relay === void 0) {
8910
+ throw err("amt_requires_relay", `discovery="${s.discovery}" requires a relay ("driad" resolves it at runtime)`);
8793
8911
  }
8794
8912
  if (s.port !== void 0 && (!Number.isInteger(s.port) || s.port < 1 || s.port > 65535)) {
8795
8913
  throw err("invalid_port", `port must be 1..65535; got ${s.port}`);
@@ -8798,13 +8916,15 @@ function validateNetworkSourceEntry(s, i) {
8798
8916
  }
8799
8917
  const inRange = (v, min, max) => Number.isInteger(v) && v >= min && v <= max;
8800
8918
  if (!inRange(s.frequency, 1, Number.MAX_SAFE_INTEGER)) {
8801
- throw err("invalid_network_source", `frequency must be a positive integer; got ${s.frequency}`);
8919
+ throw err("invalid_network_source", `frequency must be a positive integer in kHz; got ${s.frequency}`);
8920
+ }
8921
+ if (s.plpId !== void 0 && !inRange(s.plpId, 0, 63)) {
8922
+ throw err("invalid_network_source", `plpId must be 0..63; got ${s.plpId}`);
8802
8923
  }
8803
- if (!inRange(s.plpId, 0, 63)) throw err("invalid_network_source", `plpId must be 0..63; got ${s.plpId}`);
8804
- if (!inRange(s.serviceId, 0, 65535)) {
8924
+ if (s.serviceId !== void 0 && !inRange(s.serviceId, 0, 65535)) {
8805
8925
  throw err("invalid_network_source", `serviceId must be 0..65535; got ${s.serviceId}`);
8806
8926
  }
8807
- if (typeof s.slsUri !== "string" || !isAbsoluteUri(s.slsUri)) {
8927
+ if (s.slsUri !== void 0 && (typeof s.slsUri !== "string" || !isAbsoluteUri(s.slsUri))) {
8808
8928
  throw err("invalid_network_source", `slsUri must be an absolute URI; got ${JSON.stringify(s.slsUri)}`);
8809
8929
  }
8810
8930
  }
@@ -8816,7 +8936,7 @@ function isAbsoluteUri(value) {
8816
8936
  return false;
8817
8937
  }
8818
8938
  }
8819
- function validateEndpoint2(ep, idx, seenTuples) {
8939
+ function validateEndpoint2(ep, idx) {
8820
8940
  if (ep.protocol === "ssm" && (!ep.sourceAddress || ep.sourceAddress.length === 0)) {
8821
8941
  throw new MulticastInputError(
8822
8942
  "ssm_requires_source",
@@ -8824,6 +8944,13 @@ function validateEndpoint2(ep, idx, seenTuples) {
8824
8944
  `endpoint[${idx}] protocol=ssm requires sourceAddress`
8825
8945
  );
8826
8946
  }
8947
+ if (ep.protocol === "asm" && ep.sourceAddress !== void 0) {
8948
+ throw new MulticastInputError(
8949
+ "protocol_source_mismatch",
8950
+ idx,
8951
+ `endpoint[${idx}] protocol=asm with sourceAddress "${ep.sourceAddress}"; sourceAddress selects SSM (draft -01 4.1)`
8952
+ );
8953
+ }
8827
8954
  if (!isMulticastGroupAddress(ep.groupAddress)) {
8828
8955
  throw new MulticastInputError(
8829
8956
  "invalid_group_address",
@@ -8883,23 +9010,15 @@ function validateEndpoint2(ep, idx, seenTuples) {
8883
9010
  `endpoint[${idx}] bandwidth must be positive; got ${ep.bandwidth}`
8884
9011
  );
8885
9012
  }
8886
- const tupleKey = `${ep.sourceAddress ?? ""}|${ep.groupAddress}|${ep.port}`;
8887
- if (seenTuples.has(tupleKey)) {
8888
- throw new MulticastInputError(
8889
- "duplicate_endpoint_tuple",
8890
- idx,
8891
- `endpoint[${idx}] duplicates (sourceAddress, groupAddress, port) tuple "${tupleKey}"`
8892
- );
8893
- }
8894
- seenTuples.add(tupleKey);
8895
9013
  const out = {
8896
- protocol: ep.protocol,
9014
+ protocol: ep.sourceAddress === void 0 ? "asm" : "ssm",
8897
9015
  groupAddress: ep.groupAddress,
8898
9016
  port: ep.port,
8899
9017
  tracks: ep.tracks.map((t) => ({ name: t.name, packetId: t.packetId }))
8900
9018
  };
8901
9019
  if (ep.sourceAddress !== void 0) out.sourceAddress = ep.sourceAddress;
8902
9020
  if (ep.bandwidth !== void 0) out.bandwidth = ep.bandwidth;
9021
+ if (ep.auth !== void 0) out.auth = { ...ep.auth };
8903
9022
  return out;
8904
9023
  }
8905
9024
  function isMulticastGroupAddress(addr) {
@@ -8942,9 +9061,9 @@ function multicastFromEnv(env = globalThis.process?.env ?? {}) {
8942
9061
  endpoints,
8943
9062
  ...hasCatalogAmt ? {
8944
9063
  amtFallback: {
8945
- // `"manual"` mirrors `resolveNetworkSource`: a relay named in
8946
- // the catalog is, by definition, not discovered.
8947
- discovery: amtDiscovery ?? "manual",
9064
+ // No default: an omitted discovery with a relay hostname is
9065
+ // "dns" (draft-ramadan-moq-multicast-01 4.2.1).
9066
+ ...amtDiscovery ? { discovery: amtDiscovery } : {},
8948
9067
  ...amtRelayDns ? { relayDns: amtRelayDns } : {}
8949
9068
  }
8950
9069
  } : {}
@@ -9112,7 +9231,7 @@ function mergeOverrideIntoCmsfTracks(tracks, override) {
9112
9231
  if (ot.role !== void 0 && existing.role === void 0) existing.role = ot.role;
9113
9232
  if (existing.packaging === "mmtp") {
9114
9233
  const mode = existing.mmtpMode ?? ot.mmtpMode;
9115
- if (mode !== "mpu" && mode !== "mfu") {
9234
+ if (mode !== "mfu") {
9116
9235
  throw new Error(
9117
9236
  `[phase14-catalog-override] track "${ot.name}" has packaging='mmtp' but no valid mmtpMode`
9118
9237
  );
@@ -9149,7 +9268,7 @@ function mergeOverrideIntoCmsfTracks(tracks, override) {
9149
9268
  );
9150
9269
  }
9151
9270
  const mmtpMode = ot.mmtpMode;
9152
- if (packaging === "mmtp" && mmtpMode !== "mpu" && mmtpMode !== "mfu") {
9271
+ if (packaging === "mmtp" && mmtpMode !== "mfu") {
9153
9272
  throw new Error(
9154
9273
  `[phase14-catalog-override] track "${ot.name}" has packaging='mmtp' but no valid mmtpMode`
9155
9274
  );
@@ -9450,8 +9569,8 @@ function u32(v) {
9450
9569
  }
9451
9570
  var KEYFRAME_FLAGS = 33554432;
9452
9571
  var DELTA_FLAGS = 16842752;
9453
- var UINT32_MAX = 4294967295;
9454
- var MAX_TRACK_ID = UINT32_MAX - 1;
9572
+ var UINT32_MAX2 = 4294967295;
9573
+ var MAX_TRACK_ID = UINT32_MAX2 - 1;
9455
9574
  var INT32_MIN = -2147483648;
9456
9575
  var INT32_MAX = 2147483647;
9457
9576
  function assertTrackId(trackId, label) {
@@ -9460,8 +9579,8 @@ function assertTrackId(trackId, label) {
9460
9579
  }
9461
9580
  }
9462
9581
  function assertTimescale(timescale, label) {
9463
- if (!Number.isInteger(timescale) || timescale <= 0 || timescale > UINT32_MAX) {
9464
- throw new RangeError(`${label} must be an integer in 1..${UINT32_MAX}, got ${timescale}`);
9582
+ if (!Number.isInteger(timescale) || timescale <= 0 || timescale > UINT32_MAX2) {
9583
+ throw new RangeError(`${label} must be an integer in 1..${UINT32_MAX2}, got ${timescale}`);
9465
9584
  }
9466
9585
  }
9467
9586
  function assertCompositionTimeOffsets(samples) {
@@ -12294,16 +12413,6 @@ var DeliveryGapEstimator = class {
12294
12413
 
12295
12414
  // src/iso-block-locator.ts
12296
12415
  var IsoBlockLocator = class _IsoBlockLocator {
12297
- /** Known blocks and spans, in serial order of their start. */
12298
- #blocks = [];
12299
- /** Held first-arrival sources whose block no repair has stated yet. */
12300
- #held = /* @__PURE__ */ new Map();
12301
- /** End of contiguous coverage: the SS_ID the next unknown block starts at. */
12302
- #coverageEnd;
12303
- #kMax;
12304
- #retentionBlocks;
12305
- #heldEvicted = 0;
12306
- #newest;
12307
12416
  /**
12308
12417
  * @param kMax the catalog maximum K (`sourceSymbols`), the bound on SSB_length.
12309
12418
  * @param retentionBlocks how many blocks behind the newest position the
@@ -12311,12 +12420,35 @@ var IsoBlockLocator = class _IsoBlockLocator {
12311
12420
  * no locator exists without retention.
12312
12421
  */
12313
12422
  constructor(kMax, retentionBlocks) {
12423
+ /** Known blocks and spans, in serial order of their start. */
12424
+ this.#blocks = [];
12425
+ /** Held first-arrival sources whose block no repair has stated yet. */
12426
+ this.#held = /* @__PURE__ */ new Map();
12427
+ this.#heldEvicted = 0;
12428
+ /** Pending holes (see `deferIncompleteGaps`): unstated, sources still held. */
12429
+ this.#holes = [];
12430
+ /**
12431
+ * Keep a gap that is missing a source as a pending hole rather than a span,
12432
+ * so a repair FETCHed for it (draft-ramadan-moq-fec §7.5) can still state
12433
+ * its blocks. Set only while a range repair scheduler is wired; its owner
12434
+ * must close every hole it is told about (`closeHolesWithin`).
12435
+ */
12436
+ this.deferIncompleteGaps = false;
12314
12437
  if (!Number.isSafeInteger(kMax) || kMax <= 0) {
12315
12438
  throw new Error(`[IsoBlockLocator] maximum K must be a positive integer (got ${kMax})`);
12316
12439
  }
12317
12440
  this.#kMax = kMax;
12318
12441
  this.#retentionBlocks = _IsoBlockLocator.#checkedRetention(retentionBlocks);
12319
12442
  }
12443
+ #blocks;
12444
+ #held;
12445
+ /** End of contiguous coverage: the SS_ID the next unknown block starts at. */
12446
+ #coverageEnd;
12447
+ #kMax;
12448
+ #retentionBlocks;
12449
+ #heldEvicted;
12450
+ #newest;
12451
+ #holes;
12320
12452
  static #checkedRetention(retentionBlocks) {
12321
12453
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
12322
12454
  throw new Error(
@@ -12379,6 +12511,14 @@ var IsoBlockLocator = class _IsoBlockLocator {
12379
12511
  }
12380
12512
  return null;
12381
12513
  }
12514
+ /** Number of pending holes. */
12515
+ get holeCount() {
12516
+ return this.#holes.length;
12517
+ }
12518
+ /** The stated block (never a span) ending exactly at `end`. */
12519
+ blockEndingAt(end) {
12520
+ return this.#blocks.find((block) => !block.span && isoBlockEnd(block.start, block.length) === end);
12521
+ }
12382
12522
  /** The known block or span starting exactly at `start`. */
12383
12523
  blockAt(start) {
12384
12524
  return this.#blocks.find((block) => block.start === start);
@@ -12401,6 +12541,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
12401
12541
  coversBetween(a, b) {
12402
12542
  if (this.#coverageEnd === void 0) return false;
12403
12543
  if (!serial32Precedes(a, b) || serial32Distance(a, b) <= 1) return true;
12544
+ const first = a + 1 >>> 0;
12545
+ const count = serial32Distance(a, b) - 1;
12546
+ if (this.#holes.some((hole) => isoRangesOverlap(first, count, hole.start, hole.length))) return false;
12404
12547
  return serial32Precedes(b - 1 >>> 0, this.#coverageEnd);
12405
12548
  }
12406
12549
  /**
@@ -12448,6 +12591,22 @@ var IsoBlockLocator = class _IsoBlockLocator {
12448
12591
  }
12449
12592
  return { status: "placed", block: known, placed: [] };
12450
12593
  }
12594
+ const pending = this.#holes.find((h) => isoBlockContains(h.start, h.length, start));
12595
+ if (pending !== void 0) {
12596
+ if (!isoBlockContains(pending.start, pending.length, serial32Add(start, length - 1))) {
12597
+ return { status: "overlap", reason: `repair block ${start}+${length} runs past pending hole ${pending.start}+${pending.length}` };
12598
+ }
12599
+ this.#holes.splice(this.#holes.indexOf(pending), 1);
12600
+ const before = serial32Distance(pending.start, start);
12601
+ const afterStart = isoBlockEnd(start, length);
12602
+ const after = pending.length - before - length;
12603
+ if (before > 0) this.#holes.push({ start: pending.start, length: before, span: false });
12604
+ if (after > 0) this.#holes.push({ start: afterStart, length: after, span: false });
12605
+ const block2 = { start, length, span: false };
12606
+ const placed2 = this.#claim(block2);
12607
+ this.#blocks.push(block2);
12608
+ return { status: "placed", block: block2, placed: placed2 };
12609
+ }
12451
12610
  for (const block2 of this.#blocks) {
12452
12611
  if (isoBlockContains(block2.start, block2.length, start) || isoBlockContains(start, length, block2.start)) {
12453
12612
  return {
@@ -12457,6 +12616,7 @@ var IsoBlockLocator = class _IsoBlockLocator {
12457
12616
  }
12458
12617
  }
12459
12618
  let span;
12619
+ let hole;
12460
12620
  if (this.#coverageEnd === void 0) {
12461
12621
  for (const ssId of this.#held.keys()) {
12462
12622
  if (serial32Precedes(ssId, start)) this.#held.delete(ssId);
@@ -12465,21 +12625,51 @@ var IsoBlockLocator = class _IsoBlockLocator {
12465
12625
  } else if (serial32Precedes(start, this.#coverageEnd)) {
12466
12626
  return { status: "stale", reason: `repair block ${start}+${length} precedes known coverage` };
12467
12627
  } else if (start !== this.#coverageEnd) {
12468
- const spanBlock = {
12469
- start: this.#coverageEnd,
12470
- length: serial32Distance(this.#coverageEnd, start),
12471
- span: true
12472
- };
12473
- span = { block: spanBlock, placed: this.#claim(spanBlock) };
12474
- this.#blocks.push(spanBlock);
12628
+ const gap = { start: this.#coverageEnd, length: serial32Distance(this.#coverageEnd, start) };
12629
+ const lostSsId = this.deferIncompleteGaps ? this.#highestMissing(gap.start, gap.length) : void 0;
12630
+ if (lostSsId !== void 0) {
12631
+ const holeBlock = { ...gap, span: false };
12632
+ this.#holes.push(holeBlock);
12633
+ hole = { block: holeBlock, lostSsId };
12634
+ } else {
12635
+ const spanBlock = { ...gap, span: true };
12636
+ span = { block: spanBlock, placed: this.#claim(spanBlock) };
12637
+ this.#blocks.push(spanBlock);
12638
+ }
12475
12639
  }
12476
12640
  const block = { start, length, span: false };
12477
12641
  const placed = this.#claim(block);
12478
12642
  this.#blocks.push(block);
12479
12643
  this.#coverageEnd = isoBlockEnd(start, length);
12480
12644
  this.retireBehind(start);
12645
+ if (hole !== void 0) return { status: "placed", block, placed, hole };
12481
12646
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
12482
12647
  }
12648
+ /**
12649
+ * Turn every pending hole inside `[start, start + length)` into a
12650
+ * repair-less span, claiming its held sources: its range FETCH ended, so
12651
+ * nothing more will state its blocks. Returns the spans, in SS_ID order.
12652
+ */
12653
+ closeHolesWithin(start, length) {
12654
+ const closed = [];
12655
+ for (const hole of [...this.#holes]) {
12656
+ if (!isoBlockContains(start, length, hole.start)) continue;
12657
+ this.#holes.splice(this.#holes.indexOf(hole), 1);
12658
+ const spanBlock = { start: hole.start, length: hole.length, span: true };
12659
+ closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
12660
+ this.#blocks.push(spanBlock);
12661
+ }
12662
+ return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
12663
+ }
12664
+ /** The highest SS_ID in the range no source is held for, or undefined when all are. */
12665
+ #highestMissing(start, length) {
12666
+ const steps = Math.min(length, this.#held.size + 1);
12667
+ for (let i = 1; i <= steps; i++) {
12668
+ const ssId = serial32Add(start, length - i);
12669
+ if (!this.#held.has(ssId)) return ssId;
12670
+ }
12671
+ return void 0;
12672
+ }
12483
12673
  /**
12484
12674
  * Retire every block and span whose last SS_ID, and every held source,
12485
12675
  * lies more than `retentionBlocks` blocks behind `position`, with the shared
@@ -12498,6 +12688,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
12498
12688
  this.#blocks.splice(i, 1);
12499
12689
  }
12500
12690
  }
12691
+ for (let i = this.#holes.length - 1; i >= 0; i--) {
12692
+ const hole = this.#holes[i];
12693
+ const last = serial32Add(hole.start, hole.length - 1);
12694
+ if (isoBlocksBehindLowerBound(last, position, this.#kMax) > horizon) this.#holes.splice(i, 1);
12695
+ }
12501
12696
  for (const ssId of [...this.#held.keys()]) {
12502
12697
  if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon) this.#held.delete(ssId);
12503
12698
  }
@@ -12506,6 +12701,7 @@ var IsoBlockLocator = class _IsoBlockLocator {
12506
12701
  /** Forget everything (publisher restart, track reset). */
12507
12702
  reset() {
12508
12703
  this.#blocks.length = 0;
12704
+ this.#holes.length = 0;
12509
12705
  this.#held.clear();
12510
12706
  this.#coverageEnd = void 0;
12511
12707
  this.#newest = void 0;
@@ -12521,6 +12717,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
12521
12717
  return placed;
12522
12718
  }
12523
12719
  };
12720
+ function isoRangesOverlap(aStart, aLength, bStart, bLength) {
12721
+ return serial32Distance(aStart, bStart) < aLength || serial32Distance(bStart, aStart) < bLength;
12722
+ }
12524
12723
 
12525
12724
  // src/fec-state.ts
12526
12725
  var MIN_INTERLEAVE_DEPTH_MS = 1;
@@ -12543,8 +12742,8 @@ function isPositiveSafeInteger2(value) {
12543
12742
  }
12544
12743
  function catalogDeclaresFec(fec) {
12545
12744
  const block = recordOf2(fec);
12546
- if (block === void 0 || block["algorithm"] === "none") return false;
12547
- return isPositiveSafeInteger2(block["sourceSymbols"]) && isPositiveSafeInteger2(block["symbolSize"]) && isFecBlockProfile(block["blockProfile"]) && isoBlockSpanUsable(block);
12745
+ if (block === void 0 || block["algorithm"] === "none" || fecAlgorithmUnimplemented(block["algorithm"])) return false;
12746
+ return isPositiveSafeInteger2(block["sourceSymbols"]) && isPositiveSafeInteger2(block["symbolSize"]) && isFecBlockProfile(block["blockProfile"]) && isoBlockSpanUsable(block) && !catalogFecDeclaresUnconfigurableInstance(block);
12548
12747
  }
12549
12748
  function requireBoolean(value, field) {
12550
12749
  if (typeof value !== "boolean") {
@@ -13031,6 +13230,7 @@ function decideGap(input) {
13031
13230
  }
13032
13231
 
13033
13232
  // src/fec-manager.ts
13233
+ var RS_MAX_BLOCK_SYMBOLS = 255;
13034
13234
  var WORKER_ERROR_LOG_CAP = 5;
13035
13235
  var WORKER_ERROR_KIND_CAP = 32;
13036
13236
  var WORKER_ERROR_OVERFLOW_KIND = "other";
@@ -13275,6 +13475,7 @@ var FECManager = class _FECManager {
13275
13475
  // iso-ssbg1-v1 block location per stream (streamKey). A source belongs to a
13276
13476
  // block only once a repair symbol stated the block's (SS_Start, SSB_length).
13277
13477
  this.#isoLocators = /* @__PURE__ */ new Map();
13478
+ this.#deferIsoGaps = false;
13278
13479
  this.#isoRepairRefusedCount = 0;
13279
13480
  this.#isoSourceOversizeCount = 0;
13280
13481
  // Held sources a locator's capacity cap evicted (IsoBlockLocator.heldCapacity):
@@ -13349,6 +13550,14 @@ var FECManager = class _FECManager {
13349
13550
  this.onBlockReclassified = null;
13350
13551
  /** A video stream's classifier mode was established or changed. */
13351
13552
  this.onClassifierMode = null;
13553
+ /**
13554
+ * A repair stated a block past a gap that is missing a source and whose
13555
+ * every repair was lost: a lost SS_ID in an undelimited span
13556
+ * (draft-ramadan-moq-fec §7.5). Set with `setUndelimitedLossHandler`; the
13557
+ * receiver keeps the gap as a pending hole until `closeIsoHoles` is called
13558
+ * for it, which it must be.
13559
+ */
13560
+ this.#onUndelimitedLoss = null;
13352
13561
  /** A block every symbol of which vanished was created by SBN evidence. */
13353
13562
  this.onBlockVanished = null;
13354
13563
  /** A block reached a terminal state (completed, recovered, or failed). */
@@ -13430,6 +13639,7 @@ var FECManager = class _FECManager {
13430
13639
  #highestSbn;
13431
13640
  #sourceFrontiers;
13432
13641
  #isoLocators;
13642
+ #deferIsoGaps;
13433
13643
  #isoRepairRefusedCount;
13434
13644
  #isoSourceOversizeCount;
13435
13645
  #isoHeldEvictedCount;
@@ -13443,6 +13653,7 @@ var FECManager = class _FECManager {
13443
13653
  #workerErrorCounts;
13444
13654
  #decoderUnavailableEvents;
13445
13655
  #repairSymbolSizeMismatchCount;
13656
+ #onUndelimitedLoss;
13446
13657
  #encodeTrackName(catalogTrackName) {
13447
13658
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
13448
13659
  if (encoded === void 0) {
@@ -14433,8 +14644,10 @@ var FECManager = class _FECManager {
14433
14644
  );
14434
14645
  }
14435
14646
  const hasCatalogTiming = _FECManager.#hasCatalogTiming({ interleaveDepthMs: ownInterleaveDepthMs });
14647
+ const algorithm = config.algorithm ?? previous.algorithm;
14436
14648
  const next = {
14437
14649
  blockProfile,
14650
+ ...algorithm === void 0 ? {} : { algorithm },
14438
14651
  k,
14439
14652
  symbolSize: config.symbolSize != null && config.symbolSize > 0 ? config.symbolSize : previousTrack?.symbolSize ?? 0,
14440
14653
  interleaveDepthMs: ownInterleaveDepthMs,
@@ -15187,6 +15400,7 @@ var FECManager = class _FECManager {
15187
15400
  let locator = this.#isoLocators.get(streamKey);
15188
15401
  if (!locator) {
15189
15402
  locator = new IsoBlockLocator(this.#trackConfig(packetId).k, this.#isoRetentionBlocks(packetId));
15403
+ locator.deferIncompleteGaps = this.#deferIsoGaps;
15190
15404
  this.#isoLocators.set(streamKey, locator);
15191
15405
  }
15192
15406
  return locator;
@@ -15283,15 +15497,61 @@ var FECManager = class _FECManager {
15283
15497
  }
15284
15498
  return placement;
15285
15499
  }
15286
- if (placement.span !== void 0) {
15287
- const key = this.#blockKey(placement.span.block.start, packetId, catalogTrackName);
15288
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, placement.span.block.length);
15289
- }
15290
- if (placement.span !== void 0 && placement.span.placed.length === 0) {
15291
- this.#materializeBlock(placement.span.block.start, packetId, catalogTrackName, true);
15500
+ if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
15501
+ if (placement.hole !== void 0) {
15502
+ const locator = this.#isoLocatorFor(packetId, catalogTrackName);
15503
+ const hole = placement.hole.block;
15504
+ const previous = locator.blockEndingAt(hole.start);
15505
+ const loss = {
15506
+ packetId,
15507
+ catalogTrackName,
15508
+ holeStart: hole.start,
15509
+ holeLength: hole.length,
15510
+ lostSsId: placement.hole.lostSsId,
15511
+ kMax: this.#trackConfig(packetId).k,
15512
+ ...previous === void 0 ? {} : { previousBlockStart: previous.start }
15513
+ };
15514
+ this.#onUndelimitedLoss(loss);
15292
15515
  }
15293
15516
  return placement;
15294
15517
  }
15518
+ /**
15519
+ * Keep an iso-ssbg1-v1 gap missing a source as a pending hole, reported to
15520
+ * `handler`, instead of a repair-less span; null restores spans. Set by the
15521
+ * range repair scheduler; applies to every stream from its next gap. The
15522
+ * handler and the deferral are one setting, so no hole is ever created with
15523
+ * nobody to close it.
15524
+ */
15525
+ setUndelimitedLossHandler(handler) {
15526
+ this.#onUndelimitedLoss = handler;
15527
+ this.#deferIsoGaps = handler !== null;
15528
+ for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
15529
+ }
15530
+ /**
15531
+ * The range repair for a hole ended: every hole still pending inside
15532
+ * `[start, start + length)` becomes a repair-less span. Returns those spans
15533
+ * with the held sources they placed, for the caller to feed (MmtpRouter).
15534
+ */
15535
+ closeIsoHoles(packetId, catalogTrackName, start, length) {
15536
+ const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
15537
+ if (locator === void 0) return [];
15538
+ const spans = locator.closeHolesWithin(start, length);
15539
+ for (const span of spans) this.#openIsoSpan(span, packetId, catalogTrackName);
15540
+ return spans;
15541
+ }
15542
+ /**
15543
+ * A repair-less span has no repair to state its length, so it is known
15544
+ * here: its sources make it clean exactly when all of them arrived. A
15545
+ * stated block learns its SSB_length from its own repair symbol, fed after
15546
+ * its placed sources exactly as on the wire (feedRepairSymbol). A span every
15547
+ * SS_ID of which vanished resolves through its deadline like any vanished
15548
+ * block.
15549
+ */
15550
+ #openIsoSpan(span, packetId, catalogTrackName) {
15551
+ const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
15552
+ if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
15553
+ if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
15554
+ }
15295
15555
  /**
15296
15556
  * Resolution of the SS_IDs strictly between two released frames' SS_IDs on
15297
15557
  * an iso-ssbg1-v1 stream, for in-order frame release: null while a block
@@ -15827,6 +16087,18 @@ var FECManager = class _FECManager {
15827
16087
  * counted (BLO-48306). A packetId with no configured block profile admits
15828
16088
  * nothing here; its repair is dropped upstream as unreadable.
15829
16089
  */
16090
+ /**
16091
+ * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
16092
+ * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
16093
+ * block state unchanged. The router calls this before the repair places a
16094
+ * block or takes any other part in block bookkeeping. A RaptorQ track admits
16095
+ * every header that parsed (its RS_ID < RSB_length check is in the parser).
16096
+ */
16097
+ admitRepairBlockLength(packetId, ssbLength, rsbLength, rsId) {
16098
+ if (rsId >= rsbLength) return false;
16099
+ if (this.#trackConfigs.get(packetId)?.algorithm !== "reed-solomon") return true;
16100
+ return ssbLength + rsbLength <= RS_MAX_BLOCK_SYMBOLS;
16101
+ }
15830
16102
  admitRepairSymbolSize(packetId, ssStart, ssbLength, rsId, byteLength) {
15831
16103
  if (!this.#hasBlockProfile(packetId)) return false;
15832
16104
  const symbolSize = this.#trackConfig(packetId).symbolSize;
@@ -18977,6 +19249,12 @@ var MmtpRouter = class {
18977
19249
  * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
18978
19250
  */
18979
19251
  #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
19252
+ /**
19253
+ * Streams whose multicast leg delivered a RAP-flagged source packet that was
19254
+ * not parsed, typically because its overlap copy was parsed first
19255
+ * (BLO-49179). The next video keyframe emitted on the stream consumes it.
19256
+ */
19257
+ #multicastRapTwinByStream = /* @__PURE__ */ new Set();
18980
19258
  #lastDirectSourceVideoTsByStream = /* @__PURE__ */ new Map();
18981
19259
  #lastDirectEmittedVideoTsByStream = /* @__PURE__ */ new Map();
18982
19260
  #pendingDirectRecoveredVideoByStream = /* @__PURE__ */ new Map();
@@ -19110,6 +19388,12 @@ var MmtpRouter = class {
19110
19388
  ...meta.catalogTrackName === void 0 ? {} : { catalogTrackName: meta.catalogTrackName }
19111
19389
  };
19112
19390
  if (meta.source) frameMeta.source = meta.source;
19391
+ if (isVideo && frameMeta.keyframe) {
19392
+ const twinSeen = this.#multicastRapTwinByStream.delete(
19393
+ this.#mediaStreamKey(packetId, frameMeta.catalogTrackName)
19394
+ );
19395
+ if (twinSeen && frameMeta.source === "moq") frameMeta.source = "multicast";
19396
+ }
19113
19397
  if (meta.deliveryProvenance !== void 0)
19114
19398
  frameMeta.deliveryProvenance = meta.deliveryProvenance;
19115
19399
  if (meta.recovered) frameMeta.recovered = true;
@@ -19795,6 +20079,7 @@ var MmtpRouter = class {
19795
20079
  `[MmtpRouter] packetId=${ownerPacketId} is iso-ssbg1-v1 but its FEC manager cannot place ISO blocks`
19796
20080
  );
19797
20081
  }
20082
+ if (fec.admitRepairBlockLength && !fec.admitRepairBlockLength(ownerPacketId, repair.ssbLength, repair.rsbLength, repair.rsId)) return;
19798
20083
  if (fec.admitRepairSymbolSize && !fec.admitRepairSymbolSize(
19799
20084
  ownerPacketId,
19800
20085
  repair.ssStart,
@@ -19836,6 +20121,17 @@ var MmtpRouter = class {
19836
20121
  this.#routeRecoveredBlock(blockStart, recovered, ownerPacketId, catalogTrackName);
19837
20122
  }
19838
20123
  }
20124
+ /**
20125
+ * The range repair FETCH for an undelimited hole ended (draft-ramadan-moq-fec
20126
+ * §7.5): what no repair stated becomes repair-less spans, whose held sources
20127
+ * are fed exactly as a span a repair closed.
20128
+ */
20129
+ closeIsoHoles(ownerPacketId, catalogTrackName, start, length) {
20130
+ const spans = this.#fecManager?.closeIsoHoles?.(ownerPacketId, catalogTrackName, start, length) ?? [];
20131
+ for (const span of spans) {
20132
+ this.#replayIsoSources(ownerPacketId, catalogTrackName, span.block.start, span.placed);
20133
+ }
20134
+ }
19839
20135
  /**
19840
20136
  * Feed iso-ssbg1-v1 sources a repair just placed, in SS_ID order, exactly as
19841
20137
  * a first-arrival source is fed once its block is known: transport
@@ -19932,6 +20228,7 @@ var MmtpRouter = class {
19932
20228
  this.#droppedPreSyncVideo.delete(streamKey);
19933
20229
  this.#latestVideoSeqByStream.delete(streamKey);
19934
20230
  this.#ssIdSeqOffsetByStream.delete(streamKey);
20231
+ this.#multicastRapTwinByStream.delete(streamKey);
19935
20232
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
19936
20233
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
19937
20234
  this.#pendingDirectRecoveredVideoByStream.delete(streamKey);
@@ -20730,6 +21027,10 @@ var MmtpRouter = class {
20730
21027
  // An FEC source frame is anchored by its own SS_ID (C.5.2).
20731
21028
  ...fecSource && fecPayloadId ? { fecSbn: fecPayloadId.ssId } : {}
20732
21029
  }, parsed);
21030
+ } else if (source === "multicast" && info.rapFlag) {
21031
+ this.#multicastRapTwinByStream.add(
21032
+ this.#mediaStreamKey(info.packetId, catalogTrackName)
21033
+ );
20733
21034
  }
20734
21035
  if (this.#classifyPacketId(info.packetId) === null) return;
20735
21036
  if (this.#fecManager && fecPayloadId && coords && sourceSymbolAccepted && sourceSymbolTrackable) {
@@ -22038,48 +22339,6 @@ function createWasmMmtpContainerParser(config) {
22038
22339
  });
22039
22340
  }
22040
22341
 
22041
- // src/fec-codec.ts
22042
- var NoneCodec = class {
22043
- constructor() {
22044
- this.algorithm = "none";
22045
- }
22046
- addSymbol(_blockId, _symbolId, data, _isRepair) {
22047
- return data;
22048
- }
22049
- configure(_params) {
22050
- }
22051
- cleanup(_now) {
22052
- return new Uint8Array(0);
22053
- }
22054
- };
22055
- function createFecCodec(algorithm) {
22056
- switch (algorithm) {
22057
- case "none":
22058
- return new NoneCodec();
22059
- case "reed-solomon":
22060
- return new ReedSolomonCodec();
22061
- case "raptorq":
22062
- console.warn("[FEC] RaptorQ requested via createFecCodec \u2014 use FECManager.setFecDecoder() for WASM RaptorQ. Falling back to NoneCodec.");
22063
- return new NoneCodec();
22064
- default:
22065
- console.warn(`[FEC] Unknown algorithm "${algorithm}", falling back to NoneCodec`);
22066
- return new NoneCodec();
22067
- }
22068
- }
22069
- var ReedSolomonCodec = class {
22070
- constructor() {
22071
- this.algorithm = "reed-solomon";
22072
- }
22073
- addSymbol(_blockId, _symbolId, _data, _isRepair) {
22074
- return null;
22075
- }
22076
- configure(_params) {
22077
- }
22078
- cleanup(_now) {
22079
- return new Uint8Array(0);
22080
- }
22081
- };
22082
-
22083
22342
  // src/multicast-transport.ts
22084
22343
  var JOIN_SUCCEEDED = Object.freeze({ ok: true });
22085
22344
  function providerErrorOf(error) {
@@ -22229,7 +22488,8 @@ var MulticastTransport = class {
22229
22488
  amtRelayPort: config.amtRelayPort,
22230
22489
  amtDiscovery: config.amtDiscovery,
22231
22490
  packetIds: config.packetIds,
22232
- tracks: config.tracks
22491
+ tracks: config.tracks,
22492
+ atsc3: config.atsc3
22233
22493
  });
22234
22494
  failure = "provider-rejected";
22235
22495
  const subscription = await gateway.subscribe(subscribeConfig);
@@ -22834,6 +23094,25 @@ function catalogAmtNetworkSource(networkSource) {
22834
23094
  }
22835
23095
  return void 0;
22836
23096
  }
23097
+ function intIn(value, min, max) {
23098
+ return Number.isInteger(value) && value >= min && value <= max;
23099
+ }
23100
+ function catalogAtsc3NetworkSource(networkSource) {
23101
+ const entries = Array.isArray(networkSource) ? networkSource : networkSource ? [networkSource] : [];
23102
+ for (const raw of entries) {
23103
+ if (!raw || typeof raw !== "object") continue;
23104
+ const ns = raw;
23105
+ if (ns.type !== "atsc3" || !intIn(ns.frequency, 1, Number.MAX_SAFE_INTEGER)) continue;
23106
+ const slsUri = typeof ns.slsUri === "string" ? ns.slsUri.trim() : "";
23107
+ return {
23108
+ frequency: ns.frequency,
23109
+ ...intIn(ns.plpId, 0, 63) ? { plpId: ns.plpId } : {},
23110
+ ...intIn(ns.serviceId, 0, 65535) ? { serviceId: ns.serviceId } : {},
23111
+ ...slsUri ? { slsUri } : {}
23112
+ };
23113
+ }
23114
+ return void 0;
23115
+ }
22837
23116
 
22838
23117
  // src/catalog-fec-params.ts
22839
23118
  var MAX_SAFE_TICKS_PER_HZ = Number.MAX_SAFE_INTEGER / 1e3;
@@ -23049,6 +23328,13 @@ function isoSpanUnavailable(fec, path, declaresFecInstance) {
23049
23328
  function catalogFecUnavailable(fec, fecPath) {
23050
23329
  if (catalogFecAvailable(fec)) return void 0;
23051
23330
  const block = recordOf3(fec);
23331
+ if (fecAlgorithmUnimplemented(block["algorithm"])) {
23332
+ return Object.freeze({
23333
+ code: "track_fec_algorithm_unimplemented",
23334
+ path: `${fecPath}.algorithm`,
23335
+ message: `algorithm ${JSON.stringify(block["algorithm"])} is not implemented: the track plays without FEC`
23336
+ });
23337
+ }
23052
23338
  const declaresFecInstance = block["algorithm"] !== "none";
23053
23339
  const reason = blockProfileUnavailable(block["blockProfile"], `${fecPath}.blockProfile`, declaresFecInstance) ?? isoSpanUnavailable(block, `${fecPath}.interleaveDepthMs`, declaresFecInstance);
23054
23340
  if (reason === void 0) {
@@ -23068,7 +23354,7 @@ function fecParams(catalog, track, rendition, fps, sampleRate) {
23068
23354
  throwRepairContractError(
23069
23355
  "track_fec",
23070
23356
  `${fecPath}.${kValid ? "symbolSize" : "sourceSymbols"}`,
23071
- "must be a positive integer"
23357
+ kValid && Number.isSafeInteger(fec.symbolSize) && (fec.symbolSize ?? 0) > 0 ? `iso-ssbg1-v1 symbolSize must be at least ${ISO_SSBG1_MIN_SYMBOL_SIZE}` : "must be a positive integer"
23072
23358
  );
23073
23359
  }
23074
23360
  const fecUnavailable = catalogFecUnavailable(fec, fecPath);
@@ -23077,6 +23363,7 @@ function fecParams(catalog, track, rendition, fps, sampleRate) {
23077
23363
  const fecBlockProfile = readFecBlockProfile(fec.blockProfile, `${fecPath}.blockProfile`, true, throwRepairContractError);
23078
23364
  return {
23079
23365
  fecK: fec.sourceSymbols ?? 0,
23366
+ fecAlgorithm: fec.algorithm === "reed-solomon" ? "reed-solomon" : "raptorq",
23080
23367
  fecBlockProfile,
23081
23368
  fecRepairCount: fec.repairSymbols ?? 0,
23082
23369
  // The wire RSB_length: every base layer's packets carry the base total (§7.1).
@@ -23173,8 +23460,10 @@ function newBlockPolicyStats(packetId, catalogTrackName, epoch) {
23173
23460
  repairsSkippedRttUnmeasured: 0,
23174
23461
  repairsSkippedRttExceedsBudget: 0,
23175
23462
  repairsSkippedPresentationDelayUnavailable: 0,
23463
+ repairsSkippedRangeNoAnchor: 0,
23176
23464
  lastRepairSkip: null,
23177
23465
  keyframeRepairFetchesSent: 0,
23466
+ rangeRepairFetchesSent: 0,
23178
23467
  keyframeBudgetHolds: 0,
23179
23468
  keyframeBudgetHoldMs: 0,
23180
23469
  deltaBlocksFailed: 0,
@@ -23253,6 +23542,12 @@ var REPAIR_PRIORITY_REASONS = /* @__PURE__ */ new Set([
23253
23542
  "repair-priority-absent",
23254
23543
  "repair-priority-invalid"
23255
23544
  ]);
23545
+ var REPAIR_SKIP_REASONS = /* @__PURE__ */ new Set([
23546
+ "rtt-unmeasured",
23547
+ "rtt-exceeds-budget",
23548
+ "presentation-delay-unavailable"
23549
+ ]);
23550
+ var REPAIR_DEADLINE_BOUNDS = /* @__PURE__ */ new Set(["wait", "presentation", "keyframe", "retention"]);
23256
23551
  var GAP_REASONS = {
23257
23552
  "rap-lost": "stall",
23258
23553
  "rap-unknown": "stall",
@@ -23275,6 +23570,9 @@ function isSymbolCounts(value) {
23275
23570
  function isNullableNonNegative(value) {
23276
23571
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
23277
23572
  }
23573
+ function isFiniteNumber(value) {
23574
+ return typeof value === "number" && Number.isFinite(value);
23575
+ }
23278
23576
  function isRepairLifecycleEvent(value) {
23279
23577
  if (!isRecord(value) || value["version"] !== 2) return false;
23280
23578
  const block = value["block"];
@@ -23292,6 +23590,20 @@ function isRepairLifecycleEvent(value) {
23292
23590
  case "repair-preempted":
23293
23591
  case "repair-deferred":
23294
23592
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
23593
+ case "repair-sent":
23594
+ return hasExactKeys(value, [
23595
+ "version",
23596
+ "type",
23597
+ "block",
23598
+ "priority",
23599
+ "rttMs",
23600
+ "budgetMs",
23601
+ "delayMs",
23602
+ "blockAgeMs",
23603
+ "bound"
23604
+ ]) && isRepairBlockIdentity(block) && (value["priority"] === 0 || value["priority"] === 1 || value["priority"] === 2) && isFiniteNumber(value["rttMs"]) && value["rttMs"] > 0 && isFiniteNumber(value["budgetMs"]) && value["budgetMs"] > value["rttMs"] && isNullableNonNegative(value["delayMs"]) && isNullableNonNegative(value["blockAgeMs"]) && value["delayMs"] === null === (value["blockAgeMs"] === null) && REPAIR_DEADLINE_BOUNDS.has(value["bound"]);
23605
+ case "repair-skipped":
23606
+ return hasExactKeys(value, ["version", "type", "block", "reason", "rttMs", "budgetMs"]) && isRepairBlockIdentity(block) && REPAIR_SKIP_REASONS.has(value["reason"]) && isNullableNonNegative(value["rttMs"]) && isFiniteNumber(value["budgetMs"]);
23295
23607
  case "repair-priority": {
23296
23608
  const blockClass = value["blockClass"];
23297
23609
  const action = value["action"];
@@ -24481,7 +24793,7 @@ var MulticastManager = class {
24481
24793
  *
24482
24794
  * D-04: Validates completeness via validateSwitchingSet — throws if incomplete.
24483
24795
  * D-07: Applies per-track FEC configs (base+delta get decoders; repair does not).
24484
- * D-17: Builds altGroup → track-name index for getSwitchingSet().
24796
+ * D-17: Builds altGroup → track-name index for getSwitchingSet() (repair legs excluded).
24485
24797
  * D-26: Registers packetId → TrackRole on MmtpRouter for block-complete fanout.
24486
24798
  *
24487
24799
  * FEC availability is per track (draft-ramadan-moq-fec §5.1). A media track
@@ -24532,11 +24844,9 @@ var MulticastManager = class {
24532
24844
  }
24533
24845
  }
24534
24846
  const repairOwnerGroup = /* @__PURE__ */ new Map();
24535
- const repairOwnerAltGroup = /* @__PURE__ */ new Map();
24536
24847
  for (const track of catalog.tracks) {
24537
24848
  for (const repairName of repairNamesBySource.get(track.name) ?? []) {
24538
24849
  repairOwnerGroup.set(repairName, altGroupKey(track));
24539
- repairOwnerAltGroup.set(repairName, track.altGroup);
24540
24850
  }
24541
24851
  }
24542
24852
  const groupKeyFor = (track) => repairOwnerGroup.get(track.name) ?? altGroupKey(track);
@@ -24635,11 +24945,10 @@ var MulticastManager = class {
24635
24945
  for (let i = 0; i < catalog.tracks.length; i++) {
24636
24946
  const track = catalog.tracks[i];
24637
24947
  const role = resolvedRoles[i];
24638
- const altGroup = repairOwnerAltGroup.has(track.name) ? repairOwnerAltGroup.get(track.name) : track.altGroup;
24639
- if (altGroup !== void 0) {
24640
- const existing = this.#switchingSets.get(altGroup) ?? [];
24948
+ if (role !== "repair" && track.altGroup !== void 0) {
24949
+ const existing = this.#switchingSets.get(track.altGroup) ?? [];
24641
24950
  existing.push(track.name);
24642
- this.#switchingSets.set(altGroup, existing);
24951
+ this.#switchingSets.set(track.altGroup, existing);
24643
24952
  }
24644
24953
  if (track.packetId !== void 0) {
24645
24954
  this.#router.setPacketIdRole(track.packetId, role);
@@ -24714,7 +25023,7 @@ var MulticastManager = class {
24714
25023
  #multiTrackFecTracks = /* @__PURE__ */ new Map();
24715
25024
  /**
24716
25025
  * Return the track names belonging to the given altGroup switching set.
24717
- * D-17: altGroup groups base+delta+repair into one switching set.
25026
+ * D-17: tracks with equal altGroup form one switching set; repair legs are in none.
24718
25027
  *
24719
25028
  * @param altGroup - The altGroup number to look up.
24720
25029
  * @returns Array of track names in that switching set (empty if none).
@@ -24742,6 +25051,19 @@ var MulticastManager = class {
24742
25051
  this.requestRepairForBlock(sbn, packetId, catalogTrackName, blockClass);
24743
25052
  };
24744
25053
  }
25054
+ /**
25055
+ * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
25056
+ * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
25057
+ * pending hole and reported here, and `closeIsoHoles` must be called for it
25058
+ * once its range FETCH ends (or none is sent).
25059
+ */
25060
+ onUndelimitedLoss(cb) {
25061
+ this.#fec.setUndelimitedLossHandler(cb);
25062
+ }
25063
+ /** End a pending hole's range repair: feed what no repair stated as spans. */
25064
+ closeIsoHoles(packetId, catalogTrackName, start, length) {
25065
+ this.#router.closeIsoHoles(packetId, catalogTrackName, start, length);
25066
+ }
24745
25067
  /**
24746
25068
  * Record a repair request whose SUBSCRIBER_PRIORITY the catalog could not
24747
25069
  * supply (draft-ramadan-moq-fec §11.4.5): sent without the parameter, or
@@ -24763,6 +25085,7 @@ var MulticastManager = class {
24763
25085
  stats.repairsSkipped++;
24764
25086
  if (reason === "rtt-unmeasured") stats.repairsSkippedRttUnmeasured++;
24765
25087
  else if (reason === "rtt-exceeds-budget") stats.repairsSkippedRttExceedsBudget++;
25088
+ else if (reason === "range-no-anchor") stats.repairsSkippedRangeNoAnchor++;
24766
25089
  else stats.repairsSkippedPresentationDelayUnavailable++;
24767
25090
  stats.lastRepairSkip = {
24768
25091
  reason,
@@ -24794,8 +25117,20 @@ var MulticastManager = class {
24794
25117
  stats.keyframeBudgetHoldMs += extensionMs;
24795
25118
  }
24796
25119
  /** Record a repair FETCH the scheduler admitted and sent. */
24797
- noteRepairFetchSent(priority, _sbn, packetId, catalogTrackName) {
25120
+ noteRepairFetchSent(priority, sbn, packetId, catalogTrackName, measurement) {
24798
25121
  if (priority === 0) this.#statsFor(packetId, catalogTrackName).keyframeRepairFetchesSent++;
25122
+ if (measurement.range) this.#statsFor(packetId, catalogTrackName).rangeRepairFetchesSent++;
25123
+ this.#emitRepairLifecycle({
25124
+ version: 2,
25125
+ type: "repair-sent",
25126
+ block: repairBlockIdentity(packetId, sbn, catalogTrackName),
25127
+ priority,
25128
+ rttMs: measurement.rttMs,
25129
+ budgetMs: measurement.budgetMs,
25130
+ delayMs: measurement.delayMs,
25131
+ blockAgeMs: measurement.blockAgeMs,
25132
+ bound: measurement.bound
25133
+ });
24799
25134
  }
24800
25135
  /**
24801
25136
  * Record a repair-scheduler decision about a delta block: preempted for
@@ -25022,7 +25357,7 @@ async function setupFecWorkerForTrack(opts) {
25022
25357
  trackType: opts.trackType,
25023
25358
  framerate: opts.framerate,
25024
25359
  sampleRate: opts.sampleRate,
25025
- algorithm: "raptor",
25360
+ algorithm: opts.fecAlgorithm ?? "raptorq",
25026
25361
  blockProfile,
25027
25362
  k: opts.fecK,
25028
25363
  // P as this receiver joined it, not the catalog total: the worker snapshot
@@ -25039,6 +25374,7 @@ async function setupFecWorkerForTrack(opts) {
25039
25374
  try {
25040
25375
  opts.multicastManager.setFecWorker(opts.packetId, client, opts.trackType, {
25041
25376
  blockProfile,
25377
+ algorithm: opts.fecAlgorithm ?? "raptorq",
25042
25378
  k: opts.fecK,
25043
25379
  symbolSize: opts.fecSymbolSize,
25044
25380
  interleaveDepthMs: opts.fecInterleaveMs,
@@ -25712,7 +26048,7 @@ function asSeconds(n) {
25712
26048
  }
25713
26049
  return n;
25714
26050
  }
25715
- function groupIdForTicks(ticks, groupDurationTicks) {
26051
+ function groupIdForTicks(ticks, groupDurationTicks, presentationAnchorTicks = 0) {
25716
26052
  if (!Number.isInteger(ticks)) {
25717
26053
  throw new Error(
25718
26054
  `[align] groupIdForTicks: ticks must be an integer, got ${ticks}`
@@ -25723,8 +26059,23 @@ function groupIdForTicks(ticks, groupDurationTicks) {
25723
26059
  `[align] groupIdForTicks: groupDurationTicks must be a positive integer, got ${groupDurationTicks}`
25724
26060
  );
25725
26061
  }
25726
- if (ticks < 0) return 0;
25727
- return Math.floor(ticks / groupDurationTicks);
26062
+ if (!Number.isInteger(presentationAnchorTicks)) {
26063
+ throw new Error(
26064
+ `[align] groupIdForTicks: presentationAnchorTicks must be an integer, got ${presentationAnchorTicks}`
26065
+ );
26066
+ }
26067
+ const relativeTicks = ticks - presentationAnchorTicks;
26068
+ if (!Number.isSafeInteger(relativeTicks)) {
26069
+ throw new Error(
26070
+ `[align] groupIdForTicks: ticks - presentationAnchorTicks = ${relativeTicks} is not a safe integer`
26071
+ );
26072
+ }
26073
+ if (relativeTicks < 0) {
26074
+ throw new Error(
26075
+ `[align] groupIdForTicks: ticks ${ticks} precede presentationAnchorTicks ${presentationAnchorTicks}; the publisher must reject this MPU (moq-mmt-01 4.4.1)`
26076
+ );
26077
+ }
26078
+ return Math.floor(relativeTicks / groupDurationTicks);
25728
26079
  }
25729
26080
  function groupIdFor(mediaTimeSec, groupDurationSec) {
25730
26081
  if (!Number.isFinite(mediaTimeSec)) {
@@ -25737,7 +26088,11 @@ function groupIdFor(mediaTimeSec, groupDurationSec) {
25737
26088
  `[align] groupIdFor: groupDurationSec must be a positive finite number, got ${groupDurationSec}`
25738
26089
  );
25739
26090
  }
25740
- if (mediaTimeSec < 0) return 0;
26091
+ if (mediaTimeSec < 0) {
26092
+ throw new Error(
26093
+ `[align] groupIdFor: mediaTimeSec ${mediaTimeSec} precedes presentationAnchorTicks 0; the publisher must reject this MPU (moq-mmt-01 4.4.1)`
26094
+ );
26095
+ }
25741
26096
  const TS = 1e9;
25742
26097
  const ticks = Math.round(mediaTimeSec * TS);
25743
26098
  const durTicks = Math.round(groupDurationSec * TS);
@@ -26708,6 +27063,346 @@ var CmcdProducer = class {
26708
27063
  }
26709
27064
  };
26710
27065
 
27066
+ // src/mmtp-fec-session.ts
27067
+ var PATH_BITS = { moq: 1, multicast: 2 };
27068
+ var MIXED_PATHS = PATH_BITS.moq | PATH_BITS.multicast;
27069
+ var MmtpFecSession = class {
27070
+ #decoder;
27071
+ /** Blocks a repair has defined and that are not settled yet, by SS_Start. */
27072
+ #blocks = /* @__PURE__ */ new Map();
27073
+ /** SS_Starts of settled blocks, so a later repair for one is refused. */
27074
+ #settled = /* @__PURE__ */ new Set();
27075
+ /**
27076
+ * SS_IDs whose packet the parser has, with the PATH_BITS of the path it was
27077
+ * received on, or 0 for one the session recovered.
27078
+ */
27079
+ #have = /* @__PURE__ */ new Map();
27080
+ #newest;
27081
+ /** The newest SS_ID when the remembered SS_IDs were last pruned. */
27082
+ #prunedAt;
27083
+ #repairPacketId;
27084
+ #stats = {
27085
+ sourceSymbols: 0,
27086
+ repairSymbols: 0,
27087
+ blocksClean: 0,
27088
+ blocksRecovered: 0,
27089
+ blocksFailed: 0,
27090
+ blocksReleased: 0,
27091
+ packetsRecovered: 0,
27092
+ packetsLost: 0,
27093
+ dropped: {},
27094
+ sourceSymbolsByPath: { moq: 0, multicast: 0 },
27095
+ repairSymbolsByPath: { moq: 0, multicast: 0 },
27096
+ mixedPath: { clean: 0, recovered: 0, failed: 0, released: 0 }
27097
+ };
27098
+ /**
27099
+ * @throws when the catalog block lacks or misstates a field the session
27100
+ * needs: the block profile, K, T, `interleaveDepthMs` or
27101
+ * `reorderToleranceMs`. None is defaulted.
27102
+ */
27103
+ constructor(config) {
27104
+ const fec = config?.fec;
27105
+ if (!fec || typeof fec !== "object") {
27106
+ throw new Error("MmtpFecSession: the catalog fec block is required");
27107
+ }
27108
+ this.blockProfile = parseFecBlockProfile(fec.blockProfile, "fec.blockProfile");
27109
+ if (fec.algorithm !== void 0 && fec.algorithm !== "raptorq" && fec.algorithm !== "reed-solomon") {
27110
+ throw new Error(`MmtpFecSession: fec.algorithm ${JSON.stringify(fec.algorithm)} is not implemented`);
27111
+ }
27112
+ this.algorithm = fec.algorithm === "reed-solomon" ? "reed-solomon" : "raptorq";
27113
+ this.sourceSymbols = requirePositiveInteger(fec.sourceSymbols, "fec.sourceSymbols");
27114
+ this.symbolSize = requirePositiveInteger(fec.symbolSize, "fec.symbolSize");
27115
+ const interleaveDepthMs = requireNumber(fec.interleaveDepthMs, "fec.interleaveDepthMs");
27116
+ const reorderToleranceMs = requireNumber(fec.reorderToleranceMs, "fec.reorderToleranceMs");
27117
+ this.retentionBlocks = deriveFecRetentionBlocks(
27118
+ fecBlockBudgetMs(interleaveDepthMs, reorderToleranceMs),
27119
+ interleaveDepthMs
27120
+ );
27121
+ if (typeof config.Decoder !== "function") {
27122
+ throw new Error("MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required");
27123
+ }
27124
+ const decoder = new config.Decoder(this.retentionBlocks, this.blockProfile, this.algorithm);
27125
+ try {
27126
+ decoder.configure_params(this.sourceSymbols, this.symbolSize);
27127
+ } catch (error) {
27128
+ decoder.free();
27129
+ throw error;
27130
+ }
27131
+ this.#decoder = decoder;
27132
+ }
27133
+ /** True once release() ran. */
27134
+ get released() {
27135
+ return this.#decoder === null;
27136
+ }
27137
+ get stats() {
27138
+ return {
27139
+ ...this.#stats,
27140
+ dropped: { ...this.#stats.dropped },
27141
+ sourceSymbolsByPath: { ...this.#stats.sourceSymbolsByPath },
27142
+ repairSymbolsByPath: { ...this.#stats.repairSymbolsByPath },
27143
+ mixedPath: { ...this.#stats.mixedPath }
27144
+ };
27145
+ }
27146
+ /**
27147
+ * Feeds one received source packet: the MMTP packet without its four-byte
27148
+ * Source FEC Payload ID, under the SS_ID that ID stated. This is what
27149
+ * MmtpContainerParser's onSourceSymbol() hands over. `path` is where it
27150
+ * was received; a caller that only subscribes over MoQT can leave it out.
27151
+ *
27152
+ * @returns the protected packets of this packet's block that it recovered,
27153
+ * in SS_ID order, for the caller to feed to its parser with
27154
+ * `{skipFecPayloadId: true, recovered: true}`. Usually empty.
27155
+ */
27156
+ addSource(ssId, packet, path = "moq") {
27157
+ const decoder = this.#decoder;
27158
+ if (!decoder) return this.#drop("source:released");
27159
+ const pathBit = PATH_BITS[path];
27160
+ if (!pathBit) return this.#drop("source:unknown-path");
27161
+ if (!Number.isInteger(ssId) || ssId < 0 || ssId > 4294967295) return this.#drop("source:bad-ss-id");
27162
+ if (!ssbg1FitsSymbol(packet.byteLength, this.symbolSize)) return this.#drop("source:exceeds-symbol");
27163
+ if (this.#have.has(ssId)) return this.#drop("source:duplicate");
27164
+ this.#have.set(ssId, pathBit);
27165
+ this.#stats.sourceSymbols++;
27166
+ this.#stats.sourceSymbolsByPath[path]++;
27167
+ this.#noteNewest(ssId);
27168
+ const start = this.#blockStartOf(ssId);
27169
+ const block = start === void 0 ? void 0 : this.#blocks.get(start);
27170
+ if (block) {
27171
+ block.received++;
27172
+ block.paths |= pathBit;
27173
+ }
27174
+ let output;
27175
+ try {
27176
+ output = decoder.add_source(ssId, packet, 0);
27177
+ } catch {
27178
+ this.#drop("source:decoder-refused");
27179
+ output = void 0;
27180
+ }
27181
+ const recovered = [];
27182
+ if (start !== void 0 && block) {
27183
+ if (output) {
27184
+ recovered.push(...this.#settleDecoded(start, block, output));
27185
+ } else if (block.received >= block.ssbLength) {
27186
+ this.#settleClean(start);
27187
+ }
27188
+ }
27189
+ this.#retireBehindHorizon();
27190
+ return recovered;
27191
+ }
27192
+ /**
27193
+ * Feeds one object of the repair track: a whole MMTP repair packet (ISO/IEC
27194
+ * 23008-1 C.5.3). A repair track carries one repair flow, so the first
27195
+ * repair packet fixes its packet ID and a packet of any other is refused.
27196
+ * `path` is where it was received, as for addSource().
27197
+ *
27198
+ * @returns the protected packets this repair symbol recovered, as for
27199
+ * addSource().
27200
+ */
27201
+ addRepair(packet, path = "moq") {
27202
+ const decoder = this.#decoder;
27203
+ if (!decoder) return this.#drop("repair:released");
27204
+ const pathBit = PATH_BITS[path];
27205
+ if (!pathBit) return this.#drop("repair:unknown-path");
27206
+ let header;
27207
+ try {
27208
+ header = parseMMTPHeader(packet);
27209
+ } catch {
27210
+ return this.#drop("repair:malformed");
27211
+ }
27212
+ const frame = parseMoqRepairFrameWithHeader(packet, header);
27213
+ if (!frame) return this.#drop("repair:malformed");
27214
+ if (this.#repairPacketId === void 0) {
27215
+ this.#repairPacketId = frame.packetId;
27216
+ } else if (frame.packetId !== this.#repairPacketId) {
27217
+ return this.#drop("repair:foreign-packet-id");
27218
+ }
27219
+ if (frame.symbolData.byteLength !== this.symbolSize) return this.#drop("repair:symbol-size");
27220
+ if (frame.ssbLength > this.sourceSymbols) return this.#drop("repair:ssb-length");
27221
+ if (this.algorithm === "reed-solomon" && frame.ssbLength + frame.rsbLength > 255) {
27222
+ return this.#drop("repair:rs-block-length");
27223
+ }
27224
+ const start = frame.ssStart;
27225
+ let block = this.#blocks.get(start);
27226
+ if (block && block.ssbLength !== frame.ssbLength) return this.#drop("repair:conflicting-ssb-length");
27227
+ if (block?.rsIds.has(frame.rsId)) return this.#drop("repair:duplicate");
27228
+ if (!block) {
27229
+ if (this.#settled.has(start)) return this.#drop("repair:block-settled");
27230
+ if (this.#behindHorizon(start)) return this.#drop("repair:behind-horizon");
27231
+ block = { ssbLength: frame.ssbLength, received: 0, paths: 0, rsIds: /* @__PURE__ */ new Set() };
27232
+ this.#countHeld(start, block);
27233
+ this.#blocks.set(start, block);
27234
+ }
27235
+ this.#noteNewest(serial32Add(start, frame.ssbLength - 1));
27236
+ if (block.received >= block.ssbLength) {
27237
+ this.#settleClean(start);
27238
+ this.#retireBehindHorizon();
27239
+ return [];
27240
+ }
27241
+ let output;
27242
+ try {
27243
+ output = decoder.add_repair(start, frame.ssbLength, frame.rsId, frame.symbolData, 0);
27244
+ } catch {
27245
+ return this.#drop("repair:decoder-refused");
27246
+ }
27247
+ block.rsIds.add(frame.rsId);
27248
+ this.#stats.repairSymbols++;
27249
+ this.#stats.repairSymbolsByPath[path]++;
27250
+ block.paths |= pathBit;
27251
+ const recovered = output ? this.#settleDecoded(start, block, output) : [];
27252
+ this.#retireBehindHorizon();
27253
+ return recovered;
27254
+ }
27255
+ /**
27256
+ * Frees the decoder and every block. Blocks still unsettled are counted as
27257
+ * released, not failed: nothing proved them unrecoverable. Idempotent;
27258
+ * returns whether this call released anything.
27259
+ */
27260
+ release() {
27261
+ const decoder = this.#decoder;
27262
+ if (!decoder) return false;
27263
+ this.#decoder = null;
27264
+ this.#stats.blocksReleased += this.#blocks.size;
27265
+ for (const block of this.#blocks.values()) this.#noteMixed(block, "released");
27266
+ this.#blocks.clear();
27267
+ this.#settled.clear();
27268
+ this.#have.clear();
27269
+ decoder.free();
27270
+ return true;
27271
+ }
27272
+ #drop(reason) {
27273
+ this.#stats.dropped[reason] = (this.#stats.dropped[reason] ?? 0) + 1;
27274
+ return [];
27275
+ }
27276
+ #noteNewest(ssId) {
27277
+ if (this.#newest === void 0 || serial32Precedes(this.#newest, ssId)) this.#newest = ssId;
27278
+ }
27279
+ #blockStartOf(ssId) {
27280
+ for (const [start, block] of this.#blocks) {
27281
+ if (isoBlockContains(start, block.ssbLength, ssId)) return start;
27282
+ }
27283
+ return void 0;
27284
+ }
27285
+ /** Counts the sources of a new block the parser already has, and their paths. */
27286
+ #countHeld(start, block) {
27287
+ for (let i = 0; i < block.ssbLength; i++) {
27288
+ const pathBit = this.#have.get(serial32Add(start, i));
27289
+ if (pathBit === void 0) continue;
27290
+ block.received++;
27291
+ block.paths |= pathBit;
27292
+ }
27293
+ }
27294
+ #noteMixed(block, outcome) {
27295
+ if ((block.paths & MIXED_PATHS) === MIXED_PATHS) this.#stats.mixedPath[outcome]++;
27296
+ }
27297
+ /** The decoder's own rule: more than its retention behind, counted from below. */
27298
+ #behindHorizon(start) {
27299
+ const newest = this.#newest;
27300
+ if (newest === void 0) return false;
27301
+ return isoBlocksBehindLowerBound(start, newest, this.sourceSymbols) > this.retentionBlocks;
27302
+ }
27303
+ #settle(start) {
27304
+ this.#blocks.delete(start);
27305
+ this.#settled.add(start);
27306
+ }
27307
+ #settleClean(start) {
27308
+ const block = this.#blocks.get(start);
27309
+ if (!block) return;
27310
+ this.#settle(start);
27311
+ this.#stats.blocksClean++;
27312
+ this.#noteMixed(block, "clean");
27313
+ try {
27314
+ this.#decoder?.cleanup_blocks_detailed(Uint32Array.of(start));
27315
+ } catch {
27316
+ }
27317
+ }
27318
+ /**
27319
+ * The decoder returns a completed block as its K' ssbg_mode1 symbols,
27320
+ * concatenated: split by T, trim by each symbol's length field, and hand
27321
+ * back the packets the parser does not have yet.
27322
+ */
27323
+ #settleDecoded(start, block, output) {
27324
+ this.#settle(start);
27325
+ if (output.byteLength !== block.ssbLength * this.symbolSize) {
27326
+ this.#stats.blocksFailed++;
27327
+ this.#stats.packetsLost += block.ssbLength - block.received;
27328
+ this.#noteMixed(block, "failed");
27329
+ this.#drop("block:decoded-length");
27330
+ return [];
27331
+ }
27332
+ const recovered = [];
27333
+ let refused = 0;
27334
+ for (let i = 0; i < block.ssbLength; i++) {
27335
+ const ssId = serial32Add(start, i);
27336
+ if (this.#have.has(ssId)) continue;
27337
+ const symbol = output.subarray(i * this.symbolSize, (i + 1) * this.symbolSize);
27338
+ const packet = trimSsbg1SourceSymbol(symbol);
27339
+ if (!packet) {
27340
+ refused++;
27341
+ continue;
27342
+ }
27343
+ this.#have.set(ssId, 0);
27344
+ recovered.push(packet.slice());
27345
+ }
27346
+ if (refused > 0) {
27347
+ this.#stats.blocksFailed++;
27348
+ this.#stats.packetsLost += refused;
27349
+ this.#noteMixed(block, "failed");
27350
+ this.#drop("block:bad-ssbg1-symbol");
27351
+ } else if (recovered.length === 0) {
27352
+ this.#stats.blocksClean++;
27353
+ this.#noteMixed(block, "clean");
27354
+ } else {
27355
+ this.#stats.blocksRecovered++;
27356
+ this.#noteMixed(block, "recovered");
27357
+ }
27358
+ this.#stats.packetsRecovered += recovered.length;
27359
+ return recovered;
27360
+ }
27361
+ /**
27362
+ * Retires every block, and every SS_ID the session remembers, that the
27363
+ * newest SS_ID has moved past the retention. An unsettled block retired
27364
+ * here is a failure: more of its sources were lost than its repair could
27365
+ * restore, or its repair never arrived.
27366
+ */
27367
+ #retireBehindHorizon() {
27368
+ const decoder = this.#decoder;
27369
+ const newest = this.#newest;
27370
+ if (!decoder || newest === void 0) return;
27371
+ try {
27372
+ decoder.cleanup_by_ss_start(newest);
27373
+ } catch {
27374
+ }
27375
+ for (const [start, block] of this.#blocks) {
27376
+ if (!this.#behindHorizon(start)) continue;
27377
+ this.#settle(start);
27378
+ this.#stats.blocksFailed++;
27379
+ this.#stats.packetsLost += block.ssbLength - block.received;
27380
+ this.#noteMixed(block, "failed");
27381
+ }
27382
+ const prunedAt = this.#prunedAt;
27383
+ if (prunedAt !== void 0 && serial32Distance(prunedAt, newest) < this.sourceSymbols) return;
27384
+ this.#prunedAt = newest;
27385
+ for (const ssId of this.#have.keys()) {
27386
+ if (this.#behindHorizon(ssId)) this.#have.delete(ssId);
27387
+ }
27388
+ for (const start of this.#settled) {
27389
+ if (this.#behindHorizon(start)) this.#settled.delete(start);
27390
+ }
27391
+ }
27392
+ };
27393
+ function requirePositiveInteger(value, path) {
27394
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
27395
+ throw new Error(`MmtpFecSession: ${path} must be a positive integer (got ${String(value)})`);
27396
+ }
27397
+ return value;
27398
+ }
27399
+ function requireNumber(value, path) {
27400
+ if (typeof value !== "number") {
27401
+ throw new Error(`MmtpFecSession: ${path} is required (got ${String(value)}); it is never defaulted`);
27402
+ }
27403
+ return value;
27404
+ }
27405
+
26711
27406
  // src/repair-fetch.ts
26712
27407
  var MOQT_PRIORITY_MAX = 255;
26713
27408
  var SOURCE_MEDIA_PRIORITY_MAX = REPAIR_PRIORITY_MIN - 1;
@@ -26742,6 +27437,9 @@ function wireRepairFetch(mc, opts) {
26742
27437
  if (typeof opts.presentationDelayMs !== "function") {
26743
27438
  throw new Error("[RepairFetch] presentationDelayMs is required: a repair FETCH is due by the block's presentation deadline");
26744
27439
  }
27440
+ if (opts.rangeTransport !== void 0 && (typeof opts.repairEpochReference !== "function" || !mc.onUndelimitedLoss || !mc.closeIsoHoles)) {
27441
+ throw new Error("[RepairFetch] rangeTransport needs repairEpochReference and a host that reports undelimited losses");
27442
+ }
26745
27443
  const entries = /* @__PURE__ */ new Map();
26746
27444
  const warnedNoTarget = /* @__PURE__ */ new Set();
26747
27445
  let disposed = false;
@@ -26755,7 +27453,12 @@ function wireRepairFetch(mc, opts) {
26755
27453
  const note = (type, entry) => {
26756
27454
  mc.noteRepairScheduling(type, entry.sbn, entry.packetId, entry.catalogTrackName);
26757
27455
  };
27456
+ const clearEntry = (entry) => {
27457
+ if (entry.range) mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, entry.range.holeLength);
27458
+ else clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27459
+ };
26758
27460
  const releaseHold = (entry) => {
27461
+ if (entry.range) return;
26759
27462
  if (entry.catalogTrackName === void 0) mc.fecManager.releaseRepairHold(entry.sbn, entry.packetId);
26760
27463
  else mc.fecManager.releaseRepairHold(entry.sbn, entry.packetId, entry.catalogTrackName);
26761
27464
  };
@@ -26788,10 +27491,10 @@ function wireRepairFetch(mc, opts) {
26788
27491
  const admit = (entry, now) => {
26789
27492
  const budgetMs = entry.deadlineAt - now;
26790
27493
  const rttMs = readRtt();
26791
- if (rttMs !== null && rttMs < budgetMs) return true;
27494
+ if (rttMs !== null && rttMs < budgetMs) return rttMs;
26792
27495
  retire(entry);
26793
27496
  releaseHold(entry);
26794
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27497
+ clearEntry(entry);
26795
27498
  mc.noteRepairSkipped(
26796
27499
  rttMs === null ? "rtt-unmeasured" : "rtt-exceeds-budget",
26797
27500
  { rttMs, budgetMs, priority: entry.priority },
@@ -26799,10 +27502,11 @@ function wireRepairFetch(mc, opts) {
26799
27502
  entry.packetId,
26800
27503
  entry.catalogTrackName
26801
27504
  );
26802
- return false;
27505
+ return null;
26803
27506
  };
26804
27507
  const retire = (entry) => {
26805
27508
  if (entries.get(entry.key) === entry) entries.delete(entry.key);
27509
+ if (entry.expiry !== void 0) clearTimeout(entry.expiry);
26806
27510
  };
26807
27511
  const urgentOutstanding = () => {
26808
27512
  for (const entry of entries.values()) {
@@ -26831,17 +27535,28 @@ function wireRepairFetch(mc, opts) {
26831
27535
  return derived.kind === "omit" ? { subscriberPriority: void 0 } : null;
26832
27536
  };
26833
27537
  const start = (entry, counted = true) => {
26834
- if (!admit(entry, performance.now())) return;
27538
+ const now = performance.now();
27539
+ const rttMs = admit(entry, now);
27540
+ if (rttMs === null) return;
26835
27541
  if (counted) entry.attempts++;
26836
- mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName);
27542
+ mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName, {
27543
+ rttMs,
27544
+ budgetMs: entry.deadlineAt - now,
27545
+ delayMs: entry.delayMs,
27546
+ blockAgeMs: entry.anchorAt === null ? null : Math.max(0, now - entry.anchorAt),
27547
+ bound: entry.bound,
27548
+ ...entry.range ? { range: true } : {}
27549
+ });
26837
27550
  const run = { controller: new AbortController(), stopped: null };
26838
27551
  entry.running = run;
26839
- mc.fecManager.holdBlockForRepair(
26840
- entry.sbn,
26841
- entry.packetId,
26842
- entry.catalogTrackName,
26843
- entry.deadlineAt
26844
- );
27552
+ if (!entry.range) {
27553
+ mc.fecManager.holdBlockForRepair(
27554
+ entry.sbn,
27555
+ entry.packetId,
27556
+ entry.catalogTrackName,
27557
+ entry.deadlineAt
27558
+ );
27559
+ }
26845
27560
  void execute(entry, run);
26846
27561
  };
26847
27562
  const dispatch = () => {
@@ -26853,14 +27568,14 @@ function wireRepairFetch(mc, opts) {
26853
27568
  if (entry.deadlineAt <= now) {
26854
27569
  stop(entry, "expired");
26855
27570
  retire(entry);
26856
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27571
+ clearEntry(entry);
26857
27572
  }
26858
27573
  continue;
26859
27574
  }
26860
27575
  if (entry.deadlineAt <= now) {
26861
27576
  retire(entry);
26862
27577
  if (entry.priority === 2 && entry.attempts === 0) note("repair-deferred", entry);
26863
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27578
+ clearEntry(entry);
26864
27579
  continue;
26865
27580
  }
26866
27581
  queued.push(entry);
@@ -26897,9 +27612,9 @@ function wireRepairFetch(mc, opts) {
26897
27612
  entry.running = null;
26898
27613
  if (error === void 0) {
26899
27614
  retire(entry);
26900
- if (fed === 0 || !decodable(entry)) {
27615
+ if (entry.range || fed === 0 || !decodable(entry)) {
26901
27616
  releaseHold(entry);
26902
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27617
+ clearEntry(entry);
26903
27618
  }
26904
27619
  dispatch();
26905
27620
  return;
@@ -26911,7 +27626,7 @@ function wireRepairFetch(mc, opts) {
26911
27626
  }
26912
27627
  retire(entry);
26913
27628
  if (fed === 0) releaseHold(entry);
26914
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27629
+ clearEntry(entry);
26915
27630
  console.warn(
26916
27631
  `[RepairFetch] fetch failed pid=${entry.packetId} sbn=${entry.sbn} track=${entry.repairTrack}:`,
26917
27632
  error
@@ -26927,15 +27642,21 @@ function wireRepairFetch(mc, opts) {
26927
27642
  };
26928
27643
  const execute = async (entry, run) => {
26929
27644
  let fed = 0;
27645
+ const common = {
27646
+ repairTrack: entry.repairTrack,
27647
+ blockProfile: entry.blockProfile,
27648
+ packetId: entry.packetId,
27649
+ signal: run.controller.signal,
27650
+ subscriberPriority: entry.subscriberPriority
27651
+ };
26930
27652
  try {
26931
- for await (const packet of opts.transport({
26932
- repairTrack: entry.repairTrack,
26933
- sbn: entry.sbn,
26934
- blockProfile: entry.blockProfile,
26935
- packetId: entry.packetId,
26936
- signal: run.controller.signal,
26937
- subscriberPriority: entry.subscriberPriority
26938
- })) {
27653
+ const packets = entry.range ? opts.rangeTransport({
27654
+ ...common,
27655
+ startGroup: entry.range.startGroup,
27656
+ endGroup: entry.range.endGroup,
27657
+ lostSsId: entry.range.lostSsId
27658
+ }) : opts.transport({ ...common, sbn: entry.sbn });
27659
+ for await (const packet of packets) {
26939
27660
  if (run.stopped !== null || entry.running !== run) break;
26940
27661
  fed++;
26941
27662
  if (entry.catalogTrackName === void 0) {
@@ -26954,6 +27675,7 @@ function wireRepairFetch(mc, opts) {
26954
27675
  if (entry.packetId !== packetId || entry.catalogTrackName !== catalogTrackName) continue;
26955
27676
  retire(entry);
26956
27677
  stop(entry, "reset");
27678
+ if (entry.range) clearEntry(entry);
26957
27679
  }
26958
27680
  warnedNoTarget.delete(noTargetKey(packetId, catalogTrackName));
26959
27681
  dispatch();
@@ -26980,6 +27702,9 @@ function wireRepairFetch(mc, opts) {
26980
27702
  );
26981
27703
  if (promotedDeadline !== null && promotedDeadline.deadlineAt > entry2.deadlineAt) {
26982
27704
  entry2.deadlineAt = promotedDeadline.deadlineAt;
27705
+ entry2.anchorAt = promotedDeadline.anchorAt;
27706
+ entry2.delayMs = promotedDeadline.delayMs;
27707
+ entry2.bound = promotedDeadline.bound;
26983
27708
  noteBudget(entry2, promotedDeadline.extensionMs);
26984
27709
  }
26985
27710
  if (entry2.running) {
@@ -27005,7 +27730,9 @@ function wireRepairFetch(mc, opts) {
27005
27730
  if (waitMs === void 0) return null;
27006
27731
  const waitDeadlineAt = now + waitMs;
27007
27732
  const anchor = mc.fecManager.blockAnchorAtMs(sbn, packetId, catalogTrackName);
27008
- if (anchor === void 0) return { deadlineAt: waitDeadlineAt, extensionMs: 0 };
27733
+ if (anchor === void 0) {
27734
+ return { deadlineAt: waitDeadlineAt, extensionMs: 0, anchorAt: null, delayMs: null, bound: "wait" };
27735
+ }
27009
27736
  let delayMs;
27010
27737
  try {
27011
27738
  delayMs = opts.presentationDelayMs(packetId, catalogTrackName);
@@ -27016,12 +27743,21 @@ function wireRepairFetch(mc, opts) {
27016
27743
  const retentionMs = mc.fecManager.terminalRetentionMsForPacket(packetId);
27017
27744
  if (retentionMs === void 0) return null;
27018
27745
  const ceilingAt = Math.min(anchor, earliestGatedFrameAt(packetId, catalogTrackName) ?? anchor) + retentionMs;
27019
- const deadlineAt = (delay) => Math.max(waitDeadlineAt, Math.min(anchor + delay, ceilingAt));
27020
- const base = deadlineAt(delayMs);
27746
+ const at = (delay, delayBound) => {
27747
+ const presentAt = Math.min(anchor + delay, ceilingAt);
27748
+ if (waitDeadlineAt >= presentAt) return { deadlineAt: waitDeadlineAt, bound: "wait" };
27749
+ return { deadlineAt: presentAt, bound: anchor + delay <= ceilingAt ? delayBound : "retention" };
27750
+ };
27751
+ const base = at(delayMs, "presentation");
27021
27752
  const budgetMs = keyframeBudgetEligible(blockClass, classifierMode(packetId, catalogTrackName)) && groupCanComplete(sbn, packetId, catalogTrackName) ? readKeyframeBudget(packetId, catalogTrackName) : null;
27022
- if (budgetMs === null || budgetMs <= delayMs) return { deadlineAt: base, extensionMs: 0 };
27023
- const extended = deadlineAt(budgetMs);
27024
- return { deadlineAt: extended, extensionMs: extended - base };
27753
+ if (budgetMs === null || budgetMs <= delayMs) return { ...base, extensionMs: 0, anchorAt: anchor, delayMs };
27754
+ const extended = at(budgetMs, "keyframe");
27755
+ return {
27756
+ ...extended,
27757
+ extensionMs: extended.deadlineAt - base.deadlineAt,
27758
+ anchorAt: anchor,
27759
+ delayMs: budgetMs
27760
+ };
27025
27761
  };
27026
27762
  const earliestGatedFrameAt = (packetId, catalogTrackName) => {
27027
27763
  try {
@@ -27098,6 +27834,9 @@ function wireRepairFetch(mc, opts) {
27098
27834
  priority,
27099
27835
  subscriberPriority: wire.subscriberPriority,
27100
27836
  deadlineAt: deadline.deadlineAt,
27837
+ anchorAt: deadline.anchorAt,
27838
+ delayMs: deadline.delayMs,
27839
+ bound: deadline.bound,
27101
27840
  order: enqueueOrder++,
27102
27841
  attempts: 0,
27103
27842
  running: null
@@ -27107,14 +27846,92 @@ function wireRepairFetch(mc, opts) {
27107
27846
  if (entry.priority < 2) preemptDeltas();
27108
27847
  dispatch();
27109
27848
  });
27849
+ const rangeFor = (loss, repairTrack) => {
27850
+ let reference;
27851
+ try {
27852
+ reference = opts.repairEpochReference(repairTrack);
27853
+ } catch {
27854
+ return null;
27855
+ }
27856
+ if (reference === void 0) return null;
27857
+ try {
27858
+ const anchor = loss.previousBlockStart === void 0 ? { reference } : { previousBlockStart: extendSsId(reference, loss.previousBlockStart) };
27859
+ return repairFetchRange(loss.lostSsId, loss.kMax, anchor);
27860
+ } catch (error) {
27861
+ if (error instanceof RangeError) return null;
27862
+ throw error;
27863
+ }
27864
+ };
27865
+ if (opts.rangeTransport !== void 0) {
27866
+ mc.onUndelimitedLoss((loss) => {
27867
+ const { packetId, catalogTrackName, holeStart, holeLength } = loss;
27868
+ const close = () => mc.closeIsoHoles(packetId, catalogTrackName, holeStart, holeLength);
27869
+ if (disposed) return close();
27870
+ const blockProfile = blockProfileOf(packetId);
27871
+ const target = opts.resolveTarget(packetId, catalogTrackName);
27872
+ if (!target) return close();
27873
+ const priority = repairPriorityForClass("unknown");
27874
+ const range = rangeFor(loss, target.repairTrack);
27875
+ if (range === null) {
27876
+ close();
27877
+ mc.noteRepairSkipped("range-no-anchor", { rttMs: readRtt(), budgetMs: 0, priority }, holeStart, packetId, catalogTrackName);
27878
+ return;
27879
+ }
27880
+ const identity = {
27881
+ target,
27882
+ sbn: holeStart,
27883
+ packetId,
27884
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
27885
+ };
27886
+ const wire = wirePriority(identity, "unknown");
27887
+ const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, performance.now(), "unknown");
27888
+ if (deadline === null) {
27889
+ close();
27890
+ mc.noteRepairSkipped(
27891
+ "presentation-delay-unavailable",
27892
+ { rttMs: readRtt(), budgetMs: 0, priority },
27893
+ holeStart,
27894
+ packetId,
27895
+ catalogTrackName
27896
+ );
27897
+ return;
27898
+ }
27899
+ const entry = {
27900
+ key: JSON.stringify(["range", packetId, catalogTrackName ?? null, holeStart]),
27901
+ ...identity,
27902
+ repairTrack: target.repairTrack,
27903
+ blockProfile,
27904
+ priority,
27905
+ subscriberPriority: wire.subscriberPriority,
27906
+ deadlineAt: deadline.deadlineAt,
27907
+ anchorAt: deadline.anchorAt,
27908
+ delayMs: deadline.delayMs,
27909
+ bound: deadline.bound,
27910
+ order: enqueueOrder++,
27911
+ attempts: 0,
27912
+ running: null,
27913
+ range: { ...range, lostSsId: loss.lostSsId, holeLength }
27914
+ };
27915
+ const previous = entries.get(entry.key);
27916
+ if (previous) {
27917
+ retire(previous);
27918
+ stop(previous, "reset");
27919
+ }
27920
+ entries.set(entry.key, entry);
27921
+ entry.expiry = setTimeout(dispatch, Math.max(0, entry.deadlineAt - performance.now()) + 1);
27922
+ preemptDeltas();
27923
+ dispatch();
27924
+ });
27925
+ }
27110
27926
  return () => {
27111
27927
  disposed = true;
27112
27928
  removeResetObserver();
27113
27929
  removeLifecycleObserver();
27114
27930
  for (const entry of [...entries.values()]) {
27115
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27931
+ clearEntry(entry);
27116
27932
  if (entry.running) releaseHold(entry);
27117
27933
  stop(entry, "disposed");
27934
+ if (entry.expiry !== void 0) clearTimeout(entry.expiry);
27118
27935
  }
27119
27936
  entries.clear();
27120
27937
  };
@@ -27153,20 +27970,19 @@ export {
27153
27970
  MfuReassemblyError,
27154
27971
  MmtpContainerParser,
27155
27972
  MmtpDecodePipeline,
27973
+ MmtpFecSession,
27156
27974
  MmtpRouter,
27157
27975
  MmtpToCmaf,
27158
27976
  MulticastContainerContractError,
27159
27977
  MulticastInputError,
27160
27978
  MulticastManager,
27161
27979
  MulticastTransport,
27162
- NoneCodec,
27163
27980
  REPAIR_LIFECYCLE_EVENT_TYPE,
27164
27981
  REPAIR_LIFECYCLE_LOG_PREFIX,
27165
27982
  REPAIR_PRIORITY_MAX,
27166
27983
  REPAIR_PRIORITY_MIN,
27167
27984
  REPAIR_TRACK_GEOMETRY_KEYS,
27168
27985
  REPAIR_TRACK_ONLY_KEYS,
27169
- ReedSolomonCodec,
27170
27986
  RepairContractError,
27171
27987
  SOURCE_MEDIA_PRIORITY_MAX,
27172
27988
  SampleCombineError,
@@ -27187,6 +28003,7 @@ export {
27187
28003
  buildHevcVideoInitSegment,
27188
28004
  buildVideoInitSegment,
27189
28005
  catalogAmtNetworkSource,
28006
+ catalogAtsc3NetworkSource,
27190
28007
  catalogDeclaresFec,
27191
28008
  catalogFecAvailable,
27192
28009
  catalogFecDeclaresUnconfigurableInstance,
@@ -27203,7 +28020,6 @@ export {
27203
28020
  computeFecDeliveryWindowMediaUnits,
27204
28021
  computeFecDeliveryWindowMs,
27205
28022
  computeFecLossWindowMs,
27206
- createFecCodec,
27207
28023
  createFragment,
27208
28024
  createWasmMmtpContainerParser,
27209
28025
  datagramMfuReassembly,
@@ -27231,6 +28047,7 @@ export {
27231
28047
  extractHevcCodecDescription,
27232
28048
  extractHevcParameterSets,
27233
28049
  extractSpsPpsFromAvcC,
28050
+ fecAlgorithmUnimplemented,
27234
28051
  findAnnexBStartCode,
27235
28052
  forwardRepairLifecycleEvents,
27236
28053
  frameSamplesFromInit,