@blockcast/mmt-container 0.4.0 → 0.4.1-main.30f0611c24e8

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 (215) hide show
  1. package/README.md +36 -20
  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 +1904 -692
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +76 -39
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +321 -205
  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 +28 -7
  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/cmcd-producer.d.ts +8 -0
  25. package/dist/cmcd-producer.d.ts.map +1 -1
  26. package/dist/cmcd-producer.js +14 -0
  27. package/dist/cmcd-producer.js.map +2 -2
  28. package/dist/delivery-catalog.js +98 -234
  29. package/dist/delivery-catalog.js.map +4 -4
  30. package/dist/fec-manager.d.ts +108 -1
  31. package/dist/fec-manager.d.ts.map +1 -1
  32. package/dist/fec-manager.js +452 -66
  33. package/dist/fec-manager.js.map +4 -4
  34. package/dist/fec-state.d.ts +2 -1
  35. package/dist/fec-state.d.ts.map +1 -1
  36. package/dist/fec-state.js +18 -3
  37. package/dist/fec-state.js.map +3 -3
  38. package/dist/fec-worker-setup.d.ts +10 -0
  39. package/dist/fec-worker-setup.d.ts.map +1 -1
  40. package/dist/fec-worker-setup.js +15 -4
  41. package/dist/fec-worker-setup.js.map +2 -2
  42. package/dist/held-layer-admission.d.ts +58 -0
  43. package/dist/held-layer-admission.d.ts.map +1 -0
  44. package/dist/held-layer-admission.js +105 -0
  45. package/dist/held-layer-admission.js.map +7 -0
  46. package/dist/index.d.ts +5 -5
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +8 -8
  49. package/dist/index.js.map +2 -2
  50. package/dist/iso-block-locator.d.ts +39 -1
  51. package/dist/iso-block-locator.d.ts.map +1 -1
  52. package/dist/iso-block-locator.js +109 -17
  53. package/dist/iso-block-locator.js.map +3 -3
  54. package/dist/manifest-auth-plan.d.ts +26 -25
  55. package/dist/manifest-auth-plan.d.ts.map +1 -1
  56. package/dist/manifest-auth-plan.js +331 -1171
  57. package/dist/manifest-auth-plan.js.map +4 -4
  58. package/dist/mfu-reassembler.js +21 -13
  59. package/dist/mfu-reassembler.js.map +2 -2
  60. package/dist/mmtp-container-parser.d.ts.map +1 -1
  61. package/dist/mmtp-container-parser.js +93 -22
  62. package/dist/mmtp-container-parser.js.map +2 -2
  63. package/dist/mmtp-container-parser.no-modules.js +1250 -317
  64. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  65. package/dist/mmtp-decode-pipeline.js +93 -22
  66. package/dist/mmtp-decode-pipeline.js.map +2 -2
  67. package/dist/mmtp-fec-session.d.ts +192 -0
  68. package/dist/mmtp-fec-session.d.ts.map +1 -0
  69. package/dist/mmtp-fec-session.js +640 -0
  70. package/dist/mmtp-fec-session.js.map +7 -0
  71. package/dist/mmtp-router.d.ts +39 -6
  72. package/dist/mmtp-router.d.ts.map +1 -1
  73. package/dist/mmtp-router.js +184 -27
  74. package/dist/mmtp-router.js.map +2 -2
  75. package/dist/multicast-auth-catalog.d.ts +86 -92
  76. package/dist/multicast-auth-catalog.d.ts.map +1 -1
  77. package/dist/multicast-auth-catalog.js +347 -132
  78. package/dist/multicast-auth-catalog.js.map +4 -4
  79. package/dist/multicast-input.d.ts +31 -8
  80. package/dist/multicast-input.d.ts.map +1 -1
  81. package/dist/multicast-input.js +299 -35
  82. package/dist/multicast-input.js.map +3 -3
  83. package/dist/multicast-manager.d.ts +94 -5
  84. package/dist/multicast-manager.d.ts.map +1 -1
  85. package/dist/multicast-manager.js +908 -357
  86. package/dist/multicast-manager.js.map +4 -4
  87. package/dist/multicast-transport.d.ts +12 -2
  88. package/dist/multicast-transport.d.ts.map +1 -1
  89. package/dist/multicast-transport.js +108 -238
  90. package/dist/multicast-transport.js.map +4 -4
  91. package/dist/multicast-unwrap.js +21 -13
  92. package/dist/multicast-unwrap.js.map +2 -2
  93. package/dist/no-modules.d.ts +4 -1
  94. package/dist/no-modules.d.ts.map +1 -1
  95. package/dist/no-modules.js +1195 -301
  96. package/dist/no-modules.js.map +4 -4
  97. package/dist/phase14-catalog-override.d.ts +1 -1
  98. package/dist/phase14-catalog-override.d.ts.map +1 -1
  99. package/dist/phase14-catalog-override.js +2 -2
  100. package/dist/phase14-catalog-override.js.map +2 -2
  101. package/dist/repair-fetch.d.ts +81 -6
  102. package/dist/repair-fetch.d.ts.map +1 -1
  103. package/dist/repair-fetch.js +156 -31
  104. package/dist/repair-fetch.js.map +3 -3
  105. package/dist/repair-layers.d.ts +2 -0
  106. package/dist/repair-layers.d.ts.map +1 -1
  107. package/dist/repair-layers.js +19 -2
  108. package/dist/repair-layers.js.map +2 -2
  109. package/dist/sample-combiner.d.ts +7 -1
  110. package/dist/sample-combiner.d.ts.map +1 -1
  111. package/dist/sample-combiner.js +14 -2
  112. package/dist/sample-combiner.js.map +2 -2
  113. package/dist/signaling.d.ts +2 -2
  114. package/dist/signaling.d.ts.map +1 -1
  115. package/dist/signaling.js +3 -3
  116. package/dist/signaling.js.map +2 -2
  117. package/dist/source-auth.js +2710 -7
  118. package/dist/source-auth.js.map +4 -4
  119. package/dist/switching-set-alignment.d.ts +1 -1
  120. package/dist/switching-set-alignment.js.map +1 -1
  121. package/dist/timestamp-codec.js +21 -13
  122. package/dist/timestamp-codec.js.map +2 -2
  123. package/dist/wasm-mfu-reassembler.js.map +1 -1
  124. package/dist/wasm-mmtp-container-parser.js +93 -22
  125. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  126. package/package.json +6 -9
  127. package/schemas/catalog.schema.json +133 -38
  128. package/src/align.ts +52 -21
  129. package/src/carp-catalog.ts +188 -68
  130. package/src/catalog-fec-params.ts +28 -3
  131. package/src/catalog-network-source.ts +49 -7
  132. package/src/catalog-validator.ts +4 -11
  133. package/src/cmcd-producer.ts +17 -0
  134. package/src/fec-manager.ts +366 -63
  135. package/src/fec-state.ts +11 -4
  136. package/src/fec-worker-setup.ts +30 -2
  137. package/src/held-layer-admission.ts +161 -0
  138. package/src/index.ts +27 -10
  139. package/src/iso-block-locator.ts +110 -7
  140. package/src/manifest-auth-plan.ts +39 -91
  141. package/src/mmtp-container-parser.ts +75 -7
  142. package/src/mmtp-fec-session.ts +606 -0
  143. package/src/mmtp-router.ts +166 -7
  144. package/src/multicast-auth-catalog.ts +131 -238
  145. package/src/multicast-input.ts +148 -124
  146. package/src/multicast-manager.ts +267 -21
  147. package/src/multicast-transport.ts +17 -3
  148. package/src/no-modules.ts +7 -1
  149. package/src/phase14-catalog-override.ts +3 -3
  150. package/src/repair-fetch.ts +283 -39
  151. package/src/repair-layers.ts +22 -2
  152. package/src/sample-combiner.ts +15 -2
  153. package/src/signaling.ts +2 -2
  154. package/src/switching-set-alignment.ts +1 -1
  155. package/test-vectors/align.json +108 -32
  156. package/test-vectors/bc-provenance-v2.json +1526 -0
  157. package/test-vectors/catalog/README.md +71 -4
  158. package/test-vectors/catalog/negative/fec-block-profile-missing.json +1 -1
  159. package/test-vectors/catalog/negative/fec-block-profile-retired.json +1 -1
  160. package/test-vectors/catalog/negative/fec-block-profile-unknown.json +1 -1
  161. package/test-vectors/catalog/negative/fec-iso-symbol-size-below-floor.json +28 -0
  162. package/test-vectors/catalog/negative/fec-reed-solomon-iso-symbol-size-13.json +28 -0
  163. package/test-vectors/catalog/negative/fec-reed-solomon-k-plus-p-over-255.json +39 -0
  164. package/test-vectors/catalog/negative/fec-reed-solomon-overlay-over-255.json +40 -0
  165. package/test-vectors/catalog/negative/fec-repair-overlay-source-symbols-zero.json +43 -0
  166. package/test-vectors/catalog/negative/fec-repair-symbols-zero.json +28 -0
  167. package/test-vectors/catalog/negative/fec-source-symbols-zero.json +28 -0
  168. package/test-vectors/catalog/negative/fec-symbol-size-zero.json +28 -0
  169. package/test-vectors/catalog/negative/init-data-inline-without-data.json +22 -0
  170. package/test-vectors/catalog/negative/mmtp-mode-mpu.json +15 -0
  171. package/test-vectors/catalog/negative/multicast-amt-dns-without-relay.json +37 -0
  172. package/test-vectors/catalog/negative/multicast-amt-driad-with-relay.json +38 -0
  173. package/test-vectors/catalog/negative/multicast-auth-asm-missing-sender-address.json +77 -0
  174. package/test-vectors/catalog/negative/multicast-auth-duplicate-first-epoch.json +56 -0
  175. package/test-vectors/catalog/negative/multicast-auth-duplicate-kid.json +56 -0
  176. package/test-vectors/catalog/negative/multicast-auth-endpoint-auth-without-object-auth.json +38 -0
  177. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-auth.json +49 -0
  178. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-bandwidth.json +55 -0
  179. package/test-vectors/catalog/negative/multicast-auth-manifest-port-equals-port.json +56 -0
  180. package/test-vectors/catalog/negative/multicast-auth-manifest-timer-out-of-range.json +56 -0
  181. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-above-max.json +56 -0
  182. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-below-min.json +56 -0
  183. package/test-vectors/catalog/negative/multicast-auth-root-dotted-key.json +55 -0
  184. package/test-vectors/catalog/negative/multicast-auth-sender-address-on-ssm.json +57 -0
  185. package/test-vectors/catalog/negative/multicast-auth-version-1.json +56 -0
  186. package/test-vectors/catalog/negative/multicast-auth-version-3.json +56 -0
  187. package/test-vectors/catalog/negative/multicast-auth-version-missing.json +55 -0
  188. package/test-vectors/catalog/negative/multicast-endpoint-foreign-namespace-track.json +44 -0
  189. package/test-vectors/catalog/negative/multicast-endpoint-protocol-amt.json +38 -0
  190. package/test-vectors/catalog/negative/multicast-endpoint-protocol-atsc3.json +38 -0
  191. package/test-vectors/catalog/negative/presentation-anchor-unsafe.json +16 -0
  192. package/test-vectors/catalog/positive/fec-algorithm-unimplemented.json +29 -0
  193. package/test-vectors/catalog/positive/fec-iso-ssbg1.json +1 -1
  194. package/test-vectors/catalog/positive/fec-multicast.json +1 -1
  195. package/test-vectors/catalog/positive/fec-reed-solomon-layered.json +50 -0
  196. package/test-vectors/catalog/positive/mmt01-12-1-init-ref-anchor.json +29 -0
  197. package/test-vectors/catalog/positive/multicast-amt-discovery-omitted.json +37 -0
  198. package/test-vectors/catalog/positive/multicast-amt-dns-relay.json +38 -0
  199. package/test-vectors/catalog/positive/multicast-amt-manual-relay.json +3 -3
  200. package/test-vectors/catalog/{negative/multicast-endpoint-missing-protocol-and-source.json → positive/multicast-asm-unprotected.json} +10 -5
  201. package/test-vectors/catalog/positive/multicast-auth-asm-sender.json +78 -0
  202. package/test-vectors/catalog/positive/multicast-auth-rotation.json +39 -38
  203. package/test-vectors/catalog/positive/multicast-draft01-4-1-example.json +81 -0
  204. package/test-vectors/catalog/positive/multicast-draft01-7-2-6-example.json +70 -0
  205. package/test-vectors/catalog/positive/presentation-anchor-negative.json +27 -0
  206. package/test-vectors/catalog/section-codes.json +31 -1
  207. package/test-vectors/catalog-multicast-auth-v1.json +38 -20
  208. package/test-vectors/catalog-validation.json +101 -5
  209. package/test-vectors/catalog-validator-public-api.mjs +14 -9
  210. package/test-vectors/generate-bc-provenance-v2.mjs +252 -0
  211. package/dist/fec-codec.d.ts +0 -32
  212. package/dist/fec-codec.d.ts.map +0 -1
  213. package/dist/fec-codec.js +0 -47
  214. package/dist/fec-codec.js.map +0 -7
  215. package/src/fec-codec.ts +0 -61
@@ -655,26 +655,30 @@ function isEmptyOrExactLegacyTrailer(payload, start, end) {
655
655
  const authLength = view2.getUint16(2, false);
656
656
  return start + LEGACY_TRAILER_HEADER_SIZE + authLength === end;
657
657
  }
658
- function resolveDeclaredTrailers(payload, declaredEnd, fecType, options) {
658
+ function resolveDeclaredTrailers(payload, declaredEnd, fecType, options, rapFlag = false) {
659
659
  if (declaredEnd > payload.length)
660
660
  return null;
661
661
  if (options?.skipFecId) {
662
- return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false } : null;
662
+ return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false, hasOverlayFecId: false } : null;
663
663
  }
664
+ const overlay = options?.overlayDeclared === true && rapFlag;
664
665
  if (fecType === 1) {
665
- const fecStart = payload.length - SOURCE_FEC_PAYLOAD_ID_SIZE;
666
+ const fecStart = payload.length - sourceFecTrailerSize(overlay);
666
667
  if (fecStart < declaredEnd || !isEmptyOrExactLegacyTrailer(payload, declaredEnd, fecStart)) {
667
668
  return null;
668
669
  }
669
- return { hasFecId: true };
670
+ return { hasFecId: true, hasOverlayFecId: overlay };
670
671
  }
671
- if (fecType !== 0)
672
+ if (fecType !== 0 || overlay)
672
673
  return null;
673
674
  if (isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)) {
674
- return { hasFecId: false };
675
+ return { hasFecId: false, hasOverlayFecId: false };
675
676
  }
676
677
  return null;
677
678
  }
679
+ function sourceFecTrailerSize(overlay) {
680
+ return overlay ? 2 * SOURCE_FEC_PAYLOAD_ID_SIZE : SOURCE_FEC_PAYLOAD_ID_SIZE;
681
+ }
678
682
  function extractNALUnit(mmtpPacket) {
679
683
  const extraction = extractMFUPayload(mmtpPacket);
680
684
  if (!extraction)
@@ -733,15 +737,16 @@ function planMfuExtraction(mmtpPacket, options, parsedHeader) {
733
737
  if ("rejection" in layoutResult)
734
738
  return layoutResult;
735
739
  const { layout } = layoutResult;
736
- const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options);
740
+ const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options, header.rapFlag);
737
741
  if (!trailerLayout) {
738
742
  if (!options?.skipFecId && header.fecType === 1) {
739
743
  const observed = payload.length - layout.dataEnd;
740
- if (observed !== SOURCE_FEC_PAYLOAD_ID_SIZE) {
744
+ const expected = sourceFecTrailerSize(options?.overlayDeclared === true && header.rapFlag);
745
+ if (observed !== expected) {
741
746
  return {
742
747
  rejection: {
743
748
  gate: "source-fec-payload-id-width-mismatch",
744
- detail: `producer wrote a ${observed}-byte Source FEC Payload ID, ISO/IEC 23008-1 \xA7C.5.2 requires ${SOURCE_FEC_PAYLOAD_ID_SIZE} (payload=${payload.length}, declaredEnd=${layout.dataEnd})`
749
+ detail: `producer wrote a ${observed}-byte Source FEC Payload ID, ISO/IEC 23008-1 \xA7C.5.2 requires ${expected} (payload=${payload.length}, declaredEnd=${layout.dataEnd})`
745
750
  }
746
751
  };
747
752
  }
@@ -771,10 +776,13 @@ function extractPlannedMfu(mmtpPacket, result) {
771
776
  const mfuDuHeader = mfuDuHeaderPresent && mpu.timedFlag === 1 ? parseTimedMfuDuHeader(payload, MPU_HEADER_SIZE) : null;
772
777
  const itemId = mfuDuHeaderPresent && mpu.timedFlag === 0 ? new DataView(payload.buffer, payload.byteOffset + MPU_HEADER_SIZE, 4).getUint32(0, false) : null;
773
778
  const data = payload.subarray(mfuOffset, dataEnd);
774
- const fecPayloadId = trailerLayout.hasFecId ? {
775
- ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE, SOURCE_FEC_PAYLOAD_ID_SIZE).getUint32(0, false)
776
- } : null;
777
- return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId };
779
+ const trailerStart = mmtpPacket.length - sourceFecTrailerSize(trailerLayout.hasOverlayFecId);
780
+ const ssIdAt = (offset) => ({
781
+ ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + offset, 4).getUint32(0, false)
782
+ });
783
+ const fecPayloadId = trailerLayout.hasFecId ? ssIdAt(trailerStart) : null;
784
+ const overlayFecPayloadId = trailerLayout.hasOverlayFecId ? ssIdAt(trailerStart + SOURCE_FEC_PAYLOAD_ID_SIZE) : null;
785
+ return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId, overlayFecPayloadId };
778
786
  }
779
787
  function extractTimestamp(mmtpPacket) {
780
788
  const { header } = unwrapMMTP(mmtpPacket);
@@ -999,19 +1007,275 @@ function catalogFecAvailable(fec) {
999
1007
  const block = recordOf(fec);
1000
1008
  if (block === void 0)
1001
1009
  return true;
1010
+ if (fecAlgorithmUnimplemented(block["algorithm"]))
1011
+ return false;
1002
1012
  const declaresFecInstance = block["algorithm"] !== "none";
1003
1013
  const profile = block["blockProfile"];
1004
1014
  const profileOk = isFecBlockProfile(profile) || profile === void 0 && !declaresFecInstance;
1005
1015
  return profileOk && (!declaresFecInstance || isoBlockSpanUsable(block));
1006
1016
  }
1017
+ function fecAlgorithmUnimplemented(algorithm) {
1018
+ return typeof algorithm === "string" && algorithm !== "none" && algorithm !== "raptorq" && algorithm !== "reed-solomon";
1019
+ }
1007
1020
  function isPositiveSafeInteger(value) {
1008
1021
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
1009
1022
  }
1023
+ var ISO_SSBG1_MIN_SYMBOL_SIZE = 14;
1010
1024
  function catalogFecDeclaresUnconfigurableInstance(fec) {
1011
1025
  const block = recordOf(fec);
1012
- if (block === void 0 || block["algorithm"] === "none")
1026
+ if (block === void 0 || block["algorithm"] === "none" || fecAlgorithmUnimplemented(block["algorithm"]))
1013
1027
  return false;
1014
- 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;
1015
1279
  }
1016
1280
 
1017
1281
  // src/mfu-reassembler.ts
@@ -3886,8 +4150,14 @@ var SampleCombiner = class {
3886
4150
  /**
3887
4151
  * Add one reassembled data unit. Returns the combined sample once every
3888
4152
  * constituent data unit has arrived and totals the authored size.
4153
+ *
4154
+ * `sampleSize` is the authored size the host resolves for the sample as the
4155
+ * data unit completes. It stands in only when no size was registered, which
4156
+ * happens when the data unit's FI=0/FI=1 reached the reassembler without the
4157
+ * host's own FT=2 parse: an FEC-recovered first fragment completed by source
4158
+ * fragments, or one decoded before its source copy arrived.
3889
4159
  */
3890
- addMfu(mfu) {
4160
+ addMfu(mfu, sampleSize) {
3891
4161
  if (mfu.movieFragmentSequenceNumber === void 0 || mfu.sampleNumber === void 0) {
3892
4162
  this.#stats.passthroughSamples++;
3893
4163
  return fromPassthrough(mfu);
@@ -3903,7 +4173,7 @@ var SampleCombiner = class {
3903
4173
  return null;
3904
4174
  }
3905
4175
  const dataLen = mfu.data.byteLength;
3906
- const authoredSize = this.#authoredSizes.get(key);
4176
+ const authoredSize = this.#authoredSizes.get(key) ?? sampleSize;
3907
4177
  if (offset === 0 && !this.#pending.has(key)) {
3908
4178
  const passesThrough = authoredSize === void 0 ? !this.#requireAuthoredSize : dataLen === authoredSize;
3909
4179
  if (passesThrough) {
@@ -4197,6 +4467,12 @@ if (void 0) {
4197
4467
  const out = c.addMfu(mfu(1, 9, 17, 5, [6, 7, 8, 9, 10], 1001n, false));
4198
4468
  expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
4199
4469
  });
4470
+ test("a size handed with the data unit completes a sample no head registered", () => {
4471
+ const c = combiner({ requireAuthoredSize: true });
4472
+ const out = c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5);
4473
+ expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5]));
4474
+ expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5)).toBeNull();
4475
+ });
4200
4476
  test("duplicate offset is rejected", () => {
4201
4477
  const c = combiner();
4202
4478
  c.registerAuthoredSize(void 0, 1, 9, 17, 10);
@@ -6003,197 +6279,6 @@ if (void 0) {
6003
6279
  });
6004
6280
  }
6005
6281
 
6006
- // src/multicast-auth-catalog.ts
6007
- var RAW_ED25519_KEY_LENGTH = 32;
6008
- var SOURCE_AUTH_SCOPE_LENGTH = 32;
6009
- var BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
6010
- function encodeBase64Url(bytes) {
6011
- let output = "";
6012
- for (let i = 0; i < bytes.length; i += 3) {
6013
- const b0 = bytes[i];
6014
- const b1 = bytes[i + 1];
6015
- const b2 = bytes[i + 2];
6016
- output += BASE64URL_ALPHABET[b0 >> 2];
6017
- output += BASE64URL_ALPHABET[(b0 & 3) << 4 | (b1 === void 0 ? 0 : b1 >> 4)];
6018
- if (b1 === void 0) break;
6019
- output += BASE64URL_ALPHABET[(b1 & 15) << 2 | (b2 === void 0 ? 0 : b2 >> 6)];
6020
- if (b2 === void 0) break;
6021
- output += BASE64URL_ALPHABET[b2 & 63];
6022
- }
6023
- return output;
6024
- }
6025
- var BASE64URL_DECODE_TABLE = (() => {
6026
- const table = new Int8Array(128).fill(-1);
6027
- for (let i = 0; i < BASE64URL_ALPHABET.length; i++) {
6028
- table[BASE64URL_ALPHABET.charCodeAt(i)] = i;
6029
- }
6030
- return table;
6031
- })();
6032
- function decodeBase64Url(text) {
6033
- if (text.length % 4 === 1) {
6034
- throw new Error(`[multicast-auth-catalog] invalid unpadded base64url length for "${text}"`);
6035
- }
6036
- const bytes = [];
6037
- let buffer = 0;
6038
- let bits = 0;
6039
- for (let i = 0; i < text.length; i++) {
6040
- const code = text.charCodeAt(i);
6041
- const value = code < 128 ? BASE64URL_DECODE_TABLE[code] : -1;
6042
- if (value === void 0 || value < 0) {
6043
- throw new Error(`[multicast-auth-catalog] invalid base64url character in "${text}"`);
6044
- }
6045
- buffer = buffer << 6 | value;
6046
- bits += 6;
6047
- if (bits >= 8) {
6048
- bits -= 8;
6049
- bytes.push(buffer >> bits & 255);
6050
- }
6051
- }
6052
- const decoded = Uint8Array.from(bytes);
6053
- if (encodeBase64Url(decoded) !== text) {
6054
- throw new Error(`[multicast-auth-catalog] non-canonical base64url encoding "${text}"`);
6055
- }
6056
- return decoded;
6057
- }
6058
- function decodeAuthScope(authScope) {
6059
- const bytes = decodeBase64Url(authScope);
6060
- if (bytes.byteLength !== SOURCE_AUTH_SCOPE_LENGTH) {
6061
- throw new Error(
6062
- `[multicast-auth-catalog] authScope must decode to ${SOURCE_AUTH_SCOPE_LENGTH} raw bytes, got ${bytes.byteLength}`
6063
- );
6064
- }
6065
- return bytes;
6066
- }
6067
- function decodeEd25519PublicKey(publicKey) {
6068
- const bytes = decodeBase64Url(publicKey);
6069
- if (bytes.byteLength !== RAW_ED25519_KEY_LENGTH) {
6070
- throw new Error(
6071
- `[multicast-auth-catalog] public key must decode to ${RAW_ED25519_KEY_LENGTH} raw bytes, got ${bytes.byteLength}`
6072
- );
6073
- }
6074
- return bytes;
6075
- }
6076
- function isNonEmptyString(value) {
6077
- return typeof value === "string" && value.length > 0;
6078
- }
6079
- function isValidAuthScopeField(value) {
6080
- if (!isNonEmptyString(value)) return false;
6081
- try {
6082
- decodeAuthScope(value);
6083
- return true;
6084
- } catch {
6085
- return false;
6086
- }
6087
- }
6088
- function isValidPublicKeyField(value) {
6089
- if (!isNonEmptyString(value)) return false;
6090
- try {
6091
- decodeEd25519PublicKey(value);
6092
- return true;
6093
- } catch {
6094
- return false;
6095
- }
6096
- }
6097
- function hasOnlyKeys(object2, allowed) {
6098
- const allowedKeys = new Set(allowed);
6099
- return Object.keys(object2).every((key) => allowedKeys.has(key));
6100
- }
6101
- function isMulticastAuthTrackConfig(obj) {
6102
- if (typeof obj !== "object" || obj === null) return false;
6103
- const o = obj;
6104
- return hasOnlyKeys(o, ["mediaTrack", "manifestTrack", "authScope", "sourceSymbolFormat"]) && isNonEmptyString(o["mediaTrack"]) && isNonEmptyString(o["manifestTrack"]) && o["mediaTrack"] !== o["manifestTrack"] && isValidAuthScopeField(o["authScope"]) && isNonEmptyString(o["sourceSymbolFormat"]);
6105
- }
6106
- var VALID_COMPACTION = /* @__PURE__ */ new Set(["merkle", "none"]);
6107
- var VALID_ENFORCEMENT = /* @__PURE__ */ new Set(["shadow", "enforce"]);
6108
- function hasUniqueMulticastAuthTrackBindings(tracks) {
6109
- const bindings = tracks.flatMap((track) => {
6110
- if (typeof track !== "object" || track === null) return [];
6111
- const value = track;
6112
- if (typeof value["mediaTrack"] !== "string" || typeof value["sourceSymbolFormat"] !== "string") {
6113
- return [];
6114
- }
6115
- return [JSON.stringify([value["mediaTrack"], value["sourceSymbolFormat"]])];
6116
- });
6117
- return new Set(bindings).size === bindings.length;
6118
- }
6119
- function isMulticastAuthConfig(obj) {
6120
- if (typeof obj !== "object" || obj === null) return false;
6121
- const o = obj;
6122
- if (o["scheme"] !== "bc-provenance") return false;
6123
- if (o["hash"] !== "blake3") return false;
6124
- if (o["sig"] !== "ed25519") return false;
6125
- if (!hasOnlyKeys(o, ["scheme", "hash", "sig", "publicKey", "keyId", "previousKey", "compaction", "enforcement", "tracks"])) return false;
6126
- if (!isValidPublicKeyField(o["publicKey"])) return false;
6127
- if (!isNonEmptyString(o["keyId"])) return false;
6128
- if (o["previousKey"] !== void 0 && !isValidPublicKeyField(o["previousKey"])) return false;
6129
- if (o["previousKey"] === o["publicKey"]) return false;
6130
- if (typeof o["compaction"] !== "string" || !VALID_COMPACTION.has(o["compaction"])) return false;
6131
- if (o["enforcement"] !== void 0) {
6132
- if (typeof o["enforcement"] !== "string" || !VALID_ENFORCEMENT.has(o["enforcement"])) return false;
6133
- }
6134
- if (!Array.isArray(o["tracks"]) || o["tracks"].length === 0) return false;
6135
- const tracks = o["tracks"];
6136
- if (!tracks.every((t) => isMulticastAuthTrackConfig(t))) return false;
6137
- const typedTracks = tracks;
6138
- const scopes = typedTracks.map((t) => t.authScope);
6139
- if (new Set(scopes).size !== scopes.length) return false;
6140
- if (!hasUniqueMulticastAuthTrackBindings(typedTracks)) return false;
6141
- const manifestTracks = typedTracks.map((t) => t.manifestTrack);
6142
- if (new Set(manifestTracks).size !== manifestTracks.length) return false;
6143
- return true;
6144
- }
6145
- function resolveMulticastAuthMode(playerMode, auth) {
6146
- if (playerMode !== void 0) return playerMode;
6147
- if (auth === void 0) return "off";
6148
- return auth.enforcement ?? "shadow";
6149
- }
6150
- function resolveMulticastAuthCatalog(catalog, playerMode) {
6151
- if (typeof catalog !== "object" || catalog === null || Array.isArray(catalog)) {
6152
- throw new Error("[multicast-auth-catalog] catalog must be an object");
6153
- }
6154
- const root = catalog;
6155
- const rawAuth = root["multicast.auth"];
6156
- if (rawAuth === void 0) {
6157
- if (playerMode === "enforce") {
6158
- throw new Error("[multicast-auth-catalog] player enforce mode requires multicast.auth");
6159
- }
6160
- return void 0;
6161
- }
6162
- if (!isMulticastAuthConfig(rawAuth)) {
6163
- throw new Error("[multicast-auth-catalog] invalid multicast.auth v2 block");
6164
- }
6165
- const rawTracks = root["tracks"];
6166
- if (!Array.isArray(rawTracks)) {
6167
- throw new Error("[multicast-auth-catalog] catalog tracks must be an array");
6168
- }
6169
- const catalogTrackNames = new Set(
6170
- rawTracks.flatMap(
6171
- (track) => typeof track === "object" && track !== null && typeof track["name"] === "string" ? [track["name"]] : []
6172
- )
6173
- );
6174
- for (const track of rawAuth.tracks) {
6175
- if (!catalogTrackNames.has(track.mediaTrack)) {
6176
- throw new Error(`[multicast-auth-catalog] unknown mediaTrack "${track.mediaTrack}"`);
6177
- }
6178
- if (!catalogTrackNames.has(track.manifestTrack)) {
6179
- throw new Error(`[multicast-auth-catalog] unknown manifestTrack "${track.manifestTrack}"`);
6180
- }
6181
- }
6182
- return {
6183
- keyId: rawAuth.keyId,
6184
- acceptedPublicKeys: [
6185
- decodeEd25519PublicKey(rawAuth.publicKey),
6186
- ...rawAuth.previousKey === void 0 ? [] : [decodeEd25519PublicKey(rawAuth.previousKey)]
6187
- ],
6188
- mode: resolveMulticastAuthMode(playerMode, rawAuth),
6189
- compaction: rawAuth.compaction,
6190
- tracks: rawAuth.tracks.map((track) => ({
6191
- ...track,
6192
- authScope: decodeAuthScope(track.authScope)
6193
- }))
6194
- };
6195
- }
6196
-
6197
6282
  // src/repair-layers.ts
