@blockcast/mmt-container 0.4.0 → 0.4.1-main.22841c1f0a2d

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 (220) hide show
  1. package/README.md +37 -21
  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 +2037 -881
  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 +13 -1
  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/mfu-reassembler.js +21 -13
  55. package/dist/mfu-reassembler.js.map +2 -2
  56. package/dist/mmtp-container-parser.d.ts.map +1 -1
  57. package/dist/mmtp-container-parser.js +93 -22
  58. package/dist/mmtp-container-parser.js.map +2 -2
  59. package/dist/mmtp-container-parser.no-modules.js +3677 -1213
  60. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  61. package/dist/mmtp-decode-pipeline.js +93 -22
  62. package/dist/mmtp-decode-pipeline.js.map +2 -2
  63. package/dist/mmtp-fec-session.d.ts +192 -0
  64. package/dist/mmtp-fec-session.d.ts.map +1 -0
  65. package/dist/mmtp-fec-session.js +640 -0
  66. package/dist/mmtp-fec-session.js.map +7 -0
  67. package/dist/mmtp-router.d.ts +69 -32
  68. package/dist/mmtp-router.d.ts.map +1 -1
  69. package/dist/mmtp-router.js +296 -192
  70. package/dist/mmtp-router.js.map +2 -2
  71. package/dist/multicast-auth-catalog.d.ts +86 -92
  72. package/dist/multicast-auth-catalog.d.ts.map +1 -1
  73. package/dist/multicast-auth-catalog.js +313 -124
  74. package/dist/multicast-auth-catalog.js.map +3 -3
  75. package/dist/multicast-input.d.ts +31 -8
  76. package/dist/multicast-input.d.ts.map +1 -1
  77. package/dist/multicast-input.js +299 -35
  78. package/dist/multicast-input.js.map +3 -3
  79. package/dist/multicast-manager.d.ts +97 -11
  80. package/dist/multicast-manager.d.ts.map +1 -1
  81. package/dist/multicast-manager.js +1022 -527
  82. package/dist/multicast-manager.js.map +4 -4
  83. package/dist/multicast-transport.d.ts +12 -2
  84. package/dist/multicast-transport.d.ts.map +1 -1
  85. package/dist/multicast-transport.js +108 -238
  86. package/dist/multicast-transport.js.map +4 -4
  87. package/dist/multicast-unwrap.js +21 -13
  88. package/dist/multicast-unwrap.js.map +2 -2
  89. package/dist/no-modules.d.ts +5 -3
  90. package/dist/no-modules.d.ts.map +1 -1
  91. package/dist/no-modules.js +3625 -1194
  92. package/dist/no-modules.js.map +4 -4
  93. package/dist/phase14-catalog-override.d.ts +1 -1
  94. package/dist/phase14-catalog-override.d.ts.map +1 -1
  95. package/dist/phase14-catalog-override.js +2 -2
  96. package/dist/phase14-catalog-override.js.map +2 -2
  97. package/dist/repair-fetch.d.ts +81 -6
  98. package/dist/repair-fetch.d.ts.map +1 -1
  99. package/dist/repair-fetch.js +156 -31
  100. package/dist/repair-fetch.js.map +3 -3
  101. package/dist/repair-layers.d.ts +2 -0
  102. package/dist/repair-layers.d.ts.map +1 -1
  103. package/dist/repair-layers.js +19 -2
  104. package/dist/repair-layers.js.map +2 -2
  105. package/dist/sample-combiner.d.ts +7 -1
  106. package/dist/sample-combiner.d.ts.map +1 -1
  107. package/dist/sample-combiner.js +14 -2
  108. package/dist/sample-combiner.js.map +2 -2
  109. package/dist/signaling.d.ts +2 -2
  110. package/dist/signaling.d.ts.map +1 -1
  111. package/dist/signaling.js +3 -3
  112. package/dist/signaling.js.map +2 -2
  113. package/dist/switching-set-alignment.d.ts +1 -1
  114. package/dist/switching-set-alignment.js.map +1 -1
  115. package/dist/timestamp-codec.js +21 -13
  116. package/dist/timestamp-codec.js.map +2 -2
  117. package/dist/wasm-mfu-reassembler.js.map +1 -1
  118. package/dist/wasm-mmtp-container-parser.js +93 -22
  119. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  120. package/package.json +6 -18
  121. package/schemas/catalog.schema.json +133 -38
  122. package/src/align.ts +52 -21
  123. package/src/carp-catalog.ts +188 -68
  124. package/src/catalog-fec-params.ts +28 -3
  125. package/src/catalog-network-source.ts +49 -7
  126. package/src/catalog-validator.ts +4 -11
  127. package/src/cmcd-producer.ts +23 -1
  128. package/src/fec-manager.ts +366 -63
  129. package/src/fec-state.ts +11 -4
  130. package/src/fec-worker-setup.ts +30 -2
  131. package/src/held-layer-admission.ts +161 -0
  132. package/src/index.ts +32 -19
  133. package/src/iso-block-locator.ts +110 -7
  134. package/src/mmtp-container-parser.ts +75 -7
  135. package/src/mmtp-fec-session.ts +606 -0
  136. package/src/mmtp-router.ts +301 -240
  137. package/src/multicast-auth-catalog.ts +134 -238
  138. package/src/multicast-input.ts +148 -124
  139. package/src/multicast-manager.ts +271 -40
  140. package/src/multicast-transport.ts +17 -3
  141. package/src/no-modules.ts +8 -7
  142. package/src/phase14-catalog-override.ts +3 -3
  143. package/src/repair-fetch.ts +283 -39
  144. package/src/repair-layers.ts +22 -2
  145. package/src/sample-combiner.ts +15 -2
  146. package/src/signaling.ts +2 -2
  147. package/src/switching-set-alignment.ts +1 -1
  148. package/test-vectors/align.json +108 -32
  149. package/test-vectors/bc-provenance-v2.json +1526 -0
  150. package/test-vectors/catalog/README.md +71 -4
  151. package/test-vectors/catalog/negative/fec-block-profile-missing.json +1 -1
  152. package/test-vectors/catalog/negative/fec-block-profile-retired.json +1 -1
  153. package/test-vectors/catalog/negative/fec-block-profile-unknown.json +1 -1
  154. package/test-vectors/catalog/negative/fec-iso-symbol-size-below-floor.json +28 -0
  155. package/test-vectors/catalog/negative/fec-reed-solomon-iso-symbol-size-13.json +28 -0
  156. package/test-vectors/catalog/negative/fec-reed-solomon-k-plus-p-over-255.json +39 -0
  157. package/test-vectors/catalog/negative/fec-reed-solomon-overlay-over-255.json +40 -0
  158. package/test-vectors/catalog/negative/fec-repair-overlay-source-symbols-zero.json +43 -0
  159. package/test-vectors/catalog/negative/fec-repair-symbols-zero.json +28 -0
  160. package/test-vectors/catalog/negative/fec-source-symbols-zero.json +28 -0
  161. package/test-vectors/catalog/negative/fec-symbol-size-zero.json +28 -0
  162. package/test-vectors/catalog/negative/init-data-inline-without-data.json +22 -0
  163. package/test-vectors/catalog/negative/mmtp-mode-mpu.json +15 -0
  164. package/test-vectors/catalog/negative/multicast-amt-dns-without-relay.json +37 -0
  165. package/test-vectors/catalog/negative/multicast-amt-driad-with-relay.json +38 -0
  166. package/test-vectors/catalog/negative/multicast-auth-asm-missing-sender-address.json +77 -0
  167. package/test-vectors/catalog/negative/multicast-auth-duplicate-first-epoch.json +56 -0
  168. package/test-vectors/catalog/negative/multicast-auth-duplicate-kid.json +56 -0
  169. package/test-vectors/catalog/negative/multicast-auth-endpoint-auth-without-object-auth.json +38 -0
  170. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-auth.json +49 -0
  171. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-bandwidth.json +55 -0
  172. package/test-vectors/catalog/negative/multicast-auth-manifest-port-equals-port.json +56 -0
  173. package/test-vectors/catalog/negative/multicast-auth-manifest-timer-out-of-range.json +56 -0
  174. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-above-max.json +56 -0
  175. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-below-min.json +56 -0
  176. package/test-vectors/catalog/negative/multicast-auth-root-dotted-key.json +55 -0
  177. package/test-vectors/catalog/negative/multicast-auth-sender-address-on-ssm.json +57 -0
  178. package/test-vectors/catalog/negative/multicast-auth-version-1.json +56 -0
  179. package/test-vectors/catalog/negative/multicast-auth-version-3.json +56 -0
  180. package/test-vectors/catalog/negative/multicast-auth-version-missing.json +55 -0
  181. package/test-vectors/catalog/negative/multicast-endpoint-foreign-namespace-track.json +44 -0
  182. package/test-vectors/catalog/negative/multicast-endpoint-protocol-amt.json +38 -0
  183. package/test-vectors/catalog/negative/multicast-endpoint-protocol-atsc3.json +38 -0
  184. package/test-vectors/catalog/negative/presentation-anchor-unsafe.json +16 -0
  185. package/test-vectors/catalog/positive/fec-algorithm-unimplemented.json +29 -0
  186. package/test-vectors/catalog/positive/fec-iso-ssbg1.json +1 -1
  187. package/test-vectors/catalog/positive/fec-multicast.json +1 -1
  188. package/test-vectors/catalog/positive/fec-reed-solomon-layered.json +50 -0
  189. package/test-vectors/catalog/positive/mmt01-12-1-init-ref-anchor.json +29 -0
  190. package/test-vectors/catalog/positive/multicast-amt-discovery-omitted.json +37 -0
  191. package/test-vectors/catalog/positive/multicast-amt-dns-relay.json +38 -0
  192. package/test-vectors/catalog/positive/multicast-amt-manual-relay.json +3 -3
  193. package/test-vectors/catalog/{negative/multicast-endpoint-missing-protocol-and-source.json → positive/multicast-asm-unprotected.json} +10 -5
  194. package/test-vectors/catalog/positive/multicast-auth-asm-sender.json +78 -0
  195. package/test-vectors/catalog/positive/multicast-auth-rotation.json +39 -38
  196. package/test-vectors/catalog/positive/multicast-draft01-4-1-example.json +81 -0
  197. package/test-vectors/catalog/positive/multicast-draft01-7-2-6-example.json +70 -0
  198. package/test-vectors/catalog/positive/presentation-anchor-negative.json +27 -0
  199. package/test-vectors/catalog/section-codes.json +31 -1
  200. package/test-vectors/catalog-multicast-auth-v1.json +38 -20
  201. package/test-vectors/catalog-validation.json +101 -5
  202. package/test-vectors/catalog-validator-public-api.mjs +14 -9
  203. package/test-vectors/generate-bc-provenance-v2.mjs +252 -0
  204. package/dist/fec-codec.d.ts +0 -32
  205. package/dist/fec-codec.d.ts.map +0 -1
  206. package/dist/fec-codec.js +0 -47
  207. package/dist/fec-codec.js.map +0 -7
  208. package/dist/manifest-auth-plan.d.ts +0 -30
  209. package/dist/manifest-auth-plan.d.ts.map +0 -1
  210. package/dist/manifest-auth-plan.js +0 -1266
  211. package/dist/manifest-auth-plan.js.map +0 -7
  212. package/dist/source-auth.d.ts +0 -2
  213. package/dist/source-auth.d.ts.map +0 -1
  214. package/dist/source-auth.js +0 -1209
  215. package/dist/source-auth.js.map +0 -7
  216. package/src/fec-codec.ts +0 -61
  217. package/src/manifest-auth-plan.ts +0 -107
  218. package/src/source-auth.ts +0 -1
  219. package/test-vectors/generate-source-auth-fixture.mjs +0 -114
  220. package/test-vectors/source-auth-v1.json +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,24 +7297,63 @@ var AdaptiveBitrateController = class {
7337
7297
  }
7338
7298
  };
7339
7299
 
7340
- // node_modules/@blockcast/mmt-transport/dist/multicast-orchestrator.js
7341
- var DEFAULT_DWELL_MS = 3e3;
7342
- var DEFAULT_JOIN_DEADLINE_MS = 5e3;
7343
- var MulticastOrchestrator = class {
7344
- options;
7345
- #state = "stable";
7346
- #current;
7347
- #target;
7348
- #estimate;
7349
- #favored;
7350
- #joinStartedAt = 0;
7351
- /**
7352
- * Latest active-tier send time (NTP short), or undefined before the first.
7353
- * "Latest" is serial order, not the numerically largest value: after the
7354
- * field wraps, the largest value is the stale one.
7355
- */
7356
- #highWater;
7357
- #dwellMs;
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
+
7339
+ // node_modules/@blockcast/mmt-transport/dist/multicast-orchestrator.js
7340
+ var DEFAULT_DWELL_MS = 3e3;
7341
+ var DEFAULT_JOIN_DEADLINE_MS = 5e3;
7342
+ var MulticastOrchestrator = class {
7343
+ options;
7344
+ #state = "stable";
7345
+ #current;
7346
+ #target;
7347
+ #estimate;
7348
+ #favored;
7349
+ #joinStartedAt = 0;
7350
+ /**
7351
+ * Latest active-tier send time (NTP short), or undefined before the first.
7352
+ * "Latest" is serial order, not the numerically largest value: after the
7353
+ * field wraps, the largest value is the stale one.
7354
+ */
7355
+ #highWater;
7356
+ #dwellMs;
7358
7357
  #joinDeadlineMs;
7359
7358
  constructor(options) {
7360
7359
  this.options = options;
@@ -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}`);
8936
+ }
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}`);
8914
8939
  }
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)) {
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 });
14389
+ }
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 });
14171
14395
  }