6198
6283
  var REPAIR_PRIORITY_MIN = 192;
6199
6284
  var REPAIR_PRIORITY_MAX = 255;
@@ -6201,6 +6286,7 @@ var DEFAULT_REPAIR_PRIORITY = 240;
6201
6286
  var MAX_RAPTORQ_SOURCE_SYMBOLS = 56403;
6202
6287
  var MAX_REPAIR_SYMBOLS = 16777215;
6203
6288
  var MAX_ENCODING_SYMBOL_ID = 16777215;
6289
+ var MAX_REED_SOLOMON_BLOCK_SYMBOLS = 255;
6204
6290
  var RepairContractError = class extends Error {
6205
6291
  constructor(code, path, message) {
6206
6292
  super(`[repair-layers:${code}] ${path}: ${message}`);
@@ -6383,11 +6469,12 @@ function assembleRepairLayers(source, descriptors, fail = throwRepairContractErr
6383
6469
  if (layered && !positiveInteger(source.sourceSymbols)) {
6384
6470
  fail("track_fec", `${source.path}.sourceSymbols`, "layered or overlay repair needs a positive integer sourceSymbols on the source");
6385
6471
  }
6386
- if (layered && source.algorithm !== "raptorq") {
6472
+ const reedSolomon = source.algorithm === "reed-solomon";
6473
+ if (layered && source.algorithm !== "raptorq" && !reedSolomon) {
6387
6474
  fail(
6388
6475
  "track_fec",
6389
6476
  `${source.path}.algorithm`,
6390
- "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)"
6391
6478
  );
6392
6479
  }
6393
6480
  let layerZeroPriority = DEFAULT_REPAIR_PRIORITY;
@@ -6446,6 +6533,13 @@ function assembleRepairLayers(source, descriptors, fail = throwRepairContractErr
6446
6533
  `overlay sourceSymbols + repairSymbols - 1 exceeds the 24-bit ESI space (${MAX_ENCODING_SYMBOL_ID})`
6447
6534
  );
6448
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
+ }
6449
6543
  overlays.push({ repairTrackName: d.name, scope: "keyframe", sourceSymbols, repairSymbols, priority: d.priority });
6450
6544
  }
6451
6545
  let offset = layerZeroSymbols;
@@ -6490,6 +6584,13 @@ function assembleRepairLayers(source, descriptors, fail = throwRepairContractErr
6490
6584
  `sourceSymbols + total base repair symbols - 1 exceeds the 24-bit ESI space (${MAX_ENCODING_SYMBOL_ID})`
6491
6585
  );
6492
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
+ }
6493
6594
  return { sourceTrackName: source.name, baseLayers, overlays, totalBaseRepairSymbols };
6494
6595
  }
6495
6596
 
@@ -6537,7 +6638,7 @@ function isFecCatalogGeometry(obj) {
6537
6638
  const o = obj;
6538
6639
  const algorithm = o["algorithm"];
6539
6640
  const symbolSize = o["symbolSize"];
6540
- 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;
6541
6642
  }
6542
6643
  function isFecCatalogConfig(obj) {
6543
6644
  if (!isFecCatalogGeometry(obj)) return false;
@@ -6552,8 +6653,7 @@ function isMulticastTrackObject(obj) {
6552
6653
  function isMulticastEndpoint(obj) {
6553
6654
  if (typeof obj !== "object" || obj === null) return false;
6554
6655
  const o = obj;
6555
- const protocol = o["protocol"] ?? (typeof o["sourceAddress"] === "string" && o["sourceAddress"].length > 0 ? "ssm" : void 0);
6556
- 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));
6557
6657
  }