14396
+ if (symbol === "source") this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
14397
+ anchorHere();
14172
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;
@@ -18937,11 +19397,14 @@ var MmtpRouter = class {
18937
19397
  #fecManager;
18938
19398
  #defaultFecMapper;
18939
19399
  #fecMappersByPacketId = /* @__PURE__ */ new Map();
18940
- #manifestVerifier;
18941
- #ownsManifestVerifier;
18942
- #resolveManifestIdentity;
18943
- #resolveManifestIdentityForRoute;
18944
- #manifestRecoveryQueues = /* @__PURE__ */ new Map();
19400
+ /** Protected flows: one 7.2.7 receiver each, and the ingress its datagrams arrive with. */
19401
+ #provenance = /* @__PURE__ */ new Map();
19402
+ /** The ingress a held datagram arrived with; the receiver returns the same bytes on release. */
19403
+ #heldIngress = /* @__PURE__ */ new WeakMap();
19404
+ /** The flow whose receiver admitted a stream's source datagrams, by packetId then catalog track name: recovered packets answer to it. */
19405
+ #provenanceStreamFlow = /* @__PURE__ */ new Map();
19406
+ #unregisteredFlowDrops = 0;
19407
+ #ambiguousRecoveredDrops = 0;
18945
19408
  // Temp state set by #processMMTP before calling parser.feed(),
18946
19409
  // read by the parser's onFrame callback for CMAF assembly + dedup.
18947
19410
  #currentFecInfo;
@@ -18975,6 +19438,18 @@ var MmtpRouter = class {
18975
19438
  // MSE recovery routes through CmafBlockAssembler and can reorder by block; the
18976
19439
  // direct callback path has to preserve decode order before frames leave libmmt.
18977
19440
  #latestVideoSeqByStream = /* @__PURE__ */ new Map();
19441
+ /**
19442
+ * Per stream, SS_ID - packet_sequence_number (mod 2^32) of its latest
19443
+ * first-arrival FEC source packet. A recovered source symbol's wire
19444
+ * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
19445
+ */
19446
+ #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
19447
+ /**
19448
+ * Streams whose multicast leg delivered a RAP-flagged source packet that was
19449
+ * not parsed, typically because its overlap copy was parsed first
19450
+ * (BLO-49179). The next video keyframe emitted on the stream consumes it.
19451
+ */
19452
+ #multicastRapTwinByStream = /* @__PURE__ */ new Set();
18978
19453
  #lastDirectSourceVideoTsByStream = /* @__PURE__ */ new Map();
18979
19454
  #lastDirectEmittedVideoTsByStream = /* @__PURE__ */ new Map();
18980
19455
  #pendingDirectRecoveredVideoByStream = /* @__PURE__ */ new Map();
@@ -19049,11 +19524,14 @@ var MmtpRouter = class {
19049
19524
  */
19050
19525
  #onPublisherRestart;
19051
19526
  #publisherRestarts = 0;
19527
+ #restampedRecoveredSeqs = 0;
19052
19528
  /** Inits delivered with no onTrackInit handler for their packetId (MOQT-01). */
19053
19529
  #unmappedInitDeliveries = 0;
19054
19530
  // FEC Payload IDs left unread because their (owner) packetId had no
19055
19531
  // configured fec.blockProfile (see #noteUnreadableFecPayloadId).
19056
19532
  #fecPayloadIdsWithoutProfile = 0;
19533
+ // Repair packets discarded by the fec-01 4.5 block-length rule.
19534
+ #repairBlockLengthDiscards = 0;
19057
19535
  /** The staged in-place stream switch, if any (stageStreamSwitch). */
19058
19536
  #staged = null;
19059
19537
  #disposed = false;
@@ -19063,10 +19541,6 @@ var MmtpRouter = class {
19063
19541
  this.#fecManager = config?.fecManager ?? null;
19064
19542
  this.#onFrameGap = config?.onFrameGap ?? null;
19065
19543
  this.#defaultFecMapper = config?.fecMapper ?? null;
19066
- this.#manifestVerifier = config?.manifestVerifier ?? null;
19067
- this.#ownsManifestVerifier = config?.manifestVerifierOwnership !== "caller";
19068
- this.#resolveManifestIdentity = config?.resolveManifestIdentity ?? null;
19069
- this.#resolveManifestIdentityForRoute = config?.resolveManifestIdentityForRoute ?? null;
19070
19544
  this.#parser = new MmtpContainerParser({
19071
19545
  mfuTimeoutMs: config?.mfuTimeoutMs,
19072
19546
  reassemblyPolicy: config?.reassemblyPolicy,
@@ -19107,6 +19581,12 @@ var MmtpRouter = class {
19107
19581
  ...meta.catalogTrackName === void 0 ? {} : { catalogTrackName: meta.catalogTrackName }
19108
19582
  };
19109
19583
  if (meta.source) frameMeta.source = meta.source;
19584
+ if (isVideo && frameMeta.keyframe) {
19585
+ const twinSeen = this.#multicastRapTwinByStream.delete(
19586
+ this.#mediaStreamKey(packetId, frameMeta.catalogTrackName)
19587
+ );
19588
+ if (twinSeen && frameMeta.source === "moq") frameMeta.source = "multicast";
19589
+ }
19110
19590
  if (meta.deliveryProvenance !== void 0)
19111
19591
  frameMeta.deliveryProvenance = meta.deliveryProvenance;
19112
19592
  if (meta.recovered) frameMeta.recovered = true;
@@ -19269,6 +19749,14 @@ var MmtpRouter = class {
19269
19749
  get publisherRestartCount() {
19270
19750
  return this.#publisherRestarts;
19271
19751
  }
19752
+ /**
19753
+ * FEC-recovered source symbols whose reconstructed header named a
19754
+ * packet_sequence_number other than the wire sequence their SS_ID maps to:
19755
+ * a hop re-stamped the sequence after the sender protected the packet.
19756
+ */
19757
+ get restampedRecoveredSequenceCount() {
19758
+ return this.#restampedRecoveredSeqs;
19759
+ }
19272
19760
  /**
19273
19761
  * Packets whose Source or Repair FEC Payload ID was left unread because
19274
19762
  * their (owner) packetId had no configured `fec.blockProfile`: FEC not
@@ -19280,6 +19768,14 @@ var MmtpRouter = class {
19280
19768
  get fecPayloadIdsWithoutProfile() {
19281
19769
  return this.#fecPayloadIdsWithoutProfile;
19282
19770
  }
19771
+ /**
19772
+ * Repair packets discarded at admission by the fec-01 4.5 rule (RS_ID not
19773
+ * below RSB_length, or a reed-solomon SSB_length + RSB_length above 255),
19774
+ * before they touched any block state.
19775
+ */
19776
+ get repairBlockLengthDiscards() {
19777
+ return this.#repairBlockLengthDiscards;
19778
+ }
19283
19779
  get reassembler() {
19284
19780
  return this.#parser.reassembler;
19285
19781
  }
@@ -19576,30 +20072,52 @@ var MmtpRouter = class {
19576
20072
  }
19577
20073
  });
19578
20074
  }
19579
- registerManifestTrack(context) {
19580
- if (!this.#manifestVerifier) throw new Error("manifest verifier is not configured");
19581
- this.#manifestVerifier.registerTrack(context);
19582
- }
19583
- feedManifestFrame(trackName, frame) {
19584
- this.#manifestVerifier?.ingestManifestFrame(trackName, frame);
19585
- }
19586
- setManifestAuthMode(mode) {
19587
- this.#manifestVerifier?.setMode(mode);
19588
- if (mode !== "enforce") {
19589
- for (const queue of this.#manifestRecoveryQueues.values()) {
19590
- for (const item of queue) {
19591
- this.#routeProcessedFecSymbols(
19592
- item.blockId,
19593
- item.result,
19594
- item.ownerPacketId,
19595
- item.catalogTrackName
19596
- );
20075
+ /**
20076
+ * Protect a flow (draft-ramadan-moq-multicast-01 7.2.7): every multicast
20077
+ * datagram whose ingress names `ingress.flow`, source and repair alike, is
20078
+ * admitted by `receiver` before anything reads it, and an unadmitted one is
20079
+ * held or dropped. The caller owns the receiver's configuration; the router
20080
+ * releases it on `releaseProvenanceFlow` and on dispose.
20081
+ */
20082
+ registerProvenanceFlow(ingress, receiver) {
20083
+ this.#provenance.get(ingress.flow)?.receiver.release();
20084
+ this.#provenance.set(ingress.flow, { receiver, ingress });
20085
+ }
20086
+ /**
20087
+ * Feed one bc-provenance record of `flow`: a datagram from `manifestPort`
20088
+ * (`multicast`) or an object of the manifest track (`mirror`). Held
20089
+ * datagrams the record admits are routed before this returns.
20090
+ */
20091
+ feedProvenanceRecord(flow, record, path) {
20092
+ const entry = this.#provenance.get(flow);
20093
+ if (!entry || this.#disposed) return "unregistered";
20094
+ const result = entry.receiver.onRecord(record, path);
20095
+ if (result.admitted.length > 0) {
20096
+ this.#withDeferredFecPokes(() => {
20097
+ for (const datagram of result.admitted) {
20098
+ this.#processMMTP(datagram, "multicast", true, this.#heldIngress.get(datagram) ?? entry.ingress, false, true);
19597
20099
  }
19598
- }
19599
- this.#manifestRecoveryQueues.clear();
20100
+ });
19600
20101
  }
20102
+ return result.verdict;
19601
20103
  }
19602
- /**
20104
+ /** The receiver ceased to hold the flow: its hold queues are dropped, not expired. */
20105
+ releaseProvenanceFlow(flow) {
20106
+ this.#provenance.get(flow)?.receiver.release();
20107
+ this.#provenance.delete(flow);
20108
+ for (const byName of this.#provenanceStreamFlow.values()) {
20109
+ for (const [name, bound] of byName) if (bound === flow) byName.delete(name);
20110
+ }
20111
+ }
20112
+ /** Multicast datagrams dropped because their ingress names a flow with no registered receiver. */
20113
+ get unregisteredFlowDropCount() {
20114
+ return this.#unregisteredFlowDrops;
20115
+ }
20116
+ /** Recovered packets dropped because more than one protected flow could own their stream. */
20117
+ get ambiguousRecoveredDropCount() {
20118
+ return this.#ambiguousRecoveredDrops;
20119
+ }
20120
+ /**
19603
20121
  * Main entry point: feed a raw MMTP packet for processing.
19604
20122
  *
19605
20123
  * Source packets are played immediately AND fed to FECManager for recovery.
@@ -19613,10 +20131,10 @@ var MmtpRouter = class {
19613
20131
  * they may never have crossed — and that attribution is what the physical-
19614
20132
  * delivery evidence path is built on. Absence is not multicast; say which.
19615
20133
  */
19616
- feedPacket(packet, source, manifestIdentity, ingress) {
20134
+ feedPacket(packet, source, ingress) {
19617
20135
  if (this.#disposed) return;
19618
20136
  this.#withDeferredFecPokes(() => {
19619
- this.#processMMTP(packet, source, manifestIdentity, false, ingress);
20137
+ this.#processMMTP(packet, source, false, ingress);
19620
20138
  });
19621
20139
  }
19622
20140
  /**
@@ -19651,20 +20169,20 @@ var MmtpRouter = class {
19651
20169
  feedOverlapCopy(packet, ingress) {
19652
20170
  if (this.#disposed) return;
19653
20171
  this.#withDeferredFecPokes(() => {
19654
- this.#processMMTP(packet, "moq", void 0, false, ingress, true);
20172
+ this.#processMMTP(packet, "moq", false, ingress, true);
19655
20173
  });
19656
20174
  }
19657
20175
  /**
19658
20176
  * Feed a repair packet from MoQ (reliable QUIC) — parses MMTP repair
19659
20177
  * header and delegates to FECManager for FEC recovery.
19660
20178
  */
19661
- feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName) {
20179
+ feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName) {
19662
20180
  if (this.#disposed) return;
19663
20181
  this.#withDeferredFecPokes(() => {
19664
- this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName);
20182
+ this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName);
19665
20183
  });
19666
20184
  }
19667
- #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName) {
20185
+ #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName) {
19668
20186
  let header;
19669
20187
  try {
19670
20188
  header = parseMMTPHeader(packet);
@@ -19695,7 +20213,7 @@ var MmtpRouter = class {
19695
20213
  this.#noteUnreadableFecPayloadId(ownerPacketId, "repair");
19696
20214
  return;
19697
20215
  }
19698
- this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, "moq");
20216
+ this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, "moq", repairTrackName);
19699
20217
  }
19700
20218
  }
19701
20219
  // ── Packet FEC geometry and block profile ───────────────────────
@@ -19777,13 +20295,25 @@ var MmtpRouter = class {
19777
20295
  * the repair, the order they had on the wire, so a loss-free block completes
19778
20296
  * clean on its repair. A repair contradicting a known block is dropped.
19779
20297
  */
19780
- #handleIsoRepair(ownerPacketId, catalogTrackName, repair, source) {
20298
+ #handleIsoRepair(ownerPacketId, catalogTrackName, repair, source, repairTrackName) {
19781
20299
  const fec = this.#fecManager;
19782
20300
  if (!fec?.placeIsoRepair) {
19783
20301
  throw new Error(
19784
20302
  `[MmtpRouter] packetId=${ownerPacketId} is iso-ssbg1-v1 but its FEC manager cannot place ISO blocks`
19785
20303
  );
19786
20304
  }
20305
+ if (fec.admitRepairBlockLength && !fec.admitRepairBlockLength(ownerPacketId, repair.ssbLength, repair.rsbLength, repair.rsId)) {
20306
+ this.#repairBlockLengthDiscards++;
20307
+ return;
20308
+ }
20309
+ if (fec.admitRepairSymbolSize && !fec.admitRepairSymbolSize(
20310
+ ownerPacketId,
20311
+ repair.ssStart,
20312
+ repair.ssbLength,
20313
+ repair.rsId,
20314
+ repair.symbolData.byteLength
20315
+ )) return;
20316
+ if (fec.admitRepairLayerTotal && !fec.admitRepairLayerTotal(ownerPacketId, catalogTrackName, repairTrackName, repair.ssStart, repair.rsbLength)) return;
19787
20317
  const placement = fec.placeIsoRepair(ownerPacketId, catalogTrackName, repair.ssStart, repair.ssbLength);
19788
20318
  if (placement.status !== "placed") return;
19789
20319
  const blockStart = placement.block.start;
@@ -19818,6 +20348,17 @@ var MmtpRouter = class {
19818
20348
  this.#routeRecoveredBlock(blockStart, recovered, ownerPacketId, catalogTrackName);
19819
20349
  }
19820
20350
  }
20351
+ /**
20352
+ * The range repair FETCH for an undelimited hole ended (draft-ramadan-moq-fec
20353
+ * §7.5): what no repair stated becomes repair-less spans, whose held sources
20354
+ * are fed exactly as a span a repair closed.
20355
+ */
20356
+ closeIsoHoles(ownerPacketId, catalogTrackName, start, length) {
20357
+ const spans = this.#fecManager?.closeIsoHoles?.(ownerPacketId, catalogTrackName, start, length) ?? [];
20358
+ for (const span of spans) {
20359
+ this.#replayIsoSources(ownerPacketId, catalogTrackName, span.block.start, span.placed);
20360
+ }
20361
+ }
19821
20362
  /**
19822
20363
  * Feed iso-ssbg1-v1 sources a repair just placed, in SS_ID order, exactly as
19823
20364
  * a first-arrival source is fed once its block is known: transport
@@ -19913,13 +20454,14 @@ var MmtpRouter = class {
19913
20454
  this.#trackSynced.delete(streamKey);
19914
20455
  this.#droppedPreSyncVideo.delete(streamKey);
19915
20456
  this.#latestVideoSeqByStream.delete(streamKey);
20457
+ this.#ssIdSeqOffsetByStream.delete(streamKey);
20458
+ this.#multicastRapTwinByStream.delete(streamKey);
19916
20459
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
19917
20460
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
19918
20461
  this.#pendingDirectRecoveredVideoByStream.delete(streamKey);
19919
20462
  this.#lastDirectSourceAudioCursorByStream.delete(streamKey);
19920
20463
  this.#lastDirectEmittedAudioCursorByStream.delete(streamKey);
19921
20464
  this.#pendingDirectRecoveredAudioByStream.delete(streamKey);
19922
- this.#manifestRecoveryQueues.delete(streamKey);
19923
20465
  this.#deliveredVideoHighWaterByStream.delete(streamKey);
19924
20466
  this.#stream(packetId, catalogTrackName).duplicates.clear();
19925
20467
  const assemblersToReset = /* @__PURE__ */ new Set();
@@ -19969,7 +20511,6 @@ var MmtpRouter = class {
19969
20511
  this.#lastDirectSourceAudioCursorByStream.delete(key);
19970
20512
  this.#lastDirectEmittedAudioCursorByStream.delete(key);
19971
20513
  this.#pendingDirectRecoveredAudioByStream.delete(key);
19972
- this.#manifestRecoveryQueues.delete(key);
19973
20514
  this.#trackInitDelivered.delete(key);
19974
20515
  this.#parserDiagnostics.delete(key);
19975
20516
  this.#pendingFecPokes.delete(key);
@@ -20230,8 +20771,9 @@ var MmtpRouter = class {
20230
20771
  this.#parserDiagnostics.clear();
20231
20772
  this.#catalogTrackNamesByPacketId.clear();
20232
20773
  this.#repairOwnersByPacketId.clear();
20233
- if (this.#ownsManifestVerifier) this.#manifestVerifier?.dispose();
20234
- this.#manifestRecoveryQueues.clear();
20774
+ for (const { receiver } of this.#provenance.values()) receiver.release();
20775
+ this.#provenance.clear();
20776
+ this.#provenanceStreamFlow.clear();
20235
20777
  for (const assembler of this.#mseAssemblers.values()) assembler.dispose();
20236
20778
  this.#mseAssemblers.clear();
20237
20779
  }
@@ -20508,7 +21050,7 @@ var MmtpRouter = class {
20508
21050
  * 1. parseHeader() → extract packetId + fecPayloadId for FEC feeding
20509
21051
  * 2. feed() → MFU extraction, reassembly, keyframe detection, emit via callbacks
20510
21052
  */
20511
- #processMMTP(packet, source, manifestIdentity, manifestAdmitted = false, ingress, overlapCopy = false, releasedFromQuarantine = false) {
21053
+ #processMMTP(packet, source, manifestAdmitted = false, ingress, overlapCopy = false, releasedFromQuarantine = false) {
20512
21054
  const parsed = this.#parser.parsePacket(packet);
20513
21055
  if (!parsed) return;
20514
21056
  const info = parsed.info;
@@ -20533,45 +21075,22 @@ var MmtpRouter = class {
20533
21075
  }
20534
21076
  const fecUnreadable = !info.isRepair && info.fecPayloadId != null && this.#fecManager !== null && this.#classifyPacketId(info.packetId) !== null && this.#configuredBlockProfile(info.packetId) === void 0;
20535
21077
  if (fecUnreadable && !manifestAdmitted) this.#noteUnreadableFecPayloadId(info.packetId, "source");
20536
- if (!info.isRepair && this.#manifestVerifier && !manifestAdmitted) {
20537
- let identity = manifestIdentity;
20538
- if (!identity && info.fecPayloadId && !fecUnreadable && (this.#resolveManifestIdentityForRoute || this.#resolveManifestIdentity)) {
20539
- const catalogTrackName = catalogTrackNameForPacket(ingress, info.packetId);
20540
- const coordinates = this.#locateFecSource(info.packetId, catalogTrackName, info.fecPayloadId.ssId);
20541
- identity = coordinates === null ? void 0 : (this.#resolveManifestIdentityForRoute ? this.#resolveManifestIdentityForRoute({
20542
- packetId: info.packetId,
20543
- sbn: coordinates.sbn,
20544
- esi: coordinates.esi,
20545
- ...catalogTrackName === void 0 ? {} : { catalogTrackName },
20546
- recovered: false,
20547
- sourceSymbolFormat: "full-mmtp-packet"
20548
- }) : this.#resolveManifestIdentity(
20549
- info.packetId,
20550
- coordinates.sbn,
20551
- coordinates.esi,
20552
- catalogTrackName
20553
- )) ?? void 0;
20554
- }
20555
- if (identity) {
20556
- identity = {
20557
- ...identity,
20558
- packetId: info.packetId,
20559
- ...info.fecPayloadId ? { ssId: info.fecPayloadId.ssId } : {}
20560
- };
20561
- const authenticated = info.fecPayloadId ? packet.subarray(0, packet.length - 4) : packet;
20562
- let quarantined = false;
20563
- const admission = this.#manifestVerifier.admitObject(identity, authenticated, () => {
20564
- if (!this.#disposed) {
20565
- this.#processMMTP(packet, source, identity, true, ingress, overlapCopy, quarantined);
20566
- }
20567
- });
20568
- quarantined = admission.action === "stall";
20569
- return;
20570
- }
20571
- if (this.#manifestVerifier.config.mode === "enforce" && this.#manifestVerifier.config.onMissingManifest === "stall") {
20572
- console.warn(`[MmtpRouter] manifest identity absent; stalling packetId=${info.packetId}`);
21078
+ if (source === "multicast" && manifestAdmitted && !info.isRepair && ingress?.flow !== void 0) {
21079
+ let byName = this.#provenanceStreamFlow.get(info.packetId);
21080
+ if (!byName) this.#provenanceStreamFlow.set(info.packetId, byName = /* @__PURE__ */ new Map());
21081
+ byName.set(catalogTrackNameForPacket(ingress, info.packetId), ingress.flow);
21082
+ }
21083
+ if (source === "multicast" && !manifestAdmitted && ingress?.flow !== void 0) {
21084
+ const protectedFlow = this.#provenance.get(ingress.flow);
21085
+ if (!protectedFlow) {
21086
+ this.#unregisteredFlowDrops++;
21087
+ debugRouter(`[MmtpRouter] Dropping multicast packet pid=${info.packetId}: flow ${ingress.flow} has no receiver`);
20573
21088
  return;
20574
21089
  }
21090
+ const { verdict } = protectedFlow.receiver.onDatagram(packet, "multicast");
21091
+ if (verdict === "admitted") this.#processMMTP(packet, source, true, ingress, overlapCopy);
21092
+ else if (verdict === "held") this.#heldIngress.set(packet, ingress);
21093
+ return;
20575
21094
  }
20576
21095
  if (info.isRepair) {
20577
21096
  const repair = parseMoqRepairFrameWithHeader(packet, parsed.header);
@@ -20683,6 +21202,12 @@ var MmtpRouter = class {
20683
21202
  } else if (fecUnreadable && info.fecPayloadId) {
20684
21203
  parseSourceSymbol = !duplicates.parsedSymbols.has(info.fecPayloadId.ssId);
20685
21204
  }
21205
+ if (fecPayloadId && !overlapCopy) {
21206
+ this.#ssIdSeqOffsetByStream.set(
21207
+ this.#mediaStreamKey(info.packetId, catalogTrackName),
21208
+ fecPayloadId.ssId - info.sequenceNumber >>> 0
21209
+ );
21210
+ }
20686
21211
  if (!this.#fecManager || !info.fecPayloadId || parseSourceSymbol) {
20687
21212
  if (this.#fecManager && info.fecPayloadId) {
20688
21213
  duplicates.parsedSymbols.add(info.fecPayloadId.ssId);
@@ -20705,6 +21230,10 @@ var MmtpRouter = class {
20705
21230
  // An FEC source frame is anchored by its own SS_ID (C.5.2).
20706
21231
  ...fecSource && fecPayloadId ? { fecSbn: fecPayloadId.ssId } : {}
20707
21232
  }, parsed);
21233
+ } else if (source === "multicast" && info.rapFlag) {
21234
+ this.#multicastRapTwinByStream.add(
21235
+ this.#mediaStreamKey(info.packetId, catalogTrackName)
21236
+ );
20708
21237
  }
20709
21238
  if (this.#classifyPacketId(info.packetId) === null) return;
20710
21239
  if (this.#fecManager && fecPayloadId && coords && sourceSymbolAccepted && sourceSymbolTrackable) {
@@ -21160,105 +21689,69 @@ var MmtpRouter = class {
21160
21689
  });
21161
21690
  this.#routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
21162
21691
  }
21692
+ /**
21693
+ * A recovered source packet of a protected flow is admitted on its own
21694
+ * digest: its bytes with the SS_ID it was sent with (SS_Start + ESI)
21695
+ * appended are the datagram the record listed (7.2.7). One that no record
21696
+ * lists is dropped; holding it would let it out later as a multicast arrival.
21697
+ */
21163
21698
  #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName) {
21164
- if (!this.#manifestVerifier || ownerPacketId == null) {
21165
- this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
21166
- return;
21167
- }
21168
- if (!this.#resolveManifestIdentity && !this.#resolveManifestIdentityForRoute) {
21169
- console.warn(`[MmtpRouter] manifest identity resolver unavailable; recovered media is fail-open for packetId=${ownerPacketId} block=${blockId}`);
21170
- this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
21171
- return;
21699
+ const receiver = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
21700
+ if (receiver === "ambiguous") {
21701
+ this.#ambiguousRecoveredDrops += result.symbols.length;
21702
+ result = { ...result, symbols: [] };
21703
+ } else if (receiver) {
21704
+ result = {
21705
+ ...result,
21706
+ symbols: result.symbols.filter((sym) => {
21707
+ const wire = new Uint8Array(sym.rawSymbol.byteLength + 4);
21708
+ wire.set(sym.rawSymbol);
21709
+ new DataView(wire.buffer).setUint32(sym.rawSymbol.byteLength, this.#fecAnchorForRecovered(blockId, sym.index));
21710
+ return receiver.admitRecovered(wire);
21711
+ })
21712
+ };
21172
21713
  }
21173
- const queueKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
21174
- const queue = this.#manifestRecoveryQueues.get(queueKey) ?? [];
21175
- queue.push({ blockId, result, ownerPacketId, catalogTrackName });
21176
- this.#manifestRecoveryQueues.set(queueKey, queue);
21177
- if (queue.length > 1) return;
21178
- const drain = () => {
21179
- const next = queue[0];
21180
- if (!next) {
21181
- this.#manifestRecoveryQueues.delete(queueKey);
21182
- return;
21714
+ this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
21715
+ }
21716
+ /**
21717
+ * The receiver a recovered packet of `packetId` answers to: the flow that
21718
+ * admitted the stream's source datagrams. Before any was admitted, the one
21719
+ * flow whose registration lists the stream; more than one (a repair flow
21720
+ * also lists its owners' source tracks) cannot be told apart, so none.
21721
+ */
21722
+ #provenanceFor(packetId, catalogTrackName) {
21723
+ const byName = this.#provenanceStreamFlow.get(packetId);
21724
+ const flows = new Set(
21725
+ catalogTrackName === void 0 || !byName ? byName?.values() : byName.has(catalogTrackName) ? [byName.get(catalogTrackName)] : []
21726
+ );
21727
+ if (flows.size > 1) return "ambiguous";
21728
+ for (const bound of flows) return this.#provenance.get(bound)?.receiver ?? "ambiguous";
21729
+ let match;
21730
+ for (const { receiver, ingress } of this.#provenance.values()) {
21731
+ if (ingress.tracks.some((t) => t.packetId === packetId && (catalogTrackName === void 0 || t.name === catalogTrackName))) {
21732
+ if (match) return "ambiguous";
21733
+ match = receiver;
21183
21734
  }
21184
- this.#admitRecoveredResult(
21185
- next.blockId,
21186
- next.result,
21187
- next.ownerPacketId,
21188
- next.catalogTrackName,
21189
- () => {
21190
- queue.shift();
21191
- drain();
21192
- }
21193
- );
21194
- };
21195
- drain();
21196
- }
21197
- #admitRecoveredResult(blockId, result, ownerPacketId, catalogTrackName, done) {
21198
- const verifier = this.#manifestVerifier;
21199
- const resolveIdentity = this.#resolveManifestIdentity;
21200
- const resolveIdentityForRoute = this.#resolveManifestIdentityForRoute;
21201
- if (!verifier) {
21202
- this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
21203
- done();
21204
- return;
21205
21735
  }
21206
- if (!resolveIdentity && !resolveIdentityForRoute) throw new Error("manifest identity resolver disappeared during admission");
21207
- const symbols = result.symbols;
21208
- const admitNext = (index) => {
21209
- const symbol = symbols[index];
21210
- if (!symbol) {
21211
- done();
21212
- return;
21213
- }
21214
- const identity = resolveIdentityForRoute ? resolveIdentityForRoute({
21215
- packetId: ownerPacketId,
21216
- sbn: blockId,
21217
- esi: symbol.index,
21218
- ...catalogTrackName === void 0 ? {} : { catalogTrackName },
21219
- recovered: true,
21220
- sourceSymbolFormat: "fec-padded-recovery"
21221
- }) : resolveIdentity(ownerPacketId, blockId, symbol.index, catalogTrackName);
21222
- if (!identity) {
21223
- console.warn(`[MmtpRouter] manifest identity unresolved; recovered symbol is fail-open for packetId=${ownerPacketId} block=${blockId} esi=${symbol.index}`);
21224
- this.#routeProcessedFecSymbols(
21225
- blockId,
21226
- { ...result, symbols: [symbol] },
21227
- ownerPacketId,
21228
- catalogTrackName
21229
- );
21230
- admitNext(index + 1);
21231
- return;
21232
- }
21233
- const admission = verifier.admitObject(
21234
- {
21235
- ...identity,
21236
- packetId: ownerPacketId
21237
- },
21238
- symbol.rawSymbol,
21239
- () => {
21240
- if (!this.#disposed) {
21241
- this.#routeProcessedFecSymbols(
21242
- blockId,
21243
- { ...result, symbols: [symbol] },
21244
- ownerPacketId,
21245
- catalogTrackName
21246
- );
21247
- }
21248
- admitNext(index + 1);
21249
- },
21250
- // A stalled symbol that is later discarded instead of played must still
21251
- // advance this loop; enforce mode never calls the release callback for
21252
- // it (BLO-30095).
21253
- () => admitNext(index + 1)
21254
- );
21255
- if (admission.action === "drop") admitNext(index + 1);
21256
- };
21257
- admitNext(0);
21736
+ return match;
21258
21737
  }