6558
6658
  function isMulticastCatalogConfig(obj) {
6559
6659
  if (typeof obj !== "object" || obj === null) return false;
@@ -6657,13 +6757,22 @@ var CmsfCatalogValidationError = class extends Error {
6657
6757
  function catalogError(code, path, message) {
6658
6758
  throw new CmsfCatalogValidationError(code, path, message);
6659
6759
  }
6660
- function validateCmsfMmtpCatalog(value) {
6760
+ function validateNetworkSourceRelays(sources, path) {
6761
+ if (!Array.isArray(sources)) return;
6762
+ sources.forEach((source, i) => {
6763
+ const s = source;
6764
+ if (s?.["type"] === "amt" && s["discovery"] === "driad" && s["relay"] !== void 0) {
6765
+ catalogError("multicast_network_source", `${path}[${i}].relay`, 'relay must be omitted with discovery "driad"');
6766
+ }
6767
+ });
6768
+ }
6769
+ function validateCmsfMmtpCatalog(value, options = {}) {
6661
6770
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
6662
6771
  catalogError("catalog_object", "$", "catalog must be an object");
6663
6772
  }
6664
6773
  const catalog = value;
6665
6774
  const rawVersion = catalog["version"];
6666
- const normalizedVersion = typeof rawVersion === "string" ? Number.isFinite(Number(rawVersion)) ? Number(rawVersion) : rawVersion.startsWith("draft-ietf-moq-catalogformat") ? 1 : NaN : rawVersion;
6775
+ const normalizedVersion = typeof rawVersion === "string" ? Number.isFinite(Number(rawVersion)) ? Number(rawVersion) : rawVersion.startsWith("draft-ietf-moq-catalogformat") || rawVersion === "draft-01" ? 1 : NaN : rawVersion;
6667
6776
  if (!Number.isInteger(normalizedVersion) || normalizedVersion <= 0) {
6668
6777
  catalogError("catalog_version", "$.version", "version must be a positive integer or a recognized format tag");
6669
6778
  }
@@ -6678,6 +6787,22 @@ function validateCmsfMmtpCatalog(value) {
6678
6787
  "commonTrackFields is retired; every track carries its own fields"
6679
6788
  );
6680
6789
  }
6790
+ const initDataList = catalog["initDataList"];
6791
+ if (initDataList !== void 0) {
6792
+ if (!Array.isArray(initDataList)) {
6793
+ catalogError("catalog_init_data_list", "$.initDataList", "initDataList must be an array");
6794
+ }
6795
+ initDataList.forEach((entry, i) => {
6796
+ const e = entry;
6797
+ const entryPath = `$.initDataList[${i}]`;
6798
+ 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) {
6799
+ catalogError("catalog_init_data_list", entryPath, "entry needs a non-empty string id and type");
6800
+ }
6801
+ if (e["type"] === "inline" && (typeof e["data"] !== "string" || e["data"].length === 0)) {
6802
+ catalogError("catalog_init_data_list", `${entryPath}.data`, 'an "inline" entry needs non-empty data');
6803
+ }
6804
+ });
6805
+ }
6681
6806
  const tracks = catalog["tracks"];
6682
6807
  const trackRecords = [];
6683
6808
  const positiveInteger3 = (input) => Number.isSafeInteger(input) && input > 0;
@@ -6729,6 +6854,14 @@ function validateCmsfMmtpCatalog(value) {
6729
6854
  if (keyframeIntervalMs !== void 0 && !positiveNumber2(keyframeIntervalMs) || keyframeIntervalTicks !== void 0 && !positiveInteger3(keyframeIntervalTicks)) {
6730
6855
  catalogError("track_keyframe_interval", path, "keyframe interval fields must be positive numbers");
6731
6856
  }
6857
+ const anchor = track["presentationAnchorTicks"];
6858
+ if (anchor !== void 0 && !Number.isSafeInteger(anchor)) {
6859
+ catalogError("track_presentation_anchor", `${path}.presentationAnchorTicks`, "must be a safe integer");
6860
+ }
6861
+ const initRef = track["initRef"];
6862
+ if (initRef !== void 0 && (typeof initRef !== "string" || initRef.length === 0)) {
6863
+ catalogError("track_init_ref", `${path}.initRef`, "must be a non-empty string");
6864
+ }
6732
6865
  if (packaging === "fec-repair") {
6733
6866
  rejectRepairTrackGeometry(path, track, catalogError);
6734
6867
  validateRepairTrackFields(describeRepairTrack(name, path, track), catalogError);
@@ -6736,9 +6869,8 @@ function validateCmsfMmtpCatalog(value) {
6736
6869
  rejectRepairFieldsOnMediaTrack(path, track, catalogError);
6737
6870
  }
6738
6871
  if (packaging === "mmtp") {
6739
- const mmtpMode = track["mmtpMode"];
6740
- if (mmtpMode !== "mpu" && mmtpMode !== "mfu") {
6741
- catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mpu or mfu");
6872
+ if (track["mmtpMode"] !== "mfu") {
6873
+ catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mfu");
6742
6874
  }
6743
6875
  if (!positiveInteger3(timescale)) {
6744
6876
  catalogError("track_timescale", `${path}.timescale`, "must be a positive integer");
@@ -6761,8 +6893,8 @@ function validateCmsfMmtpCatalog(value) {
6761
6893
  }
6762
6894
  const config = fec;
6763
6895
  const algorithm = config["algorithm"];
6764
- if (algorithm !== "none" && algorithm !== "raptorq" && algorithm !== "reed-solomon") {
6765
- catalogError("track_fec", `${path}.fec.algorithm`, "algorithm is not supported");
6896
+ if (typeof algorithm !== "string" || algorithm.length === 0) {
6897
+ catalogError("track_fec", `${path}.fec.algorithm`, "must be a non-empty string");
6766
6898
  }
6767
6899
  if ("interleaveDepth" in config || "interleaveMs" in config) {
6768
6900
  catalogError("track_fec", `${path}.fec`, "interleaveDepthMs is the only supported interleave field");
@@ -6791,6 +6923,9 @@ function validateCmsfMmtpCatalog(value) {
6791
6923
  }
6792
6924
  }
6793
6925
  readFecBlockProfile(config["blockProfile"], `${path}.fec.blockProfile`, algorithm !== "none", catalogError);
6926
+ if (algorithm !== "none" && config["symbolSize"] < ISO_SSBG1_MIN_SYMBOL_SIZE) {
6927
+ catalogError("track_fec", `${path}.fec.symbolSize`, "iso-ssbg1-v1 symbolSize must be at least 14");
6928
+ }
6794
6929
  }
6795
6930
  }
6796
6931
  const repairDescriptors = trackRecords.flatMap(
@@ -6840,19 +6975,34 @@ function validateCmsfMmtpCatalog(value) {
6840
6975
  const timescale = BigInt(track["timescale"]);
6841
6976
  const durationTicks = track["groupDurationTicks"];
6842
6977
  const ticks = durationTicks !== void 0 ? BigInt(durationTicks) : BigInt(track["groupDurationMs"]) * timescale / 1000n;
6843
- const anchor = switchingSets.get(altGroup);
6844
- if (anchor && ticks * anchor.timescale !== anchor.ticks * timescale) {
6845
- catalogError("track_switching_set", `$.tracks[${index}]`, `group duration does not match ${JSON.stringify(anchor.name)} in altGroup ${altGroup}`);
6978
+ const framerate = track["framerate"];
6979
+ const intraOnly = positiveNumber2(framerate) && Math.abs(Number(ticks) * framerate - Number(timescale)) <= Number(timescale) * 1e-3;
6980
+ const members = switchingSets.get(altGroup) ?? [];
6981
+ members.push({ index, name: track["name"], ticks, timescale, intraOnly });
6982
+ switchingSets.set(altGroup, members);
6983
+ }
6984
+ for (const [altGroup, members] of switchingSets) {
6985
+ const anchor = members.find((member) => !member.intraOnly) ?? members[0];
6986
+ for (const member of members) {
6987
+ if (member === anchor || member.ticks * anchor.timescale === anchor.ticks * member.timescale) continue;
6988
+ const nests = member.intraOnly && !anchor.intraOnly && anchor.ticks * member.timescale % (member.ticks * anchor.timescale) === 0n;
6989
+ if (!nests) {
6990
+ catalogError("track_switching_set", `$.tracks[${member.index}]`, `group duration does not match ${JSON.stringify(anchor.name)} in altGroup ${altGroup}`);
6991
+ }
6846
6992
  }
6847
- if (!anchor) switchingSets.set(altGroup, { name: track["name"], ticks, timescale });
6848
6993
  }
6849
6994
  const multicast = catalog["multicast"];
6850
6995
  if (typeof multicast === "object" && multicast !== null && !Array.isArray(multicast)) {
6996
+ validateNetworkSourceRelays(multicast["networkSource"], "$.multicast.networkSource");
6851
6997
  const endpoints = multicast["endpoints"];
6852
6998
  if (Array.isArray(endpoints)) {
6853
6999
  for (let endpointIndex = 0; endpointIndex < endpoints.length; endpointIndex++) {
6854
7000
  const endpoint = endpoints[endpointIndex];
6855
7001
  if (typeof endpoint !== "object" || endpoint === null || Array.isArray(endpoint)) continue;
7002
+ validateNetworkSourceRelays(
7003
+ endpoint["networkSource"],
7004
+ `$.multicast.endpoints[${endpointIndex}].networkSource`
7005
+ );
6856
7006
  if ("relayAddress" in endpoint) {
6857
7007
  catalogError(
6858
7008
  "multicast_relay_address",
@@ -6892,15 +7042,8 @@ function validateCmsfMmtpCatalog(value) {
6892
7042
  }
6893
7043
  }
6894
7044
  }
6895
- try {
6896
- resolveMulticastAuthCatalog(catalog);
6897
- } catch (error) {
6898
- catalogError(
6899
- "multicast_auth",
6900
- "$.multicast.auth",
6901
- error instanceof Error ? error.message : "invalid multicast.auth v2 block"
6902
- );
6903
- }
7045
+ const [multicastIssue] = multicastCatalogIssues(catalog, options);
7046
+ if (multicastIssue) catalogError(multicastIssue.code, multicastIssue.path, multicastIssue.message);
6904
7047
  validateArchive(catalog);
6905
7048
  return catalog;
6906
7049
  }
@@ -6926,7 +7069,7 @@ function resolveGroupDurationTicks(timing, timescale) {
6926
7069
  const product = timing.groupDurationMs * timescale;
6927
7070
  if (product % 1e3 !== 0) {
6928
7071
  throw new Error(
6929
- `[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)`
7072
+ `[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)`
6930
7073
  );
6931
7074
  }
6932
7075
  return product / 1e3;
@@ -6947,189 +7090,6 @@ function validateSwitchingSetTiming(tracks) {
6947
7090
  return { ok: false, expectedTicks, mismatches };
6948
7091
  }
6949
7092
 
6950
- // node_modules/@blockcast/mmt-transport/dist/types.js
6951
- var MoqFecAlgorithm;
6952
- (function(MoqFecAlgorithm2) {
6953
- MoqFecAlgorithm2[MoqFecAlgorithm2["None"] = 0] = "None";
6954
- MoqFecAlgorithm2[MoqFecAlgorithm2["Xor"] = 1] = "Xor";
6955
- MoqFecAlgorithm2[MoqFecAlgorithm2["RaptorQ"] = 2] = "RaptorQ";
6956
- })(MoqFecAlgorithm || (MoqFecAlgorithm = {}));
6957
-
6958
- // node_modules/@blockcast/mmt-base/dist/mmtp.js
6959
- var MPU_HEADER_SIZE2 = 8;
6960
- var MPU_LENGTH_FIELD_SIZE2 = 2;
6961
- var MPU_HEADER_REMAINDER_SIZE2 = MPU_HEADER_SIZE2 - MPU_LENGTH_FIELD_SIZE2;
6962
- var MMTP_SIGNALING_PACKET_ID2 = 0;
6963
- var MMTP_PACKET_ID_MAX2 = 65535;
6964
-
6965
- // node_modules/@blockcast/mmt-base/dist/net-constants.js
6966
- var DEFAULT_AMT_RELAY_PORT2 = 2268;
6967
-
6968
- // node_modules/@blockcast/mmt-base/dist/ntp-short.js
6969
- var NTP_SHORT_BITS2 = 32;
6970
- var NTP_SHORT_MODULUS2 = 2 ** NTP_SHORT_BITS2;
6971
- var NTP_SHORT_HALF_RANGE2 = 2 ** (NTP_SHORT_BITS2 - 1);
6972
- function isNtpShort(value) {
6973
- return Number.isInteger(value) && value >= 0 && value < NTP_SHORT_MODULUS2;
6974
- }
6975
- function compareNtpShort(a, b) {
6976
- if (!isNtpShort(a) || !isNtpShort(b)) {
6977
- throw new RangeError(`NTP-short values must be integers in [0, 2^${NTP_SHORT_BITS2}), got ${String(a)} and ${String(b)}`);
6978
- }
6979
- if (a === b)
6980
- return "equal";
6981
- const forward = (a - b + NTP_SHORT_MODULUS2) % NTP_SHORT_MODULUS2;
6982
- if (forward < NTP_SHORT_HALF_RANGE2)
6983
- return "after";
6984
- if (forward > NTP_SHORT_HALF_RANGE2)
6985
- return "before";
6986
- return "unordered";
6987
- }
6988
-
6989
- // node_modules/@blockcast/mmt-base/dist/fec-block-profile.js
6990
- var FEC_BLOCK_PROFILES2 = Object.freeze([
6991
- "iso-ssbg1-v1"
6992
- ]);
6993
-
6994
- // node_modules/@blockcast/mmt-base/dist/catalog-fec-source.js
6995
- var ALL_ROLES2 = Object.freeze(["video", "audio"]);
6996
-
6997
- // node_modules/@blockcast/mmt-transport/dist/driad-discovery.js
6998
- var DRIADDiscovery = class {
6999
- cache = /* @__PURE__ */ new Map();
7000
- cacheExpiry = 3e5;
7001
- // 5 minutes
7002
- /**
7003
- * Discover AMT relays for a multicast source address (RFC 8777)
7004
- *
7005
- * @param source - The multicast source IP address (NOT the group!)
7006
- * @returns Array of discovered AMT relays that can tunnel traffic from this source
7007
- */
7008
- async discoverRelays(source) {
7009
- const cached = this.cache.get(source);
7010
- if (cached) {
7011
- return cached;
7012
- }
7013
- try {
7014
- const reversedSource = source.split(".").reverse().join(".");
7015
- const queryDomain = `${reversedSource}.amt.in-addr.arpa`;
7016
- console.log(`[DRIAD] Discovering relays for source ${source} via ${queryDomain}`);
7017
- const relays = await this.queryDRIADProxy(source);
7018
- if (relays.length > 0) {
7019
- this.cache.set(source, relays);
7020
- setTimeout(() => this.cache.delete(source), this.cacheExpiry);
7021
- }
7022
- return relays;
7023
- } catch (error) {
7024
- console.warn(`[DRIAD] Discovery failed for source ${source}:`, error);
7025
- return [];
7026
- }
7027
- }
7028
- /**
7029
- * Query DRIAD proxy service (browser-compatible)
7030
- */
7031
- async queryDRIADProxy(source) {
7032
- const proxyEndpoints = [
7033
- "https://driad.amt.net/api/v1/relays",
7034
- "https://multicast-gateway.cloudflare.com/driad"
7035
- ];
7036
- for (const endpoint of proxyEndpoints) {
7037
- try {
7038
- const response = await fetch(`${endpoint}?source=${encodeURIComponent(source)}`, {
7039
- method: "GET",
7040
- headers: { Accept: "application/json" },
7041
- signal: AbortSignal.timeout(5e3)
7042
- });
7043
- if (response.ok) {
7044
- const data = await response.json();
7045
- return data.relays || [];
7046
- }
7047
- } catch {
7048
- }
7049
- }
7050
- const dohRelay = await this.queryDNSOverHTTPS(source);
7051
- if (dohRelay) {
7052
- return [dohRelay];
7053
- }
7054
- return [];
7055
- }
7056
- /**
7057
- * Query DNS-over-HTTPS for DRIAD relay based on source address (RFC 8777)
7058
- */
7059
- async queryDNSOverHTTPS(source) {
7060
- try {
7061
- const reversedSource = source.split(".").reverse().join(".");
7062
- const queryName = `${reversedSource}.amt.in-addr.arpa`;
7063
- const dohUrl = `https://cloudflare-dns.com/dns-query?name=${queryName}&type=A`;
7064
- const response = await fetch(dohUrl, {
7065
- headers: { Accept: "application/dns-json" },
7066
- signal: AbortSignal.timeout(3e3)
7067
- });
7068
- if (!response.ok) {
7069
- return null;
7070
- }
7071
- const result = await response.json();
7072
- if (result.Answer && result.Answer.length > 0) {
7073
- return {
7074
- host: result.Answer[0].data,
7075
- port: DEFAULT_AMT_RELAY_PORT2,
7076
- priority: 10,
7077
- weight: 100,
7078
- asn: 0
7079
- };
7080
- }
7081
- return null;
7082
- } catch (error) {
7083
- console.warn("[DRIAD] DNS-over-HTTPS query failed:", error);
7084
- return null;
7085
- }
7086
- }
7087
- /**
7088
- * Select best relay based on RTT measurements
7089
- */
7090
- async selectBestRelay(relays) {
7091
- if (relays.length === 0)
7092
- return null;
7093
- const measured = await Promise.all(relays.map(async (relay) => {
7094
- const rtt = await this.measureRTT(relay.host, relay.port);
7095
- return { ...relay, rtt };
7096
- }));
7097
- measured.sort((a, b) => {
7098
- if (a.priority !== b.priority)
7099
- return a.priority - b.priority;
7100
- return (a.rtt || Infinity) - (b.rtt || Infinity);
7101
- });
7102
- console.log(`[DRIAD] Selected relay: ${measured[0].host} (RTT: ${measured[0].rtt}ms)`);
7103
- return measured[0];
7104
- }
7105
- async measureRTT(host, _port) {
7106
- const start = performance.now();
7107
- try {
7108
- await fetch(`https://${host}/health`, {
7109
- method: "HEAD",
7110
- signal: AbortSignal.timeout(2e3),
7111
- mode: "no-cors"
7112
- });
7113
- return performance.now() - start;
7114
- } catch {
7115
- return Infinity;
7116
- }
7117
- }
7118
- /**
7119
- * Clear the relay cache
7120
- */
7121
- clearCache() {
7122
- this.cache.clear();
7123
- }
7124
- /**
7125
- * Get cached relays for a source address
7126
- */
7127
- getCached(source) {
7128
- return this.cache.get(source);
7129
- }
7130
- };
7131
- var driadDiscovery = new DRIADDiscovery();
7132
-
7133
7093
  // node_modules/@blockcast/mmt-transport/dist/multicast-tier.js
7134
7094
  function endpointKey(endpoint) {
7135
7095
  return `${endpoint.sourceAddress ?? ""}|${endpoint.groupAddress}|${endpoint.port}`;
@@ -7260,8 +7220,8 @@ var AdaptiveBitrateController = class {
7260
7220
  /**
7261
7221
  * Update FEC statistics for ABR decisions
7262
7222
  *
7263
- * Per draft-ramadan-moq-fec-00, ABR should use the effective loss rate
7264
- * (after FEC recovery) rather than raw transport loss rate.
7223
+ * ABR uses the effective loss rate (after FEC recovery) rather than the
7224
+ * raw transport loss rate.
7265
7225
  *
7266
7226
  * @param stats - FEC statistics from the FEC decoder
7267
7227
  */
@@ -7337,6 +7297,45 @@ var AdaptiveBitrateController = class {
7337
7297
  }
7338
7298
  };
7339
7299
 
7300
+ // node_modules/@blockcast/mmt-base/dist/mmtp.js
7301
+ var MPU_HEADER_SIZE2 = 8;
7302
+ var MPU_LENGTH_FIELD_SIZE2 = 2;
7303
+ var MPU_HEADER_REMAINDER_SIZE2 = MPU_HEADER_SIZE2 - MPU_LENGTH_FIELD_SIZE2;
7304
+ var MMTP_SIGNALING_PACKET_ID2 = 0;
7305
+ var MMTP_PACKET_ID_MAX2 = 65535;
7306
+
7307
+ // node_modules/@blockcast/mmt-base/dist/net-constants.js
7308
+ var DEFAULT_AMT_RELAY_PORT2 = 2268;
7309
+
7310
+ // node_modules/@blockcast/mmt-base/dist/ntp-short.js
7311
+ var NTP_SHORT_BITS2 = 32;
7312
+ var NTP_SHORT_MODULUS2 = 2 ** NTP_SHORT_BITS2;
7313
+ var NTP_SHORT_HALF_RANGE2 = 2 ** (NTP_SHORT_BITS2 - 1);
7314
+ function isNtpShort(value) {
7315
+ return Number.isInteger(value) && value >= 0 && value < NTP_SHORT_MODULUS2;
7316
+ }
7317
+ function compareNtpShort(a, b) {
7318
+ if (!isNtpShort(a) || !isNtpShort(b)) {
7319
+ throw new RangeError(`NTP-short values must be integers in [0, 2^${NTP_SHORT_BITS2}), got ${String(a)} and ${String(b)}`);
7320
+ }
7321
+ if (a === b)
7322
+ return "equal";
7323
+ const forward = (a - b + NTP_SHORT_MODULUS2) % NTP_SHORT_MODULUS2;
7324
+ if (forward < NTP_SHORT_HALF_RANGE2)
7325
+ return "after";
7326
+ if (forward > NTP_SHORT_HALF_RANGE2)
7327
+ return "before";
7328
+ return "unordered";
7329
+ }
7330
+
7331
+ // node_modules/@blockcast/mmt-base/dist/fec-block-profile.js
7332
+ var FEC_BLOCK_PROFILES2 = Object.freeze([
7333
+ "iso-ssbg1-v1"
7334
+ ]);
7335
+
7336
+ // node_modules/@blockcast/mmt-base/dist/catalog-fec-source.js
7337
+ var ALL_ROLES2 = Object.freeze(["video", "audio"]);
7338
+
7340
7339
  // node_modules/@blockcast/mmt-transport/dist/multicast-orchestrator.js
7341
7340
  var DEFAULT_DWELL_MS = 3e3;
7342
7341
  var DEFAULT_JOIN_DEADLINE_MS = 5e3;
@@ -7574,8 +7573,23 @@ function toWindowMulticastSubscribeConfig(input) {
7574
7573
  consume: "bytes",
7575
7574
  ...input.packetIds?.length ? { packetIds: [...input.packetIds] } : {}
7576
7575
  };
7576
+ if (input.atsc3) {
7577
+ const { frequency, plpId, serviceId } = input.atsc3;
7578
+ if (!Number.isInteger(frequency) || frequency < 1) {
7579
+ throw new TypeError(`ATSC3 tuning requires a positive integer frequency in kHz, got ${String(frequency)}`);
7580
+ }
7581
+ return {
7582
+ ...base,
7583
+ origin: "tuner",
7584
+ standard: "atsc3",
7585
+ frequency,
7586
+ ...plpId !== void 0 ? { plpId } : {},
7587
+ ...serviceId !== void 0 ? { serviceId } : {}
7588
+ };
7589
+ }
7577
7590
  const relay = input.amtRelay?.trim();
7578
- const wantsAmt = input.mode === "tunnel" || input.mode !== "native" && relay !== void 0 && relay !== "";
7591
+ const driad = !relay && input.amtDiscovery === "driad";
7592
+ const wantsAmt = input.mode === "tunnel" || input.mode !== "native" && (relay !== void 0 && relay !== "" || driad);
7579
7593
  if (!wantsAmt) {
7580
7594
  const native = {
7581
7595
  ...base,
@@ -7585,6 +7599,20 @@ function toWindowMulticastSubscribeConfig(input) {
7585
7599
  return native;
7586
7600
  }
7587
7601
  const relayPort = input.amtRelayPort;
7602
+ if (driad) {
7603
+ if (!base.source)
7604
+ throw new TypeError("AMT DRIAD discovery requires a source address");
7605
+ if (relayPort !== void 0 && !isPositivePort(relayPort)) {
7606
+ throw new TypeError("AMT DRIAD discovery requires a valid relay port when one is given");
7607
+ }
7608
+ return {
7609
+ ...base,
7610
+ source: base.source,
7611
+ origin: "amt",
7612
+ discovery: "driad",
7613
+ ...relayPort !== void 0 ? { relayPort } : {}
7614
+ };
7615
+ }
7588
7616
  if (!relay || relayPort === void 0 || !isPositivePort(relayPort)) {
7589
7617
  throw new TypeError("AMT requires a resolved relay and a valid relay port");
7590
7618
  }
@@ -7628,7 +7656,8 @@ function normalizeMulticastEndpoint(endpoint) {
7628
7656
  port: endpoint.port,
7629
7657
  ...endpoint.mode ? { mode: endpoint.mode } : {},
7630
7658
  ...amtRelay ? { amtRelay } : {},
7631
- ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
7659
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {},
7660
+ ...endpoint.amtDiscovery === "driad" ? { amtDiscovery: "driad" } : {}
7632
7661
  };
7633
7662
  }
7634
7663
  function multicastEndpointKey(endpoint) {
@@ -7641,7 +7670,9 @@ function multicastEndpointKey(endpoint) {
7641
7670
  normalized.port,
7642
7671
  normalized.mode ?? "auto",
7643
7672
  normalized.amtRelay ?? "",
7644
- normalized.amtRelayPort ?? ""
7673
+ normalized.amtRelayPort ?? "",
7674
+ // A DRIAD join is a different gateway subscription from a native one.
7675
+ ...normalized.amtDiscovery ? [normalized.amtDiscovery] : []
7645
7676
  ]);
7646
7677
  }
7647
7678
  function isMulticastTrackPacketId(value) {
@@ -7681,7 +7712,8 @@ var MulticastSubscriptionPool = class {
7681
7712
  port: config.port,
7682
7713
  mode: config.mode,
7683
7714
  amtRelay: config.amtRelay,
7684
- amtRelayPort: config.amtRelayPort
7715
+ amtRelayPort: config.amtRelayPort,
7716
+ amtDiscovery: config.amtDiscovery
7685
7717
  });
7686
7718
  if (!endpoint)
7687
7719
  throw new Error("Invalid multicast endpoint");
@@ -7747,7 +7779,8 @@ var MulticastSubscriptionPool = class {
7747
7779
  port: endpoint.port,
7748
7780
  ...endpoint.mode ? { mode: endpoint.mode } : {},
7749
7781
  ...endpoint.amtRelay ? { amtRelay: endpoint.amtRelay } : {},
7750
- ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
7782
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {},
7783
+ ...endpoint.amtDiscovery ? { amtDiscovery: endpoint.amtDiscovery } : {}
7751
7784
  }));
7752
7785
  const consumers = /* @__PURE__ */ new Map();
7753
7786
  let entry;
@@ -7827,7 +7860,6 @@ var TransportManager = class {
7827
7860
  };
7828
7861
  capabilities = null;
7829
7862
  subscription = null;
7830
- driad = new DRIADDiscovery();
7831
7863
  /** Built by `connect()` from the caller's ladder; there is no built-in one. */
7832
7864
  abr = null;
7833
7865
  multicastOrchestrator = null;
@@ -7877,8 +7909,8 @@ var TransportManager = class {
7877
7909
  nativeIGMP: hasGatewayBytes,
7878
7910
  directSockets: typeof win?.UDPSocket !== "undefined",
7879
7911
  amt: false,
7880
- driad: true,
7881
- // DRIAD uses HTTP proxy, always available
7912
+ driad: hasGatewayBytes,
7913
+ // the gateway runs RFC 8777 discovery
7882
7914
  fecDecode: false
7883
7915
  };
7884
7916
  console.log("[Transport] Capabilities:", this.capabilities);
@@ -7889,7 +7921,7 @@ var TransportManager = class {
7889
7921
  *
7890
7922
  * Promotion hierarchy:
7891
7923
  * 1. window.multicast gateway bytes
7892
- * 2. AMT proxy (specified or discovered via DRIAD)
7924
+ * 2. AMT: a configured relay via the AMT proxy, else gateway DRIAD discovery
7893
7925
  * 3. MOQ WebTransport (final fallback)
7894
7926
  *
7895
7927
  * The ABR ladder (`abrLadder`) and initial rendition (`initialQuality`)
@@ -7983,7 +8015,7 @@ var TransportManager = class {
7983
8015
  /**
7984
8016
  * Connect via the lowercase window.multicast bytes gateway.
7985
8017
  */
7986
- async connectWindowMulticast(config, generation) {
8018
+ async connectWindowMulticast(config, generation, mode = "multicast") {
7987
8019
  try {
7988
8020
  const gateway = this.getWindowMulticastGateway();
7989
8021
  if (typeof gateway?.subscribe !== "function")
@@ -8018,7 +8050,7 @@ var TransportManager = class {
8018
8050
  }
8019
8051
  };
8020
8052
  this.state = {
8021
- mode: "multicast",
8053
+ mode,
8022
8054
  connected: true,
8023
8055
  group: config.group,
8024
8056
  source: config.source,
@@ -8036,29 +8068,19 @@ var TransportManager = class {
8036
8068
  }
8037
8069
  }
8038
8070
  /**
8039
- * Connect via AMT proxy (with optional DRIAD discovery)
8071
+ * Connect via AMT: a configured relay goes through the AMT proxy; with no
8072
+ * relay, the window.multicast gateway discovers one per RFC 8777 (DRIAD).
8040
8073
  */
8041
8074
  async connectAmt(config, generation) {
8042
8075
  try {
8043
- let amtRelay = config.amtRelay;
8044
- if (!amtRelay && config.driadEnabled !== false && config.source) {
8045
- console.log(`[Transport] Discovering AMT relay via DRIAD for source ${config.source}...`);
8046
- const relays = await this.driad.discoverRelays(config.source);
8047
- if (generation !== this.connectionGeneration)
8048
- return false;
8049
- const bestRelay = await this.driad.selectBestRelay(relays);
8050
- if (generation !== this.connectionGeneration)
8051
- return false;
8052
- if (bestRelay) {
8053
- amtRelay = bestRelay.host;
8054
- this.state.amtRelay = amtRelay;
8055
- }
8056
- }
8057
- if (!amtRelay) {
8076
+ if (config.amtRelay)
8077
+ return await this.connectAmtProxy(config, config.amtRelay, generation);
8078
+ if (config.driadEnabled === false || !config.source || config.mode === "native") {
8058
8079
  console.warn("[Transport] No AMT relay available (DRIAD requires source address for SSM)");
8059
8080
  return false;
8060
8081
  }
8061
- return await this.connectAmtProxy(config, amtRelay, generation);
8082
+ console.log(`[Transport] Asking the gateway for a DRIAD relay for source ${config.source}...`);
8083
+ return await this.connectWindowMulticast({ ...config, amtDiscovery: "driad" }, generation, "amt");
8062
8084
  } catch (error) {
8063
8085
  console.warn("[Transport] AMT connection failed:", error);
8064
8086
  return false;
@@ -8289,7 +8311,6 @@ var AMTGatewayManager = class {
8289
8311
  subscriptions = /* @__PURE__ */ new Map();
8290
8312
  messageHandler;
8291
8313
  pendingPackets = /* @__PURE__ */ new Map();
8292
- driad = new DRIADDiscovery();
8293
8314
  constructor() {
8294
8315
  this.messageHandler = (event) => {
8295
8316
  const data = event.data;
@@ -8320,26 +8341,12 @@ var AMTGatewayManager = class {
8320
8341
  return keyStr;
8321
8342
  }
8322
8343
  try {
8323
- let relayAddress;
8324
- let discoveryMethod;
8344
+ const relayAddress = config.relayAddress;
8325
8345
  const relayPort = config.relayPort || DEFAULT_AMT_RELAY_PORT2;
8326
- if (config.relayAddress) {
8327
- relayAddress = config.relayAddress;
8328
- discoveryMethod = "manual";
8329
- console.log(`[AMT] Using configured relay ${relayAddress}:${relayPort}`);
8330
- } else if (key.source) {
8331
- console.log(`[AMT] No relay configured, discovering via DRIAD for source ${key.source}...`);
8332
- const relays = await this.driad.discoverRelays(key.source);
8333
- const bestRelay = await this.driad.selectBestRelay(relays);
8334
- if (!bestRelay) {
8335
- throw new Error(`AMT relay discovery failed for source ${key.source}. Please specify a relay address in the subscription configuration.`);
8336
- }
8337
- relayAddress = bestRelay.host;
8338
- discoveryMethod = "driad";
8339
- console.log(`[AMT] Discovered relay via DRIAD: ${relayAddress}:${relayPort}`);
8340
- } else {
8341
- throw new Error(`AMT relay discovery requires a source address for SSM (RFC 8777). Please specify either a relay address or source address.`);
8346
+ if (!relayAddress) {
8347
+ throw new Error(`AMT relay address required: this manager does no relay discovery. For RFC 8777 DRIAD discovery, join through window.multicast with amtDiscovery: "driad".`);
8342
8348
  }
8349
+ console.log(`[AMT] Using configured relay ${relayAddress}:${relayPort}`);
8343
8350
  const subscriptionId = keyStr;
8344
8351
  this.pendingPackets.set(subscriptionId, []);
8345
8352
  const subscription = {
@@ -8350,7 +8357,7 @@ var AMTGatewayManager = class {
8350
8357
  relay: {
8351
8358
  address: relayAddress,
8352
8359
  port: relayPort,
8353
- discoveryMethod,
8360
+ discoveryMethod: "manual",
8354
8361
  discoveredAt: Date.now()
8355
8362
  }
8356
8363
  };
@@ -8825,25 +8832,20 @@ function multicastFromConfig(input) {
8825
8832
  );
8826
8833
  }
8827
8834
  }
8828
- const seenTuples = /* @__PURE__ */ new Set();
8829
- const endpoints = input.endpoints.map((ep, idx) => validateEndpoint2(ep, idx, seenTuples));
8835
+ const endpoints = input.endpoints.map((ep, idx) => validateEndpoint2(ep, idx));
8830
8836
  const out = { endpoints };
8831
8837
  const { entries: networkSource, relayFrom } = resolveNetworkSource(input);
8832
8838
  networkSource.forEach(validateNetworkSourceEntry);
8833
8839
  if (networkSource.length > 0) out.networkSource = networkSource;
8834
8840
  const amtRelays = new Set(
8835
- networkSource.flatMap((s) => s.type === "amt" && s.discovery !== "driad" && s.relay?.trim() ? [s.relay.trim()] : []).slice(0, 1)
8841
+ networkSource.flatMap((s) => s.type === "amt" && s.relay?.trim() ? [s.relay.trim()] : []).slice(0, 1)
8836
8842
  );
8837
8843
  input.endpoints.forEach((ep, idx) => {
8838
8844
  const relay = ep.relayAddress?.trim();
8839
8845
  if (!relay || amtRelays.has(relay)) return;
8840
- const demoted = networkSource.some(
8841
- (s) => s.type === "amt" && s.discovery === "driad" && s.relay?.trim() === relay
8842
- );
8843
8846
  const shadowed = networkSource.some(
8844
- (s) => s.type === "amt" && s.discovery !== "driad" && s.relay?.trim() === relay
8847
+ (s) => s.type === "amt" && s.relay?.trim() === relay
8845
8848
  );
8846
- const derived = input.networkSource === void 0;
8847
8849
  const fromAmtFallback = ", derived from amtFallback/MOQCAST_MULTICAST_AMT_*";
8848
8850
  const fromRelay = relayFrom === "amtFallback.relayDns" ? fromAmtFallback : relayFrom === "endpoint.relayAddress" ? ", derived from the endpoint relayAddress values" : "";
8849
8851
  const relayDns = input.amtFallback?.relayDns?.trim();
@@ -8851,7 +8853,7 @@ function multicastFromConfig(input) {
8851
8853
  throw new MulticastInputError(
8852
8854
  "conflicting_amt_relay",
8853
8855
  idx,
8854
- `endpoint[${idx}] relayAddress ${JSON.stringify(relay)} ` + (demoted ? `is carried only by a multicast.networkSource AMT entry with discovery="driad"${derived ? fromAmtFallback : ""}, whose relay is a DRIAD discovery hint that both readers skip, so the catalog names no relay to join; to join it, add a manual entry beside the driad one: [{type:"amt",discovery:"manual",relay:${JSON.stringify(relay)}},{type:"amt",discovery:"driad"}]` : shadowed ? `is carried by a multicast.networkSource AMT entry that is not the first one: both readers join the first AMT entry (${[...amtRelays].join(", ")}) and ignore the rest, so this relay is never joined; keep a single AMT entry, or put this one first` : `is not the relay of any multicast.networkSource AMT entry (${[...amtRelays].join(", ") || "none"})${fromRelay}; ` + (outranked ? `amtFallback.relayDns/MOQCAST_MULTICAST_AMT_RELAY_DNS (${relayDns}) outranks an endpoint relay when networkSource is derived -- drop one, or make them agree` : "networkSource is catalog-level and cannot represent per-endpoint relays"))
8856
+ `endpoint[${idx}] relayAddress ${JSON.stringify(relay)} ` + (shadowed ? `is carried by a multicast.networkSource AMT entry that is not the first one: both readers join the first AMT entry (${[...amtRelays].join(", ")}) and ignore the rest, so this relay is never joined; keep a single AMT entry, or put this one first` : `is not the relay of any multicast.networkSource AMT entry (${[...amtRelays].join(", ") || "none"})${fromRelay}; ` + (outranked ? `amtFallback.relayDns/MOQCAST_MULTICAST_AMT_RELAY_DNS (${relayDns}) outranks an endpoint relay when networkSource is derived -- drop one, or make them agree` : "networkSource is catalog-level and cannot represent per-endpoint relays"))
8855
8857
  );
8856
8858
  });
8857
8859
  input.endpoints.forEach((ep, idx) => {
@@ -8860,9 +8862,20 @@ function multicastFromConfig(input) {
8860
8862
  throw new MulticastInputError(
8861
8863
  ep.protocol === "amt" ? "amt_requires_relay" : "atsc3_requires_tuning",
8862
8864
  idx,
8863
- `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" : "")
8865
+ `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" : "")
8864
8866
  );
8865
8867
  });
8868
+ input.endpoints.forEach((ep, idx) => {
8869
+ if (ep.protocol !== "amt" && ep.protocol !== "atsc3") return;
8870
+ endpoints[idx].networkSource = networkSource.filter((s) => s.type === ep.protocol).map((s) => ({ ...s }));
8871
+ });
8872
+ if (input.auth !== void 0) out.auth = input.auth;
8873
+ const [issue] = multicastCatalogIssues({ multicast: out });
8874
+ if (issue) {
8875
+ 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";
8876
+ const where = issue.endpointIndex === void 0 ? "" : `endpoint[${issue.endpointIndex}] `;
8877
+ throw new MulticastInputError(kind, issue.endpointIndex ?? null, `${where}${issue.path.replace("$.multicast.", "")}: ${issue.message}`);
8878
+ }
8866
8879
  if (input.enabled !== void 0) out.enabled = input.enabled;
8867
8880
  if (input.version !== void 0) out.version = input.version;
8868
8881
  if (input.validUntil !== void 0) out.validUntil = input.validUntil;
@@ -8874,10 +8887,10 @@ function resolveNetworkSource(input) {
8874
8887
  }
8875
8888
  const relayDns = input.amtFallback?.relayDns?.trim();
8876
8889
  const relay = relayDns || input.endpoints.map((ep) => ep.relayAddress?.trim()).find((r) => !!r);
8877
- const discovery = input.amtFallback?.discovery ?? (relay ? "manual" : void 0);
8878
- if (discovery === void 0) return { entries: [], relayFrom: null };
8890
+ const discovery = input.amtFallback?.discovery;
8891
+ if (discovery === void 0 && !relay) return { entries: [], relayFrom: null };
8879
8892
  return {
8880
- entries: [{ type: "amt", discovery, ...relay ? { relay } : {} }],
8893
+ entries: [{ type: "amt", ...discovery ? { discovery } : {}, ...relay ? { relay } : {} }],
8881
8894
  relayFrom: !relay ? null : relayDns ? "amtFallback.relayDns" : "endpoint.relayAddress"
8882
8895
  };
8883
8896
  }
@@ -8890,8 +8903,11 @@ function validateNetworkSourceEntry(s, i) {
8890
8903
  const extra = Object.keys(s).filter((k) => !keys.has(k) && s[k] !== void 0);
8891
8904
  if (extra.length > 0) throw err("invalid_network_source", `has keys the schema rejects: ${extra.join(", ")}`);
8892
8905
  if (s.type === "amt") {
8893
- if (s.discovery !== "driad" && s.discovery !== "manual") {
8894
- throw err("invalid_amt_discovery", `discovery must be "driad" or "manual"; got ${JSON.stringify(s.discovery)}`);
8906
+ if (s.discovery !== void 0 && s.discovery !== "dns" && s.discovery !== "driad" && s.discovery !== "manual") {
8907
+ throw err(
8908
+ "invalid_amt_discovery",
8909
+ `discovery must be "dns", "driad" or "manual" when present; got ${JSON.stringify(s.discovery)}`
8910
+ );
8895
8911
  }
8896
8912
  if (s.relay !== void 0) {
8897
8913
  const relay = typeof s.relay === "string" ? s.relay.trim() : "";
@@ -8900,8 +8916,14 @@ function validateNetworkSourceEntry(s, i) {
8900
8916
  }
8901
8917
  s.relay = relay;
8902
8918
  }
8903
- if (s.discovery === "manual" && s.relay === void 0) {
8904
- throw err("amt_requires_relay", `discovery="manual" requires a relay ("driad" resolves it at runtime)`);
8919
+ if ((s.discovery === "dns" || s.discovery === "manual") && s.relay === void 0) {
8920
+ throw err("amt_requires_relay", `discovery="${s.discovery}" requires a relay ("driad" resolves it at runtime)`);
8921
+ }
8922
+ if (s.discovery === "driad" && s.relay !== void 0) {
8923
+ throw err(
8924
+ "invalid_network_source",
8925
+ `discovery="driad" must omit relay: DRIAD supplies the relay candidates (draft -01 4.2.1); drop the relay (amtFallback.relayDns / endpoint relayAddress on the derived path), or use "dns" or "manual"`
8926
+ );
8905
8927
  }
8906
8928
  if (s.port !== void 0 && (!Number.isInteger(s.port) || s.port < 1 || s.port > 65535)) {
8907
8929
  throw err("invalid_port", `port must be 1..65535; got ${s.port}`);
@@ -8910,13 +8932,15 @@ function validateNetworkSourceEntry(s, i) {
8910
8932
  }
8911
8933
  const inRange = (v, min, max) => Number.isInteger(v) && v >= min && v <= max;
8912
8934
  if (!inRange(s.frequency, 1, Number.MAX_SAFE_INTEGER)) {
8913
- throw err("invalid_network_source", `frequency must be a positive integer; got ${s.frequency}`);
8935
+ throw err("invalid_network_source", `frequency must be a positive integer in kHz; got ${s.frequency}`);
8914
8936
  }
8915
- if (!inRange(s.plpId, 0, 63)) throw err("invalid_network_source", `plpId must be 0..63; got ${s.plpId}`);
8916
- if (!inRange(s.serviceId, 0, 65535)) {
8937
+ if (s.plpId !== void 0 && !inRange(s.plpId, 0, 63)) {
8938
+ throw err("invalid_network_source", `plpId must be 0..63; got ${s.plpId}`);
8939
+ }
8940
+ if (s.serviceId !== void 0 && !inRange(s.serviceId, 0, 65535)) {
8917
8941
  throw err("invalid_network_source", `serviceId must be 0..65535; got ${s.serviceId}`);
8918
8942
  }
8919
- if (typeof s.slsUri !== "string" || !isAbsoluteUri(s.slsUri)) {
8943
+ if (s.slsUri !== void 0 && (typeof s.slsUri !== "string" || !isAbsoluteUri(s.slsUri))) {
8920
8944
  throw err("invalid_network_source", `slsUri must be an absolute URI; got ${JSON.stringify(s.slsUri)}`);
8921
8945
  }
8922
8946
  }
@@ -8928,7 +8952,7 @@ function isAbsoluteUri(value) {
8928
8952
  return false;
8929
8953
  }
8930
8954
  }
8931
- function validateEndpoint2(ep, idx, seenTuples) {
8955
+ function validateEndpoint2(ep, idx) {
8932
8956
  if (ep.protocol === "ssm" && (!ep.sourceAddress || ep.sourceAddress.length === 0)) {
8933
8957
  throw new MulticastInputError(
8934
8958
  "ssm_requires_source",
@@ -8936,6 +8960,13 @@ function validateEndpoint2(ep, idx, seenTuples) {
8936
8960
  `endpoint[${idx}] protocol=ssm requires sourceAddress`
8937
8961
  );
8938
8962
  }
8963
+ if (ep.protocol === "asm" && ep.sourceAddress !== void 0) {
8964
+ throw new MulticastInputError(
8965
+ "protocol_source_mismatch",
8966
+ idx,
8967
+ `endpoint[${idx}] protocol=asm with sourceAddress "${ep.sourceAddress}"; sourceAddress selects SSM (draft -01 4.1)`
8968
+ );
8969
+ }
8939
8970
  if (!isMulticastGroupAddress(ep.groupAddress)) {
8940
8971
  throw new MulticastInputError(
8941
8972
  "invalid_group_address",
@@ -8995,23 +9026,15 @@ function validateEndpoint2(ep, idx, seenTuples) {
8995
9026
  `endpoint[${idx}] bandwidth must be positive; got ${ep.bandwidth}`
8996
9027
  );
8997
9028
  }
8998
- const tupleKey = `${ep.sourceAddress ?? ""}|${ep.groupAddress}|${ep.port}`;
8999
- if (seenTuples.has(tupleKey)) {
9000
- throw new MulticastInputError(
9001
- "duplicate_endpoint_tuple",
9002
- idx,
9003
- `endpoint[${idx}] duplicates (sourceAddress, groupAddress, port) tuple "${tupleKey}"`
9004
- );
9005
- }
9006
- seenTuples.add(tupleKey);
9007
9029
  const out = {
9008
- protocol: ep.protocol,
9030
+ protocol: ep.sourceAddress === void 0 ? "asm" : "ssm",
9009
9031
  groupAddress: ep.groupAddress,
9010
9032
  port: ep.port,
9011
9033
  tracks: ep.tracks.map((t) => ({ name: t.name, packetId: t.packetId }))
9012
9034
  };
9013
9035
  if (ep.sourceAddress !== void 0) out.sourceAddress = ep.sourceAddress;
9014
9036
  if (ep.bandwidth !== void 0) out.bandwidth = ep.bandwidth;
9037
+ if (ep.auth !== void 0) out.auth = { ...ep.auth };
9015
9038
  return out;
9016
9039
  }
9017
9040
  function isMulticastGroupAddress(addr) {
@@ -9054,9 +9077,9 @@ function multicastFromEnv(env = globalThis.process?.env ?? {}) {
9054
9077
  endpoints,
9055
9078
  ...hasCatalogAmt ? {
9056
9079
  amtFallback: {
9057
- // `"manual"` mirrors `resolveNetworkSource`: a relay named in
9058
- // the catalog is, by definition, not discovered.
9059
- discovery: amtDiscovery ?? "manual",
9080
+ // No default: an omitted discovery with a relay hostname is
9081
+ // "dns" (draft-ramadan-moq-multicast-01 4.2.1).
9082
+ ...amtDiscovery ? { discovery: amtDiscovery } : {},
9060
9083
  ...amtRelayDns ? { relayDns: amtRelayDns } : {}
9061
9084
  }
9062
9085
  } : {}
@@ -9224,7 +9247,7 @@ function mergeOverrideIntoCmsfTracks(tracks, override) {
9224
9247
  if (ot.role !== void 0 && existing.role === void 0) existing.role = ot.role;
9225
9248
  if (existing.packaging === "mmtp") {
9226
9249
  const mode = existing.mmtpMode ?? ot.mmtpMode;
9227
- if (mode !== "mpu" && mode !== "mfu") {
9250
+ if (mode !== "mfu") {
9228
9251
  throw new Error(
9229
9252
  `[phase14-catalog-override] track "${ot.name}" has packaging='mmtp' but no valid mmtpMode`
9230
9253
  );
@@ -9261,7 +9284,7 @@ function mergeOverrideIntoCmsfTracks(tracks, override) {
9261
9284
  );
9262
9285
  }
9263
9286
  const mmtpMode = ot.mmtpMode;
9264
- if (packaging === "mmtp" && mmtpMode !== "mpu" && mmtpMode !== "mfu") {
9287
+ if (packaging === "mmtp" && mmtpMode !== "mfu") {
9265
9288
  throw new Error(
9266
9289
  `[phase14-catalog-override] track "${ot.name}" has packaging='mmtp' but no valid mmtpMode`
9267
9290
  );
@@ -9562,8 +9585,8 @@ function u32(v) {
9562
9585
  }
9563
9586
  var KEYFRAME_FLAGS = 33554432;
9564
9587
  var DELTA_FLAGS = 16842752;
9565
- var UINT32_MAX = 4294967295;
9566
- var MAX_TRACK_ID = UINT32_MAX - 1;
9588
+ var UINT32_MAX2 = 4294967295;
9589
+ var MAX_TRACK_ID = UINT32_MAX2 - 1;
9567
9590
  var INT32_MIN = -2147483648;
9568
9591
  var INT32_MAX = 2147483647;
9569
9592
  function assertTrackId(trackId, label) {
@@ -9572,8 +9595,8 @@ function assertTrackId(trackId, label) {
9572
9595
  }
9573
9596
  }
9574
9597
  function assertTimescale(timescale, label) {
9575
- if (!Number.isInteger(timescale) || timescale <= 0 || timescale > UINT32_MAX) {
9576
- throw new RangeError(`${label} must be an integer in 1..${UINT32_MAX}, got ${timescale}`);
9598
+ if (!Number.isInteger(timescale) || timescale <= 0 || timescale > UINT32_MAX2) {
9599
+ throw new RangeError(`${label} must be an integer in 1..${UINT32_MAX2}, got ${timescale}`);
9577
9600
  }
9578
9601
  }
9579
9602
  function assertCompositionTimeOffsets(samples) {
@@ -12406,16 +12429,6 @@ var DeliveryGapEstimator = class {
12406
12429
 
12407
12430
  // src/iso-block-locator.ts
12408
12431
  var IsoBlockLocator = class _IsoBlockLocator {
12409
- /** Known blocks and spans, in serial order of their start. */
12410
- #blocks = [];
12411
- /** Held first-arrival sources whose block no repair has stated yet. */
12412
- #held = /* @__PURE__ */ new Map();
12413
- /** End of contiguous coverage: the SS_ID the next unknown block starts at. */
12414
- #coverageEnd;
12415
- #kMax;
12416
- #retentionBlocks;
12417
- #heldEvicted = 0;
12418
- #newest;
12419
12432
  /**
12420
12433
  * @param kMax the catalog maximum K (`sourceSymbols`), the bound on SSB_length.
12421
12434
  * @param retentionBlocks how many blocks behind the newest position the
@@ -12423,12 +12436,35 @@ var IsoBlockLocator = class _IsoBlockLocator {
12423
12436
  * no locator exists without retention.
12424
12437
  */
12425
12438
  constructor(kMax, retentionBlocks) {
12439
+ /** Known blocks and spans, in serial order of their start. */
12440
+ this.#blocks = [];
12441
+ /** Held first-arrival sources whose block no repair has stated yet. */
12442
+ this.#held = /* @__PURE__ */ new Map();
12443
+ this.#heldEvicted = 0;
12444
+ /** Pending holes (see `deferIncompleteGaps`): unstated, sources still held. */
12445
+ this.#holes = [];
12446
+ /**
12447
+ * Keep a gap that is missing a source as a pending hole rather than a span,
12448
+ * so a repair FETCHed for it (draft-ramadan-moq-fec §7.5) can still state
12449
+ * its blocks. Set only while a range repair scheduler is wired; its owner
12450
+ * must close every hole it is told about (`closeHolesWithin`).
12451
+ */
12452
+ this.deferIncompleteGaps = false;
12426
12453
  if (!Number.isSafeInteger(kMax) || kMax <= 0) {
12427
12454
  throw new Error(`[IsoBlockLocator] maximum K must be a positive integer (got ${kMax})`);
12428
12455
  }
12429
12456
  this.#kMax = kMax;
12430
12457
  this.#retentionBlocks = _IsoBlockLocator.#checkedRetention(retentionBlocks);
12431
12458
  }
12459
+ #blocks;
12460
+ #held;
12461
+ /** End of contiguous coverage: the SS_ID the next unknown block starts at. */
12462
+ #coverageEnd;
12463
+ #kMax;
12464
+ #retentionBlocks;
12465
+ #heldEvicted;
12466
+ #newest;
12467
+ #holes;
12432
12468
  static #checkedRetention(retentionBlocks) {
12433
12469
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
12434
12470
  throw new Error(
@@ -12491,6 +12527,14 @@ var IsoBlockLocator = class _IsoBlockLocator {
12491
12527
  }
12492
12528
  return null;
12493
12529
  }
12530
+ /** Number of pending holes. */
12531
+ get holeCount() {
12532
+ return this.#holes.length;
12533
+ }
12534
+ /** The stated block (never a span) ending exactly at `end`. */
12535
+ blockEndingAt(end) {
12536
+ return this.#blocks.find((block) => !block.span && isoBlockEnd(block.start, block.length) === end);
12537
+ }
12494
12538
  /** The known block or span starting exactly at `start`. */
12495
12539
  blockAt(start) {
12496
12540
  return this.#blocks.find((block) => block.start === start);
@@ -12513,6 +12557,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
12513
12557
  coversBetween(a, b) {
12514
12558
  if (this.#coverageEnd === void 0) return false;
12515
12559
  if (!serial32Precedes(a, b) || serial32Distance(a, b) <= 1) return true;
12560
+ const first = a + 1 >>> 0;
12561
+ const count = serial32Distance(a, b) - 1;
12562
+ if (this.#holes.some((hole) => isoRangesOverlap(first, count, hole.start, hole.length))) return false;
12516
12563
  return serial32Precedes(b - 1 >>> 0, this.#coverageEnd);
12517
12564
  }
12518
12565
  /**
@@ -12542,6 +12589,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
12542
12589
  * known block (a different length, or an overlap with another block or a
12543
12590
  * span) fails closed: the repair symbol is dropped and no block changes.
12544
12591
  * A newly stated block retires behind its SS_Start (see the class note).
12592
+ * A block so far past `newest` that stating it would retire the position
12593
+ * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
12594
+ * this is slightly conservative (retirement measures that block from its
12595
+ * last SS_ID), dropping up to one block-length of repairs past the horizon
12596
+ * until a source moves `newest`. Placing it would turn everything
12597
+ * between into a repair-less span and leave every real repair behind it
12598
+ * `stale`. Sources move `newest` (`hold`, `observe`), so after a real outage
12599
+ * the first source back brings the next repair inside the horizon; until one
12600
+ * arrives, a stream's repairs alone cannot pass it.
12545
12601
  */
12546
12602
  placeRepair(start, length) {
12547
12603
  if (!Number.isSafeInteger(length) || length <= 0 || length > this.#kMax) {
@@ -12560,6 +12616,22 @@ var IsoBlockLocator = class _IsoBlockLocator {
12560
12616
  }
12561
12617
  return { status: "placed", block: known, placed: [] };
12562
12618
  }
12619
+ const pending = this.#holes.find((h) => isoBlockContains(h.start, h.length, start));
12620
+ if (pending !== void 0) {
12621
+ if (!isoBlockContains(pending.start, pending.length, serial32Add(start, length - 1))) {
12622
+ return { status: "overlap", reason: `repair block ${start}+${length} runs past pending hole ${pending.start}+${pending.length}` };
12623
+ }
12624
+ this.#holes.splice(this.#holes.indexOf(pending), 1);
12625
+ const before = serial32Distance(pending.start, start);
12626
+ const afterStart = isoBlockEnd(start, length);
12627
+ const after = pending.length - before - length;
12628
+ if (before > 0) this.#holes.push({ start: pending.start, length: before, span: false });
12629
+ if (after > 0) this.#holes.push({ start: afterStart, length: after, span: false });
12630
+ const block2 = { start, length, span: false };
12631
+ const placed2 = this.#claim(block2);
12632
+ this.#blocks.push(block2);
12633
+ return { status: "placed", block: block2, placed: placed2 };
12634
+ }
12563
12635
  for (const block2 of this.#blocks) {
12564
12636
  if (isoBlockContains(block2.start, block2.length, start) || isoBlockContains(start, length, block2.start)) {
12565
12637
  return {
@@ -12568,7 +12640,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
12568
12640
  };
12569
12641
  }
12570
12642
  }
12643
+ if (this.#newest !== void 0 && isoBlocksBehindLowerBound(this.#newest, start, this.#kMax) > this.#retentionBlocks) {
12644
+ return { status: "ahead", reason: `repair block ${start}+${length} is past the retention horizon ahead of ${this.#newest}` };
12645
+ }
12571
12646
  let span;
12647
+ let hole;
12572
12648
  if (this.#coverageEnd === void 0) {
12573
12649
  for (const ssId of this.#held.keys()) {
12574
12650
  if (serial32Precedes(ssId, start)) this.#held.delete(ssId);
@@ -12577,21 +12653,51 @@ var IsoBlockLocator = class _IsoBlockLocator {
12577
12653
  } else if (serial32Precedes(start, this.#coverageEnd)) {
12578
12654
  return { status: "stale", reason: `repair block ${start}+${length} precedes known coverage` };
12579
12655
  } else if (start !== this.#coverageEnd) {
12580
- const spanBlock = {
12581
- start: this.#coverageEnd,
12582
- length: serial32Distance(this.#coverageEnd, start),
12583
- span: true
12584
- };
12585
- span = { block: spanBlock, placed: this.#claim(spanBlock) };
12586
- this.#blocks.push(spanBlock);
12656
+ const gap = { start: this.#coverageEnd, length: serial32Distance(this.#coverageEnd, start) };
12657
+ const lostSsId = this.deferIncompleteGaps ? this.#highestMissing(gap.start, gap.length) : void 0;
12658
+ if (lostSsId !== void 0) {
12659
+ const holeBlock = { ...gap, span: false };
12660
+ this.#holes.push(holeBlock);
12661
+ hole = { block: holeBlock, lostSsId };
12662
+ } else {
12663
+ const spanBlock = { ...gap, span: true };
12664
+ span = { block: spanBlock, placed: this.#claim(spanBlock) };
12665
+ this.#blocks.push(spanBlock);
12666
+ }
12587
12667
  }
12588
12668
  const block = { start, length, span: false };
12589
12669
  const placed = this.#claim(block);
12590
12670
  this.#blocks.push(block);
12591
12671
  this.#coverageEnd = isoBlockEnd(start, length);
12592
12672
  this.retireBehind(start);
12673
+ if (hole !== void 0) return { status: "placed", block, placed, hole };
12593
12674
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
12594
12675
  }
12676
+ /**
12677
+ * Turn every pending hole inside `[start, start + length)` into a
12678
+ * repair-less span, claiming its held sources: its range FETCH ended, so
12679
+ * nothing more will state its blocks. Returns the spans, in SS_ID order.
12680
+ */
12681
+ closeHolesWithin(start, length) {
12682
+ const closed = [];
12683
+ for (const hole of [...this.#holes]) {
12684
+ if (!isoBlockContains(start, length, hole.start)) continue;
12685
+ this.#holes.splice(this.#holes.indexOf(hole), 1);
12686
+ const spanBlock = { start: hole.start, length: hole.length, span: true };
12687
+ closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
12688
+ this.#blocks.push(spanBlock);
12689
+ }
12690
+ return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
12691
+ }
12692
+ /** The highest SS_ID in the range no source is held for, or undefined when all are. */
12693
+ #highestMissing(start, length) {
12694
+ const steps = Math.min(length, this.#held.size + 1);
12695
+ for (let i = 1; i <= steps; i++) {
12696
+ const ssId = serial32Add(start, length - i);
12697
+ if (!this.#held.has(ssId)) return ssId;
12698
+ }
12699
+ return void 0;
12700
+ }
12595
12701
  /**
12596
12702
  * Retire every block and span whose last SS_ID, and every held source,
12597
12703
  * lies more than `retentionBlocks` blocks behind `position`, with the shared
@@ -12610,6 +12716,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
12610
12716
  this.#blocks.splice(i, 1);
12611
12717
  }
12612
12718
  }
12719
+ for (let i = this.#holes.length - 1; i >= 0; i--) {
12720
+ const hole = this.#holes[i];
12721
+ const last = serial32Add(hole.start, hole.length - 1);
12722
+ if (isoBlocksBehindLowerBound(last, position, this.#kMax) > horizon) this.#holes.splice(i, 1);
12723
+ }
12613
12724
  for (const ssId of [...this.#held.keys()]) {
12614
12725
  if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon) this.#held.delete(ssId);
12615
12726
  }
@@ -12618,6 +12729,7 @@ var IsoBlockLocator = class _IsoBlockLocator {
12618
12729
  /** Forget everything (publisher restart, track reset). */
12619
12730
  reset() {
12620
12731
  this.#blocks.length = 0;
12732
+ this.#holes.length = 0;
12621
12733
  this.#held.clear();
12622
12734
  this.#coverageEnd = void 0;
12623
12735
  this.#newest = void 0;
@@ -12633,6 +12745,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
12633
12745
  return placed;
12634
12746
  }
12635
12747
  };
12748
+ function isoRangesOverlap(aStart, aLength, bStart, bLength) {
12749
+ return serial32Distance(aStart, bStart) < aLength || serial32Distance(bStart, aStart) < bLength;
12750
+ }
12636
12751
 
12637
12752
  // src/fec-state.ts
12638
12753
  var MIN_INTERLEAVE_DEPTH_MS = 1;
@@ -12655,8 +12770,8 @@ function isPositiveSafeInteger2(value) {
12655
12770
  }
12656
12771
  function catalogDeclaresFec(fec) {
12657
12772
  const block = recordOf2(fec);
12658
- if (block === void 0 || block["algorithm"] === "none") return false;
12659
- return isPositiveSafeInteger2(block["sourceSymbols"]) && isPositiveSafeInteger2(block["symbolSize"]) && isFecBlockProfile(block["blockProfile"]) && isoBlockSpanUsable(block);
12773
+ if (block === void 0 || block["algorithm"] === "none" || fecAlgorithmUnimplemented(block["algorithm"])) return false;
12774
+ return isPositiveSafeInteger2(block["sourceSymbols"]) && isPositiveSafeInteger2(block["symbolSize"]) && isFecBlockProfile(block["blockProfile"]) && isoBlockSpanUsable(block) && !catalogFecDeclaresUnconfigurableInstance(block);
12660
12775
  }
12661
12776
  function requireBoolean(value, field) {
12662
12777
  if (typeof value !== "boolean") {
@@ -13142,7 +13257,81 @@ function decideGap(input) {
13142
13257
  });
13143
13258
  }
13144
13259
 
13260
+ // src/held-layer-admission.ts
13261
+ var HORIZON_CAP = 1073741824;
13262
+ function heldLayerAnchorHorizon(retentionBlocks, k) {
13263
+ return retentionBlocks === void 0 || k <= 0 ? HORIZON_CAP : Math.min(HORIZON_CAP, retentionBlocks * k);
13264
+ }
13265
+ var HeldLayerAdmission = class {
13266
+ #layerNames;
13267
+ #states;
13268
+ constructor(layers, heldLayers = [0]) {
13269
+ const held = new Set(heldLayers);
13270
+ this.#layerNames = new Set(layers.map((l) => l.repairTrackName));
13271
+ this.#states = layers.filter((l) => held.has(l.layer)).map((l) => ({ layer: l.layer, repairTrackName: l.repairTrackName, total: l.rsIdOffset + l.repairSymbols }));
13272
+ }
13273
+ /**
13274
+ * Judges one repair packet, after the 4.5 discards and the size check and
13275
+ * before it places a block. `repairTrackName` is the subscribed repair
13276
+ * track, never inferred from RS_ID; without it only (b) runs. A packet on a
13277
+ * repair track the catalog does not list is `'discard'` and anchors nothing.
13278
+ * `sourceFrontier` is the newest source SS_ID, if any: a repair more than
13279
+ * `horizon` past it is judged without moving the anchored state.
13280
+ *
13281
+ * @returns undefined to admit, `'discard'`, or the fail-closed reason.
13282
+ */
13283
+ admit(repairTrackName, ssStart, rsbLength, horizon, sourceFrontier) {
13284
+ if (repairTrackName !== void 0 && !this.#layerNames.has(repairTrackName)) return "discard";
13285
+ const farAhead = sourceFrontier !== void 0 && serial32Precedes(sourceFrontier, ssStart) && serial32Distance(sourceFrontier, ssStart) > horizon;
13286
+ for (const state of this.#states) {
13287
+ let code;
13288
+ if (farAhead) {
13289
+ if (rsbLength < state.total) {
13290
+ if (state.layer > 0 && repairTrackName === state.repairTrackName) code = "below_own_track_total";
13291
+ else if (state.anchor !== void 0 || state.settled) code = "below_anchored_total";
13292
+ }
13293
+ } else {
13294
+ if (state.newest === void 0 || serial32Precedes(state.newest, ssStart)) state.newest = ssStart;
13295
+ const stale = (s) => serial32Distance(s, state.newest) > horizon;
13296
+ if (state.latestBelow !== void 0 && stale(state.latestBelow)) {
13297
+ delete state.latestBelow;
13298
+ delete state.latestBelowRsb;
13299
+ }
13300
+ if (state.anchor !== void 0 && stale(state.anchor)) state.settled = true;
13301
+ if (rsbLength < state.total) {
13302
+ if (state.layer > 0 && repairTrackName === state.repairTrackName) code = "below_own_track_total";
13303
+ else if (stale(ssStart)) continue;
13304
+ else if (state.settled || state.anchor !== void 0 && !serial32Precedes(ssStart, state.anchor)) code = "below_anchored_total";
13305
+ else if (state.latestBelow === void 0 || serial32Precedes(state.latestBelow, ssStart)) {
13306
+ state.latestBelow = ssStart;
13307
+ state.latestBelowRsb = rsbLength;
13308
+ }
13309
+ } else if (!state.settled && !stale(ssStart)) {
13310
+ if (state.anchor === void 0 || serial32Precedes(ssStart, state.anchor)) state.anchor = ssStart;
13311
+ if (state.latestBelow !== void 0 && !serial32Precedes(state.latestBelow, state.anchor)) {
13312
+ code = "below_anchored_total";
13313
+ ssStart = state.latestBelow;
13314
+ rsbLength = state.latestBelowRsb;
13315
+ }
13316
+ }
13317
+ }
13318
+ if (code !== void 0) {
13319
+ return {
13320
+ code,
13321
+ layer: state.layer,
13322
+ total: state.total,
13323
+ rsbLength,
13324
+ ssStart,
13325
+ ...state.anchor === void 0 ? {} : { anchor: state.anchor }
13326
+ };
13327
+ }
13328
+ }
13329
+ return void 0;
13330
+ }
13331
+ };
13332
+
13145
13333
  // src/fec-manager.ts
13334
+ var RS_MAX_BLOCK_SYMBOLS = 255;
13146
13335
  var WORKER_ERROR_LOG_CAP = 5;
13147
13336
  var WORKER_ERROR_KIND_CAP = 32;
13148
13337
  var WORKER_ERROR_OVERFLOW_KIND = "other";
@@ -13257,6 +13446,11 @@ var FECManager = class _FECManager {
13257
13446
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
13258
13447
  // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
13259
13448
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
13449
+ /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
13450
+ this.#heldLayerStates = /* @__PURE__ */ new Map();
13451
+ /** Streams whose FEC failed closed at runtime (fec-01 6.3.9). */
13452
+ this.#fecFailClosed = /* @__PURE__ */ new Map();
13453
+ this.#onFecFailClosed = null;
13260
13454
  // Blocks already recovered — prevents late source symbols from restarting timeouts.
13261
13455
  // WASM removes blocks after recovery; late symbols create empty blocks returning null,
13262
13456
  // which would falsely start new timeouts without this guard.
@@ -13377,12 +13571,17 @@ var FECManager = class _FECManager {
13377
13571
  // per stream. Not only throws: the ordinary out-of-range case is detected by
13378
13572
  // arithmetic and never throws at all.
13379
13573
  this.#orderedHorizonWarnedFor = /* @__PURE__ */ new Set();
13380
- // Newest block start (SS_Start) seen per stream and when: the frontier for
13381
- // source-discontinuity detection and isoSpanResolution.
13574
+ // Newest block start (SS_Start) any symbol carried per stream and when: the
13575
+ // frontier isoSpanResolution reads.
13382
13576
  this.#highestSbn = /* @__PURE__ */ new Map();
13577
+ // The same from source symbols alone: the frontier a source is judged
13578
+ // against for a discontinuity. Repairs ride their own group, which can run
13579
+ // blocks ahead of the media they protect.
13580
+ this.#sourceFrontiers = /* @__PURE__ */ new Map();
13383
13581
  // iso-ssbg1-v1 block location per stream (streamKey). A source belongs to a
13384
13582
  // block only once a repair symbol stated the block's (SS_Start, SSB_length).
13385
13583
  this.#isoLocators = /* @__PURE__ */ new Map();
13584
+ this.#deferIsoGaps = false;
13386
13585
  this.#isoRepairRefusedCount = 0;
13387
13586
  this.#isoSourceOversizeCount = 0;
13388
13587
  // Held sources a locator's capacity cap evicted (IsoBlockLocator.heldCapacity):
@@ -13397,8 +13596,8 @@ var FECManager = class _FECManager {
13397
13596
  // rate-limited like the other per-symbol warns here. Cumulative.
13398
13597
  this.#isoDecoderUnplacedRetireFailed = 0;
13399
13598
  // The latest source symbol per stream that carried its MMTP
13400
- // packet_sequence_number: the anchor that bounds how many blocks the
13401
- // producer can have started before a later source symbol.
13599
+ // packet_sequence_number, by its own SS_ID: the anchor that bounds how far
13600
+ // the producer's SS_IDs can have moved before or after another source symbol.
13402
13601
  this.#sourceAnchors = /* @__PURE__ */ new Map();
13403
13602
  // Catalog/reset epoch per packetId. Gap decisions carry it for fencing.
13404
13603
  this.#packetEpochs = /* @__PURE__ */ new Map();
@@ -13457,6 +13656,14 @@ var FECManager = class _FECManager {
13457
13656
  this.onBlockReclassified = null;
13458
13657
  /** A video stream's classifier mode was established or changed. */
13459
13658
  this.onClassifierMode = null;
13659
+ /**
13660
+ * A repair stated a block past a gap that is missing a source and whose
13661
+ * every repair was lost: a lost SS_ID in an undelimited span
13662
+ * (draft-ramadan-moq-fec §7.5). Set with `setUndelimitedLossHandler`; the
13663
+ * receiver keeps the gap as a pending hole until `closeIsoHoles` is called
13664
+ * for it, which it must be.
13665
+ */
13666
+ this.#onUndelimitedLoss = null;
13460
13667
  /** A block every symbol of which vanished was created by SBN evidence. */
13461
13668
  this.onBlockVanished = null;
13462
13669
  /** A block reached a terminal state (completed, recovered, or failed). */
@@ -13498,6 +13705,9 @@ var FECManager = class _FECManager {
13498
13705
  #ssbLengthConflictCount;
13499
13706
  #blockRepairRsIds;
13500
13707
  #blockRsbLengths;
13708
+ #heldLayerStates;
13709
+ #fecFailClosed;
13710
+ #onFecFailClosed;
13501
13711
  #completedBlocks;
13502
13712
  #terminalExpiryMs;
13503
13713
  #terminalQueues;
@@ -13536,7 +13746,9 @@ var FECManager = class _FECManager {
13536
13746
  #materializedBlocks;
13537
13747
  #orderedHorizonWarnedFor;
13538
13748
  #highestSbn;
13749
+ #sourceFrontiers;
13539
13750
  #isoLocators;
13751
+ #deferIsoGaps;
13540
13752
  #isoRepairRefusedCount;
13541
13753
  #isoSourceOversizeCount;
13542
13754
  #isoHeldEvictedCount;
@@ -13550,6 +13762,7 @@ var FECManager = class _FECManager {
13550
13762
  #workerErrorCounts;
13551
13763
  #decoderUnavailableEvents;
13552
13764
  #repairSymbolSizeMismatchCount;
13765
+ #onUndelimitedLoss;
13553
13766
  #encodeTrackName(catalogTrackName) {
13554
13767
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
13555
13768
  if (encoded === void 0) {
@@ -14126,8 +14339,8 @@ var FECManager = class _FECManager {
14126
14339
  // Deliberately one block tighter than deriveFecRetentionBlocks over the same
14127
14340
  // inputs (that function's `+ 1`). Different question: the retention horizon
14128
14341
  // asks how long the decoder still ACCEPTS symbols for a block, this asks how
14129
- // many blocks a stream can live behind (or ahead of) its frontier before a
14130
- // source symbol there is a discontinuity rather than loss (see #noteSbnSeen).
14342
+ // many blocks a stream can jump ahead of its frontier before a source symbol
14343
+ // there is a discontinuity rather than loss (see #noteSbnSeen).
14131
14344
  // The extra block of retention is slack for a block still being fed; a block
14132
14345
  // nothing has been heard from does not get it. Not the units defect — but it
14133
14346
  // is the next place the two can drift, so change both or neither.
@@ -14137,55 +14350,72 @@ var FECManager = class _FECManager {
14137
14350
  }
14138
14351
  /**
14139
14352
  * Record that a symbol for block `sbn` (the block's SS_Start) arrived and
14140
- * advance the stream's frontier, the newest block start seen.
14353
+ * advance the stream's frontiers, the newest block start seen.
14141
14354
  *
14142
- * A SOURCE symbol whose block goes back further than one live window, or
14143
- * jumps further than the stream could have produced since its last symbol,
14144
- * is a source discontinuity, not loss. A repair symbol can only advance the
14355
+ * A SOURCE symbol is judged against the newest source block alone: repairs
14356
+ * ride their own group, which can run blocks ahead of the media. One whose
14357
+ * block goes back further than the blocks this manager retains, or that
14358
+ * cannot have been sent before the source it lies behind, or that jumps
14359
+ * further than the stream could have produced since its last symbol, is a
14360
+ * source discontinuity, not loss. A repair symbol can only advance the
14145
14361
  * frontier: a D-28 fetch legitimately answers for an old block, so it never
14146
14362
  * signals a discontinuity.
14147
14363
  *
14148
14364
  * The producer closes a block at its Dth media-unit boundary OR when K
14149
14365
  * source symbols filled it, so one interleave span can start several blocks
14150
- * (every large keyframe does). What bounds a forward jump is therefore
14151
- * packet evidence, not a block rate: SS_ID advances by one per FEC source
14152
- * packet (ISO/IEC 23008-1 C.5.2) and the MMTP packet_sequence_number by one
14153
- * per packet of the packet_id, so with both source symbols'
14154
- * packet_sequence_number a block start can move at most the packets sent
14155
- * between them plus the anchor's own offset into its block (< K). Without
14156
- * it, only the D-close rate is known.
14366
+ * (every large keyframe does). What bounds a jump is therefore packet
14367
+ * evidence, not a block rate: SS_ID advances by one per FEC source packet
14368
+ * (ISO/IEC 23008-1 C.5.2) and the MMTP packet_sequence_number by one per
14369
+ * packet of the packet_id, so with both source symbols'
14370
+ * packet_sequence_number their SS_IDs (`ssId`, not their block starts,
14371
+ * which a repair-less span can put far behind) can move at most the packets
14372
+ * sent between them, in either direction, plus K of slack for sources lost
14373
+ * before a hop that renumbers packets. Without it, only the D-close rate is
14374
+ * known.
14157
14375
  *
14158
14376
  * Vanished blocks are not enumerated here: their starts are unknown until a
14159
14377
  * repair states them. The SS_IDs between two stated blocks become one
14160
14378
  * repair-less span when the later block's repair arrives (placeIsoRepair).
14161
14379
  */
14162
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber) {
14380
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
14163
14381
  const streamKey = this.#streamKey(packetId, catalogTrackName);
14164
14382
  const now = performance.now();
14165
- const previous = this.#highestSbn.get(streamKey);
14383
+ const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
14166
14384
  const anchor = this.#sourceAnchors.get(streamKey);
14167
14385
  const psn = symbol === "source" && packetSequenceNumber !== void 0 && Number.isSafeInteger(packetSequenceNumber) && packetSequenceNumber >= 0 && packetSequenceNumber <= 4294967295 ? packetSequenceNumber : void 0;
14168
14386
  const anchorHere = () => {
14169
- if (psn !== void 0 && (anchor === void 0 || !this.#blockPrecedes(sbn, anchor.sbn))) {
14170
- this.#sourceAnchors.set(streamKey, { sbn, psn, atMs: now });
14387
+ if (psn !== void 0 && (anchor === void 0 || !serial32Precedes(ssId, anchor.ssId))) {
14388
+ this.#sourceAnchors.set(streamKey, { ssId, psn, atMs: now });
14171
14389
  }
14172
14390
  };
14391
+ const advance = () => {
14392
+ const highest = this.#highestSbn.get(streamKey);
14393
+ if (highest === void 0 || this.#blockPrecedes(highest.sbn, sbn)) {
14394
+ this.#highestSbn.set(streamKey, { sbn, atMs: now });
14395
+ }
14396
+ if (symbol === "source") this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
14397
+ anchorHere();
14398
+ };
14173
14399
  const discontinuity = () => {
14174
14400
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity();
14175
14401
  this.#highestSbn.set(streamKey, { sbn, atMs: now });
14402
+ this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
14176
14403
  if (psn === void 0) this.#sourceAnchors.delete(streamKey);
14177
- else this.#sourceAnchors.set(streamKey, { sbn, psn, atMs: now });
14404
+ else this.#sourceAnchors.set(streamKey, { ssId, psn, atMs: now });
14178
14405
  this.onSourceDiscontinuity?.(packetId, catalogTrackName);
14179
14406
  };
14180
14407
  if (previous === void 0) {
14181
- this.#highestSbn.set(streamKey, { sbn, atMs: now });
14182
- anchorHere();
14408
+ advance();
14183
14409
  return;
14184
14410
  }
14185
14411
  const config = this.#trackConfig(packetId);
14186
14412
  const window2 = this.#liveWindowBlocks(config);
14413
+ const sentInOrder = (from, to) => {
14414
+ const sent = to.psn - from.psn >>> 0;
14415
+ return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
14416
+ };
14187
14417
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
14188
- if (symbol === "source" && window2 !== null && this.#blocksBehind(sbn, previous.sbn, packetId) > window2) {
14418
+ if (symbol === "source" && window2 !== null && this.#blockPrecedes(sbn, previous.sbn) && (this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId) || psn !== void 0 && anchor !== void 0 && serial32Precedes(ssId, anchor.ssId) && psn !== anchor.psn && !sentInOrder({ ssId, psn }, anchor))) {
14189
14419
  discontinuity();
14190
14420
  return;
14191
14421
  }
@@ -14195,9 +14425,8 @@ var FECManager = class _FECManager {
14195
14425
  const missing = this.#blocksBehind(previous.sbn, sbn, packetId) - 1;
14196
14426
  let plausible = true;
14197
14427
  if (window2 !== null) {
14198
- if (psn !== void 0 && anchor !== void 0 && this.#blockPrecedes(anchor.sbn, sbn) && psn !== anchor.psn) {
14199
- const sent = psn - anchor.psn >>> 0;
14200
- plausible = sent <= 2147483647 && serial32Distance(anchor.sbn, sbn) <= sent + config.k;
14428
+ if (psn !== void 0 && anchor !== void 0 && serial32Precedes(anchor.ssId, ssId) && psn !== anchor.psn) {
14429
+ plausible = sentInOrder(anchor, { ssId, psn });
14201
14430
  } else {
14202
14431
  plausible = missing <= window2 + Math.ceil((now - previous.atMs) / config.interleaveDepthMs);
14203
14432
  }
@@ -14207,8 +14436,7 @@ var FECManager = class _FECManager {
14207
14436
  discontinuity();
14208
14437
  return;
14209
14438
  }
14210
- this.#highestSbn.set(streamKey, { sbn, atMs: now });
14211
- anchorHere();
14439
+ advance();
14212
14440
  }
14213
14441
  /*
14214
14442
  * Block order for one stream (BLO-35597 iso:5). A block is keyed by its
@@ -14525,8 +14753,10 @@ var FECManager = class _FECManager {
14525
14753
  );
14526
14754
  }
14527
14755
  const hasCatalogTiming = _FECManager.#hasCatalogTiming({ interleaveDepthMs: ownInterleaveDepthMs });
14756
+ const algorithm = config.algorithm ?? previous.algorithm;
14528
14757
  const next = {
14529
14758
  blockProfile,
14759
+ ...algorithm === void 0 ? {} : { algorithm },
14530
14760
  k,
14531
14761
  symbolSize: config.symbolSize != null && config.symbolSize > 0 ? config.symbolSize : previousTrack?.symbolSize ?? 0,
14532
14762
  interleaveDepthMs: ownInterleaveDepthMs,
@@ -14534,8 +14764,19 @@ var FECManager = class _FECManager {
14534
14764
  timeoutMs: config.timeoutMs ?? (timingChanged ? 0 : previous.timeoutMs ?? 0),
14535
14765
  ...(config.trackKind ?? previous.trackKind) === void 0 ? {} : { trackKind: config.trackKind ?? previous.trackKind },
14536
14766
  ...(config.codec ?? previous.codec) === void 0 ? {} : { codec: config.codec ?? previous.codec },
14537
- ...(config.geometry ?? previous.geometry) === void 0 ? {} : { geometry: config.geometry ?? previous.geometry }
14767
+ ...(config.geometry ?? previous.geometry) === void 0 ? {} : { geometry: config.geometry ?? previous.geometry },
14768
+ ...(config.repairLayers ?? previous.repairLayers) === void 0 ? {} : { repairLayers: config.repairLayers ?? previous.repairLayers },
14769
+ ...(config.heldLayers ?? previous.heldLayers) === void 0 ? {} : { heldLayers: config.heldLayers ?? previous.heldLayers }
14538
14770
  };
14771
+ if (
14772
+ // By content: a catalog refresh rebuilds equal arrays, and forgetting
14773
+ // the anchors on one would fail open.
14774
+ JSON.stringify(next.repairLayers) !== JSON.stringify(previous.repairLayers) || JSON.stringify(next.heldLayers) !== JSON.stringify(previous.heldLayers)
14775
+ ) {
14776
+ for (const key of [...this.#heldLayerStates.keys()]) {
14777
+ if (this.#belongsToPacket(key, packetId)) this.#heldLayerStates.delete(key);
14778
+ }
14779
+ }
14539
14780
  if (!hasCatalogTiming) {
14540
14781
  next.timeoutMs = config.timeoutMs !== void 0 && config.timeoutMs > 0 ? config.timeoutMs : previousTrack !== void 0 && previousTrack.interleaveDepthMs === 0 ? previousTrack.timeoutMs : LOCAL_FEC_TIMEOUT_MS;
14541
14782
  } else {
@@ -14770,6 +15011,8 @@ var FECManager = class _FECManager {
14770
15011
  resetMap(this.#blockAuthoredLengths);
14771
15012
  resetMap(this.#blockRepairRsIds);
14772
15013
  resetMap(this.#blockRsbLengths);
15014
+ resetMap(this.#heldLayerStates);
15015
+ resetMap(this.#fecFailClosed);
14773
15016
  resetMap(this.#blockPathCounts);
14774
15017
  resetMap(this.#blockAnchorsMs);
14775
15018
  resetMap(this.#blockCatalogTrackNames);
@@ -14792,6 +15035,7 @@ var FECManager = class _FECManager {
14792
15035
  resetSet(this.#materializedBlocks);
14793
15036
  resetMap(this.#resolvedBlockClasses);
14794
15037
  resetMap(this.#highestSbn);
15038
+ resetMap(this.#sourceFrontiers);
14795
15039
  resetMap(this.#isoLocators);
14796
15040
  resetMap(this.#sourceAnchors);
14797
15041
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName));
@@ -14897,6 +15141,7 @@ var FECManager = class _FECManager {
14897
15141
  dropMap(this.#orderedPendingBlocks);
14898
15142
  dropMap(this.#resolvedBlockClasses);
14899
15143
  dropMap(this.#highestSbn);
15144
+ dropMap(this.#sourceFrontiers);
14900
15145
  dropMap(this.#isoLocators);
14901
15146
  dropMap(this.#sourceAnchors);
14902
15147
  dropMap(this.#classifiers);
@@ -14989,7 +15234,13 @@ var FECManager = class _FECManager {
14989
15234
  if (isSourceSymbol && esi === 0) {
14990
15235
  this.#startupPartialBlocks.delete(blockKey);
14991
15236
  this.#startupAlignedPackets.add(streamKey);
14992
- } else if (isStartupPartial && !isReadyMulticastRepair || !this.#startupAlignedPackets.has(streamKey) && !isReadyMulticastRepair) {
15237
+ } else if (
15238
+ // A ready multicast repair opens a block the join has not seen yet, never
15239
+ // a join partial: its sources were refused, so its repairs alone open a
15240
+ // block that cannot decode and fails at its deadline, once per packet ID
15241
+ // per join (BLO-48308).
15242
+ isStartupPartial || !this.#startupAlignedPackets.has(streamKey) && !isReadyMulticastRepair
15243
+ ) {
14993
15244
  this.#markStartupPartial(blockKey);
14994
15245
  return false;
14995
15246
  }
@@ -15271,6 +15522,7 @@ var FECManager = class _FECManager {
15271
15522
  let locator = this.#isoLocators.get(streamKey);
15272
15523
  if (!locator) {
15273
15524
  locator = new IsoBlockLocator(this.#trackConfig(packetId).k, this.#isoRetentionBlocks(packetId));
15525
+ locator.deferIncompleteGaps = this.#deferIsoGaps;
15274
15526
  this.#isoLocators.set(streamKey, locator);
15275
15527
  }
15276
15528
  return locator;
@@ -15314,6 +15566,10 @@ var FECManager = class _FECManager {
15314
15566
  }
15315
15567
  return blocks;
15316
15568
  }
15569
+ /** The iso-ssbg1-v1 locator horizon of a configured packetId, in blocks (#isoRetentionBlocks). */
15570
+ isoRetentionBlocksForPacket(packetId) {
15571
+ return this.#hasBlockProfile(packetId) ? this.#isoRetentionBlocks(packetId) : void 0;
15572
+ }
15317
15573
  /** Whether an iso-ssbg1-v1 protected packet fits one ssbg_mode1 symbol (len + 2 <= T). */
15318
15574
  isoSourceFits(packetId, packetLength) {
15319
15575
  const symbolSize = this.#trackConfigs.get(packetId)?.symbolSize;
@@ -15363,15 +15619,61 @@ var FECManager = class _FECManager {
15363
15619
  }
15364
15620
  return placement;
15365
15621
  }
15366
- if (placement.span !== void 0) {
15367
- const key = this.#blockKey(placement.span.block.start, packetId, catalogTrackName);
15368
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, placement.span.block.length);
15369
- }
15370
- if (placement.span !== void 0 && placement.span.placed.length === 0) {
15371
- this.#materializeBlock(placement.span.block.start, packetId, catalogTrackName, true);
15622
+ if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
15623
+ if (placement.hole !== void 0) {
15624
+ const locator = this.#isoLocatorFor(packetId, catalogTrackName);
15625
+ const hole = placement.hole.block;
15626
+ const previous = locator.blockEndingAt(hole.start);
15627
+ const loss = {
15628
+ packetId,
15629
+ catalogTrackName,
15630
+ holeStart: hole.start,
15631
+ holeLength: hole.length,
15632
+ lostSsId: placement.hole.lostSsId,
15633
+ kMax: this.#trackConfig(packetId).k,
15634
+ ...previous === void 0 ? {} : { previousBlockStart: previous.start }
15635
+ };
15636
+ this.#onUndelimitedLoss(loss);
15372
15637
  }
15373
15638
  return placement;
15374
15639
  }
15640
+ /**
15641
+ * Keep an iso-ssbg1-v1 gap missing a source as a pending hole, reported to
15642
+ * `handler`, instead of a repair-less span; null restores spans. Set by the
15643
+ * range repair scheduler; applies to every stream from its next gap. The
15644
+ * handler and the deferral are one setting, so no hole is ever created with
15645
+ * nobody to close it.
15646
+ */
15647
+ setUndelimitedLossHandler(handler) {
15648
+ this.#onUndelimitedLoss = handler;
15649
+ this.#deferIsoGaps = handler !== null;
15650
+ for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
15651
+ }
15652
+ /**
15653
+ * The range repair for a hole ended: every hole still pending inside
15654
+ * `[start, start + length)` becomes a repair-less span. Returns those spans
15655
+ * with the held sources they placed, for the caller to feed (MmtpRouter).
15656
+ */
15657
+ closeIsoHoles(packetId, catalogTrackName, start, length) {
15658
+ const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
15659
+ if (locator === void 0) return [];
15660
+ const spans = locator.closeHolesWithin(start, length);
15661
+ for (const span of spans) this.#openIsoSpan(span, packetId, catalogTrackName);
15662
+ return spans;
15663
+ }
15664
+ /**
15665
+ * A repair-less span has no repair to state its length, so it is known
15666
+ * here: its sources make it clean exactly when all of them arrived. A
15667
+ * stated block learns its SSB_length from its own repair symbol, fed after
15668
+ * its placed sources exactly as on the wire (feedRepairSymbol). A span every
15669
+ * SS_ID of which vanished resolves through its deadline like any vanished
15670
+ * block.
15671
+ */
15672
+ #openIsoSpan(span, packetId, catalogTrackName) {
15673
+ const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
15674
+ if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
15675
+ if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
15676
+ }
15375
15677
  /**
15376
15678
  * Resolution of the SS_IDs strictly between two released frames' SS_IDs on
15377
15679
  * an iso-ssbg1-v1 stream, for in-order frame release: null while a block
@@ -15888,6 +16190,112 @@ var FECManager = class _FECManager {
15888
16190
  }
15889
16191
  return recovered;
15890
16192
  }
16193
+ /**
16194
+ * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
16195
+ * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
16196
+ * block state unchanged. The router calls this before the repair places a
16197
+ * block or takes any other part in block bookkeeping. A RaptorQ track admits
16198
+ * every header that parsed (its RS_ID < RSB_length check is in the parser).
16199
+ */
16200
+ admitRepairBlockLength(packetId, ssbLength, rsbLength, rsId) {
16201
+ if (rsId >= rsbLength) return false;
16202
+ if (this.#trackConfigs.get(packetId)?.algorithm !== "reed-solomon") return true;
16203
+ return ssbLength + rsbLength <= RS_MAX_BLOCK_SYMBOLS;
16204
+ }
16205
+ /**
16206
+ * Whether a repair symbol of `byteLength` bytes is a valid member of a
16207
+ * `packetId` block: every repair symbol is exactly the track's T. A symbol of
16208
+ * any other size is counted on `repairSymbolSizeMismatches`, warned (rate
16209
+ * limited) and refused. The router calls this before the symbol takes any
16210
+ * other part in block state (placement, first-arrival dedup, completed-block
16211
+ * accounting), so a malformed repair is counted whatever its arrival order:
16212
+ * judged after dedup, one landing on an already-complete block, or behind a
16213
+ * valid copy from the other transport, was swallowed as a duplicate and never
16214
+ * counted (BLO-48306). A packetId with no configured block profile admits
16215
+ * nothing here; its repair is dropped upstream as unreadable.
16216
+ */
16217
+ admitRepairSymbolSize(packetId, ssStart, ssbLength, rsId, byteLength) {
16218
+ if (!this.#hasBlockProfile(packetId)) return false;
16219
+ const symbolSize = this.#trackConfig(packetId).symbolSize;
16220
+ if (symbolSize > 0 && byteLength !== symbolSize) {
16221
+ this.#repairSymbolSizeMismatchCount++;
16222
+ if (this.#repairSymbolSizeMismatchCount <= 5 || this.#repairSymbolSizeMismatchCount % 100 === 0) {
16223
+ console.warn(
16224
+ `[FECManager] Dropping repair symbol with invalid size: got ${byteLength}B, expected ${symbolSize}B (packetId=${packetId}, ssStart=${ssStart}, ssbLength=${ssbLength}, rsId=${rsId})`
16225
+ );
16226
+ }
16227
+ return false;
16228
+ }
16229
+ return true;
16230
+ }
16231
+ /**
16232
+ * fec-01 6.3.9 receiver check, run on a repair packet after the 4.5 discard
16233
+ * and the size check, before it places a block. For each held layer i with
16234
+ * total B_i = O_i + P_i: the anchor is the earliest block, in SS_Start
16235
+ * serial order, whose repair carried RSB_length >= B_i. The source track
16236
+ * fails closed on (a) a packet on layer i's own repair track (i > 0) below
16237
+ * B_i, or (b) any packet of the instance at or after the anchor below B_i.
16238
+ * Blocks before the anchor (pre-append) stay valid at the previous total. A
16239
+ * packet on a repair track the catalog does not list is discarded and
16240
+ * anchors nothing. `repairTrackName` is the subscribed repair track, never
16241
+ * inferred from RS_ID; without it only (b) runs. Returns false when the
16242
+ * repair must be dropped, including every repair once the track failed.
16243
+ */
16244
+ admitRepairLayerTotal(packetId, catalogTrackName, repairTrackName, ssStart, rsbLength) {
16245
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
16246
+ if (this.#fecFailClosed.has(streamKey)) return false;
16247
+ const config = this.#trackConfigs.get(packetId);
16248
+ const layers = config?.repairLayers;
16249
+ if (layers === void 0 || layers.length === 0) return true;
16250
+ let admission = this.#heldLayerStates.get(streamKey);
16251
+ if (admission === void 0) {
16252
+ admission = new HeldLayerAdmission(layers, config.heldLayers);
16253
+ this.#heldLayerStates.set(streamKey, admission);
16254
+ }
16255
+ const verdict = admission.admit(
16256
+ repairTrackName,
16257
+ ssStart,
16258
+ rsbLength,
16259
+ this.#layerAnchorHorizon(packetId),
16260
+ this.#sourceFrontiers.get(streamKey)?.sbn
16261
+ );
16262
+ if (verdict === "discard") return false;
16263
+ if (verdict !== void 0) {
16264
+ this.#fecFailClosed.set(streamKey, verdict);
16265
+ this.#onFecFailClosed?.({ ...verdict, packetId, catalogTrackName });
16266
+ console.warn(
16267
+ `[FECManager] FEC failed closed (fec-01 6.3.9) packetId=${packetId} track=${catalogTrackName ?? "-"}: ${JSON.stringify(verdict)}`
16268
+ );
16269
+ return false;
16270
+ }
16271
+ return true;
16272
+ }
16273
+ /**
16274
+ * How far (in SS_Start symbols) behind the newest block a 6.3.9 anchor or
16275
+ * below-total block can still matter: the iso locator's retention in blocks
16276
+ * times K, capped at 2^30 so compared serials stay inside one half-window.
16277
+ */
16278
+ #layerAnchorHorizon(packetId) {
16279
+ let blocks;
16280
+ try {
16281
+ blocks = this.isoRetentionBlocksForPacket(packetId);
16282
+ } catch {
16283
+ blocks = void 0;
16284
+ }
16285
+ return heldLayerAnchorHorizon(blocks, this.#trackConfigs.get(packetId)?.k ?? 0);
16286
+ }
16287
+ /**
16288
+ * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), once,
16289
+ * when it does; null stops reporting. The player wiring forwards it to
16290
+ * CmcdProducer.updateFecFailClosed.
16291
+ */
16292
+ setFecFailClosedHandler(handler) {
16293
+ this.#onFecFailClosed = handler;
16294
+ }
16295
+ /** The runtime fail-closed reason of a stream's FEC (fec-01 6.3.9), if any. */
16296
+ fecFailClosedReason(packetId, catalogTrackName) {
16297
+ return this.#fecFailClosed.get(this.#streamKey(packetId, catalogTrackName));
16298
+ }
15891
16299
  /**
15892
16300
  * Feed a repair symbol to the WASM FEC decoder.
15893
16301
  *
@@ -15899,16 +16307,7 @@ var FECManager = class _FECManager {
15899
16307
  this.#fecStats.repairPackets++;
15900
16308
  this.#statsForPacket(packetId).repairPackets++;
15901
16309
  if (!this.#hasBlockProfile(packetId)) return null;
15902
- const symbolSize = this.#trackConfig(packetId).symbolSize;
15903
- if (symbolSize > 0 && repairData.byteLength !== symbolSize) {
15904
- this.#repairSymbolSizeMismatchCount++;
15905
- if (this.#repairSymbolSizeMismatchCount <= 5 || this.#repairSymbolSizeMismatchCount % 100 === 0) {
15906
- console.warn(
15907
- `[FECManager] Dropping repair symbol with invalid size: got ${repairData.byteLength}B, expected ${symbolSize}B (packetId=${packetId}, ssStart=${ssStart}, ssbLength=${ssbLength}, rsId=${rsId})`
15908
- );
15909
- }
15910
- return null;
15911
- }
16310
+ if (!this.admitRepairSymbolSize(packetId, ssStart, ssbLength, rsId, repairData.byteLength)) return null;
15912
16311
  const fecData = repairData;
15913
16312
  const k = this.#trackConfig(packetId).k;
15914
16313
  const block = this.#isoLocatorFor(packetId, catalogTrackName).blockAt(ssStart);
@@ -16061,7 +16460,14 @@ var FECManager = class _FECManager {
16061
16460
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
16062
16461
  const k = trackConfig.k;
16063
16462
  if (this.#completedBlocks.has(key)) return;
16064
- this.#noteSbnSeen(sbn, packetId, catalogTrackName, "source", evidence.packetSequenceNumber);
16463
+ this.#noteSbnSeen(
16464
+ sbn,
16465
+ packetId,
16466
+ catalogTrackName,
16467
+ "source",
16468
+ evidence.packetSequenceNumber,
16469
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
16470
+ );
16065
16471
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
16066
16472
  if (Number.isInteger(esi) && esi >= authoredLength) {
16067
16473
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -16288,6 +16694,8 @@ var FECManager = class _FECManager {
16288
16694
  this.#blockAuthoredLengths.clear();
16289
16695
  this.#blockRepairRsIds.clear();
16290
16696
  this.#blockRsbLengths.clear();
16697
+ this.#heldLayerStates.clear();
16698
+ this.#fecFailClosed.clear();
16291
16699
  this.#completedBlocks.clear();
16292
16700
  this.#cleanlyCompletedBlocks.clear();
16293
16701
  this.#repairRequestedBlocks.clear();
@@ -16312,6 +16720,7 @@ var FECManager = class _FECManager {
16312
16720
  this.#repairedBlocks.clear();
16313
16721
  this.#materializedBlocks.clear();
16314
16722
  this.#highestSbn.clear();
16723
+ this.#sourceFrontiers.clear();
16315
16724
  this.#isoLocators.clear();
16316
16725
  this.#sourceAnchors.clear();
16317
16726
  this.#trackConfigs.clear();
@@ -17401,6 +17810,7 @@ function isFmp4Box(data) {
17401
17810
  const type = String.fromCharCode(data[4], data[5], data[6], data[7]);
17402
17811
  return FMPU_BOX_TYPES.has(type);
17403
17812
  }
17813
+ var MAX_AWAITING_TIMING_HEADS = 8;
17404
17814
  var MmtpContainerParser = class _MmtpContainerParser {
17405
17815
  constructor(config) {
17406
17816
  this.#tracks = /* @__PURE__ */ new Map();
@@ -17459,6 +17869,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
17459
17869
  * reordering into the parser. */
17460
17870
  this.#reliableMoqStartupGate = /* @__PURE__ */ new Map();
17461
17871
  this.#disposed = false;
17872
+ this.#replayingAwaitingTiming = false;
17462
17873
  this.#fedObjects = 0;
17463
17874
  this.#reassemblerFragmentsFed = 0;
17464
17875
  this.#reassemblerDataUnitsReturned = 0;
@@ -17551,6 +17962,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
17551
17962
  #reorderStats;
17552
17963
  #reliableMoqStartupGate;
17553
17964
  #disposed;
17965
+ #replayingAwaitingTiming;
17554
17966
  #fedObjects;
17555
17967
  #reassemblerFragmentsFed;
17556
17968
  #reassemblerDataUnitsReturned;
@@ -17800,7 +18212,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
17800
18212
  * a single failure bucket. Returns null so call sites stay `return this.#drop(...)`.
17801
18213
  */
17802
18214
  #drop(reason) {
17803
- this.#countOutcome(`drop:${reason}`);
18215
+ if (this.#replayingAwaitingTiming) this.#countDeferredOutcome(reason);
18216
+ else this.#countOutcome(`drop:${reason}`);
17804
18217
  return null;
17805
18218
  }
17806
18219
  get reorderDiagnostics() {
@@ -17823,6 +18236,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
17823
18236
  for (const combiner of this.#sampleCombiners.values()) {
17824
18237
  combiner.cleanupTimeouts(timeoutMs);
17825
18238
  }
18239
+ const now = Date.now();
18240
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
18241
+ while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
18242
+ awaitingTiming.shift();
18243
+ }
18244
+ }
17826
18245
  }
17827
18246
  /**
17828
18247
  * Phase 1 of two-phase parsing. Returns structured header info for FEC feeding.
@@ -17903,7 +18322,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
17903
18322
  byteLength: packet.byteLength
17904
18323
  };
17905
18324
  }
17906
- if (info.fecPayloadId !== null && this.#sourceSymbolCb) {
18325
+ if (info.fecPayloadId !== null && this.#sourceSymbolCb && !this.#replayingAwaitingTiming) {
17907
18326
  const rawSymbol = packet.subarray(0, packet.length - 4);
17908
18327
  try {
17909
18328
  this.#sourceSymbolCb(info.packetId, info.fecPayloadId.ssId, rawSymbol);
@@ -17951,6 +18370,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
17951
18370
  }
17952
18371
  return this.#drop("fragment-timing-refused");
17953
18372
  }
18373
+ this.#replayAwaitingTiming(streamKey, resolver2);
17954
18374
  return {
17955
18375
  kind: "fragment",
17956
18376
  packet: info,
@@ -17974,7 +18394,18 @@ var MmtpContainerParser = class _MmtpContainerParser {
17974
18394
  mfuDuHeader.movieFragmentSequenceNumber,
17975
18395
  mfuDuHeader.sampleNumber
17976
18396
  );
17977
- if (!headTiming) return this.#drop("mfu-sample-timing-missing");
18397
+ if (!headTiming) {
18398
+ this.#awaitTiming(streamKey, {
18399
+ packet,
18400
+ options,
18401
+ parsed,
18402
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
18403
+ movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
18404
+ sampleNumber: mfuDuHeader.sampleNumber,
18405
+ arrivedAt: Date.now()
18406
+ });
18407
+ return this.#drop("mfu-sample-timing-missing");
18408
+ }
17978
18409
  const offset = mfuDuHeader.offset;
17979
18410
  if (!Number.isSafeInteger(offset) || offset < 0 || offset >= headTiming.size)
17980
18411
  return this.#drop("mfu-offset-out-of-range");
@@ -18050,16 +18481,17 @@ var MmtpContainerParser = class _MmtpContainerParser {
18050
18481
  const sampleNumber = assembled.sampleNumber;
18051
18482
  if (movieFragmentSequenceNumber === void 0 || sampleNumber === void 0)
18052
18483
  return this.#drop("assembled-identity-missing");
18053
- if (!resolver.sampleTiming(
18484
+ const assembledTiming = resolver.sampleTiming(
18054
18485
  assembled.mpuSequenceNumber,
18055
18486
  movieFragmentSequenceNumber,
18056
18487
  sampleNumber
18057
- )) return this.#drop("assembled-timing-missing");
18488
+ );
18489
+ if (!assembledTiming) return this.#drop("assembled-timing-missing");
18058
18490
  if (assembled.mpuSequenceNumber !== mpu.mpuSequenceNumber)
18059
18491
  return this.#drop("assembled-mpu-mismatch");
18060
18492
  let combined;
18061
18493
  try {
18062
- combined = this.#sampleCombinerFor(streamKey).addMfu(assembled);
18494
+ combined = this.#sampleCombinerFor(streamKey).addMfu(assembled, assembledTiming.size);
18063
18495
  } catch (error) {
18064
18496
  if (!(error instanceof SampleCombineError)) throw error;
18065
18497
  console.warn(
@@ -18368,9 +18800,37 @@ var MmtpContainerParser = class _MmtpContainerParser {
18368
18800
  if (existing) return existing.resolver;
18369
18801
  if (!create) return null;
18370
18802
  const resolver = new IsoBmffTimingResolver(this.#maxPendingTimingSamples);
18371
- this.#timingStreams.set(streamKey, { packetId, resolver });
18803
+ this.#timingStreams.set(streamKey, { packetId, resolver, awaitingTiming: [] });
18372
18804
  return resolver;
18373
18805
  }
18806
+ #awaitTiming(streamKey, head) {
18807
+ const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
18808
+ if (!awaitingTiming) return;
18809
+ awaitingTiming.push(head);
18810
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
18811
+ }
18812
+ /**
18813
+ * Feed again the heads whose timing the FT=1 just admitted declares. That
18814
+ * FT=1 can be an FEC recovery landing after its sample's FI=1, and neither
18815
+ * FEC path routes a source symbol that already arrived a second time.
18816
+ */
18817
+ #replayAwaitingTiming(streamKey, resolver) {
18818
+ const state = this.#timingStreams.get(streamKey);
18819
+ if (!state || state.awaitingTiming.length === 0) return;
18820
+ const ready = state.awaitingTiming.filter((head) => resolver.sampleTiming(
18821
+ head.mpuSequenceNumber,
18822
+ head.movieFragmentSequenceNumber,
18823
+ head.sampleNumber
18824
+ ));
18825
+ if (ready.length === 0) return;
18826
+ state.awaitingTiming = state.awaitingTiming.filter((head) => !ready.includes(head));
18827
+ this.#replayingAwaitingTiming = true;
18828
+ try {
18829
+ for (const head of ready) this.#feed(head.packet, head.options, head.parsed);
18830
+ } finally {
18831
+ this.#replayingAwaitingTiming = false;
18832
+ }
18833
+ }
18374
18834
  #dropTimingStream(streamKey) {
18375
18835
  const state = this.#timingStreams.get(streamKey);
18376
18836
  if (!state) return;
@@ -18975,6 +19435,18 @@ var MmtpRouter = class {
18975
19435
  // MSE recovery routes through CmafBlockAssembler and can reorder by block; the
18976
19436
  // direct callback path has to preserve decode order before frames leave libmmt.
18977
19437
  #latestVideoSeqByStream = /* @__PURE__ */ new Map();
19438
+ /**
19439
+ * Per stream, SS_ID - packet_sequence_number (mod 2^32) of its latest
19440
+ * first-arrival FEC source packet. A recovered source symbol's wire
19441
+ * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
19442
+ */
19443
+ #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
19444
+ /**
19445
+ * Streams whose multicast leg delivered a RAP-flagged source packet that was
19446
+ * not parsed, typically because its overlap copy was parsed first
19447
+ * (BLO-49179). The next video keyframe emitted on the stream consumes it.
19448
+ */
19449
+ #multicastRapTwinByStream = /* @__PURE__ */ new Set();
18978
19450
  #lastDirectSourceVideoTsByStream = /* @__PURE__ */ new Map();
18979
19451
  #lastDirectEmittedVideoTsByStream = /* @__PURE__ */ new Map();
18980
19452
  #pendingDirectRecoveredVideoByStream = /* @__PURE__ */ new Map();
@@ -19049,11 +19521,14 @@ var MmtpRouter = class {
19049
19521
  */
19050
19522
  #onPublisherRestart;
19051
19523
  #publisherRestarts = 0;
19524
+ #restampedRecoveredSeqs = 0;
19052
19525
  /** Inits delivered with no onTrackInit handler for their packetId (MOQT-01). */
19053
19526
  #unmappedInitDeliveries = 0;
19054
19527
  // FEC Payload IDs left unread because their (owner) packetId had no
19055
19528
  // configured fec.blockProfile (see #noteUnreadableFecPayloadId).
19056
19529
  #fecPayloadIdsWithoutProfile = 0;
19530
+ // Repair packets discarded by the fec-01 4.5 block-length rule.
19531
+ #repairBlockLengthDiscards = 0;
19057
19532
  /** The staged in-place stream switch, if any (stageStreamSwitch). */
19058
19533
  #staged = null;
19059
19534
  #disposed = false;
@@ -19107,6 +19582,12 @@ var MmtpRouter = class {
19107
19582
  ...meta.catalogTrackName === void 0 ? {} : { catalogTrackName: meta.catalogTrackName }
19108
19583
  };
19109
19584
  if (meta.source) frameMeta.source = meta.source;
19585
+ if (isVideo && frameMeta.keyframe) {
19586
+ const twinSeen = this.#multicastRapTwinByStream.delete(
19587
+ this.#mediaStreamKey(packetId, frameMeta.catalogTrackName)
19588
+ );
19589
+ if (twinSeen && frameMeta.source === "moq") frameMeta.source = "multicast";
19590
+ }
19110
19591
  if (meta.deliveryProvenance !== void 0)
19111
19592
  frameMeta.deliveryProvenance = meta.deliveryProvenance;
19112
19593
  if (meta.recovered) frameMeta.recovered = true;
@@ -19269,6 +19750,14 @@ var MmtpRouter = class {
19269
19750
  get publisherRestartCount() {
19270
19751
  return this.#publisherRestarts;
19271
19752
  }
19753
+ /**
19754
+ * FEC-recovered source symbols whose reconstructed header named a
19755
+ * packet_sequence_number other than the wire sequence their SS_ID maps to:
19756
+ * a hop re-stamped the sequence after the sender protected the packet.
19757
+ */
19758
+ get restampedRecoveredSequenceCount() {
19759
+ return this.#restampedRecoveredSeqs;
19760
+ }
19272
19761
  /**
19273
19762
  * Packets whose Source or Repair FEC Payload ID was left unread because
19274
19763
  * their (owner) packetId had no configured `fec.blockProfile`: FEC not
@@ -19280,6 +19769,14 @@ var MmtpRouter = class {
19280
19769
  get fecPayloadIdsWithoutProfile() {
19281
19770
  return this.#fecPayloadIdsWithoutProfile;
19282
19771
  }
19772
+ /**
19773
+ * Repair packets discarded at admission by the fec-01 4.5 rule (RS_ID not
19774
+ * below RSB_length, or a reed-solomon SSB_length + RSB_length above 255),
19775
+ * before they touched any block state.
19776
+ */
19777
+ get repairBlockLengthDiscards() {
19778
+ return this.#repairBlockLengthDiscards;
19779
+ }
19283
19780
  get reassembler() {
19284
19781
  return this.#parser.reassembler;
19285
19782
  }
@@ -19658,13 +20155,13 @@ var MmtpRouter = class {
19658
20155
  * Feed a repair packet from MoQ (reliable QUIC) — parses MMTP repair
19659
20156
  * header and delegates to FECManager for FEC recovery.
19660
20157
  */
19661
- feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName) {
20158
+ feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName) {
19662
20159
  if (this.#disposed) return;
19663
20160
  this.#withDeferredFecPokes(() => {
19664
- this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName);
20161
+ this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName);
19665
20162
  });
19666
20163
  }
19667
- #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName) {
20164
+ #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName) {
19668
20165
  let header;
19669
20166
  try {
19670
20167
  header = parseMMTPHeader(packet);
@@ -19695,7 +20192,7 @@ var MmtpRouter = class {
19695
20192
  this.#noteUnreadableFecPayloadId(ownerPacketId, "repair");
19696
20193
  return;
19697
20194
  }
19698
- this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, "moq");
20195
+ this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, "moq", repairTrackName);
19699
20196
  }
19700
20197
  }
19701
20198
  // ── Packet FEC geometry and block profile ───────────────────────
@@ -19777,13 +20274,25 @@ var MmtpRouter = class {
19777
20274
  * the repair, the order they had on the wire, so a loss-free block completes
19778
20275
  * clean on its repair. A repair contradicting a known block is dropped.
19779
20276
  */
19780
- #handleIsoRepair(ownerPacketId, catalogTrackName, repair, source) {
20277
+ #handleIsoRepair(ownerPacketId, catalogTrackName, repair, source, repairTrackName) {
19781
20278
  const fec = this.#fecManager;
19782
20279
  if (!fec?.placeIsoRepair) {
19783
20280
  throw new Error(
19784
20281
  `[MmtpRouter] packetId=${ownerPacketId} is iso-ssbg1-v1 but its FEC manager cannot place ISO blocks`
19785
20282
  );
19786
20283
  }
20284
+ if (fec.admitRepairBlockLength && !fec.admitRepairBlockLength(ownerPacketId, repair.ssbLength, repair.rsbLength, repair.rsId)) {
20285
+ this.#repairBlockLengthDiscards++;
20286
+ return;
20287
+ }
20288
+ if (fec.admitRepairSymbolSize && !fec.admitRepairSymbolSize(
20289
+ ownerPacketId,
20290
+ repair.ssStart,
20291
+ repair.ssbLength,
20292
+ repair.rsId,
20293
+ repair.symbolData.byteLength
20294
+ )) return;
20295
+ if (fec.admitRepairLayerTotal && !fec.admitRepairLayerTotal(ownerPacketId, catalogTrackName, repairTrackName, repair.ssStart, repair.rsbLength)) return;
19787
20296
  const placement = fec.placeIsoRepair(ownerPacketId, catalogTrackName, repair.ssStart, repair.ssbLength);
19788
20297
  if (placement.status !== "placed") return;
19789
20298
  const blockStart = placement.block.start;
@@ -19818,6 +20327,17 @@ var MmtpRouter = class {
19818
20327
  this.#routeRecoveredBlock(blockStart, recovered, ownerPacketId, catalogTrackName);
19819
20328
  }
19820
20329
  }
20330
+ /**
20331
+ * The range repair FETCH for an undelimited hole ended (draft-ramadan-moq-fec
20332
+ * §7.5): what no repair stated becomes repair-less spans, whose held sources
20333
+ * are fed exactly as a span a repair closed.
20334
+ */
20335
+ closeIsoHoles(ownerPacketId, catalogTrackName, start, length) {
20336
+ const spans = this.#fecManager?.closeIsoHoles?.(ownerPacketId, catalogTrackName, start, length) ?? [];
20337
+ for (const span of spans) {
20338
+ this.#replayIsoSources(ownerPacketId, catalogTrackName, span.block.start, span.placed);
20339
+ }
20340
+ }
19821
20341
  /**
19822
20342
  * Feed iso-ssbg1-v1 sources a repair just placed, in SS_ID order, exactly as
19823
20343
  * a first-arrival source is fed once its block is known: transport
@@ -19913,6 +20433,8 @@ var MmtpRouter = class {
19913
20433
  this.#trackSynced.delete(streamKey);
19914
20434
  this.#droppedPreSyncVideo.delete(streamKey);
19915
20435
  this.#latestVideoSeqByStream.delete(streamKey);
20436
+ this.#ssIdSeqOffsetByStream.delete(streamKey);
20437
+ this.#multicastRapTwinByStream.delete(streamKey);
19916
20438
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
19917
20439
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
19918
20440
  this.#pendingDirectRecoveredVideoByStream.delete(streamKey);
@@ -20683,6 +21205,12 @@ var MmtpRouter = class {
20683
21205
  } else if (fecUnreadable && info.fecPayloadId) {
20684
21206
  parseSourceSymbol = !duplicates.parsedSymbols.has(info.fecPayloadId.ssId);
20685
21207
  }
21208
+ if (fecPayloadId && !overlapCopy) {
21209
+ this.#ssIdSeqOffsetByStream.set(
21210
+ this.#mediaStreamKey(info.packetId, catalogTrackName),
21211
+ fecPayloadId.ssId - info.sequenceNumber >>> 0
21212
+ );
21213
+ }
20686
21214
  if (!this.#fecManager || !info.fecPayloadId || parseSourceSymbol) {
20687
21215
  if (this.#fecManager && info.fecPayloadId) {
20688
21216
  duplicates.parsedSymbols.add(info.fecPayloadId.ssId);
@@ -20705,6 +21233,10 @@ var MmtpRouter = class {
20705
21233
  // An FEC source frame is anchored by its own SS_ID (C.5.2).
20706
21234
  ...fecSource && fecPayloadId ? { fecSbn: fecPayloadId.ssId } : {}
20707
21235
  }, parsed);
21236
+ } else if (source === "multicast" && info.rapFlag) {
21237
+ this.#multicastRapTwinByStream.add(
21238
+ this.#mediaStreamKey(info.packetId, catalogTrackName)
21239
+ );
20708
21240
  }
20709
21241
  if (this.#classifyPacketId(info.packetId) === null) return;
20710
21242
  if (this.#fecManager && fecPayloadId && coords && sourceSymbolAccepted && sourceSymbolTrackable) {
@@ -21259,6 +21791,20 @@ var MmtpRouter = class {
21259
21791
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName) {
21260
21792
  if (ownerPacketId == null) return;
21261
21793
  if (this.#classifyPacketId(ownerPacketId) === null) return;
21794
+ const ssIdSeqOffset = this.#ssIdSeqOffsetByStream.get(
21795
+ this.#mediaStreamKey(ownerPacketId, catalogTrackName)
21796
+ );
21797
+ if (ssIdSeqOffset !== void 0) {
21798
+ result = {
21799
+ ...result,
21800
+ symbols: result.symbols.map((sym) => {
21801
+ const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
21802
+ if (wire === sym.packetSequenceNumber) return sym;
21803
+ this.#restampedRecoveredSeqs++;
21804
+ return { ...sym, packetSequenceNumber: wire };
21805
+ })
21806
+ };
21807
+ }
21262
21808
  this.#stream(ownerPacketId, catalogTrackName).duplicates.advance(blockId);
21263
21809
  const deliveryProvenance = this.#fecManager?.blockDeliveryProvenance?.(
21264
21810
  blockId,
@@ -21999,48 +22545,6 @@ function createWasmMmtpContainerParser(config) {
21999
22545
  });
22000
22546
  }
22001
22547
 
22002
- // src/fec-codec.ts
22003
- var NoneCodec = class {
22004
- constructor() {
22005
- this.algorithm = "none";
22006
- }
22007
- addSymbol(_blockId, _symbolId, data, _isRepair) {
22008
- return data;
22009
- }
22010
- configure(_params) {
22011
- }
22012
- cleanup(_now) {
22013
- return new Uint8Array(0);
22014
- }
22015
- };
22016
- function createFecCodec(algorithm) {
22017
- switch (algorithm) {
22018
- case "none":
22019
- return new NoneCodec();
22020
- case "reed-solomon":
22021
- return new ReedSolomonCodec();
22022
- case "raptorq":
22023
- console.warn("[FEC] RaptorQ requested via createFecCodec \u2014 use FECManager.setFecDecoder() for WASM RaptorQ. Falling back to NoneCodec.");
22024
- return new NoneCodec();
22025
- default:
22026
- console.warn(`[FEC] Unknown algorithm "${algorithm}", falling back to NoneCodec`);
22027
- return new NoneCodec();
22028
- }
22029
- }
22030
- var ReedSolomonCodec = class {
22031
- constructor() {
22032
- this.algorithm = "reed-solomon";
22033
- }
22034
- addSymbol(_blockId, _symbolId, _data, _isRepair) {
22035
- return null;
22036
- }
22037
- configure(_params) {
22038
- }
22039
- cleanup(_now) {
22040
- return new Uint8Array(0);
22041
- }
22042
- };
22043
-
22044
22548
  // src/multicast-transport.ts
22045
22549
  var JOIN_SUCCEEDED = Object.freeze({ ok: true });
22046
22550
  function providerErrorOf(error) {
@@ -22084,7 +22588,7 @@ function sameIds(a, b) {
22084
22588
  for (const id of a) if (!b.has(id)) return false;
22085
22589
  return true;
22086
22590
  }
22087
- var MulticastTransport = class _MulticastTransport {
22591
+ var MulticastTransport = class {
22088
22592
  #onPacket;
22089
22593
  #subscription = null;
22090
22594
  #packetListener = null;
@@ -22156,8 +22660,11 @@ var MulticastTransport = class _MulticastTransport {
22156
22660
  // droppedPacketIds.
22157
22661
  #unadvertisedPacketIds = /* @__PURE__ */ new Set();
22158
22662
  #joinGeneration = 0;
22159
- constructor(onPacket) {
22663
+ // The provider to subscribe through; window.multicast when unset.
22664
+ #gateway;
22665
+ constructor(onPacket, options = {}) {
22160
22666
  this.#onPacket = onPacket;
22667
+ this.#gateway = options.gateway;
22161
22668
  }
22162
22669
  static isAvailable() {
22163
22670
  return hasMulticastGateway();
@@ -22167,7 +22674,8 @@ var MulticastTransport = class _MulticastTransport {
22167
22674
  this.#releaseSubscription();
22168
22675
  this.#dataPlaneLive = false;
22169
22676
  if (this.#disposed) return this.#declined(generation, "disposed");
22170
- if (!_MulticastTransport.isAvailable()) {
22677
+ const gateway = this.#gateway ?? getMulticastGlobals().multicast;
22678
+ if (typeof gateway?.subscribe !== "function") {
22171
22679
  console.warn("[MulticastTransport] Multicast API not available");
22172
22680
  return this.#declined(generation, "unavailable");
22173
22681
  }
@@ -22184,11 +22692,13 @@ var MulticastTransport = class _MulticastTransport {
22184
22692
  mode: config.mode,
22185
22693
  amtRelay: config.amtRelay,
22186
22694
  amtRelayPort: config.amtRelayPort,
22695
+ amtDiscovery: config.amtDiscovery,
22187
22696
  packetIds: config.packetIds,
22188
- tracks: config.tracks
22697
+ tracks: config.tracks,
22698
+ atsc3: config.atsc3
22189
22699
  });
22190
22700
  failure = "provider-rejected";
22191
- const subscription = await getMulticastGlobals().multicast.subscribe(subscribeConfig);
22701
+ const subscription = await gateway.subscribe(subscribeConfig);
22192
22702
  failure = "invalid-subscription";
22193
22703
  console.log(`[MulticastTransport] window.multicast.subscribe returned:`, !!subscription);
22194
22704
  if (this.#disposed || generation !== this.#joinGeneration) {
@@ -22790,6 +23300,25 @@ function catalogAmtNetworkSource(networkSource) {
22790
23300
  }
22791
23301
  return void 0;
22792
23302
  }
23303
+ function intIn(value, min, max) {
23304
+ return Number.isInteger(value) && value >= min && value <= max;
23305
+ }
23306
+ function catalogAtsc3NetworkSource(networkSource) {
23307
+ const entries = Array.isArray(networkSource) ? networkSource : networkSource ? [networkSource] : [];
23308
+ for (const raw of entries) {
23309
+ if (!raw || typeof raw !== "object") continue;
23310
+ const ns = raw;
23311
+ if (ns.type !== "atsc3" || !intIn(ns.frequency, 1, Number.MAX_SAFE_INTEGER)) continue;
23312
+ const slsUri = typeof ns.slsUri === "string" ? ns.slsUri.trim() : "";
23313
+ return {
23314
+ frequency: ns.frequency,
23315
+ ...intIn(ns.plpId, 0, 63) ? { plpId: ns.plpId } : {},
23316
+ ...intIn(ns.serviceId, 0, 65535) ? { serviceId: ns.serviceId } : {},
23317
+ ...slsUri ? { slsUri } : {}
23318
+ };
23319
+ }
23320
+ return void 0;
23321
+ }
22793
23322
 
22794
23323
  // src/catalog-fec-params.ts
22795
23324
  var MAX_SAFE_TICKS_PER_HZ = Number.MAX_SAFE_INTEGER / 1e3;
@@ -23005,6 +23534,13 @@ function isoSpanUnavailable(fec, path, declaresFecInstance) {
23005
23534
  function catalogFecUnavailable(fec, fecPath) {
23006
23535
  if (catalogFecAvailable(fec)) return void 0;
23007
23536
  const block = recordOf3(fec);
23537
+ if (fecAlgorithmUnimplemented(block["algorithm"])) {
23538
+ return Object.freeze({
23539
+ code: "track_fec_algorithm_unimplemented",
23540
+ path: `${fecPath}.algorithm`,
23541
+ message: `algorithm ${JSON.stringify(block["algorithm"])} is not implemented: the track plays without FEC`
23542
+ });
23543
+ }
23008
23544
  const declaresFecInstance = block["algorithm"] !== "none";
23009
23545
  const reason = blockProfileUnavailable(block["blockProfile"], `${fecPath}.blockProfile`, declaresFecInstance) ?? isoSpanUnavailable(block, `${fecPath}.interleaveDepthMs`, declaresFecInstance);
23010
23546
  if (reason === void 0) {
@@ -23024,7 +23560,7 @@ function fecParams(catalog, track, rendition, fps, sampleRate) {
23024
23560
  throwRepairContractError(
23025
23561
  "track_fec",
23026
23562
  `${fecPath}.${kValid ? "symbolSize" : "sourceSymbols"}`,
23027
- "must be a positive integer"
23563
+ 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"
23028
23564
  );
23029
23565
  }
23030
23566
  const fecUnavailable = catalogFecUnavailable(fec, fecPath);
@@ -23033,6 +23569,7 @@ function fecParams(catalog, track, rendition, fps, sampleRate) {
23033
23569
  const fecBlockProfile = readFecBlockProfile(fec.blockProfile, `${fecPath}.blockProfile`, true, throwRepairContractError);
23034
23570
  return {
23035
23571
  fecK: fec.sourceSymbols ?? 0,
23572
+ fecAlgorithm: fec.algorithm === "reed-solomon" ? "reed-solomon" : "raptorq",
23036
23573
  fecBlockProfile,
23037
23574
  fecRepairCount: fec.repairSymbols ?? 0,
23038
23575
  // The wire RSB_length: every base layer's packets carry the base total (§7.1).
@@ -23129,8 +23666,10 @@ function newBlockPolicyStats(packetId, catalogTrackName, epoch) {
23129
23666
  repairsSkippedRttUnmeasured: 0,
23130
23667
  repairsSkippedRttExceedsBudget: 0,
23131
23668
  repairsSkippedPresentationDelayUnavailable: 0,
23669
+ repairsSkippedRangeNoAnchor: 0,
23132
23670
  lastRepairSkip: null,
23133
23671
  keyframeRepairFetchesSent: 0,
23672
+ rangeRepairFetchesSent: 0,
23134
23673
  keyframeBudgetHolds: 0,
23135
23674
  keyframeBudgetHoldMs: 0,
23136
23675
  deltaBlocksFailed: 0,
@@ -23209,6 +23748,12 @@ var REPAIR_PRIORITY_REASONS = /* @__PURE__ */ new Set([
23209
23748
  "repair-priority-absent",
23210
23749
  "repair-priority-invalid"
23211
23750
  ]);
23751
+ var REPAIR_SKIP_REASONS = /* @__PURE__ */ new Set([
23752
+ "rtt-unmeasured",
23753
+ "rtt-exceeds-budget",
23754
+ "presentation-delay-unavailable"
23755
+ ]);
23756
+ var REPAIR_DEADLINE_BOUNDS = /* @__PURE__ */ new Set(["wait", "presentation", "keyframe", "retention"]);
23212
23757
  var GAP_REASONS = {
23213
23758
  "rap-lost": "stall",
23214
23759
  "rap-unknown": "stall",
@@ -23231,6 +23776,9 @@ function isSymbolCounts(value) {
23231
23776
  function isNullableNonNegative(value) {
23232
23777
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
23233
23778
  }
23779
+ function isFiniteNumber(value) {
23780
+ return typeof value === "number" && Number.isFinite(value);
23781
+ }
23234
23782
  function isRepairLifecycleEvent(value) {
23235
23783
  if (!isRecord(value) || value["version"] !== 2) return false;
23236
23784
  const block = value["block"];
@@ -23248,6 +23796,20 @@ function isRepairLifecycleEvent(value) {
23248
23796
  case "repair-preempted":
23249
23797
  case "repair-deferred":
23250
23798
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
23799
+ case "repair-sent":
23800
+ return hasExactKeys(value, [
23801
+ "version",
23802
+ "type",
23803
+ "block",
23804
+ "priority",
23805
+ "rttMs",
23806
+ "budgetMs",
23807
+ "delayMs",
23808
+ "blockAgeMs",
23809
+ "bound"
23810
+ ]) && 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"]);
23811
+ case "repair-skipped":
23812
+ return hasExactKeys(value, ["version", "type", "block", "reason", "rttMs", "budgetMs"]) && isRepairBlockIdentity(block) && REPAIR_SKIP_REASONS.has(value["reason"]) && isNullableNonNegative(value["rttMs"]) && isFiniteNumber(value["budgetMs"]);
23251
23813
  case "repair-priority": {
23252
23814
  const blockClass = value["blockClass"];
23253
23815
  const action = value["action"];
@@ -23427,6 +23989,9 @@ var MulticastManager = class {
23427
23989
  #router;
23428
23990
  #hostMfuTimeoutMs;
23429
23991
  #transport;
23992
+ /** Live joinRepairEndpoints() releases → the repair owners they registered,
23993
+ * re-applied after configureMultiTrack() clears catalog-derived owners. */
23994
+ #repairReleases = /* @__PURE__ */ new Map();
23430
23995
  #reportedFecDiagnosticsFailure = false;
23431
23996
  // ── Stream-global FEC timing reduction ──
23432
23997
  //
@@ -23690,7 +24255,9 @@ var MulticastManager = class {
23690
24255
  catalogTrackName
23691
24256
  );
23692
24257
  this.#configureTrackMapper(packetId, config);
23693
- this.#router.setPacketIdType(packetId, trackType);
24258
+ if (this.#router.trackKindFor(packetId) !== trackType) {
24259
+ this.#router.setPacketIdType(packetId, trackType);
24260
+ }
23694
24261
  }
23695
24262
  /**
23696
24263
  * Stop routing a stream's symbols to its Worker decoder. Returns false when
@@ -23771,6 +24338,14 @@ var MulticastManager = class {
23771
24338
  );
23772
24339
  }
23773
24340
  }
24341
+ for (const [packetId, c] of this.#trackFecTiming) {
24342
+ if (c.deliveryWindowMs === void 0) continue;
24343
+ mfuTimeoutMs = Math.max(
24344
+ mfuTimeoutMs ?? 0,
24345
+ this.#fec.terminalRetentionMsForPacket(packetId) ?? 0,
24346
+ this.#hostMfuTimeoutMs ?? 0
24347
+ );
24348
+ }
23774
24349
  const failbackWindowMs = deliveryWindowMs === void 0 ? minimumFailbackWindowMs : Math.max(deliveryWindowMs, minimumFailbackWindowMs ?? 0);
23775
24350
  this.#transport.setFailbackWindowMs(failbackWindowMs ?? null);
23776
24351
  this.#router.setMfuTimeoutMs(mfuTimeoutMs ?? this.#hostMfuTimeoutMs);
@@ -23954,6 +24529,7 @@ var MulticastManager = class {
23954
24529
  setMfuTimeoutMs(ms) {
23955
24530
  this.#router.setMfuTimeoutMs(ms);
23956
24531
  this.#hostMfuTimeoutMs = this.#router.reassembler.timeoutMs;
24532
+ if (this.#trackFecTiming.size > 0) this.#applyStreamGlobalFecTiming();
23957
24533
  }
23958
24534
  setTrackCodec(packetId, codec) {
23959
24535
  this.#router.setTrackCodec(packetId, codec);
@@ -24074,11 +24650,80 @@ var MulticastManager = class {
24074
24650
  // through whatever the relay looks like, since dropping it would be the
24075
24651
  // worse behaviour.
24076
24652
  amtRelayPort: config.amtRelayPort ?? config.relayPort ?? (amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : void 0),
24653
+ amtDiscovery: config.amtDiscovery,
24077
24654
  packetIds: config.packetIds,
24078
24655
  tracks: catalogTracks?.map(({ name, packetId }) => ({ name, packetId }))
24079
24656
  };
24080
24657
  return ingress === void 0 ? this.#transport.join(transportConfig) : this.#transport.join(transportConfig, ingress);
24081
24658
  }
24659
+ /**
24660
+ * Join the selected rung's dedicated repair groups beside the media join
24661
+ * (pim #3898): one subscription per endpoint, through `provider` when given
24662
+ * (a `window.multicast`-shaped gateway or a subscribe callback), otherwise a
24663
+ * new MulticastTransport on `window.multicast`. Returns the call that
24664
+ * releases every one of them; dispose() releases them too.
24665
+ *
24666
+ * Packets go straight to the router with the endpoint's ingress, never
24667
+ * through feedPacket(): repair arriving on its own group is not media
24668
+ * liveness, so it must not hold off the media leg's failback watchdog. The
24669
+ * repair roles and owners are registered here; in-band owners stay the
24670
+ * caller's. Joining is best effort: a group that fails to join is logged
24671
+ * and leaves the media join as it was.
24672
+ */
24673
+ joinRepairEndpoints(endpoints, provider) {
24674
+ const releases = [];
24675
+ let released = false;
24676
+ const safely = (each) => {
24677
+ try {
24678
+ each();
24679
+ } catch (error) {
24680
+ console.warn("[MulticastManager] repair group release failed", error);
24681
+ }
24682
+ };
24683
+ const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners);
24684
+ this.#applyRepairOwners(repairOwners);
24685
+ for (const endpoint of endpoints) {
24686
+ const ingress = {
24687
+ tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId })))
24688
+ };
24689
+ const onPacket = (packet) => {
24690
+ if (!released) this.#router.feedPacket(packet, "multicast", void 0, ingress);
24691
+ };
24692
+ const fail = (error) => console.warn(`[MulticastManager] repair group ${endpoint.group}:${endpoint.port} not joined`, error);
24693
+ if (typeof provider === "function") {
24694
+ Promise.resolve().then(() => provider(endpoint, onPacket)).then((release2) => released ? safely(release2) : releases.push(release2), fail);
24695
+ continue;
24696
+ }
24697
+ const transport = new MulticastTransport((packet) => onPacket(packet), { gateway: provider });
24698
+ releases.push(() => transport.dispose());
24699
+ void transport.join({
24700
+ sourceAddress: endpoint.source,
24701
+ groupAddress: endpoint.group,
24702
+ port: endpoint.port,
24703
+ mode: endpoint.mode,
24704
+ amtRelay: endpoint.amtRelay,
24705
+ amtRelayPort: endpoint.amtRelayPort ?? (endpoint.amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : void 0),
24706
+ packetIds: endpoint.packetIds,
24707
+ tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId }))
24708
+ }).then((joined) => {
24709
+ if (!joined && !released) fail(transport.lastJoinOutcome);
24710
+ });
24711
+ }
24712
+ const release = () => {
24713
+ if (released) return;
24714
+ released = true;
24715
+ this.#repairReleases.delete(release);
24716
+ for (const each of releases.splice(0)) safely(each);
24717
+ };
24718
+ this.#repairReleases.set(release, repairOwners);
24719
+ return release;
24720
+ }
24721
+ #applyRepairOwners(owners) {
24722
+ for (const { packetId, ownerPacketId } of owners) {
24723
+ this.#router.setPacketIdRole(packetId, "repair");
24724
+ this.#router.setRepairPacketIdOwner(packetId, ownerPacketId);
24725
+ }
24726
+ }
24082
24727
  // ---------------------------------------------------------------------------
24083
24728
  // In-place rendition switch
24084
24729
  // ---------------------------------------------------------------------------
@@ -24354,7 +24999,7 @@ var MulticastManager = class {
24354
24999
  *
24355
25000
  * D-04: Validates completeness via validateSwitchingSet — throws if incomplete.
24356
25001
  * D-07: Applies per-track FEC configs (base+delta get decoders; repair does not).
24357
- * D-17: Builds altGroup → track-name index for getSwitchingSet().
25002
+ * D-17: Builds altGroup → track-name index for getSwitchingSet() (repair legs excluded).
24358
25003
  * D-26: Registers packetId → TrackRole on MmtpRouter for block-complete fanout.
24359
25004
  *
24360
25005
  * FEC availability is per track (draft-ramadan-moq-fec §5.1). A media track
@@ -24405,11 +25050,9 @@ var MulticastManager = class {
24405
25050
  }
24406
25051
  }
24407
25052
  const repairOwnerGroup = /* @__PURE__ */ new Map();
24408
- const repairOwnerAltGroup = /* @__PURE__ */ new Map();
24409
25053
  for (const track of catalog.tracks) {
24410
25054
  for (const repairName of repairNamesBySource.get(track.name) ?? []) {
24411
25055
  repairOwnerGroup.set(repairName, altGroupKey(track));
24412
- repairOwnerAltGroup.set(repairName, track.altGroup);
24413
25056
  }
24414
25057
  }
24415
25058
  const groupKeyFor = (track) => repairOwnerGroup.get(track.name) ?? altGroupKey(track);
@@ -24440,11 +25083,7 @@ var MulticastManager = class {
24440
25083
  for (const [groupKey, roles] of resolvedRolesByGroup) {
24441
25084
  if (!(hasSwitchingSetByGroup.get(groupKey) ?? false)) continue;
24442
25085
  const presentRoles = new Set(roles.filter((r) => r !== "single"));
24443
- const required = [
24444
- "base",
24445
- "delta",
24446
- "repair"
24447
- ];
25086
+ const required = ["base", "repair"];
24448
25087
  const missing = required.filter((r) => !presentRoles.has(r));
24449
25088
  if (missing.length > 0) {
24450
25089
  throw new Error(
@@ -24491,6 +25130,7 @@ var MulticastManager = class {
24491
25130
  this.#switchingSets.clear();
24492
25131
  this.#repairPacketIds.clear();
24493
25132
  this.#router.clearRepairPacketIdOwners();
25133
+ for (const owners of this.#repairReleases.values()) this.#applyRepairOwners(owners);
24494
25134
  const fecPacketIds = new Set([...fecDecoders.keys()].map((i) => catalog.tracks[i].packetId));
24495
25135
  for (const [packetId, catalogTrackName] of this.#multiTrackFecTracks) {
24496
25136
  if (fecPacketIds.has(packetId)) continue;
@@ -24511,11 +25151,10 @@ var MulticastManager = class {
24511
25151
  for (let i = 0; i < catalog.tracks.length; i++) {
24512
25152
  const track = catalog.tracks[i];
24513
25153
  const role = resolvedRoles[i];
24514
- const altGroup = repairOwnerAltGroup.has(track.name) ? repairOwnerAltGroup.get(track.name) : track.altGroup;
24515
- if (altGroup !== void 0) {
24516
- const existing = this.#switchingSets.get(altGroup) ?? [];
25154
+ if (role !== "repair" && track.altGroup !== void 0) {
25155
+ const existing = this.#switchingSets.get(track.altGroup) ?? [];
24517
25156
  existing.push(track.name);
24518
- this.#switchingSets.set(altGroup, existing);
25157
+ this.#switchingSets.set(track.altGroup, existing);
24519
25158
  }
24520
25159
  if (track.packetId !== void 0) {
24521
25160
  this.#router.setPacketIdRole(track.packetId, role);
@@ -24590,7 +25229,7 @@ var MulticastManager = class {
24590
25229
  #multiTrackFecTracks = /* @__PURE__ */ new Map();
24591
25230
  /**
24592
25231
  * Return the track names belonging to the given altGroup switching set.
24593
- * D-17: altGroup groups base+delta+repair into one switching set.
25232
+ * D-17: tracks with equal altGroup form one switching set; repair legs are in none.
24594
25233
  *
24595
25234
  * @param altGroup - The altGroup number to look up.
24596
25235
  * @returns Array of track names in that switching set (empty if none).
@@ -24618,6 +25257,26 @@ var MulticastManager = class {
24618
25257
  this.requestRepairForBlock(sbn, packetId, catalogTrackName, blockClass);
24619
25258
  };
24620
25259
  }
25260
+ /**
25261
+ * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
25262
+ * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
25263
+ * pending hole and reported here, and `closeIsoHoles` must be called for it
25264
+ * once its range FETCH ends (or none is sent).
25265
+ */
25266
+ onUndelimitedLoss(cb) {
25267
+ this.#fec.setUndelimitedLossHandler(cb);
25268
+ }
25269
+ /**
25270
+ * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
25271
+ * to CmcdProducer.updateFecFailClosed.
25272
+ */
25273
+ onFecFailClosed(cb) {
25274
+ this.#fec.setFecFailClosedHandler(cb);
25275
+ }
25276
+ /** End a pending hole's range repair: feed what no repair stated as spans. */
25277
+ closeIsoHoles(packetId, catalogTrackName, start, length) {
25278
+ this.#router.closeIsoHoles(packetId, catalogTrackName, start, length);
25279
+ }
24621
25280
  /**
24622
25281
  * Record a repair request whose SUBSCRIBER_PRIORITY the catalog could not
24623
25282
  * supply (draft-ramadan-moq-fec §11.4.5): sent without the parameter, or
@@ -24639,6 +25298,7 @@ var MulticastManager = class {
24639
25298
  stats.repairsSkipped++;
24640
25299
  if (reason === "rtt-unmeasured") stats.repairsSkippedRttUnmeasured++;
24641
25300
  else if (reason === "rtt-exceeds-budget") stats.repairsSkippedRttExceedsBudget++;
25301
+ else if (reason === "range-no-anchor") stats.repairsSkippedRangeNoAnchor++;
24642
25302
  else stats.repairsSkippedPresentationDelayUnavailable++;
24643
25303
  stats.lastRepairSkip = {
24644
25304
  reason,
@@ -24670,8 +25330,20 @@ var MulticastManager = class {
24670
25330
  stats.keyframeBudgetHoldMs += extensionMs;
24671
25331
  }
24672
25332
  /** Record a repair FETCH the scheduler admitted and sent. */
24673
- noteRepairFetchSent(priority, _sbn, packetId, catalogTrackName) {
25333
+ noteRepairFetchSent(priority, sbn, packetId, catalogTrackName, measurement) {
24674
25334
  if (priority === 0) this.#statsFor(packetId, catalogTrackName).keyframeRepairFetchesSent++;
25335
+ if (measurement.range) this.#statsFor(packetId, catalogTrackName).rangeRepairFetchesSent++;
25336
+ this.#emitRepairLifecycle({
25337
+ version: 2,
25338
+ type: "repair-sent",
25339
+ block: repairBlockIdentity(packetId, sbn, catalogTrackName),
25340
+ priority,
25341
+ rttMs: measurement.rttMs,
25342
+ budgetMs: measurement.budgetMs,
25343
+ delayMs: measurement.delayMs,
25344
+ blockAgeMs: measurement.blockAgeMs,
25345
+ bound: measurement.bound
25346
+ });
24675
25347
  }
24676
25348
  /**
24677
25349
  * Record a repair-scheduler decision about a delta block: preempted for
@@ -24822,6 +25494,7 @@ var MulticastManager = class {
24822
25494
  this.#trackResetObservers.clear();
24823
25495
  this.#repairLifecycleObservers.clear();
24824
25496
  this.#transport.dispose();
25497
+ for (const release of [...this.#repairReleases.keys()]) release();
24825
25498
  this.#router.dispose();
24826
25499
  this.#fec.dispose();
24827
25500
  }
@@ -24897,7 +25570,7 @@ async function setupFecWorkerForTrack(opts) {
24897
25570
  trackType: opts.trackType,
24898
25571
  framerate: opts.framerate,
24899
25572
  sampleRate: opts.sampleRate,
24900
- algorithm: "raptor",
25573
+ algorithm: opts.fecAlgorithm ?? "raptorq",
24901
25574
  blockProfile,
24902
25575
  k: opts.fecK,
24903
25576
  // P as this receiver joined it, not the catalog total: the worker snapshot
@@ -24911,10 +25584,10 @@ async function setupFecWorkerForTrack(opts) {
24911
25584
  repairTrack: opts.repairTrackName,
24912
25585
  relayBlockSigEnabled: false
24913
25586
  };
24914
- client.configure(fecTrackConfig, rqWasm);
24915
25587
  try {
24916
25588
  opts.multicastManager.setFecWorker(opts.packetId, client, opts.trackType, {
24917
25589
  blockProfile,
25590
+ algorithm: opts.fecAlgorithm ?? "raptorq",
24918
25591
  k: opts.fecK,
24919
25592
  symbolSize: opts.fecSymbolSize,
24920
25593
  interleaveDepthMs: opts.fecInterleaveMs,
@@ -24922,7 +25595,9 @@ async function setupFecWorkerForTrack(opts) {
24922
25595
  // the local cleanup budget, but it must not use a guessed fps for timing
24923
25596
  // or classification.
24924
25597
  ...hasCatalogTiming ? { fps: 1e3 / opts.mediaUnitDurationMs } : {},
24925
- timeoutMs: deliveryWindowMs
25598
+ timeoutMs: deliveryWindowMs,
25599
+ ...opts.fecRepairLayers ? { repairLayers: opts.fecRepairLayers } : {},
25600
+ ...opts.heldRepairLayers ? { heldLayers: opts.heldRepairLayers } : {}
24926
25601
  }, opts.trackName);
24927
25602
  } catch (e) {
24928
25603
  try {
@@ -24931,6 +25606,14 @@ async function setupFecWorkerForTrack(opts) {
24931
25606
  }
24932
25607
  throw e;
24933
25608
  }
25609
+ fecTrackConfig.interleaveDepth = Math.min(
25610
+ MAX_FEC_RETENTION_BLOCKS,
25611
+ Math.max(
25612
+ interleaveDepthBlocks,
25613
+ opts.multicastManager.fecManager.isoRetentionBlocksForPacket(opts.packetId) ?? 0
25614
+ )
25615
+ );
25616
+ client.configure(fecTrackConfig, rqWasm);
24934
25617
  let disposed = false;
24935
25618
  return {
24936
25619
  client,
@@ -25580,7 +26263,7 @@ function asSeconds(n) {
25580
26263
  }
25581
26264
  return n;
25582
26265
  }
25583
- function groupIdForTicks(ticks, groupDurationTicks) {
26266
+ function groupIdForTicks(ticks, groupDurationTicks, presentationAnchorTicks = 0) {
25584
26267
  if (!Number.isInteger(ticks)) {
25585
26268
  throw new Error(
25586
26269
  `[align] groupIdForTicks: ticks must be an integer, got ${ticks}`
@@ -25591,8 +26274,23 @@ function groupIdForTicks(ticks, groupDurationTicks) {
25591
26274
  `[align] groupIdForTicks: groupDurationTicks must be a positive integer, got ${groupDurationTicks}`
25592
26275
  );
25593
26276
  }
25594
- if (ticks < 0) return 0;
25595
- return Math.floor(ticks / groupDurationTicks);
26277
+ if (!Number.isInteger(presentationAnchorTicks)) {
26278
+ throw new Error(
26279
+ `[align] groupIdForTicks: presentationAnchorTicks must be an integer, got ${presentationAnchorTicks}`
26280
+ );
26281
+ }
26282
+ const relativeTicks = ticks - presentationAnchorTicks;
26283
+ if (!Number.isSafeInteger(relativeTicks)) {
26284
+ throw new Error(
26285
+ `[align] groupIdForTicks: ticks - presentationAnchorTicks = ${relativeTicks} is not a safe integer`
26286
+ );
26287
+ }
26288
+ if (relativeTicks < 0) {
26289
+ throw new Error(
26290
+ `[align] groupIdForTicks: ticks ${ticks} precede presentationAnchorTicks ${presentationAnchorTicks}; the publisher must reject this MPU (moq-mmt-01 4.4.1)`
26291
+ );
26292
+ }
26293
+ return Math.floor(relativeTicks / groupDurationTicks);
25596
26294
  }
25597
26295
  function groupIdFor(mediaTimeSec, groupDurationSec) {
25598
26296
  if (!Number.isFinite(mediaTimeSec)) {
@@ -25605,7 +26303,11 @@ function groupIdFor(mediaTimeSec, groupDurationSec) {
25605
26303
  `[align] groupIdFor: groupDurationSec must be a positive finite number, got ${groupDurationSec}`
25606
26304
  );
25607
26305
  }
25608
- if (mediaTimeSec < 0) return 0;
26306
+ if (mediaTimeSec < 0) {
26307
+ throw new Error(
26308
+ `[align] groupIdFor: mediaTimeSec ${mediaTimeSec} precedes presentationAnchorTicks 0; the publisher must reject this MPU (moq-mmt-01 4.4.1)`
26309
+ );
26310
+ }
25609
26311
  const TS = 1e9;
25610
26312
  const ticks = Math.round(mediaTimeSec * TS);
25611
26313
  const durTicks = Math.round(groupDurationSec * TS);
@@ -26446,6 +27148,7 @@ var CmcdProducer = class {
26446
27148
  #deltaFailRate = null;
26447
27149
  #switchMiscount = 0;
26448
27150
  #manifestStats = null;
27151
+ #fecFailClosed = null;
26449
27152
  constructor(options) {
26450
27153
  this.#onCmcdParams = options.onCmcdParams;
26451
27154
  this.#onCmcdPost = options.onCmcdPost;
@@ -26487,6 +27190,15 @@ var CmcdProducer = class {
26487
27190
  incrementSwitchMiscount() {
26488
27191
  this.#switchMiscount += 1;
26489
27192
  }
27193
+ /**
27194
+ * Record that FEC failed closed at runtime (fec-01 6.3.9). Every later
27195
+ * snapshot carries `x-bc-fec-fail-closed` (the reason code) and
27196
+ * `x-bc-fec-fail-layer` (the held layer i whose total B_i was undercut), so a
27197
+ * stream playing without FEC is told apart from one with no loss.
27198
+ */
27199
+ updateFecFailClosed(reason) {
27200
+ this.#fecFailClosed = reason;
27201
+ }
26490
27202
  updateManifestVerification(stats) {
26491
27203
  this.#manifestStats = stats;
26492
27204
  }
@@ -26524,6 +27236,10 @@ var CmcdProducer = class {
26524
27236
  if (this.#playMode !== null) {
26525
27237
  params["x-bc-play-mode"] = this.#playMode;
26526
27238
  }
27239
+ if (this.#fecFailClosed) {
27240
+ params["x-bc-fec-fail-closed"] = this.#fecFailClosed.code;
27241
+ params["x-bc-fec-fail-layer"] = this.#fecFailClosed.layer;
27242
+ }
26527
27243
  if (this.#playMode !== null && this.#playMode !== "single-track" && this.#deltaFailRate !== null) {
26528
27244
  params["x-bc-delta-fail-rate"] = parseFloat(this.#deltaFailRate.toFixed(4));
26529
27245
  }
@@ -26576,6 +27292,380 @@ var CmcdProducer = class {
26576
27292
  }
26577
27293
  };
26578
27294
 
27295
+ // src/mmtp-fec-session.ts
27296
+ var PATH_BITS = { moq: 1, multicast: 2 };
27297
+ var MIXED_PATHS = PATH_BITS.moq | PATH_BITS.multicast;
27298
+ var MmtpFecSession = class {
27299
+ #decoder;
27300
+ /** Blocks a repair has defined and that are not settled yet, by SS_Start. */
27301
+ #blocks = /* @__PURE__ */ new Map();
27302
+ /** SS_Starts of settled blocks, so a later repair for one is refused. */
27303
+ #settled = /* @__PURE__ */ new Set();
27304
+ /**
27305
+ * SS_IDs whose packet the parser has, with the PATH_BITS of the path it was
27306
+ * received on, or 0 for one the session recovered.
27307
+ */
27308
+ #have = /* @__PURE__ */ new Map();
27309
+ #newest;
27310
+ /** The newest SS_ID when the remembered SS_IDs were last pruned. */
27311
+ #prunedAt;
27312
+ #repairPacketId;
27313
+ #newestSource;
27314
+ #heldLayers;
27315
+ #anchorHorizon;
27316
+ #stats = {
27317
+ sourceSymbols: 0,
27318
+ repairSymbols: 0,
27319
+ blocksClean: 0,
27320
+ blocksRecovered: 0,
27321
+ blocksFailed: 0,
27322
+ blocksReleased: 0,
27323
+ packetsRecovered: 0,
27324
+ packetsLost: 0,
27325
+ dropped: {},
27326
+ sourceSymbolsByPath: { moq: 0, multicast: 0 },
27327
+ repairSymbolsByPath: { moq: 0, multicast: 0 },
27328
+ mixedPath: { clean: 0, recovered: 0, failed: 0, released: 0 },
27329
+ failClosed: null
27330
+ };
27331
+ /**
27332
+ * @throws when the catalog block lacks or misstates a field the session
27333
+ * needs: the block profile, K, P_0 (`repairSymbols`), T, `interleaveDepthMs` or
27334
+ * `reorderToleranceMs`. None is defaulted.
27335
+ */
27336
+ constructor(config) {
27337
+ const fec = config?.fec;
27338
+ if (!fec || typeof fec !== "object") {
27339
+ throw new Error("MmtpFecSession: the catalog fec block is required");
27340
+ }
27341
+ this.blockProfile = parseFecBlockProfile(fec.blockProfile, "fec.blockProfile");
27342
+ if (fec.algorithm !== void 0 && fec.algorithm !== "raptorq" && fec.algorithm !== "reed-solomon") {
27343
+ throw new Error(`MmtpFecSession: fec.algorithm ${JSON.stringify(fec.algorithm)} is not implemented`);
27344
+ }
27345
+ this.algorithm = fec.algorithm === "reed-solomon" ? "reed-solomon" : "raptorq";
27346
+ this.sourceSymbols = requirePositiveInteger(fec.sourceSymbols, "fec.sourceSymbols");
27347
+ this.repairSymbols = requirePositiveInteger(fec.repairSymbols, "fec.repairSymbols");
27348
+ this.symbolSize = requirePositiveInteger(fec.symbolSize, "fec.symbolSize");
27349
+ const interleaveDepthMs = requireNumber(fec.interleaveDepthMs, "fec.interleaveDepthMs");
27350
+ const reorderToleranceMs = requireNumber(fec.reorderToleranceMs, "fec.reorderToleranceMs");
27351
+ this.retentionBlocks = deriveFecRetentionBlocks(
27352
+ fecBlockBudgetMs(interleaveDepthMs, reorderToleranceMs),
27353
+ interleaveDepthMs
27354
+ );
27355
+ this.#heldLayers = new HeldLayerAdmission(
27356
+ config.repairLayers ?? [
27357
+ {
27358
+ layer: 0,
27359
+ repairTrackName: typeof fec.repairTrack === "string" ? fec.repairTrack : "",
27360
+ rsIdOffset: 0,
27361
+ repairSymbols: this.repairSymbols
27362
+ }
27363
+ ],
27364
+ config.heldLayers
27365
+ );
27366
+ this.#anchorHorizon = heldLayerAnchorHorizon(this.retentionBlocks, this.sourceSymbols);
27367
+ if (typeof config.Decoder !== "function") {
27368
+ throw new Error("MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required");
27369
+ }
27370
+ const decoder = new config.Decoder(this.retentionBlocks, this.blockProfile, this.algorithm);
27371
+ try {
27372
+ decoder.configure_params(this.sourceSymbols, this.symbolSize);
27373
+ } catch (error) {
27374
+ decoder.free();
27375
+ throw error;
27376
+ }
27377
+ this.#decoder = decoder;
27378
+ }
27379
+ /** True once release() ran. */
27380
+ get released() {
27381
+ return this.#decoder === null;
27382
+ }
27383
+ get stats() {
27384
+ return {
27385
+ ...this.#stats,
27386
+ dropped: { ...this.#stats.dropped },
27387
+ sourceSymbolsByPath: { ...this.#stats.sourceSymbolsByPath },
27388
+ repairSymbolsByPath: { ...this.#stats.repairSymbolsByPath },
27389
+ mixedPath: { ...this.#stats.mixedPath },
27390
+ failClosed: this.#stats.failClosed && { ...this.#stats.failClosed }
27391
+ };
27392
+ }
27393
+ /**
27394
+ * Feeds one received source packet: the MMTP packet without its four-byte
27395
+ * Source FEC Payload ID, under the SS_ID that ID stated. This is what
27396
+ * MmtpContainerParser's onSourceSymbol() hands over. `path` is where it
27397
+ * was received; a caller that only subscribes over MoQT can leave it out.
27398
+ *
27399
+ * @returns the protected packets of this packet's block that it recovered,
27400
+ * in SS_ID order, for the caller to feed to its parser with
27401
+ * `{skipFecPayloadId: true, recovered: true}`. Usually empty.
27402
+ */
27403
+ addSource(ssId, packet, path = "moq") {
27404
+ const decoder = this.#decoder;
27405
+ if (!decoder) return this.#drop("source:released");
27406
+ const pathBit = PATH_BITS[path];
27407
+ if (!pathBit) return this.#drop("source:unknown-path");
27408
+ if (!Number.isInteger(ssId) || ssId < 0 || ssId > 4294967295) return this.#drop("source:bad-ss-id");
27409
+ if (!ssbg1FitsSymbol(packet.byteLength, this.symbolSize)) return this.#drop("source:exceeds-symbol");
27410
+ if (this.#have.has(ssId)) return this.#drop("source:duplicate");
27411
+ this.#have.set(ssId, pathBit);
27412
+ this.#stats.sourceSymbols++;
27413
+ this.#stats.sourceSymbolsByPath[path]++;
27414
+ this.#noteNewest(ssId);
27415
+ if (this.#newestSource === void 0 || serial32Precedes(this.#newestSource, ssId)) this.#newestSource = ssId;
27416
+ const start = this.#blockStartOf(ssId);
27417
+ const block = start === void 0 ? void 0 : this.#blocks.get(start);
27418
+ if (block) {
27419
+ block.received++;
27420
+ block.paths |= pathBit;
27421
+ }
27422
+ let output;
27423
+ try {
27424
+ output = decoder.add_source(ssId, packet, 0);
27425
+ } catch {
27426
+ this.#drop("source:decoder-refused");
27427
+ output = void 0;
27428
+ }
27429
+ const recovered = [];
27430
+ if (start !== void 0 && block) {
27431
+ if (output) {
27432
+ recovered.push(...this.#settleDecoded(start, block, output));
27433
+ } else if (block.received >= block.ssbLength) {
27434
+ this.#settleClean(start);
27435
+ }
27436
+ }
27437
+ this.#retireBehindHorizon();
27438
+ return recovered;
27439
+ }
27440
+ /**
27441
+ * Feeds one object of the repair track: a whole MMTP repair packet (ISO/IEC
27442
+ * 23008-1 C.5.3). A repair track carries one repair flow, so the first
27443
+ * repair packet fixes its packet ID and a packet of any other is refused.
27444
+ * `path` is where it was received, as for addSource(). `repairTrackName`
27445
+ * is the repair track it was received on, for the 6.3.9 own-track rule; a
27446
+ * track the layers do not list is refused as `repair:unlisted-track`.
27447
+ *
27448
+ * @returns the protected packets this repair symbol recovered, as for
27449
+ * addSource().
27450
+ */
27451
+ addRepair(packet, path = "moq", repairTrackName) {
27452
+ const decoder = this.#decoder;
27453
+ if (!decoder) return this.#drop("repair:released");
27454
+ if (this.#stats.failClosed) return this.#drop("repair:fail-closed");
27455
+ const pathBit = PATH_BITS[path];
27456
+ if (!pathBit) return this.#drop("repair:unknown-path");
27457
+ let header;
27458
+ try {
27459
+ header = parseMMTPHeader(packet);
27460
+ } catch {
27461
+ return this.#drop("repair:malformed");
27462
+ }
27463
+ const frame = parseMoqRepairFrameWithHeader(packet, header);
27464
+ if (!frame) return this.#drop("repair:malformed");
27465
+ if (this.#repairPacketId === void 0) {
27466
+ this.#repairPacketId = frame.packetId;
27467
+ } else if (frame.packetId !== this.#repairPacketId) {
27468
+ return this.#drop("repair:foreign-packet-id");
27469
+ }
27470
+ if (frame.symbolData.byteLength !== this.symbolSize) return this.#drop("repair:symbol-size");
27471
+ if (frame.ssbLength > this.sourceSymbols) return this.#drop("repair:ssb-length");
27472
+ if (this.algorithm === "reed-solomon" && frame.ssbLength + frame.rsbLength > 255) {
27473
+ return this.#drop("repair:rs-block-length");
27474
+ }
27475
+ const verdict = this.#heldLayers.admit(
27476
+ repairTrackName,
27477
+ frame.ssStart,
27478
+ frame.rsbLength,
27479
+ this.#anchorHorizon,
27480
+ this.#newestSource
27481
+ );
27482
+ if (verdict === "discard") return this.#drop("repair:unlisted-track");
27483
+ if (verdict !== void 0) {
27484
+ this.#stats.failClosed = verdict;
27485
+ return this.#drop("repair:fail-closed");
27486
+ }
27487
+ const start = frame.ssStart;
27488
+ let block = this.#blocks.get(start);
27489
+ if (block && block.ssbLength !== frame.ssbLength) return this.#drop("repair:conflicting-ssb-length");
27490
+ if (block?.rsIds.has(frame.rsId)) return this.#drop("repair:duplicate");
27491
+ if (!block) {
27492
+ if (this.#settled.has(start)) return this.#drop("repair:block-settled");
27493
+ if (this.#behindHorizon(start)) return this.#drop("repair:behind-horizon");
27494
+ block = { ssbLength: frame.ssbLength, received: 0, paths: 0, rsIds: /* @__PURE__ */ new Set() };
27495
+ this.#countHeld(start, block);
27496
+ this.#blocks.set(start, block);
27497
+ }
27498
+ this.#noteNewest(serial32Add(start, frame.ssbLength - 1));
27499
+ if (block.received >= block.ssbLength) {
27500
+ this.#settleClean(start);
27501
+ this.#retireBehindHorizon();
27502
+ return [];
27503
+ }
27504
+ let output;
27505
+ try {
27506
+ output = decoder.add_repair(start, frame.ssbLength, frame.rsId, frame.symbolData, 0);
27507
+ } catch {
27508
+ return this.#drop("repair:decoder-refused");
27509
+ }
27510
+ block.rsIds.add(frame.rsId);
27511
+ this.#stats.repairSymbols++;
27512
+ this.#stats.repairSymbolsByPath[path]++;
27513
+ block.paths |= pathBit;
27514
+ const recovered = output ? this.#settleDecoded(start, block, output) : [];
27515
+ this.#retireBehindHorizon();
27516
+ return recovered;
27517
+ }
27518
+ /**
27519
+ * Frees the decoder and every block. Blocks still unsettled are counted as
27520
+ * released, not failed: nothing proved them unrecoverable. Idempotent;
27521
+ * returns whether this call released anything.
27522
+ */
27523
+ release() {
27524
+ const decoder = this.#decoder;
27525
+ if (!decoder) return false;
27526
+ this.#decoder = null;
27527
+ this.#stats.blocksReleased += this.#blocks.size;
27528
+ for (const block of this.#blocks.values()) this.#noteMixed(block, "released");
27529
+ this.#blocks.clear();
27530
+ this.#settled.clear();
27531
+ this.#have.clear();
27532
+ decoder.free();
27533
+ return true;
27534
+ }
27535
+ #drop(reason) {
27536
+ this.#stats.dropped[reason] = (this.#stats.dropped[reason] ?? 0) + 1;
27537
+ return [];
27538
+ }
27539
+ #noteNewest(ssId) {
27540
+ if (this.#newest === void 0 || serial32Precedes(this.#newest, ssId)) this.#newest = ssId;
27541
+ }
27542
+ #blockStartOf(ssId) {
27543
+ for (const [start, block] of this.#blocks) {
27544
+ if (isoBlockContains(start, block.ssbLength, ssId)) return start;
27545
+ }
27546
+ return void 0;
27547
+ }
27548
+ /** Counts the sources of a new block the parser already has, and their paths. */
27549
+ #countHeld(start, block) {
27550
+ for (let i = 0; i < block.ssbLength; i++) {
27551
+ const pathBit = this.#have.get(serial32Add(start, i));
27552
+ if (pathBit === void 0) continue;
27553
+ block.received++;
27554
+ block.paths |= pathBit;
27555
+ }
27556
+ }
27557
+ #noteMixed(block, outcome) {
27558
+ if ((block.paths & MIXED_PATHS) === MIXED_PATHS) this.#stats.mixedPath[outcome]++;
27559
+ }
27560
+ /** The decoder's own rule: more than its retention behind, counted from below. */
27561
+ #behindHorizon(start) {
27562
+ const newest = this.#newest;
27563
+ if (newest === void 0) return false;
27564
+ return isoBlocksBehindLowerBound(start, newest, this.sourceSymbols) > this.retentionBlocks;
27565
+ }
27566
+ #settle(start) {
27567
+ this.#blocks.delete(start);
27568
+ this.#settled.add(start);
27569
+ }
27570
+ #settleClean(start) {
27571
+ const block = this.#blocks.get(start);
27572
+ if (!block) return;
27573
+ this.#settle(start);
27574
+ this.#stats.blocksClean++;
27575
+ this.#noteMixed(block, "clean");
27576
+ try {
27577
+ this.#decoder?.cleanup_blocks_detailed(Uint32Array.of(start));
27578
+ } catch {
27579
+ }
27580
+ }
27581
+ /**
27582
+ * The decoder returns a completed block as its K' ssbg_mode1 symbols,
27583
+ * concatenated: split by T, trim by each symbol's length field, and hand
27584
+ * back the packets the parser does not have yet.
27585
+ */
27586
+ #settleDecoded(start, block, output) {
27587
+ this.#settle(start);
27588
+ if (output.byteLength !== block.ssbLength * this.symbolSize) {
27589
+ this.#stats.blocksFailed++;
27590
+ this.#stats.packetsLost += block.ssbLength - block.received;
27591
+ this.#noteMixed(block, "failed");
27592
+ this.#drop("block:decoded-length");
27593
+ return [];
27594
+ }
27595
+ const recovered = [];
27596
+ let refused = 0;
27597
+ for (let i = 0; i < block.ssbLength; i++) {
27598
+ const ssId = serial32Add(start, i);
27599
+ if (this.#have.has(ssId)) continue;
27600
+ const symbol = output.subarray(i * this.symbolSize, (i + 1) * this.symbolSize);
27601
+ const packet = trimSsbg1SourceSymbol(symbol);
27602
+ if (!packet) {
27603
+ refused++;
27604
+ continue;
27605
+ }
27606
+ this.#have.set(ssId, 0);
27607
+ recovered.push(packet.slice());
27608
+ }
27609
+ if (refused > 0) {
27610
+ this.#stats.blocksFailed++;
27611
+ this.#stats.packetsLost += refused;
27612
+ this.#noteMixed(block, "failed");
27613
+ this.#drop("block:bad-ssbg1-symbol");
27614
+ } else if (recovered.length === 0) {
27615
+ this.#stats.blocksClean++;
27616
+ this.#noteMixed(block, "clean");
27617
+ } else {
27618
+ this.#stats.blocksRecovered++;
27619
+ this.#noteMixed(block, "recovered");
27620
+ }
27621
+ this.#stats.packetsRecovered += recovered.length;
27622
+ return recovered;
27623
+ }
27624
+ /**
27625
+ * Retires every block, and every SS_ID the session remembers, that the
27626
+ * newest SS_ID has moved past the retention. An unsettled block retired
27627
+ * here is a failure: more of its sources were lost than its repair could
27628
+ * restore, or its repair never arrived.
27629
+ */
27630
+ #retireBehindHorizon() {
27631
+ const decoder = this.#decoder;
27632
+ const newest = this.#newest;
27633
+ if (!decoder || newest === void 0) return;
27634
+ try {
27635
+ decoder.cleanup_by_ss_start(newest);
27636
+ } catch {
27637
+ }
27638
+ for (const [start, block] of this.#blocks) {
27639
+ if (!this.#behindHorizon(start)) continue;
27640
+ this.#settle(start);
27641
+ this.#stats.blocksFailed++;
27642
+ this.#stats.packetsLost += block.ssbLength - block.received;
27643
+ this.#noteMixed(block, "failed");
27644
+ }
27645
+ const prunedAt = this.#prunedAt;
27646
+ if (prunedAt !== void 0 && serial32Distance(prunedAt, newest) < this.sourceSymbols) return;
27647
+ this.#prunedAt = newest;
27648
+ for (const ssId of this.#have.keys()) {
27649
+ if (this.#behindHorizon(ssId)) this.#have.delete(ssId);
27650
+ }
27651
+ for (const start of this.#settled) {
27652
+ if (this.#behindHorizon(start)) this.#settled.delete(start);
27653
+ }
27654
+ }
27655
+ };
27656
+ function requirePositiveInteger(value, path) {
27657
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
27658
+ throw new Error(`MmtpFecSession: ${path} must be a positive integer (got ${String(value)})`);
27659
+ }
27660
+ return value;
27661
+ }
27662
+ function requireNumber(value, path) {
27663
+ if (typeof value !== "number") {
27664
+ throw new Error(`MmtpFecSession: ${path} is required (got ${String(value)}); it is never defaulted`);
27665
+ }
27666
+ return value;
27667
+ }
27668
+
26579
27669
  // src/repair-fetch.ts
26580
27670
  var MOQT_PRIORITY_MAX = 255;
26581
27671
  var SOURCE_MEDIA_PRIORITY_MAX = REPAIR_PRIORITY_MIN - 1;
@@ -26610,6 +27700,9 @@ function wireRepairFetch(mc, opts) {
26610
27700
  if (typeof opts.presentationDelayMs !== "function") {
26611
27701
  throw new Error("[RepairFetch] presentationDelayMs is required: a repair FETCH is due by the block's presentation deadline");
26612
27702
  }
27703
+ if (opts.rangeTransport !== void 0 && (typeof opts.repairEpochReference !== "function" || !mc.onUndelimitedLoss || !mc.closeIsoHoles)) {
27704
+ throw new Error("[RepairFetch] rangeTransport needs repairEpochReference and a host that reports undelimited losses");
27705
+ }
26613
27706
  const entries = /* @__PURE__ */ new Map();
26614
27707
  const warnedNoTarget = /* @__PURE__ */ new Set();
26615
27708
  let disposed = false;
@@ -26623,7 +27716,12 @@ function wireRepairFetch(mc, opts) {
26623
27716
  const note = (type, entry) => {
26624
27717
  mc.noteRepairScheduling(type, entry.sbn, entry.packetId, entry.catalogTrackName);
26625
27718
  };
27719
+ const clearEntry = (entry) => {
27720
+ if (entry.range) mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, entry.range.holeLength);
27721
+ else clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27722
+ };
26626
27723
  const releaseHold = (entry) => {
27724
+ if (entry.range) return;
26627
27725
  if (entry.catalogTrackName === void 0) mc.fecManager.releaseRepairHold(entry.sbn, entry.packetId);
26628
27726
  else mc.fecManager.releaseRepairHold(entry.sbn, entry.packetId, entry.catalogTrackName);
26629
27727
  };
@@ -26656,10 +27754,10 @@ function wireRepairFetch(mc, opts) {
26656
27754
  const admit = (entry, now) => {
26657
27755
  const budgetMs = entry.deadlineAt - now;
26658
27756
  const rttMs = readRtt();
26659
- if (rttMs !== null && rttMs < budgetMs) return true;
27757
+ if (rttMs !== null && rttMs < budgetMs) return rttMs;
26660
27758
  retire(entry);
26661
27759
  releaseHold(entry);
26662
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27760
+ clearEntry(entry);
26663
27761
  mc.noteRepairSkipped(
26664
27762
  rttMs === null ? "rtt-unmeasured" : "rtt-exceeds-budget",
26665
27763
  { rttMs, budgetMs, priority: entry.priority },
@@ -26667,10 +27765,11 @@ function wireRepairFetch(mc, opts) {
26667
27765
  entry.packetId,
26668
27766
  entry.catalogTrackName
26669
27767
  );
26670
- return false;
27768
+ return null;
26671
27769
  };
26672
27770
  const retire = (entry) => {
26673
27771
  if (entries.get(entry.key) === entry) entries.delete(entry.key);
27772
+ if (entry.expiry !== void 0) clearTimeout(entry.expiry);
26674
27773
  };
26675
27774
  const urgentOutstanding = () => {
26676
27775
  for (const entry of entries.values()) {
@@ -26699,17 +27798,28 @@ function wireRepairFetch(mc, opts) {
26699
27798
  return derived.kind === "omit" ? { subscriberPriority: void 0 } : null;
26700
27799
  };
26701
27800
  const start = (entry, counted = true) => {
26702
- if (!admit(entry, performance.now())) return;
27801
+ const now = performance.now();
27802
+ const rttMs = admit(entry, now);
27803
+ if (rttMs === null) return;
26703
27804
  if (counted) entry.attempts++;
26704
- mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName);
27805
+ mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName, {
27806
+ rttMs,
27807
+ budgetMs: entry.deadlineAt - now,
27808
+ delayMs: entry.delayMs,
27809
+ blockAgeMs: entry.anchorAt === null ? null : Math.max(0, now - entry.anchorAt),
27810
+ bound: entry.bound,
27811
+ ...entry.range ? { range: true } : {}
27812
+ });
26705
27813
  const run = { controller: new AbortController(), stopped: null };
26706
27814
  entry.running = run;
26707
- mc.fecManager.holdBlockForRepair(
26708
- entry.sbn,
26709
- entry.packetId,
26710
- entry.catalogTrackName,
26711
- entry.deadlineAt
26712
- );
27815
+ if (!entry.range) {
27816
+ mc.fecManager.holdBlockForRepair(
27817
+ entry.sbn,
27818
+ entry.packetId,
27819
+ entry.catalogTrackName,
27820
+ entry.deadlineAt
27821
+ );
27822
+ }
26713
27823
  void execute(entry, run);
26714
27824
  };
26715
27825
  const dispatch = () => {
@@ -26721,14 +27831,14 @@ function wireRepairFetch(mc, opts) {
26721
27831
  if (entry.deadlineAt <= now) {
26722
27832
  stop(entry, "expired");
26723
27833
  retire(entry);
26724
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27834
+ clearEntry(entry);
26725
27835
  }
26726
27836
  continue;
26727
27837
  }
26728
27838
  if (entry.deadlineAt <= now) {
26729
27839
  retire(entry);
26730
27840
  if (entry.priority === 2 && entry.attempts === 0) note("repair-deferred", entry);
26731
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27841
+ clearEntry(entry);
26732
27842
  continue;
26733
27843
  }
26734
27844
  queued.push(entry);
@@ -26765,9 +27875,9 @@ function wireRepairFetch(mc, opts) {
26765
27875
  entry.running = null;
26766
27876
  if (error === void 0) {
26767
27877
  retire(entry);
26768
- if (fed === 0 || !decodable(entry)) {
27878
+ if (entry.range || fed === 0 || !decodable(entry)) {
26769
27879
  releaseHold(entry);
26770
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27880
+ clearEntry(entry);
26771
27881
  }
26772
27882
  dispatch();
26773
27883
  return;
@@ -26779,7 +27889,7 @@ function wireRepairFetch(mc, opts) {
26779
27889
  }
26780
27890
  retire(entry);
26781
27891
  if (fed === 0) releaseHold(entry);
26782
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27892
+ clearEntry(entry);
26783
27893
  console.warn(
26784
27894
  `[RepairFetch] fetch failed pid=${entry.packetId} sbn=${entry.sbn} track=${entry.repairTrack}:`,
26785
27895
  error
@@ -26795,15 +27905,21 @@ function wireRepairFetch(mc, opts) {
26795
27905
  };
26796
27906
  const execute = async (entry, run) => {
26797
27907
  let fed = 0;
27908
+ const common = {
27909
+ repairTrack: entry.repairTrack,
27910
+ blockProfile: entry.blockProfile,
27911
+ packetId: entry.packetId,
27912
+ signal: run.controller.signal,
27913
+ subscriberPriority: entry.subscriberPriority
27914
+ };
26798
27915
  try {
26799
- for await (const packet of opts.transport({
26800
- repairTrack: entry.repairTrack,
26801
- sbn: entry.sbn,
26802
- blockProfile: entry.blockProfile,
26803
- packetId: entry.packetId,
26804
- signal: run.controller.signal,
26805
- subscriberPriority: entry.subscriberPriority
26806
- })) {
27916
+ const packets = entry.range ? opts.rangeTransport({
27917
+ ...common,
27918
+ startGroup: entry.range.startGroup,
27919
+ endGroup: entry.range.endGroup,
27920
+ lostSsId: entry.range.lostSsId
27921
+ }) : opts.transport({ ...common, sbn: entry.sbn });
27922
+ for await (const packet of packets) {
26807
27923
  if (run.stopped !== null || entry.running !== run) break;
26808
27924
  fed++;
26809
27925
  if (entry.catalogTrackName === void 0) {
@@ -26822,6 +27938,7 @@ function wireRepairFetch(mc, opts) {
26822
27938
  if (entry.packetId !== packetId || entry.catalogTrackName !== catalogTrackName) continue;
26823
27939
  retire(entry);
26824
27940
  stop(entry, "reset");
27941
+ if (entry.range) clearEntry(entry);
26825
27942
  }
26826
27943
  warnedNoTarget.delete(noTargetKey(packetId, catalogTrackName));
26827
27944
  dispatch();
@@ -26848,6 +27965,9 @@ function wireRepairFetch(mc, opts) {
26848
27965
  );
26849
27966
  if (promotedDeadline !== null && promotedDeadline.deadlineAt > entry2.deadlineAt) {
26850
27967
  entry2.deadlineAt = promotedDeadline.deadlineAt;
27968
+ entry2.anchorAt = promotedDeadline.anchorAt;
27969
+ entry2.delayMs = promotedDeadline.delayMs;
27970
+ entry2.bound = promotedDeadline.bound;
26851
27971
  noteBudget(entry2, promotedDeadline.extensionMs);
26852
27972
  }
26853
27973
  if (entry2.running) {
@@ -26873,7 +27993,9 @@ function wireRepairFetch(mc, opts) {
26873
27993
  if (waitMs === void 0) return null;
26874
27994
  const waitDeadlineAt = now + waitMs;
26875
27995
  const anchor = mc.fecManager.blockAnchorAtMs(sbn, packetId, catalogTrackName);
26876
- if (anchor === void 0) return { deadlineAt: waitDeadlineAt, extensionMs: 0 };
27996
+ if (anchor === void 0) {
27997
+ return { deadlineAt: waitDeadlineAt, extensionMs: 0, anchorAt: null, delayMs: null, bound: "wait" };
27998
+ }
26877
27999
  let delayMs;
26878
28000
  try {
26879
28001
  delayMs = opts.presentationDelayMs(packetId, catalogTrackName);
@@ -26884,12 +28006,21 @@ function wireRepairFetch(mc, opts) {
26884
28006
  const retentionMs = mc.fecManager.terminalRetentionMsForPacket(packetId);
26885
28007
  if (retentionMs === void 0) return null;
26886
28008
  const ceilingAt = Math.min(anchor, earliestGatedFrameAt(packetId, catalogTrackName) ?? anchor) + retentionMs;
26887
- const deadlineAt = (delay) => Math.max(waitDeadlineAt, Math.min(anchor + delay, ceilingAt));
26888
- const base = deadlineAt(delayMs);
28009
+ const at = (delay, delayBound) => {
28010
+ const presentAt = Math.min(anchor + delay, ceilingAt);
28011
+ if (waitDeadlineAt >= presentAt) return { deadlineAt: waitDeadlineAt, bound: "wait" };
28012
+ return { deadlineAt: presentAt, bound: anchor + delay <= ceilingAt ? delayBound : "retention" };
28013
+ };
28014
+ const base = at(delayMs, "presentation");
26889
28015
  const budgetMs = keyframeBudgetEligible(blockClass, classifierMode(packetId, catalogTrackName)) && groupCanComplete(sbn, packetId, catalogTrackName) ? readKeyframeBudget(packetId, catalogTrackName) : null;
26890
- if (budgetMs === null || budgetMs <= delayMs) return { deadlineAt: base, extensionMs: 0 };
26891
- const extended = deadlineAt(budgetMs);
26892
- return { deadlineAt: extended, extensionMs: extended - base };
28016
+ if (budgetMs === null || budgetMs <= delayMs) return { ...base, extensionMs: 0, anchorAt: anchor, delayMs };
28017
+ const extended = at(budgetMs, "keyframe");
28018
+ return {
28019
+ ...extended,
28020
+ extensionMs: extended.deadlineAt - base.deadlineAt,
28021
+ anchorAt: anchor,
28022
+ delayMs: budgetMs
28023
+ };
26893
28024
  };
26894
28025
  const earliestGatedFrameAt = (packetId, catalogTrackName) => {
26895
28026
  try {
@@ -26966,6 +28097,9 @@ function wireRepairFetch(mc, opts) {
26966
28097
  priority,
26967
28098
  subscriberPriority: wire.subscriberPriority,
26968
28099
  deadlineAt: deadline.deadlineAt,
28100
+ anchorAt: deadline.anchorAt,
28101
+ delayMs: deadline.delayMs,
28102
+ bound: deadline.bound,
26969
28103
  order: enqueueOrder++,
26970
28104
  attempts: 0,
26971
28105
  running: null
@@ -26975,14 +28109,92 @@ function wireRepairFetch(mc, opts) {
26975
28109
  if (entry.priority < 2) preemptDeltas();
26976
28110
  dispatch();
26977
28111
  });
28112
+ const rangeFor = (loss, repairTrack) => {
28113
+ let reference;
28114
+ try {
28115
+ reference = opts.repairEpochReference(repairTrack);
28116
+ } catch {
28117
+ return null;
28118
+ }
28119
+ if (reference === void 0) return null;
28120
+ try {
28121
+ const anchor = loss.previousBlockStart === void 0 ? { reference } : { previousBlockStart: extendSsId(reference, loss.previousBlockStart) };
28122
+ return repairFetchRange(loss.lostSsId, loss.kMax, anchor);
28123
+ } catch (error) {
28124
+ if (error instanceof RangeError) return null;
28125
+ throw error;
28126
+ }
28127
+ };
28128
+ if (opts.rangeTransport !== void 0) {
28129
+ mc.onUndelimitedLoss((loss) => {
28130
+ const { packetId, catalogTrackName, holeStart, holeLength } = loss;
28131
+ const close = () => mc.closeIsoHoles(packetId, catalogTrackName, holeStart, holeLength);
28132
+ if (disposed) return close();
28133
+ const blockProfile = blockProfileOf(packetId);
28134
+ const target = opts.resolveTarget(packetId, catalogTrackName);
28135
+ if (!target) return close();
28136
+ const priority = repairPriorityForClass("unknown");
28137
+ const range = rangeFor(loss, target.repairTrack);
28138
+ if (range === null) {
28139
+ close();
28140
+ mc.noteRepairSkipped("range-no-anchor", { rttMs: readRtt(), budgetMs: 0, priority }, holeStart, packetId, catalogTrackName);
28141
+ return;
28142
+ }
28143
+ const identity = {
28144
+ target,
28145
+ sbn: holeStart,
28146
+ packetId,
28147
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
28148
+ };
28149
+ const wire = wirePriority(identity, "unknown");
28150
+ const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, performance.now(), "unknown");
28151
+ if (deadline === null) {
28152
+ close();
28153
+ mc.noteRepairSkipped(
28154
+ "presentation-delay-unavailable",
28155
+ { rttMs: readRtt(), budgetMs: 0, priority },
28156
+ holeStart,
28157
+ packetId,
28158
+ catalogTrackName
28159
+ );
28160
+ return;
28161
+ }
28162
+ const entry = {
28163
+ key: JSON.stringify(["range", packetId, catalogTrackName ?? null, holeStart]),
28164
+ ...identity,
28165
+ repairTrack: target.repairTrack,
28166
+ blockProfile,
28167
+ priority,
28168
+ subscriberPriority: wire.subscriberPriority,
28169
+ deadlineAt: deadline.deadlineAt,
28170
+ anchorAt: deadline.anchorAt,
28171
+ delayMs: deadline.delayMs,
28172
+ bound: deadline.bound,
28173
+ order: enqueueOrder++,
28174
+ attempts: 0,
28175
+ running: null,
28176
+ range: { ...range, lostSsId: loss.lostSsId, holeLength }
28177
+ };
28178
+ const previous = entries.get(entry.key);
28179
+ if (previous) {
28180
+ retire(previous);
28181
+ stop(previous, "reset");
28182
+ }
28183
+ entries.set(entry.key, entry);
28184
+ entry.expiry = setTimeout(dispatch, Math.max(0, entry.deadlineAt - performance.now()) + 1);
28185
+ preemptDeltas();
28186
+ dispatch();
28187
+ });
28188
+ }
26978
28189
  return () => {
26979
28190
  disposed = true;
26980
28191
  removeResetObserver();
26981
28192
  removeLifecycleObserver();
26982
28193
  for (const entry of [...entries.values()]) {
26983
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
28194
+ clearEntry(entry);
26984
28195
  if (entry.running) releaseHold(entry);
26985
28196
  stop(entry, "disposed");
28197
+ if (entry.expiry !== void 0) clearTimeout(entry.expiry);
26986
28198
  }
26987
28199
  entries.clear();
26988
28200
  };
@@ -27021,20 +28233,19 @@ export {
27021
28233
  MfuReassemblyError,
27022
28234
  MmtpContainerParser,
27023
28235
  MmtpDecodePipeline,
28236
+ MmtpFecSession,
27024
28237
  MmtpRouter,
27025
28238
  MmtpToCmaf,
27026
28239
  MulticastContainerContractError,
27027
28240
  MulticastInputError,
27028
28241
  MulticastManager,
27029
28242
  MulticastTransport,
27030
- NoneCodec,
27031
28243
  REPAIR_LIFECYCLE_EVENT_TYPE,
27032
28244
  REPAIR_LIFECYCLE_LOG_PREFIX,
27033
28245
  REPAIR_PRIORITY_MAX,
27034
28246
  REPAIR_PRIORITY_MIN,
27035
28247
  REPAIR_TRACK_GEOMETRY_KEYS,
27036
28248
  REPAIR_TRACK_ONLY_KEYS,
27037
- ReedSolomonCodec,
27038
28249
  RepairContractError,
27039
28250
  SOURCE_MEDIA_PRIORITY_MAX,
27040
28251
  SampleCombineError,
@@ -27055,6 +28266,7 @@ export {
27055
28266
  buildHevcVideoInitSegment,
27056
28267
  buildVideoInitSegment,
27057
28268
  catalogAmtNetworkSource,
28269
+ catalogAtsc3NetworkSource,
27058
28270
  catalogDeclaresFec,
27059
28271
  catalogFecAvailable,
27060
28272
  catalogFecDeclaresUnconfigurableInstance,
@@ -27071,7 +28283,6 @@ export {
27071
28283
  computeFecDeliveryWindowMediaUnits,
27072
28284
  computeFecDeliveryWindowMs,
27073
28285
  computeFecLossWindowMs,
27074
- createFecCodec,
27075
28286
  createFragment,
27076
28287
  createWasmMmtpContainerParser,
27077
28288
  datagramMfuReassembly,
@@ -27099,6 +28310,7 @@ export {
27099
28310
  extractHevcCodecDescription,
27100
28311
  extractHevcParameterSets,
27101
28312
  extractSpsPpsFromAvcC,
28313
+ fecAlgorithmUnimplemented,
27102
28314
  findAnnexBStartCode,
27103
28315
  forwardRepairLifecycleEvents,
27104
28316
  frameSamplesFromInit,