21259
21738
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName) {
21260
21739
  if (ownerPacketId == null) return;
21261
21740
  if (this.#classifyPacketId(ownerPacketId) === null) return;
21741
+ const ssIdSeqOffset = this.#ssIdSeqOffsetByStream.get(
21742
+ this.#mediaStreamKey(ownerPacketId, catalogTrackName)
21743
+ );
21744
+ if (ssIdSeqOffset !== void 0) {
21745
+ result = {
21746
+ ...result,
21747
+ symbols: result.symbols.map((sym) => {
21748
+ const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
21749
+ if (wire === sym.packetSequenceNumber) return sym;
21750
+ this.#restampedRecoveredSeqs++;
21751
+ return { ...sym, packetSequenceNumber: wire };
21752
+ })
21753
+ };
21754
+ }
21262
21755
  this.#stream(ownerPacketId, catalogTrackName).duplicates.advance(blockId);
21263
21756
  const deliveryProvenance = this.#fecManager?.blockDeliveryProvenance?.(
21264
21757
  blockId,
@@ -21999,48 +22492,6 @@ function createWasmMmtpContainerParser(config) {
21999
22492
  });
22000
22493
  }
22001
22494
 
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
22495
  // src/multicast-transport.ts
22045
22496
  var JOIN_SUCCEEDED = Object.freeze({ ok: true });
22046
22497
  function providerErrorOf(error) {
@@ -22084,7 +22535,7 @@ function sameIds(a, b) {
22084
22535
  for (const id of a) if (!b.has(id)) return false;
22085
22536
  return true;
22086
22537
  }
22087
- var MulticastTransport = class _MulticastTransport {
22538
+ var MulticastTransport = class {
22088
22539
  #onPacket;
22089
22540
  #subscription = null;
22090
22541
  #packetListener = null;
@@ -22156,8 +22607,11 @@ var MulticastTransport = class _MulticastTransport {
22156
22607
  // droppedPacketIds.
22157
22608
  #unadvertisedPacketIds = /* @__PURE__ */ new Set();
22158
22609
  #joinGeneration = 0;
22159
- constructor(onPacket) {
22610
+ // The provider to subscribe through; window.multicast when unset.
22611
+ #gateway;
22612
+ constructor(onPacket, options = {}) {
22160
22613
  this.#onPacket = onPacket;
22614
+ this.#gateway = options.gateway;
22161
22615
  }
22162
22616
  static isAvailable() {
22163
22617
  return hasMulticastGateway();
@@ -22167,7 +22621,8 @@ var MulticastTransport = class _MulticastTransport {
22167
22621
  this.#releaseSubscription();
22168
22622
  this.#dataPlaneLive = false;
22169
22623
  if (this.#disposed) return this.#declined(generation, "disposed");
22170
- if (!_MulticastTransport.isAvailable()) {
22624
+ const gateway = this.#gateway ?? getMulticastGlobals().multicast;
22625
+ if (typeof gateway?.subscribe !== "function") {
22171
22626
  console.warn("[MulticastTransport] Multicast API not available");
22172
22627
  return this.#declined(generation, "unavailable");
22173
22628
  }
@@ -22184,11 +22639,13 @@ var MulticastTransport = class _MulticastTransport {
22184
22639
  mode: config.mode,
22185
22640
  amtRelay: config.amtRelay,
22186
22641
  amtRelayPort: config.amtRelayPort,
22642
+ amtDiscovery: config.amtDiscovery,
22187
22643
  packetIds: config.packetIds,
22188
- tracks: config.tracks
22644
+ tracks: config.tracks,
22645
+ atsc3: config.atsc3
22189
22646
  });
22190
22647
  failure = "provider-rejected";
22191
- const subscription = await getMulticastGlobals().multicast.subscribe(subscribeConfig);
22648
+ const subscription = await gateway.subscribe(subscribeConfig);
22192
22649
  failure = "invalid-subscription";
22193
22650
  console.log(`[MulticastTransport] window.multicast.subscribe returned:`, !!subscription);
22194
22651
  if (this.#disposed || generation !== this.#joinGeneration) {
@@ -22790,6 +23247,25 @@ function catalogAmtNetworkSource(networkSource) {
22790
23247
  }
22791
23248
  return void 0;
22792
23249
  }
23250
+ function intIn(value, min, max) {
23251
+ return Number.isInteger(value) && value >= min && value <= max;
23252
+ }
23253
+ function catalogAtsc3NetworkSource(networkSource) {
23254
+ const entries = Array.isArray(networkSource) ? networkSource : networkSource ? [networkSource] : [];
23255
+ for (const raw of entries) {
23256
+ if (!raw || typeof raw !== "object") continue;
23257
+ const ns = raw;
23258
+ if (ns.type !== "atsc3" || !intIn(ns.frequency, 1, Number.MAX_SAFE_INTEGER)) continue;
23259
+ const slsUri = typeof ns.slsUri === "string" ? ns.slsUri.trim() : "";
23260
+ return {
23261
+ frequency: ns.frequency,
23262
+ ...intIn(ns.plpId, 0, 63) ? { plpId: ns.plpId } : {},
23263
+ ...intIn(ns.serviceId, 0, 65535) ? { serviceId: ns.serviceId } : {},
23264
+ ...slsUri ? { slsUri } : {}
23265
+ };
23266
+ }
23267
+ return void 0;
23268
+ }
22793
23269
 
22794
23270
  // src/catalog-fec-params.ts
22795
23271
  var MAX_SAFE_TICKS_PER_HZ = Number.MAX_SAFE_INTEGER / 1e3;
@@ -23005,6 +23481,13 @@ function isoSpanUnavailable(fec, path, declaresFecInstance) {
23005
23481
  function catalogFecUnavailable(fec, fecPath) {
23006
23482
  if (catalogFecAvailable(fec)) return void 0;
23007
23483
  const block = recordOf3(fec);
23484
+ if (fecAlgorithmUnimplemented(block["algorithm"])) {
23485
+ return Object.freeze({
23486
+ code: "track_fec_algorithm_unimplemented",
23487
+ path: `${fecPath}.algorithm`,
23488
+ message: `algorithm ${JSON.stringify(block["algorithm"])} is not implemented: the track plays without FEC`
23489
+ });
23490
+ }
23008
23491
  const declaresFecInstance = block["algorithm"] !== "none";
23009
23492
  const reason = blockProfileUnavailable(block["blockProfile"], `${fecPath}.blockProfile`, declaresFecInstance) ?? isoSpanUnavailable(block, `${fecPath}.interleaveDepthMs`, declaresFecInstance);
23010
23493
  if (reason === void 0) {
@@ -23024,7 +23507,7 @@ function fecParams(catalog, track, rendition, fps, sampleRate) {
23024
23507
  throwRepairContractError(
23025
23508
  "track_fec",
23026
23509
  `${fecPath}.${kValid ? "symbolSize" : "sourceSymbols"}`,
23027
- "must be a positive integer"
23510
+ 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
23511
  );
23029
23512
  }
23030
23513
  const fecUnavailable = catalogFecUnavailable(fec, fecPath);
@@ -23033,6 +23516,7 @@ function fecParams(catalog, track, rendition, fps, sampleRate) {
23033
23516
  const fecBlockProfile = readFecBlockProfile(fec.blockProfile, `${fecPath}.blockProfile`, true, throwRepairContractError);
23034
23517
  return {
23035
23518
  fecK: fec.sourceSymbols ?? 0,
23519
+ fecAlgorithm: fec.algorithm === "reed-solomon" ? "reed-solomon" : "raptorq",
23036
23520
  fecBlockProfile,
23037
23521
  fecRepairCount: fec.repairSymbols ?? 0,
23038
23522
  // The wire RSB_length: every base layer's packets carry the base total (§7.1).
@@ -23129,8 +23613,10 @@ function newBlockPolicyStats(packetId, catalogTrackName, epoch) {
23129
23613
  repairsSkippedRttUnmeasured: 0,
23130
23614
  repairsSkippedRttExceedsBudget: 0,
23131
23615
  repairsSkippedPresentationDelayUnavailable: 0,
23616
+ repairsSkippedRangeNoAnchor: 0,
23132
23617
  lastRepairSkip: null,
23133
23618
  keyframeRepairFetchesSent: 0,
23619
+ rangeRepairFetchesSent: 0,
23134
23620
  keyframeBudgetHolds: 0,
23135
23621
  keyframeBudgetHoldMs: 0,
23136
23622
  deltaBlocksFailed: 0,
@@ -23209,6 +23695,12 @@ var REPAIR_PRIORITY_REASONS = /* @__PURE__ */ new Set([
23209
23695
  "repair-priority-absent",
23210
23696
  "repair-priority-invalid"
23211
23697
  ]);
23698
+ var REPAIR_SKIP_REASONS = /* @__PURE__ */ new Set([
23699
+ "rtt-unmeasured",
23700
+ "rtt-exceeds-budget",
23701
+ "presentation-delay-unavailable"
23702
+ ]);
23703
+ var REPAIR_DEADLINE_BOUNDS = /* @__PURE__ */ new Set(["wait", "presentation", "keyframe", "retention"]);
23212
23704
  var GAP_REASONS = {
23213
23705
  "rap-lost": "stall",
23214
23706
  "rap-unknown": "stall",
@@ -23231,6 +23723,9 @@ function isSymbolCounts(value) {
23231
23723
  function isNullableNonNegative(value) {
23232
23724
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
23233
23725
  }
23726
+ function isFiniteNumber(value) {
23727
+ return typeof value === "number" && Number.isFinite(value);
23728
+ }
23234
23729
  function isRepairLifecycleEvent(value) {
23235
23730
  if (!isRecord(value) || value["version"] !== 2) return false;
23236
23731
  const block = value["block"];
@@ -23248,6 +23743,20 @@ function isRepairLifecycleEvent(value) {
23248
23743
  case "repair-preempted":
23249
23744
  case "repair-deferred":
23250
23745
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
23746
+ case "repair-sent":
23747
+ return hasExactKeys(value, [
23748
+ "version",
23749
+ "type",
23750
+ "block",
23751
+ "priority",
23752
+ "rttMs",
23753
+ "budgetMs",
23754
+ "delayMs",
23755
+ "blockAgeMs",
23756
+ "bound"
23757
+ ]) && 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"]);
23758
+ case "repair-skipped":
23759
+ return hasExactKeys(value, ["version", "type", "block", "reason", "rttMs", "budgetMs"]) && isRepairBlockIdentity(block) && REPAIR_SKIP_REASONS.has(value["reason"]) && isNullableNonNegative(value["rttMs"]) && isFiniteNumber(value["budgetMs"]);
23251
23760
  case "repair-priority": {
23252
23761
  const blockClass = value["blockClass"];
23253
23762
  const action = value["action"];
@@ -23427,6 +23936,9 @@ var MulticastManager = class {
23427
23936
  #router;
23428
23937
  #hostMfuTimeoutMs;
23429
23938
  #transport;
23939
+ /** Live joinRepairEndpoints() releases → the repair owners they registered,
23940
+ * re-applied after configureMultiTrack() clears catalog-derived owners. */
23941
+ #repairReleases = /* @__PURE__ */ new Map();
23430
23942
  #reportedFecDiagnosticsFailure = false;
23431
23943
  // ── Stream-global FEC timing reduction ──
23432
23944
  //
@@ -23476,10 +23988,6 @@ var MulticastManager = class {
23476
23988
  reassemblyPolicy: options?.reassemblyPolicy,
23477
23989
  reassembler: options?.reassembler,
23478
23990
  maxBufferedMfus: options?.maxBufferedMfus,
23479
- manifestVerifier: options?.manifestVerifier,
23480
- manifestVerifierOwnership: options?.manifestVerifierOwnership,
23481
- resolveManifestIdentity: options?.resolveManifestIdentity,
23482
- resolveManifestIdentityForRoute: options?.resolveManifestIdentityForRoute,
23483
23991
  // The router has reset its own state for the stream; reset the rest.
23484
23992
  onPublisherRestart: (packetId, catalogTrackName) => {
23485
23993
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
@@ -23526,7 +24034,7 @@ var MulticastManager = class {
23526
24034
  });
23527
24035
  this.#hostMfuTimeoutMs = this.#router.reassembler.timeoutMs;
23528
24036
  this.#transport = new MulticastTransport((packet, ingress) => {
23529
- this.#router.feedPacket(packet, "multicast", void 0, ingress);
24037
+ this.#router.feedPacket(packet, "multicast", ingress);
23530
24038
  });
23531
24039
  this.#transport.onDelivery((delivery) => {
23532
24040
  this.#fec.setMulticastSymbolDelivery(delivery);
@@ -23690,7 +24198,9 @@ var MulticastManager = class {
23690
24198
  catalogTrackName
23691
24199
  );
23692
24200
  this.#configureTrackMapper(packetId, config);
23693
- this.#router.setPacketIdType(packetId, trackType);
24201
+ if (this.#router.trackKindFor(packetId) !== trackType) {
24202
+ this.#router.setPacketIdType(packetId, trackType);
24203
+ }
23694
24204
  }
23695
24205
  /**
23696
24206
  * Stop routing a stream's symbols to its Worker decoder. Returns false when
@@ -23771,6 +24281,14 @@ var MulticastManager = class {
23771
24281
  );
23772
24282
  }
23773
24283
  }
24284
+ for (const [packetId, c] of this.#trackFecTiming) {
24285
+ if (c.deliveryWindowMs === void 0) continue;
24286
+ mfuTimeoutMs = Math.max(
24287
+ mfuTimeoutMs ?? 0,
24288
+ this.#fec.terminalRetentionMsForPacket(packetId) ?? 0,
24289
+ this.#hostMfuTimeoutMs ?? 0
24290
+ );
24291
+ }
23774
24292
  const failbackWindowMs = deliveryWindowMs === void 0 ? minimumFailbackWindowMs : Math.max(deliveryWindowMs, minimumFailbackWindowMs ?? 0);
23775
24293
  this.#transport.setFailbackWindowMs(failbackWindowMs ?? null);
23776
24294
  this.#router.setMfuTimeoutMs(mfuTimeoutMs ?? this.#hostMfuTimeoutMs);
@@ -23954,6 +24472,7 @@ var MulticastManager = class {
23954
24472
  setMfuTimeoutMs(ms) {
23955
24473
  this.#router.setMfuTimeoutMs(ms);
23956
24474
  this.#hostMfuTimeoutMs = this.#router.reassembler.timeoutMs;
24475
+ if (this.#trackFecTiming.size > 0) this.#applyStreamGlobalFecTiming();
23957
24476
  }
23958
24477
  setTrackCodec(packetId, codec) {
23959
24478
  this.#router.setTrackCodec(packetId, codec);
@@ -24074,11 +24593,81 @@ var MulticastManager = class {
24074
24593
  // through whatever the relay looks like, since dropping it would be the
24075
24594
  // worse behaviour.
24076
24595
  amtRelayPort: config.amtRelayPort ?? config.relayPort ?? (amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : void 0),
24596
+ amtDiscovery: config.amtDiscovery,
24077
24597
  packetIds: config.packetIds,
24078
24598
  tracks: catalogTracks?.map(({ name, packetId }) => ({ name, packetId }))
24079
24599
  };
24080
24600
  return ingress === void 0 ? this.#transport.join(transportConfig) : this.#transport.join(transportConfig, ingress);
24081
24601
  }
24602
+ /**
24603
+ * Join the selected rung's dedicated repair groups beside the media join
24604
+ * (pim #3898): one subscription per endpoint, through `provider` when given
24605
+ * (a `window.multicast`-shaped gateway or a subscribe callback), otherwise a
24606
+ * new MulticastTransport on `window.multicast`. Returns the call that
24607
+ * releases every one of them; dispose() releases them too.
24608
+ *
24609
+ * Packets go straight to the router with the endpoint's ingress, never
24610
+ * through feedPacket(): repair arriving on its own group is not media
24611
+ * liveness, so it must not hold off the media leg's failback watchdog. The
24612
+ * repair roles and owners are registered here; in-band owners stay the
24613
+ * caller's. Joining is best effort: a group that fails to join is logged
24614
+ * and leaves the media join as it was.
24615
+ */
24616
+ joinRepairEndpoints(endpoints, provider) {
24617
+ const releases = [];
24618
+ let released = false;
24619
+ const safely = (each) => {
24620
+ try {
24621
+ each();
24622
+ } catch (error) {
24623
+ console.warn("[MulticastManager] repair group release failed", error);
24624
+ }
24625
+ };
24626
+ const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners);
24627
+ this.#applyRepairOwners(repairOwners);
24628
+ for (const endpoint of endpoints) {
24629
+ const ingress = {
24630
+ tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
24631
+ ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
24632
+ };
24633
+ const onPacket = (packet) => {
24634
+ if (!released) this.#router.feedPacket(packet, "multicast", ingress);
24635
+ };
24636
+ const fail = (error) => console.warn(`[MulticastManager] repair group ${endpoint.group}:${endpoint.port} not joined`, error);
24637
+ if (typeof provider === "function") {
24638
+ Promise.resolve().then(() => provider(endpoint, onPacket)).then((release2) => released ? safely(release2) : releases.push(release2), fail);
24639
+ continue;
24640
+ }
24641
+ const transport = new MulticastTransport((packet) => onPacket(packet), { gateway: provider });
24642
+ releases.push(() => transport.dispose());
24643
+ void transport.join({
24644
+ sourceAddress: endpoint.source,
24645
+ groupAddress: endpoint.group,
24646
+ port: endpoint.port,
24647
+ mode: endpoint.mode,
24648
+ amtRelay: endpoint.amtRelay,
24649
+ amtRelayPort: endpoint.amtRelayPort ?? (endpoint.amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : void 0),
24650
+ packetIds: endpoint.packetIds,
24651
+ tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId }))
24652
+ }).then((joined) => {
24653
+ if (!joined && !released) fail(transport.lastJoinOutcome);
24654
+ });
24655
+ }
24656
+ const release = () => {
24657
+ if (released) return;
24658
+ released = true;
24659
+ this.#repairReleases.delete(release);
24660
+ for (const each of releases.splice(0)) safely(each);
24661
+ };
24662
+ this.#repairReleases.set(release, repairOwners);
24663
+ return release;
24664
+ }
24665
+ #applyRepairOwners(owners) {
24666
+ for (const { packetId, ownerPacketId } of owners) {
24667
+ this.#router.setPacketIdRole(packetId, "repair");
24668
+ this.#router.setRepairPacketIdOwner(packetId, ownerPacketId);
24669
+ }
24670
+ }
24082
24671
  // ---------------------------------------------------------------------------
24083
24672
  // In-place rendition switch
24084
24673
  // ---------------------------------------------------------------------------
@@ -24354,7 +24943,7 @@ var MulticastManager = class {
24354
24943
  *
24355
24944
  * D-04: Validates completeness via validateSwitchingSet — throws if incomplete.
24356
24945
  * D-07: Applies per-track FEC configs (base+delta get decoders; repair does not).
24357
- * D-17: Builds altGroup → track-name index for getSwitchingSet().
24946
+ * D-17: Builds altGroup → track-name index for getSwitchingSet() (repair legs excluded).
24358
24947
  * D-26: Registers packetId → TrackRole on MmtpRouter for block-complete fanout.
24359
24948
  *
24360
24949
  * FEC availability is per track (draft-ramadan-moq-fec §5.1). A media track
@@ -24405,11 +24994,9 @@ var MulticastManager = class {
24405
24994
  }
24406
24995
  }
24407
24996
  const repairOwnerGroup = /* @__PURE__ */ new Map();
24408
- const repairOwnerAltGroup = /* @__PURE__ */ new Map();
24409
24997
  for (const track of catalog.tracks) {
24410
24998
  for (const repairName of repairNamesBySource.get(track.name) ?? []) {
24411
24999
  repairOwnerGroup.set(repairName, altGroupKey(track));
24412
- repairOwnerAltGroup.set(repairName, track.altGroup);
24413
25000
  }
24414
25001
  }
24415
25002
  const groupKeyFor = (track) => repairOwnerGroup.get(track.name) ?? altGroupKey(track);
@@ -24440,11 +25027,7 @@ var MulticastManager = class {
24440
25027
  for (const [groupKey, roles] of resolvedRolesByGroup) {
24441
25028
  if (!(hasSwitchingSetByGroup.get(groupKey) ?? false)) continue;
24442
25029
  const presentRoles = new Set(roles.filter((r) => r !== "single"));
24443
- const required = [
24444
- "base",
24445
- "delta",
24446
- "repair"
24447
- ];
25030
+ const required = ["base", "repair"];
24448
25031
  const missing = required.filter((r) => !presentRoles.has(r));
24449
25032
  if (missing.length > 0) {
24450
25033
  throw new Error(
@@ -24491,6 +25074,7 @@ var MulticastManager = class {
24491
25074
  this.#switchingSets.clear();
24492
25075
  this.#repairPacketIds.clear();
24493
25076
  this.#router.clearRepairPacketIdOwners();
25077
+ for (const owners of this.#repairReleases.values()) this.#applyRepairOwners(owners);
24494
25078
  const fecPacketIds = new Set([...fecDecoders.keys()].map((i) => catalog.tracks[i].packetId));
24495
25079
  for (const [packetId, catalogTrackName] of this.#multiTrackFecTracks) {
24496
25080
  if (fecPacketIds.has(packetId)) continue;
@@ -24511,11 +25095,10 @@ var MulticastManager = class {
24511
25095
  for (let i = 0; i < catalog.tracks.length; i++) {
24512
25096
  const track = catalog.tracks[i];
24513
25097
  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) ?? [];
25098
+ if (role !== "repair" && track.altGroup !== void 0) {
25099
+ const existing = this.#switchingSets.get(track.altGroup) ?? [];
24517
25100
  existing.push(track.name);
24518
- this.#switchingSets.set(altGroup, existing);
25101
+ this.#switchingSets.set(track.altGroup, existing);
24519
25102
  }
24520
25103
  if (track.packetId !== void 0) {
24521
25104
  this.#router.setPacketIdRole(track.packetId, role);
@@ -24590,7 +25173,7 @@ var MulticastManager = class {
24590
25173
  #multiTrackFecTracks = /* @__PURE__ */ new Map();
24591
25174
  /**
24592
25175
  * Return the track names belonging to the given altGroup switching set.
24593
- * D-17: altGroup groups base+delta+repair into one switching set.
25176
+ * D-17: tracks with equal altGroup form one switching set; repair legs are in none.
24594
25177
  *
24595
25178
  * @param altGroup - The altGroup number to look up.
24596
25179
  * @returns Array of track names in that switching set (empty if none).
@@ -24618,6 +25201,26 @@ var MulticastManager = class {
24618
25201
  this.requestRepairForBlock(sbn, packetId, catalogTrackName, blockClass);
24619
25202
  };
24620
25203
  }
25204
+ /**
25205
+ * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
25206
+ * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
25207
+ * pending hole and reported here, and `closeIsoHoles` must be called for it
25208
+ * once its range FETCH ends (or none is sent).
25209
+ */
25210
+ onUndelimitedLoss(cb) {
25211
+ this.#fec.setUndelimitedLossHandler(cb);
25212
+ }
25213
+ /**
25214
+ * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
25215
+ * to CmcdProducer.updateFecFailClosed.
25216
+ */
25217
+ onFecFailClosed(cb) {
25218
+ this.#fec.setFecFailClosedHandler(cb);
25219
+ }
25220
+ /** End a pending hole's range repair: feed what no repair stated as spans. */
25221
+ closeIsoHoles(packetId, catalogTrackName, start, length) {
25222
+ this.#router.closeIsoHoles(packetId, catalogTrackName, start, length);
25223
+ }
24621
25224
  /**
24622
25225
  * Record a repair request whose SUBSCRIBER_PRIORITY the catalog could not
24623
25226
  * supply (draft-ramadan-moq-fec §11.4.5): sent without the parameter, or
@@ -24639,6 +25242,7 @@ var MulticastManager = class {
24639
25242
  stats.repairsSkipped++;
24640
25243
  if (reason === "rtt-unmeasured") stats.repairsSkippedRttUnmeasured++;
24641
25244
  else if (reason === "rtt-exceeds-budget") stats.repairsSkippedRttExceedsBudget++;
25245
+ else if (reason === "range-no-anchor") stats.repairsSkippedRangeNoAnchor++;
24642
25246
  else stats.repairsSkippedPresentationDelayUnavailable++;
24643
25247
  stats.lastRepairSkip = {
24644
25248
  reason,
@@ -24670,8 +25274,20 @@ var MulticastManager = class {
24670
25274
  stats.keyframeBudgetHoldMs += extensionMs;
24671
25275
  }
24672
25276
  /** Record a repair FETCH the scheduler admitted and sent. */
24673
- noteRepairFetchSent(priority, _sbn, packetId, catalogTrackName) {
25277
+ noteRepairFetchSent(priority, sbn, packetId, catalogTrackName, measurement) {
24674
25278
  if (priority === 0) this.#statsFor(packetId, catalogTrackName).keyframeRepairFetchesSent++;
25279
+ if (measurement.range) this.#statsFor(packetId, catalogTrackName).rangeRepairFetchesSent++;
25280
+ this.#emitRepairLifecycle({
25281
+ version: 2,
25282
+ type: "repair-sent",
25283
+ block: repairBlockIdentity(packetId, sbn, catalogTrackName),
25284
+ priority,
25285
+ rttMs: measurement.rttMs,
25286
+ budgetMs: measurement.budgetMs,
25287
+ delayMs: measurement.delayMs,
25288
+ blockAgeMs: measurement.blockAgeMs,
25289
+ bound: measurement.bound
25290
+ });
24675
25291
  }
24676
25292
  /**
24677
25293
  * Record a repair-scheduler decision about a delta block: preempted for
@@ -24822,6 +25438,7 @@ var MulticastManager = class {
24822
25438
  this.#trackResetObservers.clear();
24823
25439
  this.#repairLifecycleObservers.clear();
24824
25440
  this.#transport.dispose();
25441
+ for (const release of [...this.#repairReleases.keys()]) release();
24825
25442
  this.#router.dispose();
24826
25443
  this.#fec.dispose();
24827
25444
  }
@@ -24897,7 +25514,7 @@ async function setupFecWorkerForTrack(opts) {
24897
25514
  trackType: opts.trackType,
24898
25515
  framerate: opts.framerate,
24899
25516
  sampleRate: opts.sampleRate,
24900
- algorithm: "raptor",
25517
+ algorithm: opts.fecAlgorithm ?? "raptorq",
24901
25518
  blockProfile,
24902
25519
  k: opts.fecK,
24903
25520
  // P as this receiver joined it, not the catalog total: the worker snapshot
@@ -24911,10 +25528,10 @@ async function setupFecWorkerForTrack(opts) {
24911
25528
  repairTrack: opts.repairTrackName,
24912
25529
  relayBlockSigEnabled: false
24913
25530
  };
24914
- client.configure(fecTrackConfig, rqWasm);
24915
25531
  try {
24916
25532
  opts.multicastManager.setFecWorker(opts.packetId, client, opts.trackType, {
24917
25533
  blockProfile,
25534
+ algorithm: opts.fecAlgorithm ?? "raptorq",
24918
25535
  k: opts.fecK,
24919
25536
  symbolSize: opts.fecSymbolSize,
24920
25537
  interleaveDepthMs: opts.fecInterleaveMs,
@@ -24922,7 +25539,9 @@ async function setupFecWorkerForTrack(opts) {
24922
25539
  // the local cleanup budget, but it must not use a guessed fps for timing
24923
25540
  // or classification.
24924
25541
  ...hasCatalogTiming ? { fps: 1e3 / opts.mediaUnitDurationMs } : {},
24925
- timeoutMs: deliveryWindowMs
25542
+ timeoutMs: deliveryWindowMs,
25543
+ ...opts.fecRepairLayers ? { repairLayers: opts.fecRepairLayers } : {},
25544
+ ...opts.heldRepairLayers ? { heldLayers: opts.heldRepairLayers } : {}
24926
25545
  }, opts.trackName);
24927
25546
  } catch (e) {
24928
25547
  try {
@@ -24931,6 +25550,14 @@ async function setupFecWorkerForTrack(opts) {
24931
25550
  }
24932
25551
  throw e;
24933
25552
  }
25553
+ fecTrackConfig.interleaveDepth = Math.min(
25554
+ MAX_FEC_RETENTION_BLOCKS,
25555
+ Math.max(
25556
+ interleaveDepthBlocks,
25557
+ opts.multicastManager.fecManager.isoRetentionBlocksForPacket(opts.packetId) ?? 0
25558
+ )
25559
+ );
25560
+ client.configure(fecTrackConfig, rqWasm);
24934
25561
  let disposed = false;
24935
25562
  return {
24936
25563
  client,
@@ -25580,7 +26207,7 @@ function asSeconds(n) {
25580
26207
  }
25581
26208
  return n;
25582
26209
  }
25583
- function groupIdForTicks(ticks, groupDurationTicks) {
26210
+ function groupIdForTicks(ticks, groupDurationTicks, presentationAnchorTicks = 0) {
25584
26211
  if (!Number.isInteger(ticks)) {
25585
26212
  throw new Error(
25586
26213
  `[align] groupIdForTicks: ticks must be an integer, got ${ticks}`
@@ -25591,8 +26218,23 @@ function groupIdForTicks(ticks, groupDurationTicks) {
25591
26218
  `[align] groupIdForTicks: groupDurationTicks must be a positive integer, got ${groupDurationTicks}`
25592
26219
  );
25593
26220
  }
25594
- if (ticks < 0) return 0;
25595
- return Math.floor(ticks / groupDurationTicks);
26221
+ if (!Number.isInteger(presentationAnchorTicks)) {
26222
+ throw new Error(
26223
+ `[align] groupIdForTicks: presentationAnchorTicks must be an integer, got ${presentationAnchorTicks}`
26224
+ );
26225
+ }
26226
+ const relativeTicks = ticks - presentationAnchorTicks;
26227
+ if (!Number.isSafeInteger(relativeTicks)) {
26228
+ throw new Error(
26229
+ `[align] groupIdForTicks: ticks - presentationAnchorTicks = ${relativeTicks} is not a safe integer`
26230
+ );
26231
+ }
26232
+ if (relativeTicks < 0) {
26233
+ throw new Error(
26234
+ `[align] groupIdForTicks: ticks ${ticks} precede presentationAnchorTicks ${presentationAnchorTicks}; the publisher must reject this MPU (moq-mmt-01 4.4.1)`
26235
+ );
26236
+ }
26237
+ return Math.floor(relativeTicks / groupDurationTicks);
25596
26238
  }
25597
26239
  function groupIdFor(mediaTimeSec, groupDurationSec) {
25598
26240
  if (!Number.isFinite(mediaTimeSec)) {
@@ -25605,7 +26247,11 @@ function groupIdFor(mediaTimeSec, groupDurationSec) {
25605
26247
  `[align] groupIdFor: groupDurationSec must be a positive finite number, got ${groupDurationSec}`
25606
26248
  );
25607
26249
  }
25608
- if (mediaTimeSec < 0) return 0;
26250
+ if (mediaTimeSec < 0) {
26251
+ throw new Error(
26252
+ `[align] groupIdFor: mediaTimeSec ${mediaTimeSec} precedes presentationAnchorTicks 0; the publisher must reject this MPU (moq-mmt-01 4.4.1)`
26253
+ );
26254
+ }
25609
26255
  const TS = 1e9;
25610
26256
  const ticks = Math.round(mediaTimeSec * TS);
25611
26257
  const durTicks = Math.round(groupDurationSec * TS);
@@ -26446,6 +27092,7 @@ var CmcdProducer = class {
26446
27092
  #deltaFailRate = null;
26447
27093
  #switchMiscount = 0;
26448
27094
  #manifestStats = null;
27095
+ #fecFailClosed = null;
26449
27096
  constructor(options) {
26450
27097
  this.#onCmcdParams = options.onCmcdParams;
26451
27098
  this.#onCmcdPost = options.onCmcdPost;
@@ -26487,6 +27134,15 @@ var CmcdProducer = class {
26487
27134
  incrementSwitchMiscount() {
26488
27135
  this.#switchMiscount += 1;
26489
27136
  }
27137
+ /**
27138
+ * Record that FEC failed closed at runtime (fec-01 6.3.9). Every later
27139
+ * snapshot carries `x-bc-fec-fail-closed` (the reason code) and
27140
+ * `x-bc-fec-fail-layer` (the held layer i whose total B_i was undercut), so a
27141
+ * stream playing without FEC is told apart from one with no loss.
27142
+ */
27143
+ updateFecFailClosed(reason) {
27144
+ this.#fecFailClosed = reason;
27145
+ }
26490
27146
  updateManifestVerification(stats) {
26491
27147
  this.#manifestStats = stats;
26492
27148
  }
@@ -26524,6 +27180,10 @@ var CmcdProducer = class {
26524
27180
  if (this.#playMode !== null) {
26525
27181
  params["x-bc-play-mode"] = this.#playMode;
26526
27182
  }
27183
+ if (this.#fecFailClosed) {
27184
+ params["x-bc-fec-fail-closed"] = this.#fecFailClosed.code;
27185
+ params["x-bc-fec-fail-layer"] = this.#fecFailClosed.layer;
27186
+ }
26527
27187
  if (this.#playMode !== null && this.#playMode !== "single-track" && this.#deltaFailRate !== null) {
26528
27188
  params["x-bc-delta-fail-rate"] = parseFloat(this.#deltaFailRate.toFixed(4));
26529
27189
  }
@@ -26576,6 +27236,380 @@ var CmcdProducer = class {
26576
27236
  }
26577
27237
  };
26578
27238
 
27239
+ // src/mmtp-fec-session.ts
27240
+ var PATH_BITS = { moq: 1, multicast: 2 };
27241
+ var MIXED_PATHS = PATH_BITS.moq | PATH_BITS.multicast;
27242
+ var MmtpFecSession = class {
27243
+ #decoder;
27244
+ /** Blocks a repair has defined and that are not settled yet, by SS_Start. */
27245
+ #blocks = /* @__PURE__ */ new Map();
27246
+ /** SS_Starts of settled blocks, so a later repair for one is refused. */
27247
+ #settled = /* @__PURE__ */ new Set();
27248
+ /**
27249
+ * SS_IDs whose packet the parser has, with the PATH_BITS of the path it was
27250
+ * received on, or 0 for one the session recovered.
27251
+ */
27252
+ #have = /* @__PURE__ */ new Map();
27253
+ #newest;
27254
+ /** The newest SS_ID when the remembered SS_IDs were last pruned. */
27255
+ #prunedAt;
27256
+ #repairPacketId;
27257
+ #newestSource;
27258
+ #heldLayers;
27259
+ #anchorHorizon;
27260
+ #stats = {
27261
+ sourceSymbols: 0,
27262
+ repairSymbols: 0,
27263
+ blocksClean: 0,
27264
+ blocksRecovered: 0,
27265
+ blocksFailed: 0,
27266
+ blocksReleased: 0,
27267
+ packetsRecovered: 0,
27268
+ packetsLost: 0,
27269
+ dropped: {},
27270
+ sourceSymbolsByPath: { moq: 0, multicast: 0 },
27271
+ repairSymbolsByPath: { moq: 0, multicast: 0 },
27272
+ mixedPath: { clean: 0, recovered: 0, failed: 0, released: 0 },
27273
+ failClosed: null
27274
+ };
27275
+ /**
27276
+ * @throws when the catalog block lacks or misstates a field the session
27277
+ * needs: the block profile, K, P_0 (`repairSymbols`), T, `interleaveDepthMs` or
27278
+ * `reorderToleranceMs`. None is defaulted.
27279
+ */
27280
+ constructor(config) {
27281
+ const fec = config?.fec;
27282
+ if (!fec || typeof fec !== "object") {
27283
+ throw new Error("MmtpFecSession: the catalog fec block is required");
27284
+ }
27285
+ this.blockProfile = parseFecBlockProfile(fec.blockProfile, "fec.blockProfile");
27286
+ if (fec.algorithm !== void 0 && fec.algorithm !== "raptorq" && fec.algorithm !== "reed-solomon") {
27287
+ throw new Error(`MmtpFecSession: fec.algorithm ${JSON.stringify(fec.algorithm)} is not implemented`);
27288
+ }
27289
+ this.algorithm = fec.algorithm === "reed-solomon" ? "reed-solomon" : "raptorq";
27290
+ this.sourceSymbols = requirePositiveInteger(fec.sourceSymbols, "fec.sourceSymbols");
27291
+ this.repairSymbols = requirePositiveInteger(fec.repairSymbols, "fec.repairSymbols");
27292
+ this.symbolSize = requirePositiveInteger(fec.symbolSize, "fec.symbolSize");
27293
+ const interleaveDepthMs = requireNumber(fec.interleaveDepthMs, "fec.interleaveDepthMs");
27294
+ const reorderToleranceMs = requireNumber(fec.reorderToleranceMs, "fec.reorderToleranceMs");
27295
+ this.retentionBlocks = deriveFecRetentionBlocks(
27296
+ fecBlockBudgetMs(interleaveDepthMs, reorderToleranceMs),
27297
+ interleaveDepthMs
27298
+ );
27299
+ this.#heldLayers = new HeldLayerAdmission(
27300
+ config.repairLayers ?? [
27301
+ {
27302
+ layer: 0,
27303
+ repairTrackName: typeof fec.repairTrack === "string" ? fec.repairTrack : "",
27304
+ rsIdOffset: 0,
27305
+ repairSymbols: this.repairSymbols
27306
+ }
27307
+ ],
27308
+ config.heldLayers
27309
+ );
27310
+ this.#anchorHorizon = heldLayerAnchorHorizon(this.retentionBlocks, this.sourceSymbols);
27311
+ if (typeof config.Decoder !== "function") {
27312
+ throw new Error("MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required");
27313
+ }
27314
+ const decoder = new config.Decoder(this.retentionBlocks, this.blockProfile, this.algorithm);
27315
+ try {
27316
+ decoder.configure_params(this.sourceSymbols, this.symbolSize);
27317
+ } catch (error) {
27318
+ decoder.free();
27319
+ throw error;
27320
+ }
27321
+ this.#decoder = decoder;
27322
+ }
27323
+ /** True once release() ran. */
27324
+ get released() {
27325
+ return this.#decoder === null;
27326
+ }
27327
+ get stats() {
27328
+ return {
27329
+ ...this.#stats,
27330
+ dropped: { ...this.#stats.dropped },
27331
+ sourceSymbolsByPath: { ...this.#stats.sourceSymbolsByPath },
27332
+ repairSymbolsByPath: { ...this.#stats.repairSymbolsByPath },
27333
+ mixedPath: { ...this.#stats.mixedPath },
27334
+ failClosed: this.#stats.failClosed && { ...this.#stats.failClosed }
27335
+ };
27336
+ }
27337
+ /**
27338
+ * Feeds one received source packet: the MMTP packet without its four-byte
27339
+ * Source FEC Payload ID, under the SS_ID that ID stated. This is what
27340
+ * MmtpContainerParser's onSourceSymbol() hands over. `path` is where it
27341
+ * was received; a caller that only subscribes over MoQT can leave it out.
27342
+ *
27343
+ * @returns the protected packets of this packet's block that it recovered,
27344
+ * in SS_ID order, for the caller to feed to its parser with
27345
+ * `{skipFecPayloadId: true, recovered: true}`. Usually empty.
27346
+ */
27347
+ addSource(ssId, packet, path = "moq") {
27348
+ const decoder = this.#decoder;
27349
+ if (!decoder) return this.#drop("source:released");
27350
+ const pathBit = PATH_BITS[path];
27351
+ if (!pathBit) return this.#drop("source:unknown-path");
27352
+ if (!Number.isInteger(ssId) || ssId < 0 || ssId > 4294967295) return this.#drop("source:bad-ss-id");
27353
+ if (!ssbg1FitsSymbol(packet.byteLength, this.symbolSize)) return this.#drop("source:exceeds-symbol");
27354
+ if (this.#have.has(ssId)) return this.#drop("source:duplicate");
27355
+ this.#have.set(ssId, pathBit);
27356
+ this.#stats.sourceSymbols++;
27357
+ this.#stats.sourceSymbolsByPath[path]++;
27358
+ this.#noteNewest(ssId);
27359
+ if (this.#newestSource === void 0 || serial32Precedes(this.#newestSource, ssId)) this.#newestSource = ssId;
27360
+ const start = this.#blockStartOf(ssId);
27361
+ const block = start === void 0 ? void 0 : this.#blocks.get(start);
27362
+ if (block) {
27363
+ block.received++;
27364
+ block.paths |= pathBit;
27365
+ }
27366
+ let output;
27367
+ try {
27368
+ output = decoder.add_source(ssId, packet, 0);
27369
+ } catch {
27370
+ this.#drop("source:decoder-refused");
27371
+ output = void 0;
27372
+ }
27373
+ const recovered = [];
27374
+ if (start !== void 0 && block) {
27375
+ if (output) {
27376
+ recovered.push(...this.#settleDecoded(start, block, output));
27377
+ } else if (block.received >= block.ssbLength) {
27378
+ this.#settleClean(start);
27379
+ }
27380
+ }
27381
+ this.#retireBehindHorizon();
27382
+ return recovered;
27383
+ }
27384
+ /**
27385
+ * Feeds one object of the repair track: a whole MMTP repair packet (ISO/IEC
27386
+ * 23008-1 C.5.3). A repair track carries one repair flow, so the first
27387
+ * repair packet fixes its packet ID and a packet of any other is refused.
27388
+ * `path` is where it was received, as for addSource(). `repairTrackName`
27389
+ * is the repair track it was received on, for the 6.3.9 own-track rule; a
27390
+ * track the layers do not list is refused as `repair:unlisted-track`.
27391
+ *
27392
+ * @returns the protected packets this repair symbol recovered, as for
27393
+ * addSource().
27394
+ */
27395
+ addRepair(packet, path = "moq", repairTrackName) {
27396
+ const decoder = this.#decoder;
27397
+ if (!decoder) return this.#drop("repair:released");
27398
+ if (this.#stats.failClosed) return this.#drop("repair:fail-closed");
27399
+ const pathBit = PATH_BITS[path];
27400
+ if (!pathBit) return this.#drop("repair:unknown-path");
27401
+ let header;
27402
+ try {
27403
+ header = parseMMTPHeader(packet);
27404
+ } catch {
27405
+ return this.#drop("repair:malformed");
27406
+ }
27407
+ const frame = parseMoqRepairFrameWithHeader(packet, header);
27408
+ if (!frame) return this.#drop("repair:malformed");
27409
+ if (this.#repairPacketId === void 0) {
27410
+ this.#repairPacketId = frame.packetId;
27411
+ } else if (frame.packetId !== this.#repairPacketId) {
27412
+ return this.#drop("repair:foreign-packet-id");
27413
+ }
27414
+ if (frame.symbolData.byteLength !== this.symbolSize) return this.#drop("repair:symbol-size");
27415
+ if (frame.ssbLength > this.sourceSymbols) return this.#drop("repair:ssb-length");
27416
+ if (this.algorithm === "reed-solomon" && frame.ssbLength + frame.rsbLength > 255) {
27417
+ return this.#drop("repair:rs-block-length");
27418
+ }
27419
+ const verdict = this.#heldLayers.admit(
27420
+ repairTrackName,
27421
+ frame.ssStart,
27422
+ frame.rsbLength,
27423
+ this.#anchorHorizon,
27424
+ this.#newestSource
27425
+ );
27426
+ if (verdict === "discard") return this.#drop("repair:unlisted-track");
27427
+ if (verdict !== void 0) {
27428
+ this.#stats.failClosed = verdict;
27429
+ return this.#drop("repair:fail-closed");
27430
+ }
27431
+ const start = frame.ssStart;
27432
+ let block = this.#blocks.get(start);
27433
+ if (block && block.ssbLength !== frame.ssbLength) return this.#drop("repair:conflicting-ssb-length");
27434
+ if (block?.rsIds.has(frame.rsId)) return this.#drop("repair:duplicate");
27435
+ if (!block) {
27436
+ if (this.#settled.has(start)) return this.#drop("repair:block-settled");
27437
+ if (this.#behindHorizon(start)) return this.#drop("repair:behind-horizon");
27438
+ block = { ssbLength: frame.ssbLength, received: 0, paths: 0, rsIds: /* @__PURE__ */ new Set() };
27439
+ this.#countHeld(start, block);
27440
+ this.#blocks.set(start, block);
27441
+ }
27442
+ this.#noteNewest(serial32Add(start, frame.ssbLength - 1));
27443
+ if (block.received >= block.ssbLength) {
27444
+ this.#settleClean(start);
27445
+ this.#retireBehindHorizon();
27446
+ return [];
27447
+ }
27448
+ let output;
27449
+ try {
27450
+ output = decoder.add_repair(start, frame.ssbLength, frame.rsId, frame.symbolData, 0);
27451
+ } catch {
27452
+ return this.#drop("repair:decoder-refused");
27453
+ }
27454
+ block.rsIds.add(frame.rsId);
27455
+ this.#stats.repairSymbols++;
27456
+ this.#stats.repairSymbolsByPath[path]++;
27457
+ block.paths |= pathBit;
27458
+ const recovered = output ? this.#settleDecoded(start, block, output) : [];
27459
+ this.#retireBehindHorizon();
27460
+ return recovered;
27461
+ }
27462
+ /**
27463
+ * Frees the decoder and every block. Blocks still unsettled are counted as
27464
+ * released, not failed: nothing proved them unrecoverable. Idempotent;
27465
+ * returns whether this call released anything.
27466
+ */
27467
+ release() {
27468
+ const decoder = this.#decoder;
27469
+ if (!decoder) return false;
27470
+ this.#decoder = null;
27471
+ this.#stats.blocksReleased += this.#blocks.size;
27472
+ for (const block of this.#blocks.values()) this.#noteMixed(block, "released");
27473
+ this.#blocks.clear();
27474
+ this.#settled.clear();
27475
+ this.#have.clear();
27476
+ decoder.free();
27477
+ return true;
27478
+ }
27479
+ #drop(reason) {
27480
+ this.#stats.dropped[reason] = (this.#stats.dropped[reason] ?? 0) + 1;
27481
+ return [];
27482
+ }
27483
+ #noteNewest(ssId) {
27484
+ if (this.#newest === void 0 || serial32Precedes(this.#newest, ssId)) this.#newest = ssId;
27485
+ }
27486
+ #blockStartOf(ssId) {
27487
+ for (const [start, block] of this.#blocks) {
27488
+ if (isoBlockContains(start, block.ssbLength, ssId)) return start;
27489
+ }
27490
+ return void 0;
27491
+ }
27492
+ /** Counts the sources of a new block the parser already has, and their paths. */
27493
+ #countHeld(start, block) {
27494
+ for (let i = 0; i < block.ssbLength; i++) {
27495
+ const pathBit = this.#have.get(serial32Add(start, i));
27496
+ if (pathBit === void 0) continue;
27497
+ block.received++;
27498
+ block.paths |= pathBit;
27499
+ }
27500
+ }
27501
+ #noteMixed(block, outcome) {
27502
+ if ((block.paths & MIXED_PATHS) === MIXED_PATHS) this.#stats.mixedPath[outcome]++;
27503
+ }
27504
+ /** The decoder's own rule: more than its retention behind, counted from below. */
27505
+ #behindHorizon(start) {
27506
+ const newest = this.#newest;
27507
+ if (newest === void 0) return false;
27508
+ return isoBlocksBehindLowerBound(start, newest, this.sourceSymbols) > this.retentionBlocks;
27509
+ }
27510
+ #settle(start) {
27511
+ this.#blocks.delete(start);
27512
+ this.#settled.add(start);
27513
+ }
27514
+ #settleClean(start) {
27515
+ const block = this.#blocks.get(start);
27516
+ if (!block) return;
27517
+ this.#settle(start);
27518
+ this.#stats.blocksClean++;
27519
+ this.#noteMixed(block, "clean");
27520
+ try {
27521
+ this.#decoder?.cleanup_blocks_detailed(Uint32Array.of(start));
27522
+ } catch {
27523
+ }
27524
+ }
27525
+ /**
27526
+ * The decoder returns a completed block as its K' ssbg_mode1 symbols,
27527
+ * concatenated: split by T, trim by each symbol's length field, and hand
27528
+ * back the packets the parser does not have yet.
27529
+ */
27530
+ #settleDecoded(start, block, output) {
27531
+ this.#settle(start);
27532
+ if (output.byteLength !== block.ssbLength * this.symbolSize) {
27533
+ this.#stats.blocksFailed++;
27534
+ this.#stats.packetsLost += block.ssbLength - block.received;
27535
+ this.#noteMixed(block, "failed");
27536
+ this.#drop("block:decoded-length");
27537
+ return [];
27538
+ }
27539
+ const recovered = [];
27540
+ let refused = 0;
27541
+ for (let i = 0; i < block.ssbLength; i++) {
27542
+ const ssId = serial32Add(start, i);
27543
+ if (this.#have.has(ssId)) continue;
27544
+ const symbol = output.subarray(i * this.symbolSize, (i + 1) * this.symbolSize);
27545
+ const packet = trimSsbg1SourceSymbol(symbol);
27546
+ if (!packet) {
27547
+ refused++;
27548
+ continue;
27549
+ }
27550
+ this.#have.set(ssId, 0);
27551
+ recovered.push(packet.slice());
27552
+ }
27553
+ if (refused > 0) {
27554
+ this.#stats.blocksFailed++;
27555
+ this.#stats.packetsLost += refused;
27556
+ this.#noteMixed(block, "failed");
27557
+ this.#drop("block:bad-ssbg1-symbol");
27558
+ } else if (recovered.length === 0) {
27559
+ this.#stats.blocksClean++;
27560
+ this.#noteMixed(block, "clean");
27561
+ } else {
27562
+ this.#stats.blocksRecovered++;
27563
+ this.#noteMixed(block, "recovered");
27564
+ }
27565
+ this.#stats.packetsRecovered += recovered.length;
27566
+ return recovered;
27567
+ }
27568
+ /**
27569
+ * Retires every block, and every SS_ID the session remembers, that the
27570
+ * newest SS_ID has moved past the retention. An unsettled block retired
27571
+ * here is a failure: more of its sources were lost than its repair could
27572
+ * restore, or its repair never arrived.
27573
+ */
27574
+ #retireBehindHorizon() {
27575
+ const decoder = this.#decoder;
27576
+ const newest = this.#newest;
27577
+ if (!decoder || newest === void 0) return;
27578
+ try {
27579
+ decoder.cleanup_by_ss_start(newest);
27580
+ } catch {
27581
+ }
27582
+ for (const [start, block] of this.#blocks) {
27583
+ if (!this.#behindHorizon(start)) continue;
27584
+ this.#settle(start);
27585
+ this.#stats.blocksFailed++;
27586
+ this.#stats.packetsLost += block.ssbLength - block.received;
27587
+ this.#noteMixed(block, "failed");
27588
+ }
27589
+ const prunedAt = this.#prunedAt;
27590
+ if (prunedAt !== void 0 && serial32Distance(prunedAt, newest) < this.sourceSymbols) return;
27591
+ this.#prunedAt = newest;
27592
+ for (const ssId of this.#have.keys()) {
27593
+ if (this.#behindHorizon(ssId)) this.#have.delete(ssId);
27594
+ }
27595
+ for (const start of this.#settled) {
27596
+ if (this.#behindHorizon(start)) this.#settled.delete(start);
27597
+ }
27598
+ }
27599
+ };
27600
+ function requirePositiveInteger(value, path) {
27601
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
27602
+ throw new Error(`MmtpFecSession: ${path} must be a positive integer (got ${String(value)})`);
27603
+ }
27604
+ return value;
27605
+ }
27606
+ function requireNumber(value, path) {
27607
+ if (typeof value !== "number") {
27608
+ throw new Error(`MmtpFecSession: ${path} is required (got ${String(value)}); it is never defaulted`);
27609
+ }
27610
+ return value;
27611
+ }
27612
+
26579
27613
  // src/repair-fetch.ts
26580
27614
  var MOQT_PRIORITY_MAX = 255;
26581
27615
  var SOURCE_MEDIA_PRIORITY_MAX = REPAIR_PRIORITY_MIN - 1;
@@ -26610,6 +27644,9 @@ function wireRepairFetch(mc, opts) {
26610
27644
  if (typeof opts.presentationDelayMs !== "function") {
26611
27645
  throw new Error("[RepairFetch] presentationDelayMs is required: a repair FETCH is due by the block's presentation deadline");
26612
27646
  }
27647
+ if (opts.rangeTransport !== void 0 && (typeof opts.repairEpochReference !== "function" || !mc.onUndelimitedLoss || !mc.closeIsoHoles)) {
27648
+ throw new Error("[RepairFetch] rangeTransport needs repairEpochReference and a host that reports undelimited losses");
27649
+ }
26613
27650
  const entries = /* @__PURE__ */ new Map();
26614
27651
  const warnedNoTarget = /* @__PURE__ */ new Set();
26615
27652
  let disposed = false;
@@ -26623,7 +27660,12 @@ function wireRepairFetch(mc, opts) {
26623
27660
  const note = (type, entry) => {
26624
27661
  mc.noteRepairScheduling(type, entry.sbn, entry.packetId, entry.catalogTrackName);
26625
27662
  };
27663
+ const clearEntry = (entry) => {
27664
+ if (entry.range) mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, entry.range.holeLength);
27665
+ else clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27666
+ };
26626
27667
  const releaseHold = (entry) => {
27668
+ if (entry.range) return;
26627
27669
  if (entry.catalogTrackName === void 0) mc.fecManager.releaseRepairHold(entry.sbn, entry.packetId);
26628
27670
  else mc.fecManager.releaseRepairHold(entry.sbn, entry.packetId, entry.catalogTrackName);
26629
27671
  };
@@ -26656,10 +27698,10 @@ function wireRepairFetch(mc, opts) {
26656
27698
  const admit = (entry, now) => {
26657
27699
  const budgetMs = entry.deadlineAt - now;
26658
27700
  const rttMs = readRtt();
26659
- if (rttMs !== null && rttMs < budgetMs) return true;
27701
+ if (rttMs !== null && rttMs < budgetMs) return rttMs;
26660
27702
  retire(entry);
26661
27703
  releaseHold(entry);
26662
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27704
+ clearEntry(entry);
26663
27705
  mc.noteRepairSkipped(
26664
27706
  rttMs === null ? "rtt-unmeasured" : "rtt-exceeds-budget",
26665
27707
  { rttMs, budgetMs, priority: entry.priority },
@@ -26667,10 +27709,11 @@ function wireRepairFetch(mc, opts) {
26667
27709
  entry.packetId,
26668
27710
  entry.catalogTrackName
26669
27711
  );
26670
- return false;
27712
+ return null;
26671
27713
  };
26672
27714
  const retire = (entry) => {
26673
27715
  if (entries.get(entry.key) === entry) entries.delete(entry.key);
27716
+ if (entry.expiry !== void 0) clearTimeout(entry.expiry);
26674
27717
  };
26675
27718
  const urgentOutstanding = () => {
26676
27719
  for (const entry of entries.values()) {
@@ -26699,17 +27742,28 @@ function wireRepairFetch(mc, opts) {
26699
27742
  return derived.kind === "omit" ? { subscriberPriority: void 0 } : null;
26700
27743
  };
26701
27744
  const start = (entry, counted = true) => {
26702
- if (!admit(entry, performance.now())) return;
27745
+ const now = performance.now();
27746
+ const rttMs = admit(entry, now);
27747
+ if (rttMs === null) return;
26703
27748
  if (counted) entry.attempts++;
26704
- mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName);
27749
+ mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName, {
27750
+ rttMs,
27751
+ budgetMs: entry.deadlineAt - now,
27752
+ delayMs: entry.delayMs,
27753
+ blockAgeMs: entry.anchorAt === null ? null : Math.max(0, now - entry.anchorAt),
27754
+ bound: entry.bound,
27755
+ ...entry.range ? { range: true } : {}
27756
+ });
26705
27757
  const run = { controller: new AbortController(), stopped: null };
26706
27758
  entry.running = run;
26707
- mc.fecManager.holdBlockForRepair(
26708
- entry.sbn,
26709
- entry.packetId,
26710
- entry.catalogTrackName,
26711
- entry.deadlineAt
26712
- );
27759
+ if (!entry.range) {
27760
+ mc.fecManager.holdBlockForRepair(
27761
+ entry.sbn,
27762
+ entry.packetId,
27763
+ entry.catalogTrackName,
27764
+ entry.deadlineAt
27765
+ );
27766
+ }
26713
27767
  void execute(entry, run);
26714
27768
  };
26715
27769
  const dispatch = () => {
@@ -26721,14 +27775,14 @@ function wireRepairFetch(mc, opts) {
26721
27775
  if (entry.deadlineAt <= now) {
26722
27776
  stop(entry, "expired");
26723
27777
  retire(entry);
26724
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27778
+ clearEntry(entry);
26725
27779
  }
26726
27780
  continue;
26727
27781
  }
26728
27782
  if (entry.deadlineAt <= now) {
26729
27783
  retire(entry);
26730
27784
  if (entry.priority === 2 && entry.attempts === 0) note("repair-deferred", entry);
26731
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27785
+ clearEntry(entry);
26732
27786
  continue;
26733
27787
  }
26734
27788
  queued.push(entry);
@@ -26765,9 +27819,9 @@ function wireRepairFetch(mc, opts) {
26765
27819
  entry.running = null;
26766
27820
  if (error === void 0) {
26767
27821
  retire(entry);
26768
- if (fed === 0 || !decodable(entry)) {
27822
+ if (entry.range || fed === 0 || !decodable(entry)) {
26769
27823
  releaseHold(entry);
26770
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27824
+ clearEntry(entry);
26771
27825
  }
26772
27826
  dispatch();
26773
27827
  return;
@@ -26779,7 +27833,7 @@ function wireRepairFetch(mc, opts) {
26779
27833
  }
26780
27834
  retire(entry);
26781
27835
  if (fed === 0) releaseHold(entry);
26782
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27836
+ clearEntry(entry);
26783
27837
  console.warn(
26784
27838
  `[RepairFetch] fetch failed pid=${entry.packetId} sbn=${entry.sbn} track=${entry.repairTrack}:`,
26785
27839
  error
@@ -26795,15 +27849,21 @@ function wireRepairFetch(mc, opts) {
26795
27849
  };
26796
27850
  const execute = async (entry, run) => {
26797
27851
  let fed = 0;
27852
+ const common = {
27853
+ repairTrack: entry.repairTrack,
27854
+ blockProfile: entry.blockProfile,
27855
+ packetId: entry.packetId,
27856
+ signal: run.controller.signal,
27857
+ subscriberPriority: entry.subscriberPriority
27858
+ };
26798
27859
  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
- })) {
27860
+ const packets = entry.range ? opts.rangeTransport({
27861
+ ...common,
27862
+ startGroup: entry.range.startGroup,
27863
+ endGroup: entry.range.endGroup,
27864
+ lostSsId: entry.range.lostSsId
27865
+ }) : opts.transport({ ...common, sbn: entry.sbn });
27866
+ for await (const packet of packets) {
26807
27867
  if (run.stopped !== null || entry.running !== run) break;
26808
27868
  fed++;
26809
27869
  if (entry.catalogTrackName === void 0) {
@@ -26822,6 +27882,7 @@ function wireRepairFetch(mc, opts) {
26822
27882
  if (entry.packetId !== packetId || entry.catalogTrackName !== catalogTrackName) continue;
26823
27883
  retire(entry);
26824
27884
  stop(entry, "reset");
27885
+ if (entry.range) clearEntry(entry);
26825
27886
  }
26826
27887
  warnedNoTarget.delete(noTargetKey(packetId, catalogTrackName));
26827
27888
  dispatch();
@@ -26848,6 +27909,9 @@ function wireRepairFetch(mc, opts) {
26848
27909
  );
26849
27910
  if (promotedDeadline !== null && promotedDeadline.deadlineAt > entry2.deadlineAt) {
26850
27911
  entry2.deadlineAt = promotedDeadline.deadlineAt;
27912
+ entry2.anchorAt = promotedDeadline.anchorAt;
27913
+ entry2.delayMs = promotedDeadline.delayMs;
27914
+ entry2.bound = promotedDeadline.bound;
26851
27915
  noteBudget(entry2, promotedDeadline.extensionMs);
26852
27916
  }
26853
27917
  if (entry2.running) {
@@ -26873,7 +27937,9 @@ function wireRepairFetch(mc, opts) {
26873
27937
  if (waitMs === void 0) return null;
26874
27938
  const waitDeadlineAt = now + waitMs;
26875
27939
  const anchor = mc.fecManager.blockAnchorAtMs(sbn, packetId, catalogTrackName);
26876
- if (anchor === void 0) return { deadlineAt: waitDeadlineAt, extensionMs: 0 };
27940
+ if (anchor === void 0) {
27941
+ return { deadlineAt: waitDeadlineAt, extensionMs: 0, anchorAt: null, delayMs: null, bound: "wait" };
27942
+ }
26877
27943
  let delayMs;
26878
27944
  try {
26879
27945
  delayMs = opts.presentationDelayMs(packetId, catalogTrackName);
@@ -26884,12 +27950,21 @@ function wireRepairFetch(mc, opts) {
26884
27950
  const retentionMs = mc.fecManager.terminalRetentionMsForPacket(packetId);
26885
27951
  if (retentionMs === void 0) return null;
26886
27952
  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);
27953
+ const at = (delay, delayBound) => {
27954
+ const presentAt = Math.min(anchor + delay, ceilingAt);
27955
+ if (waitDeadlineAt >= presentAt) return { deadlineAt: waitDeadlineAt, bound: "wait" };
27956
+ return { deadlineAt: presentAt, bound: anchor + delay <= ceilingAt ? delayBound : "retention" };
27957
+ };
27958
+ const base = at(delayMs, "presentation");
26889
27959
  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 };
27960
+ if (budgetMs === null || budgetMs <= delayMs) return { ...base, extensionMs: 0, anchorAt: anchor, delayMs };
27961
+ const extended = at(budgetMs, "keyframe");
27962
+ return {
27963
+ ...extended,
27964
+ extensionMs: extended.deadlineAt - base.deadlineAt,
27965
+ anchorAt: anchor,
27966
+ delayMs: budgetMs
27967
+ };
26893
27968
  };
26894
27969
  const earliestGatedFrameAt = (packetId, catalogTrackName) => {
26895
27970
  try {
@@ -26966,6 +28041,9 @@ function wireRepairFetch(mc, opts) {
26966
28041
  priority,
26967
28042
  subscriberPriority: wire.subscriberPriority,
26968
28043
  deadlineAt: deadline.deadlineAt,
28044
+ anchorAt: deadline.anchorAt,
28045
+ delayMs: deadline.delayMs,
28046
+ bound: deadline.bound,
26969
28047
  order: enqueueOrder++,
26970
28048
  attempts: 0,
26971
28049
  running: null
@@ -26975,14 +28053,92 @@ function wireRepairFetch(mc, opts) {
26975
28053
  if (entry.priority < 2) preemptDeltas();
26976
28054
  dispatch();
26977
28055
  });
28056
+ const rangeFor = (loss, repairTrack) => {
28057
+ let reference;
28058
+ try {
28059
+ reference = opts.repairEpochReference(repairTrack);
28060
+ } catch {
28061
+ return null;
28062
+ }
28063
+ if (reference === void 0) return null;
28064
+ try {
28065
+ const anchor = loss.previousBlockStart === void 0 ? { reference } : { previousBlockStart: extendSsId(reference, loss.previousBlockStart) };
28066
+ return repairFetchRange(loss.lostSsId, loss.kMax, anchor);
28067
+ } catch (error) {
28068
+ if (error instanceof RangeError) return null;
28069
+ throw error;
28070
+ }
28071
+ };
28072
+ if (opts.rangeTransport !== void 0) {
28073
+ mc.onUndelimitedLoss((loss) => {
28074
+ const { packetId, catalogTrackName, holeStart, holeLength } = loss;
28075
+ const close = () => mc.closeIsoHoles(packetId, catalogTrackName, holeStart, holeLength);
28076
+ if (disposed) return close();
28077
+ const blockProfile = blockProfileOf(packetId);
28078
+ const target = opts.resolveTarget(packetId, catalogTrackName);
28079
+ if (!target) return close();
28080
+ const priority = repairPriorityForClass("unknown");
28081
+ const range = rangeFor(loss, target.repairTrack);
28082
+ if (range === null) {
28083
+ close();
28084
+ mc.noteRepairSkipped("range-no-anchor", { rttMs: readRtt(), budgetMs: 0, priority }, holeStart, packetId, catalogTrackName);
28085
+ return;
28086
+ }
28087
+ const identity = {
28088
+ target,
28089
+ sbn: holeStart,
28090
+ packetId,
28091
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
28092
+ };
28093
+ const wire = wirePriority(identity, "unknown");
28094
+ const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, performance.now(), "unknown");
28095
+ if (deadline === null) {
28096
+ close();
28097
+ mc.noteRepairSkipped(
28098
+ "presentation-delay-unavailable",
28099
+ { rttMs: readRtt(), budgetMs: 0, priority },
28100
+ holeStart,
28101
+ packetId,
28102
+ catalogTrackName
28103
+ );
28104
+ return;
28105
+ }
28106
+ const entry = {
28107
+ key: JSON.stringify(["range", packetId, catalogTrackName ?? null, holeStart]),
28108
+ ...identity,
28109
+ repairTrack: target.repairTrack,
28110
+ blockProfile,
28111
+ priority,
28112
+ subscriberPriority: wire.subscriberPriority,
28113
+ deadlineAt: deadline.deadlineAt,
28114
+ anchorAt: deadline.anchorAt,
28115
+ delayMs: deadline.delayMs,
28116
+ bound: deadline.bound,
28117
+ order: enqueueOrder++,
28118
+ attempts: 0,
28119
+ running: null,
28120
+ range: { ...range, lostSsId: loss.lostSsId, holeLength }
28121
+ };
28122
+ const previous = entries.get(entry.key);
28123
+ if (previous) {
28124
+ retire(previous);
28125
+ stop(previous, "reset");
28126
+ }
28127
+ entries.set(entry.key, entry);
28128
+ entry.expiry = setTimeout(dispatch, Math.max(0, entry.deadlineAt - performance.now()) + 1);
28129
+ preemptDeltas();
28130
+ dispatch();
28131
+ });
28132
+ }
26978
28133
  return () => {
26979
28134
  disposed = true;
26980
28135
  removeResetObserver();
26981
28136
  removeLifecycleObserver();
26982
28137
  for (const entry of [...entries.values()]) {
26983
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
28138
+ clearEntry(entry);
26984
28139
  if (entry.running) releaseHold(entry);
26985
28140
  stop(entry, "disposed");
28141
+ if (entry.expiry !== void 0) clearTimeout(entry.expiry);
26986
28142
  }
26987
28143
  entries.clear();
26988
28144
  };
@@ -27021,20 +28177,19 @@ export {
27021
28177
  MfuReassemblyError,
27022
28178
  MmtpContainerParser,
27023
28179
  MmtpDecodePipeline,
28180
+ MmtpFecSession,
27024
28181
  MmtpRouter,
27025
28182
  MmtpToCmaf,
27026
28183
  MulticastContainerContractError,
27027
28184
  MulticastInputError,
27028
28185
  MulticastManager,
27029
28186
  MulticastTransport,
27030
- NoneCodec,
27031
28187
  REPAIR_LIFECYCLE_EVENT_TYPE,
27032
28188
  REPAIR_LIFECYCLE_LOG_PREFIX,
27033
28189
  REPAIR_PRIORITY_MAX,
27034
28190
  REPAIR_PRIORITY_MIN,
27035
28191
  REPAIR_TRACK_GEOMETRY_KEYS,
27036
28192
  REPAIR_TRACK_ONLY_KEYS,
27037
- ReedSolomonCodec,
27038
28193
  RepairContractError,
27039
28194
  SOURCE_MEDIA_PRIORITY_MAX,
27040
28195
  SampleCombineError,
@@ -27055,6 +28210,7 @@ export {
27055
28210
  buildHevcVideoInitSegment,
27056
28211
  buildVideoInitSegment,
27057
28212
  catalogAmtNetworkSource,
28213
+ catalogAtsc3NetworkSource,
27058
28214
  catalogDeclaresFec,
27059
28215
  catalogFecAvailable,
27060
28216
  catalogFecDeclaresUnconfigurableInstance,
@@ -27071,7 +28227,6 @@ export {
27071
28227
  computeFecDeliveryWindowMediaUnits,
27072
28228
  computeFecDeliveryWindowMs,
27073
28229
  computeFecLossWindowMs,
27074
- createFecCodec,
27075
28230
  createFragment,
27076
28231
  createWasmMmtpContainerParser,
27077
28232
  datagramMfuReassembly,
@@ -27099,6 +28254,7 @@ export {
27099
28254
  extractHevcCodecDescription,
27100
28255
  extractHevcParameterSets,
27101
28256
  extractSpsPpsFromAvcC,
28257
+ fecAlgorithmUnimplemented,
27102
28258
  findAnnexBStartCode,
27103
28259
  forwardRepairLifecycleEvents,
27104
28260
  frameSamplesFromInit,