@blockcast/mmt-container 0.4.0-main.1cd3cdea89da → 0.4.0-main.2654dbc2ed6d

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 (187) hide show
  1. package/README.md +33 -17
  2. package/dist/align.d.ts +24 -18
  3. package/dist/align.d.ts.map +1 -1
  4. package/dist/align.js +23 -4
  5. package/dist/align.js.map +2 -2
  6. package/dist/browser-runtime.js +1628 -647
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +63 -29
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +291 -199
  11. package/dist/carp-catalog.js.map +3 -3
  12. package/dist/catalog-fec-params.d.ts +6 -3
  13. package/dist/catalog-fec-params.d.ts.map +1 -1
  14. package/dist/catalog-fec-params.js +104 -47
  15. package/dist/catalog-fec-params.js.map +4 -4
  16. package/dist/catalog-network-source.d.ts +1 -1
  17. package/dist/catalog-network-source.d.ts.map +1 -1
  18. package/dist/catalog-network-source.js +3 -0
  19. package/dist/catalog-network-source.js.map +3 -3
  20. package/dist/catalog-validator.d.ts +4 -3
  21. package/dist/catalog-validator.d.ts.map +1 -1
  22. package/dist/catalog-validator.js +0 -29
  23. package/dist/catalog-validator.js.map +3 -3
  24. package/dist/delivery-catalog.js +90 -230
  25. package/dist/delivery-catalog.js.map +4 -4
  26. package/dist/fec-manager.d.ts +51 -1
  27. package/dist/fec-manager.d.ts.map +1 -1
  28. package/dist/fec-manager.js +260 -62
  29. package/dist/fec-manager.js.map +4 -4
  30. package/dist/fec-state.d.ts +3 -2
  31. package/dist/fec-state.d.ts.map +1 -1
  32. package/dist/fec-state.js +30 -11
  33. package/dist/fec-state.js.map +4 -4
  34. package/dist/fec-worker-setup.d.ts.map +1 -1
  35. package/dist/fec-worker-setup.js +13 -2
  36. package/dist/fec-worker-setup.js.map +3 -3
  37. package/dist/index.d.ts +4 -3
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +10 -0
  40. package/dist/index.js.map +2 -2
  41. package/dist/iso-block-locator.d.ts +29 -0
  42. package/dist/iso-block-locator.d.ts.map +1 -1
  43. package/dist/iso-block-locator.js +100 -17
  44. package/dist/iso-block-locator.js.map +4 -4
  45. package/dist/manifest-auth-plan.d.ts +26 -25
  46. package/dist/manifest-auth-plan.d.ts.map +1 -1
  47. package/dist/manifest-auth-plan.js +315 -1163
  48. package/dist/manifest-auth-plan.js.map +4 -4
  49. package/dist/mfu-reassembler.js +24 -13
  50. package/dist/mfu-reassembler.js.map +3 -3
  51. package/dist/mmtp-container-parser.d.ts.map +1 -1
  52. package/dist/mmtp-container-parser.js +96 -22
  53. package/dist/mmtp-container-parser.js.map +3 -3
  54. package/dist/mmtp-container-parser.no-modules.js +1074 -314
  55. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  56. package/dist/mmtp-decode-pipeline.js +96 -22
  57. package/dist/mmtp-decode-pipeline.js.map +3 -3
  58. package/dist/mmtp-fec-session.d.ts +156 -0
  59. package/dist/mmtp-fec-session.d.ts.map +1 -0
  60. package/dist/mmtp-fec-session.js +522 -0
  61. package/dist/mmtp-fec-session.js.map +7 -0
  62. package/dist/mmtp-router.d.ts +42 -1
  63. package/dist/mmtp-router.d.ts.map +1 -1
  64. package/dist/mmtp-router.js +173 -22
  65. package/dist/mmtp-router.js.map +3 -3
  66. package/dist/multicast-auth-catalog.d.ts +86 -92
  67. package/dist/multicast-auth-catalog.d.ts.map +1 -1
  68. package/dist/multicast-auth-catalog.js +331 -124
  69. package/dist/multicast-auth-catalog.js.map +3 -3
  70. package/dist/multicast-input.d.ts +26 -4
  71. package/dist/multicast-input.d.ts.map +1 -1
  72. package/dist/multicast-input.js +286 -23
  73. package/dist/multicast-input.js.map +3 -3
  74. package/dist/multicast-manager.d.ts +89 -5
  75. package/dist/multicast-manager.d.ts.map +1 -1
  76. package/dist/multicast-manager.js +695 -354
  77. package/dist/multicast-manager.js.map +4 -4
  78. package/dist/multicast-transport.d.ts +6 -2
  79. package/dist/multicast-transport.d.ts.map +1 -1
  80. package/dist/multicast-transport.js +99 -234
  81. package/dist/multicast-transport.js.map +4 -4
  82. package/dist/multicast-unwrap.js +24 -13
  83. package/dist/multicast-unwrap.js.map +3 -3
  84. package/dist/no-modules.d.ts +2 -0
  85. package/dist/no-modules.d.ts.map +1 -1
  86. package/dist/no-modules.js +1025 -302
  87. package/dist/no-modules.js.map +4 -4
  88. package/dist/phase14-catalog-override.d.ts +1 -1
  89. package/dist/phase14-catalog-override.d.ts.map +1 -1
  90. package/dist/phase14-catalog-override.js +2 -2
  91. package/dist/phase14-catalog-override.js.map +2 -2
  92. package/dist/repair-fetch.d.ts +81 -6
  93. package/dist/repair-fetch.d.ts.map +1 -1
  94. package/dist/repair-fetch.js +159 -31
  95. package/dist/repair-fetch.js.map +3 -3
  96. package/dist/repair-layers.js +3 -0
  97. package/dist/repair-layers.js.map +3 -3
  98. package/dist/sample-combiner.d.ts +7 -1
  99. package/dist/sample-combiner.d.ts.map +1 -1
  100. package/dist/sample-combiner.js +14 -2
  101. package/dist/sample-combiner.js.map +2 -2
  102. package/dist/signaling.d.ts +2 -2
  103. package/dist/signaling.d.ts.map +1 -1
  104. package/dist/signaling.js +6 -3
  105. package/dist/signaling.js.map +3 -3
  106. package/dist/source-auth.js +22 -6
  107. package/dist/source-auth.js.map +2 -2
  108. package/dist/switching-set-alignment.d.ts +1 -1
  109. package/dist/switching-set-alignment.js.map +1 -1
  110. package/dist/timestamp-codec.js +24 -13
  111. package/dist/timestamp-codec.js.map +3 -3
  112. package/dist/wasm-mfu-reassembler.js +3 -0
  113. package/dist/wasm-mfu-reassembler.js.map +3 -3
  114. package/dist/wasm-mmtp-container-parser.js +96 -22
  115. package/dist/wasm-mmtp-container-parser.js.map +3 -3
  116. package/package.json +5 -5
  117. package/schemas/catalog.schema.json +117 -34
  118. package/src/align.ts +52 -21
  119. package/src/carp-catalog.ts +157 -55
  120. package/src/catalog-fec-params.ts +43 -19
  121. package/src/catalog-network-source.ts +1 -1
  122. package/src/catalog-validator.ts +4 -11
  123. package/src/fec-manager.ts +210 -63
  124. package/src/fec-state.ts +6 -10
  125. package/src/fec-worker-setup.ts +16 -1
  126. package/src/index.ts +26 -2
  127. package/src/iso-block-locator.ts +97 -6
  128. package/src/manifest-auth-plan.ts +39 -91
  129. package/src/mmtp-container-parser.ts +75 -7
  130. package/src/mmtp-fec-session.ts +514 -0
  131. package/src/mmtp-router.ts +146 -1
  132. package/src/multicast-auth-catalog.ts +131 -238
  133. package/src/multicast-input.ts +109 -54
  134. package/src/multicast-manager.ts +258 -21
  135. package/src/multicast-transport.ts +14 -3
  136. package/src/no-modules.ts +2 -0
  137. package/src/phase14-catalog-override.ts +3 -3
  138. package/src/repair-fetch.ts +283 -39
  139. package/src/sample-combiner.ts +15 -2
  140. package/src/signaling.ts +2 -2
  141. package/src/switching-set-alignment.ts +1 -1
  142. package/test-vectors/align.json +108 -32
  143. package/test-vectors/bc-provenance-v2.json +1526 -0
  144. package/test-vectors/catalog/README.md +67 -5
  145. package/test-vectors/catalog/negative/fec-iso-symbol-size-below-floor.json +28 -0
  146. package/test-vectors/catalog/negative/fec-reed-solomon-iso-symbol-size-13.json +28 -0
  147. package/test-vectors/catalog/negative/fec-repair-overlay-source-symbols-zero.json +43 -0
  148. package/test-vectors/catalog/negative/fec-repair-symbols-zero.json +28 -0
  149. package/test-vectors/catalog/negative/fec-source-symbols-zero.json +28 -0
  150. package/test-vectors/catalog/negative/fec-symbol-size-zero.json +28 -0
  151. package/test-vectors/catalog/negative/init-data-inline-without-data.json +22 -0
  152. package/test-vectors/catalog/negative/mmtp-mode-mpu.json +15 -0
  153. package/test-vectors/catalog/negative/multicast-amt-dns-without-relay.json +37 -0
  154. package/test-vectors/catalog/negative/multicast-auth-asm-missing-sender-address.json +77 -0
  155. package/test-vectors/catalog/negative/multicast-auth-duplicate-first-epoch.json +56 -0
  156. package/test-vectors/catalog/negative/multicast-auth-duplicate-kid.json +56 -0
  157. package/test-vectors/catalog/negative/multicast-auth-endpoint-auth-without-object-auth.json +38 -0
  158. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-auth.json +49 -0
  159. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-bandwidth.json +55 -0
  160. package/test-vectors/catalog/negative/multicast-auth-manifest-port-equals-port.json +56 -0
  161. package/test-vectors/catalog/negative/multicast-auth-manifest-timer-out-of-range.json +56 -0
  162. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-out-of-range.json +56 -0
  163. package/test-vectors/catalog/negative/multicast-auth-root-dotted-key.json +55 -0
  164. package/test-vectors/catalog/negative/multicast-auth-sender-address-on-ssm.json +57 -0
  165. package/test-vectors/catalog/negative/multicast-auth-version-1.json +56 -0
  166. package/test-vectors/catalog/negative/multicast-auth-version-3.json +56 -0
  167. package/test-vectors/catalog/negative/multicast-auth-version-missing.json +55 -0
  168. package/test-vectors/catalog/negative/multicast-endpoint-foreign-namespace-track.json +44 -0
  169. package/test-vectors/catalog/negative/multicast-endpoint-protocol-amt.json +38 -0
  170. package/test-vectors/catalog/negative/multicast-endpoint-protocol-atsc3.json +38 -0
  171. package/test-vectors/catalog/negative/presentation-anchor-unsafe.json +16 -0
  172. package/test-vectors/catalog/negative/raptorq-unaligned-symbol.json +1 -0
  173. package/test-vectors/catalog/positive/mmt01-12-1-init-ref-anchor.json +29 -0
  174. package/test-vectors/catalog/positive/multicast-amt-discovery-omitted.json +37 -0
  175. package/test-vectors/catalog/positive/multicast-amt-dns-relay.json +38 -0
  176. package/test-vectors/catalog/positive/multicast-amt-manual-relay.json +2 -2
  177. package/test-vectors/catalog/{negative/multicast-endpoint-missing-protocol-and-source.json → positive/multicast-asm-unprotected.json} +10 -5
  178. package/test-vectors/catalog/positive/multicast-auth-asm-sender.json +78 -0
  179. package/test-vectors/catalog/positive/multicast-auth-rotation.json +39 -38
  180. package/test-vectors/catalog/positive/multicast-draft01-4-1-example.json +81 -0
  181. package/test-vectors/catalog/positive/multicast-draft01-7-2-6-example.json +70 -0
  182. package/test-vectors/catalog/positive/presentation-anchor-negative.json +27 -0
  183. package/test-vectors/catalog/section-codes.json +59 -0
  184. package/test-vectors/catalog-multicast-auth-v1.json +38 -20
  185. package/test-vectors/catalog-validation.json +98 -2
  186. package/test-vectors/catalog-validator-public-api.mjs +14 -9
  187. package/test-vectors/generate-bc-provenance-v2.mjs +252 -0
@@ -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);
@@ -949,6 +957,322 @@ function isoBlocksBehindLowerBound(a, b, kMax) {
949
957
  return serial32Precedes(a, b) ? Math.floor(serial32Distance(a, b) / kMax) : 0;
950
958
  }
951
959
 
960
+ // ../mmt-base/dist/catalog-fec-source.js
961
+ var ALL_ROLES = Object.freeze(["video", "audio"]);
962
+ function recordOf(value) {
963
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
964
+ }
965
+ function locateCatalogFecSource(catalog, source, roles = ALL_ROLES) {
966
+ const root = recordOf(catalog);
967
+ if (root === void 0)
968
+ return void 0;
969
+ for (const role of roles) {
970
+ const renditions = recordOf(recordOf(root[role])?.["renditions"]);
971
+ if (renditions === void 0 || !Object.hasOwn(renditions, source))
972
+ continue;
973
+ const entry2 = recordOf(renditions[source]);
974
+ if (entry2 === void 0)
975
+ continue;
976
+ return Object.freeze({
977
+ dialect: "hang",
978
+ role,
979
+ entry: entry2,
980
+ fec: entry2["fec"],
981
+ fecPath: `$.${role}.renditions[${JSON.stringify(source)}].fec`
982
+ });
983
+ }
984
+ const tracks = root["tracks"];
985
+ if (!Array.isArray(tracks))
986
+ return void 0;
987
+ const index = tracks.findIndex((track) => recordOf(track)?.["name"] === source);
988
+ if (index < 0)
989
+ return void 0;
990
+ const entry = recordOf(tracks[index]) ?? {};
991
+ return Object.freeze({
992
+ dialect: "msf",
993
+ index,
994
+ entry,
995
+ fec: entry["fec"],
996
+ fecPath: `$.tracks[${index}].fec`
997
+ });
998
+ }
999
+ function isoBlockSpanUsable(fec) {
1000
+ const block = recordOf(fec);
1001
+ if (block === void 0 || block["blockProfile"] !== "iso-ssbg1-v1")
1002
+ return true;
1003
+ const ms = block["interleaveDepthMs"];
1004
+ return ms === void 0 || typeof ms === "number" && Number.isSafeInteger(ms) && ms >= 0;
1005
+ }
1006
+ function catalogFecAvailable(fec) {
1007
+ const block = recordOf(fec);
1008
+ if (block === void 0)
1009
+ return true;
1010
+ const declaresFecInstance = block["algorithm"] !== "none";
1011
+ const profile = block["blockProfile"];
1012
+ const profileOk = isFecBlockProfile(profile) || profile === void 0 && !declaresFecInstance;
1013
+ return profileOk && (!declaresFecInstance || isoBlockSpanUsable(block));
1014
+ }
1015
+ function isPositiveSafeInteger(value) {
1016
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
1017
+ }
1018
+ var ISO_SSBG1_MIN_SYMBOL_SIZE = 14;
1019
+ function catalogFecDeclaresUnconfigurableInstance(fec) {
1020
+ const block = recordOf(fec);
1021
+ if (block === void 0 || block["algorithm"] === "none")
1022
+ return false;
1023
+ if (!(isPositiveSafeInteger(block["sourceSymbols"]) && isPositiveSafeInteger(block["symbolSize"])))
1024
+ return true;
1025
+ return block["blockProfile"] === "iso-ssbg1-v1" && block["symbolSize"] < ISO_SSBG1_MIN_SYMBOL_SIZE;
1026
+ }
1027
+
1028
+ // ../mmt-base/dist/multicast-catalog.js
1029
+ var ED25519_PUBLIC_KEY_BASE64URL = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;
1030
+ var UINT32_MAX = 4294967295;
1031
+ var AUTH_MEMBERS = /* @__PURE__ */ new Set(["scheme", "version", "sig", "keys", "minEpoch"]);
1032
+ var KEY_MEMBERS = /* @__PURE__ */ new Set(["kid", "publicKey", "firstEpoch"]);
1033
+ var ENDPOINT_AUTH_MEMBERS = /* @__PURE__ */ new Set([
1034
+ "manifestPort",
1035
+ "streamId",
1036
+ "senderAddress",
1037
+ "maxAuthDelayMs",
1038
+ "manifestTimerMs",
1039
+ "manifestTrack"
1040
+ ]);
1041
+ function isObject(value) {
1042
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1043
+ }
1044
+ function isNonEmptyString(value) {
1045
+ return typeof value === "string" && value.trim().length > 0;
1046
+ }
1047
+ function isIntegerIn(value, min, max) {
1048
+ return Number.isSafeInteger(value) && value >= min && value <= max;
1049
+ }
1050
+ function multicastEndpointSource(endpoint) {
1051
+ if (!isObject(endpoint))
1052
+ return void 0;
1053
+ const sourceAddress = endpoint["sourceAddress"];
1054
+ if (sourceAddress !== void 0 && !isNonEmptyString(sourceAddress))
1055
+ return void 0;
1056
+ const mode = sourceAddress === void 0 ? "asm" : "ssm";
1057
+ const protocol = endpoint["protocol"];
1058
+ if (protocol !== void 0 && protocol !== mode)
1059
+ return void 0;
1060
+ const auth = endpoint["auth"];
1061
+ const senderAddress = isObject(auth) ? auth["senderAddress"] : void 0;
1062
+ if (mode === "ssm")
1063
+ return senderAddress === void 0 ? { mode, source: sourceAddress } : void 0;
1064
+ if (auth === void 0)
1065
+ return { mode };
1066
+ return isNonEmptyString(senderAddress) ? { mode, source: senderAddress } : void 0;
1067
+ }
1068
+ function authIssues(auth) {
1069
+ const base = "$.multicast.auth";
1070
+ const issue = (path, message) => [
1071
+ { code: "multicast_auth", path: `${base}${path}`, message }
1072
+ ];
1073
+ if (!isObject(auth))
1074
+ return issue("", "auth must be an object");
1075
+ const unknown = Object.keys(auth).filter((key) => !AUTH_MEMBERS.has(key));
1076
+ if (unknown.length > 0) {
1077
+ return issue("", `auth has unknown member(s) ${unknown.join(", ")}; draft -01 7.2.6 defines scheme, version, sig, keys and minEpoch`);
1078
+ }
1079
+ if (auth["scheme"] !== "bc-provenance")
1080
+ return issue(".scheme", 'scheme must be "bc-provenance"');
1081
+ if (auth["version"] !== 2)
1082
+ return issue(".version", "version must be 2 (bc-provenance version 2, draft -01 7.2)");
1083
+ if (auth["sig"] !== "ed25519")
1084
+ return issue(".sig", 'sig must be "ed25519"');
1085
+ const keys = auth["keys"];
1086
+ if (!Array.isArray(keys) || keys.length < 1 || keys.length > 4) {
1087
+ return issue(".keys", "keys must be an array of one to four {kid, publicKey, firstEpoch} objects");
1088
+ }
1089
+ const kids = /* @__PURE__ */ new Set();
1090
+ const firstEpochs = /* @__PURE__ */ new Set();
1091
+ for (let index = 0; index < keys.length; index++) {
1092
+ const key = keys[index];
1093
+ const at = `.keys[${index}]`;
1094
+ if (!isObject(key) || Object.keys(key).some((member) => !KEY_MEMBERS.has(member))) {
1095
+ return issue(at, "a key is exactly {kid, publicKey, firstEpoch}");
1096
+ }
1097
+ if (!isIntegerIn(key["kid"], 0, UINT32_MAX))
1098
+ return issue(`${at}.kid`, "kid must be an unsigned 32-bit integer");
1099
+ if (typeof key["publicKey"] !== "string" || !ED25519_PUBLIC_KEY_BASE64URL.test(key["publicKey"])) {
1100
+ return issue(`${at}.publicKey`, "publicKey must be a 32-octet Ed25519 key in canonical unpadded base64url");
1101
+ }
1102
+ if (!isIntegerIn(key["firstEpoch"], 0, UINT32_MAX)) {
1103
+ return issue(`${at}.firstEpoch`, "firstEpoch must be an unsigned 32-bit integer");
1104
+ }
1105
+ if (kids.has(key["kid"]))
1106
+ return issue(`${at}.kid`, `kid ${key["kid"]} is repeated; the catalog holds no key set`);
1107
+ if (firstEpochs.has(key["firstEpoch"])) {
1108
+ return issue(`${at}.firstEpoch`, `firstEpoch ${key["firstEpoch"]} is repeated; the catalog holds no key set`);
1109
+ }
1110
+ kids.add(key["kid"]);
1111
+ firstEpochs.add(key["firstEpoch"]);
1112
+ }
1113
+ if (!isIntegerIn(auth["minEpoch"], 0, UINT32_MAX)) {
1114
+ return issue(".minEpoch", "minEpoch must be an unsigned 32-bit integer");
1115
+ }
1116
+ return [];
1117
+ }
1118
+ function endpointAuthIssue(endpoint, mode, at) {
1119
+ const auth = endpoint["auth"];
1120
+ if (!isObject(auth))
1121
+ return { path: `${at}.auth`, message: "auth must be an object" };
1122
+ const unknown = Object.keys(auth).filter((key) => !ENDPOINT_AUTH_MEMBERS.has(key));
1123
+ if (unknown.length > 0)
1124
+ return { path: `${at}.auth`, message: `auth has unknown member(s) ${unknown.join(", ")}` };
1125
+ if (!isIntegerIn(auth["manifestPort"], 1, 65535)) {
1126
+ return { path: `${at}.auth.manifestPort`, message: "manifestPort must be an integer from 1 to 65535" };
1127
+ }
1128
+ if (!isIntegerIn(auth["streamId"], 0, UINT32_MAX)) {
1129
+ return { path: `${at}.auth.streamId`, message: "streamId must be an unsigned 32-bit integer" };
1130
+ }
1131
+ if (mode === "ssm" && auth["senderAddress"] !== void 0) {
1132
+ return { path: `${at}.auth.senderAddress`, message: "senderAddress must not appear on an SSM endpoint; S is sourceAddress" };
1133
+ }
1134
+ if (mode === "asm" && !isNonEmptyString(auth["senderAddress"])) {
1135
+ return { path: `${at}.auth.senderAddress`, message: "a protected ASM endpoint requires senderAddress" };
1136
+ }
1137
+ if (auth["maxAuthDelayMs"] !== void 0 && !isIntegerIn(auth["maxAuthDelayMs"], 50, 1e3)) {
1138
+ return { path: `${at}.auth.maxAuthDelayMs`, message: "maxAuthDelayMs must be an integer from 50 to 1000" };
1139
+ }
1140
+ if (auth["manifestTimerMs"] !== void 0 && !isIntegerIn(auth["manifestTimerMs"], 1, Number.MAX_SAFE_INTEGER)) {
1141
+ return { path: `${at}.auth.manifestTimerMs`, message: "manifestTimerMs must be an integer of at least 1" };
1142
+ }
1143
+ if (auth["manifestTrack"] !== void 0 && !isNonEmptyString(auth["manifestTrack"])) {
1144
+ return { path: `${at}.auth.manifestTrack`, message: "manifestTrack must be a non-empty string" };
1145
+ }
1146
+ if (!isIntegerIn(endpoint["bandwidth"], 1, Number.MAX_SAFE_INTEGER)) {
1147
+ return { path: `${at}.bandwidth`, message: "a protected endpoint requires bandwidth, which bounds the receiver's hold queues" };
1148
+ }
1149
+ return void 0;
1150
+ }
1151
+ var CATALOG_NAMESPACE = /* @__PURE__ */ Symbol.for("@blockcast/mmt-base/catalogNamespace");
1152
+ function multicastCatalogIssues(catalog, options = {}) {
1153
+ if (!isObject(catalog))
1154
+ return [];
1155
+ const issues = [];
1156
+ if ("multicast.auth" in catalog) {
1157
+ issues.push({
1158
+ code: "multicast_auth",
1159
+ path: '$["multicast.auth"]',
1160
+ message: 'the root "multicast.auth" key is retired; declare auth as multicast.auth (draft -01 7.2.6)'
1161
+ });
1162
+ }
1163
+ const multicast = catalog["multicast"];
1164
+ if (!isObject(multicast))
1165
+ return issues;
1166
+ const protectedCatalog = multicast["auth"] !== void 0;
1167
+ if (protectedCatalog)
1168
+ issues.push(...authIssues(multicast["auth"]));
1169
+ const endpoints = multicast["endpoints"];
1170
+ if (!Array.isArray(endpoints))
1171
+ return issues;
1172
+ const tracks = Array.isArray(catalog["tracks"]) ? catalog["tracks"] : [];
1173
+ const namespaceOf = /* @__PURE__ */ new Map();
1174
+ for (const track of tracks) {
1175
+ if (isObject(track) && typeof track["name"] === "string")
1176
+ namespaceOf.set(track["name"], track["namespace"]);
1177
+ }
1178
+ const tagged = catalog[CATALOG_NAMESPACE];
1179
+ let referenceNamespace = options.catalogNamespace ?? (typeof tagged === "string" ? tagged : void 0);
1180
+ const sources = [];
1181
+ for (let index = 0; index < endpoints.length; index++) {
1182
+ const endpoint = endpoints[index];
1183
+ const at = `$.multicast.endpoints[${index}]`;
1184
+ const fail = (code, path, message) => {
1185
+ issues.push({ code, path, message, endpointIndex: index });
1186
+ };
1187
+ sources.push(void 0);
1188
+ if (!isObject(endpoint)) {
1189
+ fail("multicast_endpoint", at, "endpoint must be an object");
1190
+ continue;
1191
+ }
1192
+ const protocol = endpoint["protocol"];
1193
+ if (protocol !== void 0 && protocol !== "ssm" && protocol !== "asm") {
1194
+ 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)`);
1195
+ continue;
1196
+ }
1197
+ const hasAuth = endpoint["auth"] !== void 0;
1198
+ if (protectedCatalog !== hasAuth) {
1199
+ 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");
1200
+ continue;
1201
+ }
1202
+ const sourceAddress = endpoint["sourceAddress"];
1203
+ if (sourceAddress !== void 0 && !isNonEmptyString(sourceAddress)) {
1204
+ fail("multicast_endpoint", `${at}.sourceAddress`, "sourceAddress must be a non-empty string");
1205
+ continue;
1206
+ }
1207
+ const mode = sourceAddress === void 0 ? "asm" : "ssm";
1208
+ if (protocol !== void 0 && protocol !== mode) {
1209
+ fail("multicast_endpoint", `${at}.protocol`, `protocol ${JSON.stringify(protocol)} disagrees with sourceAddress, which selects ${mode}`);
1210
+ continue;
1211
+ }
1212
+ if (!isIntegerIn(endpoint["port"], 1, 65535)) {
1213
+ fail("multicast_endpoint", `${at}.port`, "port must be an integer from 1 to 65535");
1214
+ continue;
1215
+ }
1216
+ if (hasAuth) {
1217
+ const authIssue = endpointAuthIssue(endpoint, mode, at);
1218
+ if (authIssue) {
1219
+ fail("multicast_endpoint_auth", authIssue.path, authIssue.message);
1220
+ continue;
1221
+ }
1222
+ }
1223
+ sources[index] = multicastEndpointSource(endpoint);
1224
+ const refs = Array.isArray(endpoint["tracks"]) ? endpoint["tracks"] : [];
1225
+ for (let refIndex = 0; refIndex < refs.length; refIndex++) {
1226
+ const ref = refs[refIndex];
1227
+ const name = isObject(ref) ? ref["name"] : ref;
1228
+ if (typeof name !== "string")
1229
+ continue;
1230
+ const namespace = namespaceOf.get(name);
1231
+ if (typeof namespace !== "string")
1232
+ continue;
1233
+ referenceNamespace ??= namespace;
1234
+ if (namespace !== referenceNamespace) {
1235
+ fail("multicast_track", `${at}.tracks[${refIndex}].name`, `track ${JSON.stringify(name)} declares namespace ${JSON.stringify(namespace)}, not the catalog track's ${JSON.stringify(referenceNamespace)}`);
1236
+ }
1237
+ }
1238
+ }
1239
+ const tupleOf = (index) => {
1240
+ const endpoint = endpoints[index];
1241
+ const auth = endpoint["auth"];
1242
+ return {
1243
+ sg: JSON.stringify([sources[index].source ?? null, endpoint["groupAddress"]]),
1244
+ port: endpoint["port"],
1245
+ manifestPort: isObject(auth) ? auth["manifestPort"] : void 0
1246
+ };
1247
+ };
1248
+ for (let index = 0; index < endpoints.length; index++) {
1249
+ if (!sources[index])
1250
+ continue;
1251
+ const own = tupleOf(index);
1252
+ const at = `$.multicast.endpoints[${index}]`;
1253
+ if (own.manifestPort !== void 0 && own.manifestPort === own.port) {
1254
+ issues.push({ code: "multicast_endpoint_auth", path: `${at}.auth.manifestPort`, message: "manifestPort must differ from the endpoint's own port", endpointIndex: index });
1255
+ continue;
1256
+ }
1257
+ for (let other = 0; other < endpoints.length; other++) {
1258
+ if (other === index || !sources[other])
1259
+ continue;
1260
+ const peer = tupleOf(other);
1261
+ if (peer.sg !== own.sg)
1262
+ continue;
1263
+ if (peer.port === own.port) {
1264
+ 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 });
1265
+ break;
1266
+ }
1267
+ if (own.manifestPort !== void 0 && (own.manifestPort === peer.port || own.manifestPort === peer.manifestPort)) {
1268
+ 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 });
1269
+ break;
1270
+ }
1271
+ }
1272
+ }
1273
+ return issues;
1274
+ }
1275
+
952
1276
  // src/mfu-reassembler.ts
953
1277
  function fragmentProvenance(fragment) {
954
1278
  if (fragment.deliveryProvenance !== void 0) return fragment.deliveryProvenance;
@@ -3821,8 +4145,14 @@ var SampleCombiner = class {
3821
4145
  /**
3822
4146
  * Add one reassembled data unit. Returns the combined sample once every
3823
4147
  * constituent data unit has arrived and totals the authored size.
4148
+ *
4149
+ * `sampleSize` is the authored size the host resolves for the sample as the
4150
+ * data unit completes. It stands in only when no size was registered, which
4151
+ * happens when the data unit's FI=0/FI=1 reached the reassembler without the
4152
+ * host's own FT=2 parse: an FEC-recovered first fragment completed by source
4153
+ * fragments, or one decoded before its source copy arrived.
3824
4154
  */
3825
- addMfu(mfu) {
4155
+ addMfu(mfu, sampleSize) {
3826
4156
  if (mfu.movieFragmentSequenceNumber === void 0 || mfu.sampleNumber === void 0) {
3827
4157
  this.#stats.passthroughSamples++;
3828
4158
  return fromPassthrough(mfu);
@@ -3838,7 +4168,7 @@ var SampleCombiner = class {
3838
4168
  return null;
3839
4169
  }
3840
4170
  const dataLen = mfu.data.byteLength;
3841
- const authoredSize = this.#authoredSizes.get(key);
4171
+ const authoredSize = this.#authoredSizes.get(key) ?? sampleSize;
3842
4172
  if (offset === 0 && !this.#pending.has(key)) {
3843
4173
  const passesThrough = authoredSize === void 0 ? !this.#requireAuthoredSize : dataLen === authoredSize;
3844
4174
  if (passesThrough) {
@@ -4132,6 +4462,12 @@ if (void 0) {
4132
4462
  const out = c.addMfu(mfu(1, 9, 17, 5, [6, 7, 8, 9, 10], 1001n, false));
4133
4463
  expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
4134
4464
  });
4465
+ test("a size handed with the data unit completes a sample no head registered", () => {
4466
+ const c = combiner({ requireAuthoredSize: true });
4467
+ const out = c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5);
4468
+ expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5]));
4469
+ expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5)).toBeNull();
4470
+ });
4135
4471
  test("duplicate offset is rejected", () => {
4136
4472
  const c = combiner();
4137
4473
  c.registerAuthoredSize(void 0, 1, 9, 17, 10);
@@ -5938,197 +6274,6 @@ if (void 0) {
5938
6274
  });
5939
6275
  }
5940
6276
 
5941
- // src/multicast-auth-catalog.ts
5942
- var RAW_ED25519_KEY_LENGTH = 32;
5943
- var SOURCE_AUTH_SCOPE_LENGTH = 32;
5944
- var BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
5945
- function encodeBase64Url(bytes) {
5946
- let output = "";
5947
- for (let i = 0; i < bytes.length; i += 3) {
5948
- const b0 = bytes[i];
5949
- const b1 = bytes[i + 1];
5950
- const b2 = bytes[i + 2];
5951
- output += BASE64URL_ALPHABET[b0 >> 2];
5952
- output += BASE64URL_ALPHABET[(b0 & 3) << 4 | (b1 === void 0 ? 0 : b1 >> 4)];
5953
- if (b1 === void 0) break;
5954
- output += BASE64URL_ALPHABET[(b1 & 15) << 2 | (b2 === void 0 ? 0 : b2 >> 6)];
5955
- if (b2 === void 0) break;
5956
- output += BASE64URL_ALPHABET[b2 & 63];
5957
- }
5958
- return output;
5959
- }
5960
- var BASE64URL_DECODE_TABLE = (() => {
5961
- const table = new Int8Array(128).fill(-1);
5962
- for (let i = 0; i < BASE64URL_ALPHABET.length; i++) {
5963
- table[BASE64URL_ALPHABET.charCodeAt(i)] = i;
5964
- }
5965
- return table;
5966
- })();
5967
- function decodeBase64Url(text) {
5968
- if (text.length % 4 === 1) {
5969
- throw new Error(`[multicast-auth-catalog] invalid unpadded base64url length for "${text}"`);
5970
- }
5971
- const bytes = [];
5972
- let buffer = 0;
5973
- let bits = 0;
5974
- for (let i = 0; i < text.length; i++) {
5975
- const code = text.charCodeAt(i);
5976
- const value = code < 128 ? BASE64URL_DECODE_TABLE[code] : -1;
5977
- if (value === void 0 || value < 0) {
5978
- throw new Error(`[multicast-auth-catalog] invalid base64url character in "${text}"`);
5979
- }
5980
- buffer = buffer << 6 | value;
5981
- bits += 6;
5982
- if (bits >= 8) {
5983
- bits -= 8;
5984
- bytes.push(buffer >> bits & 255);
5985
- }
5986
- }
5987
- const decoded = Uint8Array.from(bytes);
5988
- if (encodeBase64Url(decoded) !== text) {
5989
- throw new Error(`[multicast-auth-catalog] non-canonical base64url encoding "${text}"`);
5990
- }
5991
- return decoded;
5992
- }
5993
- function decodeAuthScope(authScope) {
5994
- const bytes = decodeBase64Url(authScope);
5995
- if (bytes.byteLength !== SOURCE_AUTH_SCOPE_LENGTH) {
5996
- throw new Error(
5997
- `[multicast-auth-catalog] authScope must decode to ${SOURCE_AUTH_SCOPE_LENGTH} raw bytes, got ${bytes.byteLength}`
5998
- );
5999
- }
6000
- return bytes;
6001
- }
6002
- function decodeEd25519PublicKey(publicKey) {
6003
- const bytes = decodeBase64Url(publicKey);
6004
- if (bytes.byteLength !== RAW_ED25519_KEY_LENGTH) {
6005
- throw new Error(
6006
- `[multicast-auth-catalog] public key must decode to ${RAW_ED25519_KEY_LENGTH} raw bytes, got ${bytes.byteLength}`
6007
- );
6008
- }
6009
- return bytes;
6010
- }
6011
- function isNonEmptyString(value) {
6012
- return typeof value === "string" && value.length > 0;
6013
- }
6014
- function isValidAuthScopeField(value) {
6015
- if (!isNonEmptyString(value)) return false;
6016
- try {
6017
- decodeAuthScope(value);
6018
- return true;
6019
- } catch {
6020
- return false;
6021
- }
6022
- }
6023
- function isValidPublicKeyField(value) {
6024
- if (!isNonEmptyString(value)) return false;
6025
- try {
6026
- decodeEd25519PublicKey(value);
6027
- return true;
6028
- } catch {
6029
- return false;
6030
- }
6031
- }
6032
- function hasOnlyKeys(object2, allowed) {
6033
- const allowedKeys = new Set(allowed);
6034
- return Object.keys(object2).every((key) => allowedKeys.has(key));
6035
- }
6036
- function isMulticastAuthTrackConfig(obj) {
6037
- if (typeof obj !== "object" || obj === null) return false;
6038
- const o = obj;
6039
- return hasOnlyKeys(o, ["mediaTrack", "manifestTrack", "authScope", "sourceSymbolFormat"]) && isNonEmptyString(o["mediaTrack"]) && isNonEmptyString(o["manifestTrack"]) && o["mediaTrack"] !== o["manifestTrack"] && isValidAuthScopeField(o["authScope"]) && isNonEmptyString(o["sourceSymbolFormat"]);
6040
- }
6041
- var VALID_COMPACTION = /* @__PURE__ */ new Set(["merkle", "none"]);
6042
- var VALID_ENFORCEMENT = /* @__PURE__ */ new Set(["shadow", "enforce"]);
6043
- function hasUniqueMulticastAuthTrackBindings(tracks) {
6044
- const bindings = tracks.flatMap((track) => {
6045
- if (typeof track !== "object" || track === null) return [];
6046
- const value = track;
6047
- if (typeof value["mediaTrack"] !== "string" || typeof value["sourceSymbolFormat"] !== "string") {
6048
- return [];
6049
- }
6050
- return [JSON.stringify([value["mediaTrack"], value["sourceSymbolFormat"]])];
6051
- });
6052
- return new Set(bindings).size === bindings.length;
6053
- }
6054
- function isMulticastAuthConfig(obj) {
6055
- if (typeof obj !== "object" || obj === null) return false;
6056
- const o = obj;
6057
- if (o["scheme"] !== "bc-provenance") return false;
6058
- if (o["hash"] !== "blake3") return false;
6059
- if (o["sig"] !== "ed25519") return false;
6060
- if (!hasOnlyKeys(o, ["scheme", "hash", "sig", "publicKey", "keyId", "previousKey", "compaction", "enforcement", "tracks"])) return false;
6061
- if (!isValidPublicKeyField(o["publicKey"])) return false;
6062
- if (!isNonEmptyString(o["keyId"])) return false;
6063
- if (o["previousKey"] !== void 0 && !isValidPublicKeyField(o["previousKey"])) return false;
6064
- if (o["previousKey"] === o["publicKey"]) return false;
6065
- if (typeof o["compaction"] !== "string" || !VALID_COMPACTION.has(o["compaction"])) return false;
6066
- if (o["enforcement"] !== void 0) {
6067
- if (typeof o["enforcement"] !== "string" || !VALID_ENFORCEMENT.has(o["enforcement"])) return false;
6068
- }
6069
- if (!Array.isArray(o["tracks"]) || o["tracks"].length === 0) return false;
6070
- const tracks = o["tracks"];
6071
- if (!tracks.every((t) => isMulticastAuthTrackConfig(t))) return false;
6072
- const typedTracks = tracks;
6073
- const scopes = typedTracks.map((t) => t.authScope);
6074
- if (new Set(scopes).size !== scopes.length) return false;
6075
- if (!hasUniqueMulticastAuthTrackBindings(typedTracks)) return false;
6076
- const manifestTracks = typedTracks.map((t) => t.manifestTrack);
6077
- if (new Set(manifestTracks).size !== manifestTracks.length) return false;
6078
- return true;
6079
- }
6080
- function resolveMulticastAuthMode(playerMode, auth) {
6081
- if (playerMode !== void 0) return playerMode;
6082
- if (auth === void 0) return "off";
6083
- return auth.enforcement ?? "shadow";
6084
- }
6085
- function resolveMulticastAuthCatalog(catalog, playerMode) {
6086
- if (typeof catalog !== "object" || catalog === null || Array.isArray(catalog)) {
6087
- throw new Error("[multicast-auth-catalog] catalog must be an object");
6088
- }
6089
- const root = catalog;
6090
- const rawAuth = root["multicast.auth"];
6091
- if (rawAuth === void 0) {
6092
- if (playerMode === "enforce") {
6093
- throw new Error("[multicast-auth-catalog] player enforce mode requires multicast.auth");
6094
- }
6095
- return void 0;
6096
- }
6097
- if (!isMulticastAuthConfig(rawAuth)) {
6098
- throw new Error("[multicast-auth-catalog] invalid multicast.auth v2 block");
6099
- }
6100
- const rawTracks = root["tracks"];
6101
- if (!Array.isArray(rawTracks)) {
6102
- throw new Error("[multicast-auth-catalog] catalog tracks must be an array");
6103
- }
6104
- const catalogTrackNames = new Set(
6105
- rawTracks.flatMap(
6106
- (track) => typeof track === "object" && track !== null && typeof track["name"] === "string" ? [track["name"]] : []
6107
- )
6108
- );
6109
- for (const track of rawAuth.tracks) {
6110
- if (!catalogTrackNames.has(track.mediaTrack)) {
6111
- throw new Error(`[multicast-auth-catalog] unknown mediaTrack "${track.mediaTrack}"`);
6112
- }
6113
- if (!catalogTrackNames.has(track.manifestTrack)) {
6114
- throw new Error(`[multicast-auth-catalog] unknown manifestTrack "${track.manifestTrack}"`);
6115
- }
6116
- }
6117
- return {
6118
- keyId: rawAuth.keyId,
6119
- acceptedPublicKeys: [
6120
- decodeEd25519PublicKey(rawAuth.publicKey),
6121
- ...rawAuth.previousKey === void 0 ? [] : [decodeEd25519PublicKey(rawAuth.previousKey)]
6122
- ],
6123
- mode: resolveMulticastAuthMode(playerMode, rawAuth),
6124
- compaction: rawAuth.compaction,
6125
- tracks: rawAuth.tracks.map((track) => ({
6126
- ...track,
6127
- authScope: decodeAuthScope(track.authScope)
6128
- }))
6129
- };
6130
- }
6131
-
6132
6277
  // src/repair-layers.ts
6133
6278
  var REPAIR_PRIORITY_MIN = 192;
6134
6279
  var REPAIR_PRIORITY_MAX = 255;
@@ -6487,8 +6632,7 @@ function isMulticastTrackObject(obj) {
6487
6632
  function isMulticastEndpoint(obj) {
6488
6633
  if (typeof obj !== "object" || obj === null) return false;
6489
6634
  const o = obj;
6490
- const protocol = o["protocol"] ?? (typeof o["sourceAddress"] === "string" && o["sourceAddress"].length > 0 ? "ssm" : void 0);
6491
- 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));
6635
+ 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));
6492
6636
  }
6493
6637
  function isMulticastCatalogConfig(obj) {
6494
6638
  if (typeof obj !== "object" || obj === null) return false;
@@ -6592,7 +6736,7 @@ var CmsfCatalogValidationError = class extends Error {
6592
6736
  function catalogError(code, path, message) {
6593
6737
  throw new CmsfCatalogValidationError(code, path, message);
6594
6738
  }
6595
- function validateCmsfMmtpCatalog(value) {
6739
+ function validateCmsfMmtpCatalog(value, options = {}) {
6596
6740
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
6597
6741
  catalogError("catalog_object", "$", "catalog must be an object");
6598
6742
  }
@@ -6613,6 +6757,22 @@ function validateCmsfMmtpCatalog(value) {
6613
6757
  "commonTrackFields is retired; every track carries its own fields"
6614
6758
  );
6615
6759
  }
6760
+ const initDataList = catalog["initDataList"];
6761
+ if (initDataList !== void 0) {
6762
+ if (!Array.isArray(initDataList)) {
6763
+ catalogError("catalog_init_data_list", "$.initDataList", "initDataList must be an array");
6764
+ }
6765
+ initDataList.forEach((entry, i) => {
6766
+ const e = entry;
6767
+ const entryPath = `$.initDataList[${i}]`;
6768
+ 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) {
6769
+ catalogError("catalog_init_data_list", entryPath, "entry needs a non-empty string id and type");
6770
+ }
6771
+ if (e["type"] === "inline" && (typeof e["data"] !== "string" || e["data"].length === 0)) {
6772
+ catalogError("catalog_init_data_list", `${entryPath}.data`, 'an "inline" entry needs non-empty data');
6773
+ }
6774
+ });
6775
+ }
6616
6776
  const tracks = catalog["tracks"];
6617
6777
  const trackRecords = [];
6618
6778
  const positiveInteger3 = (input) => Number.isSafeInteger(input) && input > 0;
@@ -6664,6 +6824,14 @@ function validateCmsfMmtpCatalog(value) {
6664
6824
  if (keyframeIntervalMs !== void 0 && !positiveNumber2(keyframeIntervalMs) || keyframeIntervalTicks !== void 0 && !positiveInteger3(keyframeIntervalTicks)) {
6665
6825
  catalogError("track_keyframe_interval", path, "keyframe interval fields must be positive numbers");
6666
6826
  }
6827
+ const anchor = track["presentationAnchorTicks"];
6828
+ if (anchor !== void 0 && !Number.isSafeInteger(anchor)) {
6829
+ catalogError("track_presentation_anchor", `${path}.presentationAnchorTicks`, "must be a safe integer");
6830
+ }
6831
+ const initRef = track["initRef"];
6832
+ if (initRef !== void 0 && (typeof initRef !== "string" || initRef.length === 0)) {
6833
+ catalogError("track_init_ref", `${path}.initRef`, "must be a non-empty string");
6834
+ }
6667
6835
  if (packaging === "fec-repair") {
6668
6836
  rejectRepairTrackGeometry(path, track, catalogError);
6669
6837
  validateRepairTrackFields(describeRepairTrack(name, path, track), catalogError);
@@ -6671,9 +6839,8 @@ function validateCmsfMmtpCatalog(value) {
6671
6839
  rejectRepairFieldsOnMediaTrack(path, track, catalogError);
6672
6840
  }
6673
6841
  if (packaging === "mmtp") {
6674
- const mmtpMode = track["mmtpMode"];
6675
- if (mmtpMode !== "mpu" && mmtpMode !== "mfu") {
6676
- catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mpu or mfu");
6842
+ if (track["mmtpMode"] !== "mfu") {
6843
+ catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mfu");
6677
6844
  }
6678
6845
  if (!positiveInteger3(timescale)) {
6679
6846
  catalogError("track_timescale", `${path}.timescale`, "must be a positive integer");
@@ -6718,11 +6885,17 @@ function validateCmsfMmtpCatalog(value) {
6718
6885
  catalogError("track_fec", `${path}.fec.${field}`, "must be a positive integer");
6719
6886
  }
6720
6887
  }
6888
+ if (algorithm === "raptorq" && config["symbolSize"] % 8 !== 0) {
6889
+ catalogError("track_fec", `${path}.fec.symbolSize`, "RaptorQ symbolSize must be a multiple of 8");
6890
+ }
6721
6891
  if (typeof config["repairTrack"] !== "string" || config["repairTrack"].length === 0) {
6722
6892
  catalogError("track_fec", `${path}.fec.repairTrack`, "must be a non-empty string");
6723
6893
  }
6724
6894
  }
6725
6895
  readFecBlockProfile(config["blockProfile"], `${path}.fec.blockProfile`, algorithm !== "none", catalogError);
6896
+ if (algorithm !== "none" && config["symbolSize"] < ISO_SSBG1_MIN_SYMBOL_SIZE) {
6897
+ catalogError("track_fec", `${path}.fec.symbolSize`, "iso-ssbg1-v1 symbolSize must be at least 14");
6898
+ }
6726
6899
  }
6727
6900
  }
6728
6901
  const repairDescriptors = trackRecords.flatMap(
@@ -6772,11 +6945,21 @@ function validateCmsfMmtpCatalog(value) {
6772
6945
  const timescale = BigInt(track["timescale"]);
6773
6946
  const durationTicks = track["groupDurationTicks"];
6774
6947
  const ticks = durationTicks !== void 0 ? BigInt(durationTicks) : BigInt(track["groupDurationMs"]) * timescale / 1000n;
6775
- const anchor = switchingSets.get(altGroup);
6776
- if (anchor && ticks * anchor.timescale !== anchor.ticks * timescale) {
6777
- catalogError("track_switching_set", `$.tracks[${index}]`, `group duration does not match ${JSON.stringify(anchor.name)} in altGroup ${altGroup}`);
6948
+ const framerate = track["framerate"];
6949
+ const intraOnly = positiveNumber2(framerate) && Math.abs(Number(ticks) * framerate - Number(timescale)) <= Number(timescale) * 1e-3;
6950
+ const members = switchingSets.get(altGroup) ?? [];
6951
+ members.push({ index, name: track["name"], ticks, timescale, intraOnly });
6952
+ switchingSets.set(altGroup, members);
6953
+ }
6954
+ for (const [altGroup, members] of switchingSets) {
6955
+ const anchor = members.find((member) => !member.intraOnly) ?? members[0];
6956
+ for (const member of members) {
6957
+ if (member === anchor || member.ticks * anchor.timescale === anchor.ticks * member.timescale) continue;
6958
+ const nests = member.intraOnly && !anchor.intraOnly && anchor.ticks * member.timescale % (member.ticks * anchor.timescale) === 0n;
6959
+ if (!nests) {
6960
+ catalogError("track_switching_set", `$.tracks[${member.index}]`, `group duration does not match ${JSON.stringify(anchor.name)} in altGroup ${altGroup}`);
6961
+ }
6778
6962
  }
6779
- if (!anchor) switchingSets.set(altGroup, { name: track["name"], ticks, timescale });
6780
6963
  }
6781
6964
  const multicast = catalog["multicast"];
6782
6965
  if (typeof multicast === "object" && multicast !== null && !Array.isArray(multicast)) {
@@ -6824,15 +7007,8 @@ function validateCmsfMmtpCatalog(value) {
6824
7007
  }
6825
7008
  }
6826
7009
  }
6827
- try {
6828
- resolveMulticastAuthCatalog(catalog);
6829
- } catch (error) {
6830
- catalogError(
6831
- "multicast_auth",
6832
- "$.multicast.auth",
6833
- error instanceof Error ? error.message : "invalid multicast.auth v2 block"
6834
- );
6835
- }
7010
+ const [multicastIssue] = multicastCatalogIssues(catalog, options);
7011
+ if (multicastIssue) catalogError(multicastIssue.code, multicastIssue.path, multicastIssue.message);
6836
7012
  validateArchive(catalog);
6837
7013
  return catalog;
6838
7014
  }
@@ -6858,7 +7034,7 @@ function resolveGroupDurationTicks(timing, timescale) {
6858
7034
  const product = timing.groupDurationMs * timescale;
6859
7035
  if (product % 1e3 !== 0) {
6860
7036
  throw new Error(
6861
- `[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)`
7037
+ `[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)`
6862
7038
  );
6863
7039
  }
6864
7040
  return product / 1e3;
@@ -6879,186 +7055,6 @@ function validateSwitchingSetTiming(tracks) {
6879
7055
  return { ok: false, expectedTicks, mismatches };
6880
7056
  }
6881
7057
 
6882
- // node_modules/@blockcast/mmt-transport/dist/types.js
6883
- var MoqFecAlgorithm;
6884
- (function(MoqFecAlgorithm2) {
6885
- MoqFecAlgorithm2[MoqFecAlgorithm2["None"] = 0] = "None";
6886
- MoqFecAlgorithm2[MoqFecAlgorithm2["Xor"] = 1] = "Xor";
6887
- MoqFecAlgorithm2[MoqFecAlgorithm2["RaptorQ"] = 2] = "RaptorQ";
6888
- })(MoqFecAlgorithm || (MoqFecAlgorithm = {}));
6889
-
6890
- // node_modules/@blockcast/mmt-base/dist/mmtp.js
6891
- var MPU_HEADER_SIZE2 = 8;
6892
- var MPU_LENGTH_FIELD_SIZE2 = 2;
6893
- var MPU_HEADER_REMAINDER_SIZE2 = MPU_HEADER_SIZE2 - MPU_LENGTH_FIELD_SIZE2;
6894
- var MMTP_SIGNALING_PACKET_ID2 = 0;
6895
- var MMTP_PACKET_ID_MAX2 = 65535;
6896
-
6897
- // node_modules/@blockcast/mmt-base/dist/net-constants.js
6898
- var DEFAULT_AMT_RELAY_PORT2 = 2268;
6899
-
6900
- // node_modules/@blockcast/mmt-base/dist/ntp-short.js
6901
- var NTP_SHORT_BITS2 = 32;
6902
- var NTP_SHORT_MODULUS2 = 2 ** NTP_SHORT_BITS2;
6903
- var NTP_SHORT_HALF_RANGE2 = 2 ** (NTP_SHORT_BITS2 - 1);
6904
- function isNtpShort(value) {
6905
- return Number.isInteger(value) && value >= 0 && value < NTP_SHORT_MODULUS2;
6906
- }
6907
- function compareNtpShort(a, b) {
6908
- if (!isNtpShort(a) || !isNtpShort(b)) {
6909
- throw new RangeError(`NTP-short values must be integers in [0, 2^${NTP_SHORT_BITS2}), got ${String(a)} and ${String(b)}`);
6910
- }
6911
- if (a === b)
6912
- return "equal";
6913
- const forward = (a - b + NTP_SHORT_MODULUS2) % NTP_SHORT_MODULUS2;
6914
- if (forward < NTP_SHORT_HALF_RANGE2)
6915
- return "after";
6916
- if (forward > NTP_SHORT_HALF_RANGE2)
6917
- return "before";
6918
- return "unordered";
6919
- }
6920
-
6921
- // node_modules/@blockcast/mmt-base/dist/fec-block-profile.js
6922
- var FEC_BLOCK_PROFILES2 = Object.freeze([
6923
- "iso-ssbg1-v1"
6924
- ]);
6925
-
6926
- // node_modules/@blockcast/mmt-transport/dist/driad-discovery.js
6927
- var DRIADDiscovery = class {
6928
- cache = /* @__PURE__ */ new Map();
6929
- cacheExpiry = 3e5;
6930
- // 5 minutes
6931
- /**
6932
- * Discover AMT relays for a multicast source address (RFC 8777)
6933
- *
6934
- * @param source - The multicast source IP address (NOT the group!)
6935
- * @returns Array of discovered AMT relays that can tunnel traffic from this source
6936
- */
6937
- async discoverRelays(source) {
6938
- const cached = this.cache.get(source);
6939
- if (cached) {
6940
- return cached;
6941
- }
6942
- try {
6943
- const reversedSource = source.split(".").reverse().join(".");
6944
- const queryDomain = `${reversedSource}.amt.in-addr.arpa`;
6945
- console.log(`[DRIAD] Discovering relays for source ${source} via ${queryDomain}`);
6946
- const relays = await this.queryDRIADProxy(source);
6947
- if (relays.length > 0) {
6948
- this.cache.set(source, relays);
6949
- setTimeout(() => this.cache.delete(source), this.cacheExpiry);
6950
- }
6951
- return relays;
6952
- } catch (error) {
6953
- console.warn(`[DRIAD] Discovery failed for source ${source}:`, error);
6954
- return [];
6955
- }
6956
- }
6957
- /**
6958
- * Query DRIAD proxy service (browser-compatible)
6959
- */
6960
- async queryDRIADProxy(source) {
6961
- const proxyEndpoints = [
6962
- "https://driad.amt.net/api/v1/relays",
6963
- "https://multicast-gateway.cloudflare.com/driad"
6964
- ];
6965
- for (const endpoint of proxyEndpoints) {
6966
- try {
6967
- const response = await fetch(`${endpoint}?source=${encodeURIComponent(source)}`, {
6968
- method: "GET",
6969
- headers: { Accept: "application/json" },
6970
- signal: AbortSignal.timeout(5e3)
6971
- });
6972
- if (response.ok) {
6973
- const data = await response.json();
6974
- return data.relays || [];
6975
- }
6976
- } catch {
6977
- }
6978
- }
6979
- const dohRelay = await this.queryDNSOverHTTPS(source);
6980
- if (dohRelay) {
6981
- return [dohRelay];
6982
- }
6983
- return [];
6984
- }
6985
- /**
6986
- * Query DNS-over-HTTPS for DRIAD relay based on source address (RFC 8777)
6987
- */
6988
- async queryDNSOverHTTPS(source) {
6989
- try {
6990
- const reversedSource = source.split(".").reverse().join(".");
6991
- const queryName = `${reversedSource}.amt.in-addr.arpa`;
6992
- const dohUrl = `https://cloudflare-dns.com/dns-query?name=${queryName}&type=A`;
6993
- const response = await fetch(dohUrl, {
6994
- headers: { Accept: "application/dns-json" },
6995
- signal: AbortSignal.timeout(3e3)
6996
- });
6997
- if (!response.ok) {
6998
- return null;
6999
- }
7000
- const result = await response.json();
7001
- if (result.Answer && result.Answer.length > 0) {
7002
- return {
7003
- host: result.Answer[0].data,
7004
- port: DEFAULT_AMT_RELAY_PORT2,
7005
- priority: 10,
7006
- weight: 100,
7007
- asn: 0
7008
- };
7009
- }
7010
- return null;
7011
- } catch (error) {
7012
- console.warn("[DRIAD] DNS-over-HTTPS query failed:", error);
7013
- return null;
7014
- }
7015
- }
7016
- /**
7017
- * Select best relay based on RTT measurements
7018
- */
7019
- async selectBestRelay(relays) {
7020
- if (relays.length === 0)
7021
- return null;
7022
- const measured = await Promise.all(relays.map(async (relay) => {
7023
- const rtt = await this.measureRTT(relay.host, relay.port);
7024
- return { ...relay, rtt };
7025
- }));
7026
- measured.sort((a, b) => {
7027
- if (a.priority !== b.priority)
7028
- return a.priority - b.priority;
7029
- return (a.rtt || Infinity) - (b.rtt || Infinity);
7030
- });
7031
- console.log(`[DRIAD] Selected relay: ${measured[0].host} (RTT: ${measured[0].rtt}ms)`);
7032
- return measured[0];
7033
- }
7034
- async measureRTT(host, _port) {
7035
- const start = performance.now();
7036
- try {
7037
- await fetch(`https://${host}/health`, {
7038
- method: "HEAD",
7039
- signal: AbortSignal.timeout(2e3),
7040
- mode: "no-cors"
7041
- });
7042
- return performance.now() - start;
7043
- } catch {
7044
- return Infinity;
7045
- }
7046
- }
7047
- /**
7048
- * Clear the relay cache
7049
- */
7050
- clearCache() {
7051
- this.cache.clear();
7052
- }
7053
- /**
7054
- * Get cached relays for a source address
7055
- */
7056
- getCached(source) {
7057
- return this.cache.get(source);
7058
- }
7059
- };
7060
- var driadDiscovery = new DRIADDiscovery();
7061
-
7062
7058
  // node_modules/@blockcast/mmt-transport/dist/multicast-tier.js
7063
7059
  function endpointKey(endpoint) {
7064
7060
  return `${endpoint.sourceAddress ?? ""}|${endpoint.groupAddress}|${endpoint.port}`;
@@ -7189,8 +7185,8 @@ var AdaptiveBitrateController = class {
7189
7185
  /**
7190
7186
  * Update FEC statistics for ABR decisions
7191
7187
  *
7192
- * Per draft-ramadan-moq-fec-00, ABR should use the effective loss rate
7193
- * (after FEC recovery) rather than raw transport loss rate.
7188
+ * ABR uses the effective loss rate (after FEC recovery) rather than the
7189
+ * raw transport loss rate.
7194
7190
  *
7195
7191
  * @param stats - FEC statistics from the FEC decoder
7196
7192
  */
@@ -7266,6 +7262,45 @@ var AdaptiveBitrateController = class {
7266
7262
  }
7267
7263
  };
7268
7264
 
7265
+ // node_modules/@blockcast/mmt-base/dist/mmtp.js
7266
+ var MPU_HEADER_SIZE2 = 8;
7267
+ var MPU_LENGTH_FIELD_SIZE2 = 2;
7268
+ var MPU_HEADER_REMAINDER_SIZE2 = MPU_HEADER_SIZE2 - MPU_LENGTH_FIELD_SIZE2;
7269
+ var MMTP_SIGNALING_PACKET_ID2 = 0;
7270
+ var MMTP_PACKET_ID_MAX2 = 65535;
7271
+
7272
+ // node_modules/@blockcast/mmt-base/dist/net-constants.js
7273
+ var DEFAULT_AMT_RELAY_PORT2 = 2268;
7274
+
7275
+ // node_modules/@blockcast/mmt-base/dist/ntp-short.js
7276
+ var NTP_SHORT_BITS2 = 32;
7277
+ var NTP_SHORT_MODULUS2 = 2 ** NTP_SHORT_BITS2;
7278
+ var NTP_SHORT_HALF_RANGE2 = 2 ** (NTP_SHORT_BITS2 - 1);
7279
+ function isNtpShort(value) {
7280
+ return Number.isInteger(value) && value >= 0 && value < NTP_SHORT_MODULUS2;
7281
+ }
7282
+ function compareNtpShort(a, b) {
7283
+ if (!isNtpShort(a) || !isNtpShort(b)) {
7284
+ throw new RangeError(`NTP-short values must be integers in [0, 2^${NTP_SHORT_BITS2}), got ${String(a)} and ${String(b)}`);
7285
+ }
7286
+ if (a === b)
7287
+ return "equal";
7288
+ const forward = (a - b + NTP_SHORT_MODULUS2) % NTP_SHORT_MODULUS2;
7289
+ if (forward < NTP_SHORT_HALF_RANGE2)
7290
+ return "after";
7291
+ if (forward > NTP_SHORT_HALF_RANGE2)
7292
+ return "before";
7293
+ return "unordered";
7294
+ }
7295
+
7296
+ // node_modules/@blockcast/mmt-base/dist/fec-block-profile.js
7297
+ var FEC_BLOCK_PROFILES2 = Object.freeze([
7298
+ "iso-ssbg1-v1"
7299
+ ]);
7300
+
7301
+ // node_modules/@blockcast/mmt-base/dist/catalog-fec-source.js
7302
+ var ALL_ROLES2 = Object.freeze(["video", "audio"]);
7303
+
7269
7304
  // node_modules/@blockcast/mmt-transport/dist/multicast-orchestrator.js
7270
7305
  var DEFAULT_DWELL_MS = 3e3;
7271
7306
  var DEFAULT_JOIN_DEADLINE_MS = 5e3;
@@ -7504,7 +7539,8 @@ function toWindowMulticastSubscribeConfig(input) {
7504
7539
  ...input.packetIds?.length ? { packetIds: [...input.packetIds] } : {}
7505
7540
  };
7506
7541
  const relay = input.amtRelay?.trim();
7507
- const wantsAmt = input.mode === "tunnel" || input.mode !== "native" && relay !== void 0 && relay !== "";
7542
+ const driad = !relay && input.amtDiscovery === "driad";
7543
+ const wantsAmt = input.mode === "tunnel" || input.mode !== "native" && (relay !== void 0 && relay !== "" || driad);
7508
7544
  if (!wantsAmt) {
7509
7545
  const native = {
7510
7546
  ...base,
@@ -7514,6 +7550,20 @@ function toWindowMulticastSubscribeConfig(input) {
7514
7550
  return native;
7515
7551
  }
7516
7552
  const relayPort = input.amtRelayPort;
7553
+ if (driad) {
7554
+ if (!base.source)
7555
+ throw new TypeError("AMT DRIAD discovery requires a source address");
7556
+ if (relayPort !== void 0 && !isPositivePort(relayPort)) {
7557
+ throw new TypeError("AMT DRIAD discovery requires a valid relay port when one is given");
7558
+ }
7559
+ return {
7560
+ ...base,
7561
+ source: base.source,
7562
+ origin: "amt",
7563
+ discovery: "driad",
7564
+ ...relayPort !== void 0 ? { relayPort } : {}
7565
+ };
7566
+ }
7517
7567
  if (!relay || relayPort === void 0 || !isPositivePort(relayPort)) {
7518
7568
  throw new TypeError("AMT requires a resolved relay and a valid relay port");
7519
7569
  }
@@ -7557,7 +7607,8 @@ function normalizeMulticastEndpoint(endpoint) {
7557
7607
  port: endpoint.port,
7558
7608
  ...endpoint.mode ? { mode: endpoint.mode } : {},
7559
7609
  ...amtRelay ? { amtRelay } : {},
7560
- ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
7610
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {},
7611
+ ...endpoint.amtDiscovery === "driad" ? { amtDiscovery: "driad" } : {}
7561
7612
  };
7562
7613
  }
7563
7614
  function multicastEndpointKey(endpoint) {
@@ -7570,7 +7621,9 @@ function multicastEndpointKey(endpoint) {
7570
7621
  normalized.port,
7571
7622
  normalized.mode ?? "auto",
7572
7623
  normalized.amtRelay ?? "",
7573
- normalized.amtRelayPort ?? ""
7624
+ normalized.amtRelayPort ?? "",
7625
+ // A DRIAD join is a different gateway subscription from a native one.
7626
+ ...normalized.amtDiscovery ? [normalized.amtDiscovery] : []
7574
7627
  ]);
7575
7628
  }
7576
7629
  function isMulticastTrackPacketId(value) {
@@ -7610,7 +7663,8 @@ var MulticastSubscriptionPool = class {
7610
7663
  port: config.port,
7611
7664
  mode: config.mode,
7612
7665
  amtRelay: config.amtRelay,
7613
- amtRelayPort: config.amtRelayPort
7666
+ amtRelayPort: config.amtRelayPort,
7667
+ amtDiscovery: config.amtDiscovery
7614
7668
  });
7615
7669
  if (!endpoint)
7616
7670
  throw new Error("Invalid multicast endpoint");
@@ -7676,7 +7730,8 @@ var MulticastSubscriptionPool = class {
7676
7730
  port: endpoint.port,
7677
7731
  ...endpoint.mode ? { mode: endpoint.mode } : {},
7678
7732
  ...endpoint.amtRelay ? { amtRelay: endpoint.amtRelay } : {},
7679
- ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
7733
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {},
7734
+ ...endpoint.amtDiscovery ? { amtDiscovery: endpoint.amtDiscovery } : {}
7680
7735
  }));
7681
7736
  const consumers = /* @__PURE__ */ new Map();
7682
7737
  let entry;
@@ -7756,7 +7811,6 @@ var TransportManager = class {
7756
7811
  };
7757
7812
  capabilities = null;
7758
7813
  subscription = null;
7759
- driad = new DRIADDiscovery();
7760
7814
  /** Built by `connect()` from the caller's ladder; there is no built-in one. */
7761
7815
  abr = null;
7762
7816
  multicastOrchestrator = null;
@@ -7806,8 +7860,8 @@ var TransportManager = class {
7806
7860
  nativeIGMP: hasGatewayBytes,
7807
7861
  directSockets: typeof win?.UDPSocket !== "undefined",
7808
7862
  amt: false,
7809
- driad: true,
7810
- // DRIAD uses HTTP proxy, always available
7863
+ driad: hasGatewayBytes,
7864
+ // the gateway runs RFC 8777 discovery
7811
7865
  fecDecode: false
7812
7866
  };
7813
7867
  console.log("[Transport] Capabilities:", this.capabilities);
@@ -7818,7 +7872,7 @@ var TransportManager = class {
7818
7872
  *
7819
7873
  * Promotion hierarchy:
7820
7874
  * 1. window.multicast gateway bytes
7821
- * 2. AMT proxy (specified or discovered via DRIAD)
7875
+ * 2. AMT: a configured relay via the AMT proxy, else gateway DRIAD discovery
7822
7876
  * 3. MOQ WebTransport (final fallback)
7823
7877
  *
7824
7878
  * The ABR ladder (`abrLadder`) and initial rendition (`initialQuality`)
@@ -7912,7 +7966,7 @@ var TransportManager = class {
7912
7966
  /**
7913
7967
  * Connect via the lowercase window.multicast bytes gateway.
7914
7968
  */
7915
- async connectWindowMulticast(config, generation) {
7969
+ async connectWindowMulticast(config, generation, mode = "multicast") {
7916
7970
  try {
7917
7971
  const gateway = this.getWindowMulticastGateway();
7918
7972
  if (typeof gateway?.subscribe !== "function")
@@ -7947,7 +8001,7 @@ var TransportManager = class {
7947
8001
  }
7948
8002
  };
7949
8003
  this.state = {
7950
- mode: "multicast",
8004
+ mode,
7951
8005
  connected: true,
7952
8006
  group: config.group,
7953
8007
  source: config.source,
@@ -7965,29 +8019,19 @@ var TransportManager = class {
7965
8019
  }
7966
8020
  }
7967
8021
  /**
7968
- * Connect via AMT proxy (with optional DRIAD discovery)
8022
+ * Connect via AMT: a configured relay goes through the AMT proxy; with no
8023
+ * relay, the window.multicast gateway discovers one per RFC 8777 (DRIAD).
7969
8024
  */
7970
8025
  async connectAmt(config, generation) {
7971
8026
  try {
7972
- let amtRelay = config.amtRelay;
7973
- if (!amtRelay && config.driadEnabled !== false && config.source) {
7974
- console.log(`[Transport] Discovering AMT relay via DRIAD for source ${config.source}...`);
7975
- const relays = await this.driad.discoverRelays(config.source);
7976
- if (generation !== this.connectionGeneration)
7977
- return false;
7978
- const bestRelay = await this.driad.selectBestRelay(relays);
7979
- if (generation !== this.connectionGeneration)
7980
- return false;
7981
- if (bestRelay) {
7982
- amtRelay = bestRelay.host;
7983
- this.state.amtRelay = amtRelay;
7984
- }
7985
- }
7986
- if (!amtRelay) {
8027
+ if (config.amtRelay)
8028
+ return await this.connectAmtProxy(config, config.amtRelay, generation);
8029
+ if (config.driadEnabled === false || !config.source || config.mode === "native") {
7987
8030
  console.warn("[Transport] No AMT relay available (DRIAD requires source address for SSM)");
7988
8031
  return false;
7989
8032
  }
7990
- return await this.connectAmtProxy(config, amtRelay, generation);
8033
+ console.log(`[Transport] Asking the gateway for a DRIAD relay for source ${config.source}...`);
8034
+ return await this.connectWindowMulticast({ ...config, amtDiscovery: "driad" }, generation, "amt");
7991
8035
  } catch (error) {
7992
8036
  console.warn("[Transport] AMT connection failed:", error);
7993
8037
  return false;
@@ -8125,6 +8169,10 @@ var TransportManager = class {
8125
8169
  pollMulticastTierSwitch() {
8126
8170
  return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.poll());
8127
8171
  }
8172
+ /** Abandon the in-flight tier join, e.g. because the host could not join the target. */
8173
+ cancelMulticastTierJoin() {
8174
+ return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.cancel());
8175
+ }
8128
8176
  /**
8129
8177
  * Set packet callback
8130
8178
  */
@@ -8214,7 +8262,6 @@ var AMTGatewayManager = class {
8214
8262
  subscriptions = /* @__PURE__ */ new Map();
8215
8263
  messageHandler;
8216
8264
  pendingPackets = /* @__PURE__ */ new Map();
8217
- driad = new DRIADDiscovery();
8218
8265
  constructor() {
8219
8266
  this.messageHandler = (event) => {
8220
8267
  const data = event.data;
@@ -8245,26 +8292,12 @@ var AMTGatewayManager = class {
8245
8292
  return keyStr;
8246
8293
  }
8247
8294
  try {
8248
- let relayAddress;
8249
- let discoveryMethod;
8295
+ const relayAddress = config.relayAddress;
8250
8296
  const relayPort = config.relayPort || DEFAULT_AMT_RELAY_PORT2;
8251
- if (config.relayAddress) {
8252
- relayAddress = config.relayAddress;
8253
- discoveryMethod = "manual";
8254
- console.log(`[AMT] Using configured relay ${relayAddress}:${relayPort}`);
8255
- } else if (key.source) {
8256
- console.log(`[AMT] No relay configured, discovering via DRIAD for source ${key.source}...`);
8257
- const relays = await this.driad.discoverRelays(key.source);
8258
- const bestRelay = await this.driad.selectBestRelay(relays);
8259
- if (!bestRelay) {
8260
- throw new Error(`AMT relay discovery failed for source ${key.source}. Please specify a relay address in the subscription configuration.`);
8261
- }
8262
- relayAddress = bestRelay.host;
8263
- discoveryMethod = "driad";
8264
- console.log(`[AMT] Discovered relay via DRIAD: ${relayAddress}:${relayPort}`);
8265
- } else {
8266
- throw new Error(`AMT relay discovery requires a source address for SSM (RFC 8777). Please specify either a relay address or source address.`);
8297
+ if (!relayAddress) {
8298
+ 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".`);
8267
8299
  }
8300
+ console.log(`[AMT] Using configured relay ${relayAddress}:${relayPort}`);
8268
8301
  const subscriptionId = keyStr;
8269
8302
  this.pendingPackets.set(subscriptionId, []);
8270
8303
  const subscription = {
@@ -8275,7 +8308,7 @@ var AMTGatewayManager = class {
8275
8308
  relay: {
8276
8309
  address: relayAddress,
8277
8310
  port: relayPort,
8278
- discoveryMethod,
8311
+ discoveryMethod: "manual",
8279
8312
  discoveredAt: Date.now()
8280
8313
  }
8281
8314
  };
@@ -8750,8 +8783,7 @@ function multicastFromConfig(input) {
8750
8783
  );
8751
8784
  }
8752
8785
  }
8753
- const seenTuples = /* @__PURE__ */ new Set();
8754
- const endpoints = input.endpoints.map((ep, idx) => validateEndpoint2(ep, idx, seenTuples));
8786
+ const endpoints = input.endpoints.map((ep, idx) => validateEndpoint2(ep, idx));
8755
8787
  const out = { endpoints };
8756
8788
  const { entries: networkSource, relayFrom } = resolveNetworkSource(input);
8757
8789
  networkSource.forEach(validateNetworkSourceEntry);
@@ -8788,6 +8820,17 @@ function multicastFromConfig(input) {
8788
8820
  `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" : "")
8789
8821
  );
8790
8822
  });
8823
+ input.endpoints.forEach((ep, idx) => {
8824
+ if (ep.protocol !== "amt" && ep.protocol !== "atsc3") return;
8825
+ endpoints[idx].networkSource = networkSource.filter((s) => s.type === ep.protocol).map((s) => ({ ...s }));
8826
+ });
8827
+ if (input.auth !== void 0) out.auth = input.auth;
8828
+ const [issue] = multicastCatalogIssues({ multicast: out });
8829
+ if (issue) {
8830
+ 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";
8831
+ const where = issue.endpointIndex === void 0 ? "" : `endpoint[${issue.endpointIndex}] `;
8832
+ throw new MulticastInputError(kind, issue.endpointIndex ?? null, `${where}${issue.path.replace("$.multicast.", "")}: ${issue.message}`);
8833
+ }
8791
8834
  if (input.enabled !== void 0) out.enabled = input.enabled;
8792
8835
  if (input.version !== void 0) out.version = input.version;
8793
8836
  if (input.validUntil !== void 0) out.validUntil = input.validUntil;
@@ -8799,10 +8842,10 @@ function resolveNetworkSource(input) {
8799
8842
  }
8800
8843
  const relayDns = input.amtFallback?.relayDns?.trim();
8801
8844
  const relay = relayDns || input.endpoints.map((ep) => ep.relayAddress?.trim()).find((r) => !!r);
8802
- const discovery = input.amtFallback?.discovery ?? (relay ? "manual" : void 0);
8803
- if (discovery === void 0) return { entries: [], relayFrom: null };
8845
+ const discovery = input.amtFallback?.discovery;
8846
+ if (discovery === void 0 && !relay) return { entries: [], relayFrom: null };
8804
8847
  return {
8805
- entries: [{ type: "amt", discovery, ...relay ? { relay } : {} }],
8848
+ entries: [{ type: "amt", ...discovery ? { discovery } : {}, ...relay ? { relay } : {} }],
8806
8849
  relayFrom: !relay ? null : relayDns ? "amtFallback.relayDns" : "endpoint.relayAddress"
8807
8850
  };
8808
8851
  }
@@ -8815,8 +8858,11 @@ function validateNetworkSourceEntry(s, i) {
8815
8858
  const extra = Object.keys(s).filter((k) => !keys.has(k) && s[k] !== void 0);
8816
8859
  if (extra.length > 0) throw err("invalid_network_source", `has keys the schema rejects: ${extra.join(", ")}`);
8817
8860
  if (s.type === "amt") {
8818
- if (s.discovery !== "driad" && s.discovery !== "manual") {
8819
- throw err("invalid_amt_discovery", `discovery must be "driad" or "manual"; got ${JSON.stringify(s.discovery)}`);
8861
+ if (s.discovery !== void 0 && s.discovery !== "dns" && s.discovery !== "driad" && s.discovery !== "manual") {
8862
+ throw err(
8863
+ "invalid_amt_discovery",
8864
+ `discovery must be "dns", "driad" or "manual" when present; got ${JSON.stringify(s.discovery)}`
8865
+ );
8820
8866
  }
8821
8867
  if (s.relay !== void 0) {
8822
8868
  const relay = typeof s.relay === "string" ? s.relay.trim() : "";
@@ -8825,8 +8871,8 @@ function validateNetworkSourceEntry(s, i) {
8825
8871
  }
8826
8872
  s.relay = relay;
8827
8873
  }
8828
- if (s.discovery === "manual" && s.relay === void 0) {
8829
- throw err("amt_requires_relay", `discovery="manual" requires a relay ("driad" resolves it at runtime)`);
8874
+ if ((s.discovery === "dns" || s.discovery === "manual") && s.relay === void 0) {
8875
+ throw err("amt_requires_relay", `discovery="${s.discovery}" requires a relay ("driad" resolves it at runtime)`);
8830
8876
  }
8831
8877
  if (s.port !== void 0 && (!Number.isInteger(s.port) || s.port < 1 || s.port > 65535)) {
8832
8878
  throw err("invalid_port", `port must be 1..65535; got ${s.port}`);
@@ -8853,7 +8899,7 @@ function isAbsoluteUri(value) {
8853
8899
  return false;
8854
8900
  }
8855
8901
  }
8856
- function validateEndpoint2(ep, idx, seenTuples) {
8902
+ function validateEndpoint2(ep, idx) {
8857
8903
  if (ep.protocol === "ssm" && (!ep.sourceAddress || ep.sourceAddress.length === 0)) {
8858
8904
  throw new MulticastInputError(
8859
8905
  "ssm_requires_source",
@@ -8861,6 +8907,13 @@ function validateEndpoint2(ep, idx, seenTuples) {
8861
8907
  `endpoint[${idx}] protocol=ssm requires sourceAddress`
8862
8908
  );
8863
8909
  }
8910
+ if (ep.protocol === "asm" && ep.sourceAddress !== void 0) {
8911
+ throw new MulticastInputError(
8912
+ "protocol_source_mismatch",
8913
+ idx,
8914
+ `endpoint[${idx}] protocol=asm with sourceAddress "${ep.sourceAddress}"; sourceAddress selects SSM (draft -01 4.1)`
8915
+ );
8916
+ }
8864
8917
  if (!isMulticastGroupAddress(ep.groupAddress)) {
8865
8918
  throw new MulticastInputError(
8866
8919
  "invalid_group_address",
@@ -8920,23 +8973,15 @@ function validateEndpoint2(ep, idx, seenTuples) {
8920
8973
  `endpoint[${idx}] bandwidth must be positive; got ${ep.bandwidth}`
8921
8974
  );
8922
8975
  }
8923
- const tupleKey = `${ep.sourceAddress ?? ""}|${ep.groupAddress}|${ep.port}`;
8924
- if (seenTuples.has(tupleKey)) {
8925
- throw new MulticastInputError(
8926
- "duplicate_endpoint_tuple",
8927
- idx,
8928
- `endpoint[${idx}] duplicates (sourceAddress, groupAddress, port) tuple "${tupleKey}"`
8929
- );
8930
- }
8931
- seenTuples.add(tupleKey);
8932
8976
  const out = {
8933
- protocol: ep.protocol,
8977
+ protocol: ep.sourceAddress === void 0 ? "asm" : "ssm",
8934
8978
  groupAddress: ep.groupAddress,
8935
8979
  port: ep.port,
8936
8980
  tracks: ep.tracks.map((t) => ({ name: t.name, packetId: t.packetId }))
8937
8981
  };
8938
8982
  if (ep.sourceAddress !== void 0) out.sourceAddress = ep.sourceAddress;
8939
8983
  if (ep.bandwidth !== void 0) out.bandwidth = ep.bandwidth;
8984
+ if (ep.auth !== void 0) out.auth = { ...ep.auth };
8940
8985
  return out;
8941
8986
  }
8942
8987
  function isMulticastGroupAddress(addr) {
@@ -8979,9 +9024,9 @@ function multicastFromEnv(env = globalThis.process?.env ?? {}) {
8979
9024
  endpoints,
8980
9025
  ...hasCatalogAmt ? {
8981
9026
  amtFallback: {
8982
- // `"manual"` mirrors `resolveNetworkSource`: a relay named in
8983
- // the catalog is, by definition, not discovered.
8984
- discovery: amtDiscovery ?? "manual",
9027
+ // No default: an omitted discovery with a relay hostname is
9028
+ // "dns" (draft-ramadan-moq-multicast-01 4.2.1).
9029
+ ...amtDiscovery ? { discovery: amtDiscovery } : {},
8985
9030
  ...amtRelayDns ? { relayDns: amtRelayDns } : {}
8986
9031
  }
8987
9032
  } : {}
@@ -9149,7 +9194,7 @@ function mergeOverrideIntoCmsfTracks(tracks, override) {
9149
9194
  if (ot.role !== void 0 && existing.role === void 0) existing.role = ot.role;
9150
9195
  if (existing.packaging === "mmtp") {
9151
9196
  const mode = existing.mmtpMode ?? ot.mmtpMode;
9152
- if (mode !== "mpu" && mode !== "mfu") {
9197
+ if (mode !== "mfu") {
9153
9198
  throw new Error(
9154
9199
  `[phase14-catalog-override] track "${ot.name}" has packaging='mmtp' but no valid mmtpMode`
9155
9200
  );
@@ -9186,7 +9231,7 @@ function mergeOverrideIntoCmsfTracks(tracks, override) {
9186
9231
  );
9187
9232
  }
9188
9233
  const mmtpMode = ot.mmtpMode;
9189
- if (packaging === "mmtp" && mmtpMode !== "mpu" && mmtpMode !== "mfu") {
9234
+ if (packaging === "mmtp" && mmtpMode !== "mfu") {
9190
9235
  throw new Error(
9191
9236
  `[phase14-catalog-override] track "${ot.name}" has packaging='mmtp' but no valid mmtpMode`
9192
9237
  );
@@ -9487,8 +9532,8 @@ function u32(v) {
9487
9532
  }
9488
9533
  var KEYFRAME_FLAGS = 33554432;
9489
9534
  var DELTA_FLAGS = 16842752;
9490
- var UINT32_MAX = 4294967295;
9491
- var MAX_TRACK_ID = UINT32_MAX - 1;
9535
+ var UINT32_MAX2 = 4294967295;
9536
+ var MAX_TRACK_ID = UINT32_MAX2 - 1;
9492
9537
  var INT32_MIN = -2147483648;
9493
9538
  var INT32_MAX = 2147483647;
9494
9539
  function assertTrackId(trackId, label) {
@@ -9497,8 +9542,8 @@ function assertTrackId(trackId, label) {
9497
9542
  }
9498
9543
  }
9499
9544
  function assertTimescale(timescale, label) {
9500
- if (!Number.isInteger(timescale) || timescale <= 0 || timescale > UINT32_MAX) {
9501
- throw new RangeError(`${label} must be an integer in 1..${UINT32_MAX}, got ${timescale}`);
9545
+ if (!Number.isInteger(timescale) || timescale <= 0 || timescale > UINT32_MAX2) {
9546
+ throw new RangeError(`${label} must be an integer in 1..${UINT32_MAX2}, got ${timescale}`);
9502
9547
  }
9503
9548
  }
9504
9549
  function assertCompositionTimeOffsets(samples) {
@@ -12331,16 +12376,6 @@ var DeliveryGapEstimator = class {
12331
12376
 
12332
12377
  // src/iso-block-locator.ts
12333
12378
  var IsoBlockLocator = class _IsoBlockLocator {
12334
- /** Known blocks and spans, in serial order of their start. */
12335
- #blocks = [];
12336
- /** Held first-arrival sources whose block no repair has stated yet. */
12337
- #held = /* @__PURE__ */ new Map();
12338
- /** End of contiguous coverage: the SS_ID the next unknown block starts at. */
12339
- #coverageEnd;
12340
- #kMax;
12341
- #retentionBlocks;
12342
- #heldEvicted = 0;
12343
- #newest;
12344
12379
  /**
12345
12380
  * @param kMax the catalog maximum K (`sourceSymbols`), the bound on SSB_length.
12346
12381
  * @param retentionBlocks how many blocks behind the newest position the
@@ -12348,12 +12383,35 @@ var IsoBlockLocator = class _IsoBlockLocator {
12348
12383
  * no locator exists without retention.
12349
12384
  */
12350
12385
  constructor(kMax, retentionBlocks) {
12386
+ /** Known blocks and spans, in serial order of their start. */
12387
+ this.#blocks = [];
12388
+ /** Held first-arrival sources whose block no repair has stated yet. */
12389
+ this.#held = /* @__PURE__ */ new Map();
12390
+ this.#heldEvicted = 0;
12391
+ /** Pending holes (see `deferIncompleteGaps`): unstated, sources still held. */
12392
+ this.#holes = [];
12393
+ /**
12394
+ * Keep a gap that is missing a source as a pending hole rather than a span,
12395
+ * so a repair FETCHed for it (draft-ramadan-moq-fec §7.5) can still state
12396
+ * its blocks. Set only while a range repair scheduler is wired; its owner
12397
+ * must close every hole it is told about (`closeHolesWithin`).
12398
+ */
12399
+ this.deferIncompleteGaps = false;
12351
12400
  if (!Number.isSafeInteger(kMax) || kMax <= 0) {
12352
12401
  throw new Error(`[IsoBlockLocator] maximum K must be a positive integer (got ${kMax})`);
12353
12402
  }
12354
12403
  this.#kMax = kMax;
12355
12404
  this.#retentionBlocks = _IsoBlockLocator.#checkedRetention(retentionBlocks);
12356
12405
  }
12406
+ #blocks;
12407
+ #held;
12408
+ /** End of contiguous coverage: the SS_ID the next unknown block starts at. */
12409
+ #coverageEnd;
12410
+ #kMax;
12411
+ #retentionBlocks;
12412
+ #heldEvicted;
12413
+ #newest;
12414
+ #holes;
12357
12415
  static #checkedRetention(retentionBlocks) {
12358
12416
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
12359
12417
  throw new Error(
@@ -12416,6 +12474,14 @@ var IsoBlockLocator = class _IsoBlockLocator {
12416
12474
  }
12417
12475
  return null;
12418
12476
  }
12477
+ /** Number of pending holes. */
12478
+ get holeCount() {
12479
+ return this.#holes.length;
12480
+ }
12481
+ /** The stated block (never a span) ending exactly at `end`. */
12482
+ blockEndingAt(end) {
12483
+ return this.#blocks.find((block) => !block.span && isoBlockEnd(block.start, block.length) === end);
12484
+ }
12419
12485
  /** The known block or span starting exactly at `start`. */
12420
12486
  blockAt(start) {
12421
12487
  return this.#blocks.find((block) => block.start === start);
@@ -12438,6 +12504,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
12438
12504
  coversBetween(a, b) {
12439
12505
  if (this.#coverageEnd === void 0) return false;
12440
12506
  if (!serial32Precedes(a, b) || serial32Distance(a, b) <= 1) return true;
12507
+ const first = a + 1 >>> 0;
12508
+ const count = serial32Distance(a, b) - 1;
12509
+ if (this.#holes.some((hole) => isoRangesOverlap(first, count, hole.start, hole.length))) return false;
12441
12510
  return serial32Precedes(b - 1 >>> 0, this.#coverageEnd);
12442
12511
  }
12443
12512
  /**
@@ -12485,6 +12554,22 @@ var IsoBlockLocator = class _IsoBlockLocator {
12485
12554
  }
12486
12555
  return { status: "placed", block: known, placed: [] };
12487
12556
  }
12557
+ const pending = this.#holes.find((h) => isoBlockContains(h.start, h.length, start));
12558
+ if (pending !== void 0) {
12559
+ if (!isoBlockContains(pending.start, pending.length, serial32Add(start, length - 1))) {
12560
+ return { status: "overlap", reason: `repair block ${start}+${length} runs past pending hole ${pending.start}+${pending.length}` };
12561
+ }
12562
+ this.#holes.splice(this.#holes.indexOf(pending), 1);
12563
+ const before = serial32Distance(pending.start, start);
12564
+ const afterStart = isoBlockEnd(start, length);
12565
+ const after = pending.length - before - length;
12566
+ if (before > 0) this.#holes.push({ start: pending.start, length: before, span: false });
12567
+ if (after > 0) this.#holes.push({ start: afterStart, length: after, span: false });
12568
+ const block2 = { start, length, span: false };
12569
+ const placed2 = this.#claim(block2);
12570
+ this.#blocks.push(block2);
12571
+ return { status: "placed", block: block2, placed: placed2 };
12572
+ }
12488
12573
  for (const block2 of this.#blocks) {
12489
12574
  if (isoBlockContains(block2.start, block2.length, start) || isoBlockContains(start, length, block2.start)) {
12490
12575
  return {
@@ -12494,6 +12579,7 @@ var IsoBlockLocator = class _IsoBlockLocator {
12494
12579
  }
12495
12580
  }
12496
12581
  let span;
12582
+ let hole;
12497
12583
  if (this.#coverageEnd === void 0) {
12498
12584
  for (const ssId of this.#held.keys()) {
12499
12585
  if (serial32Precedes(ssId, start)) this.#held.delete(ssId);
@@ -12502,21 +12588,51 @@ var IsoBlockLocator = class _IsoBlockLocator {
12502
12588
  } else if (serial32Precedes(start, this.#coverageEnd)) {
12503
12589
  return { status: "stale", reason: `repair block ${start}+${length} precedes known coverage` };
12504
12590
  } else if (start !== this.#coverageEnd) {
12505
- const spanBlock = {
12506
- start: this.#coverageEnd,
12507
- length: serial32Distance(this.#coverageEnd, start),
12508
- span: true
12509
- };
12510
- span = { block: spanBlock, placed: this.#claim(spanBlock) };
12511
- this.#blocks.push(spanBlock);
12591
+ const gap = { start: this.#coverageEnd, length: serial32Distance(this.#coverageEnd, start) };
12592
+ const lostSsId = this.deferIncompleteGaps ? this.#highestMissing(gap.start, gap.length) : void 0;
12593
+ if (lostSsId !== void 0) {
12594
+ const holeBlock = { ...gap, span: false };
12595
+ this.#holes.push(holeBlock);
12596
+ hole = { block: holeBlock, lostSsId };
12597
+ } else {
12598
+ const spanBlock = { ...gap, span: true };
12599
+ span = { block: spanBlock, placed: this.#claim(spanBlock) };
12600
+ this.#blocks.push(spanBlock);
12601
+ }
12512
12602
  }
12513
12603
  const block = { start, length, span: false };
12514
12604
  const placed = this.#claim(block);
12515
12605
  this.#blocks.push(block);
12516
12606
  this.#coverageEnd = isoBlockEnd(start, length);
12517
12607
  this.retireBehind(start);
12608
+ if (hole !== void 0) return { status: "placed", block, placed, hole };
12518
12609
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
12519
12610
  }
12611
+ /**
12612
+ * Turn every pending hole inside `[start, start + length)` into a
12613
+ * repair-less span, claiming its held sources: its range FETCH ended, so
12614
+ * nothing more will state its blocks. Returns the spans, in SS_ID order.
12615
+ */
12616
+ closeHolesWithin(start, length) {
12617
+ const closed = [];
12618
+ for (const hole of [...this.#holes]) {
12619
+ if (!isoBlockContains(start, length, hole.start)) continue;
12620
+ this.#holes.splice(this.#holes.indexOf(hole), 1);
12621
+ const spanBlock = { start: hole.start, length: hole.length, span: true };
12622
+ closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
12623
+ this.#blocks.push(spanBlock);
12624
+ }
12625
+ return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
12626
+ }
12627
+ /** The highest SS_ID in the range no source is held for, or undefined when all are. */
12628
+ #highestMissing(start, length) {
12629
+ const steps = Math.min(length, this.#held.size + 1);
12630
+ for (let i = 1; i <= steps; i++) {
12631
+ const ssId = serial32Add(start, length - i);
12632
+ if (!this.#held.has(ssId)) return ssId;
12633
+ }
12634
+ return void 0;
12635
+ }
12520
12636
  /**
12521
12637
  * Retire every block and span whose last SS_ID, and every held source,
12522
12638
  * lies more than `retentionBlocks` blocks behind `position`, with the shared
@@ -12535,6 +12651,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
12535
12651
  this.#blocks.splice(i, 1);
12536
12652
  }
12537
12653
  }
12654
+ for (let i = this.#holes.length - 1; i >= 0; i--) {
12655
+ const hole = this.#holes[i];
12656
+ const last = serial32Add(hole.start, hole.length - 1);
12657
+ if (isoBlocksBehindLowerBound(last, position, this.#kMax) > horizon) this.#holes.splice(i, 1);
12658
+ }
12538
12659
  for (const ssId of [...this.#held.keys()]) {
12539
12660
  if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon) this.#held.delete(ssId);
12540
12661
  }
@@ -12543,6 +12664,7 @@ var IsoBlockLocator = class _IsoBlockLocator {
12543
12664
  /** Forget everything (publisher restart, track reset). */
12544
12665
  reset() {
12545
12666
  this.#blocks.length = 0;
12667
+ this.#holes.length = 0;
12546
12668
  this.#held.clear();
12547
12669
  this.#coverageEnd = void 0;
12548
12670
  this.#newest = void 0;
@@ -12558,6 +12680,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
12558
12680
  return placed;
12559
12681
  }
12560
12682
  };
12683
+ function isoRangesOverlap(aStart, aLength, bStart, bLength) {
12684
+ return serial32Distance(aStart, bStart) < aLength || serial32Distance(bStart, aStart) < bLength;
12685
+ }
12561
12686
 
12562
12687
  // src/fec-state.ts
12563
12688
  var MIN_INTERLEAVE_DEPTH_MS = 1;
@@ -12572,22 +12697,16 @@ var INACTIVE = Object.freeze({
12572
12697
  "reliable-moq": Object.freeze({ state: "inactive", reason: "reliable-moq" }),
12573
12698
  "no-multicast-bridge": Object.freeze({ state: "inactive", reason: "no-multicast-bridge" })
12574
12699
  });
12575
- function recordOf(value) {
12700
+ function recordOf2(value) {
12576
12701
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
12577
12702
  }
12578
- function isPositiveSafeInteger(value) {
12703
+ function isPositiveSafeInteger2(value) {
12579
12704
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
12580
12705
  }
12581
12706
  function catalogDeclaresFec(fec) {
12582
- const block = recordOf(fec);
12707
+ const block = recordOf2(fec);
12583
12708
  if (block === void 0 || block["algorithm"] === "none") return false;
12584
- return isPositiveSafeInteger(block["sourceSymbols"]) && isPositiveSafeInteger(block["symbolSize"]) && isFecBlockProfile(block["blockProfile"]) && isoBlockSpanUsable(block);
12585
- }
12586
- function isoBlockSpanUsable(fec) {
12587
- const block = recordOf(fec);
12588
- if (block === void 0 || block["blockProfile"] !== "iso-ssbg1-v1") return true;
12589
- const ms = block["interleaveDepthMs"];
12590
- return ms === void 0 || typeof ms === "number" && Number.isSafeInteger(ms) && ms >= 0;
12709
+ return isPositiveSafeInteger2(block["sourceSymbols"]) && isPositiveSafeInteger2(block["symbolSize"]) && isFecBlockProfile(block["blockProfile"]) && isoBlockSpanUsable(block) && !catalogFecDeclaresUnconfigurableInstance(block);
12591
12710
  }
12592
12711
  function requireBoolean(value, field) {
12593
12712
  if (typeof value !== "boolean") {
@@ -12603,7 +12722,7 @@ function resolveFecState(evidence) {
12603
12722
  if (typeof transportPolicy !== "string" || !TRANSPORT_POLICIES.has(transportPolicy)) {
12604
12723
  throw new TypeError(`resolveFecState: unsupported transportPolicy ${JSON.stringify(transportPolicy)}`);
12605
12724
  }
12606
- if (stats !== null && stats !== void 0 && recordOf(stats) === void 0) {
12725
+ if (stats !== null && stats !== void 0 && recordOf2(stats) === void 0) {
12607
12726
  throw new TypeError("resolveFecState: stats must be a plain object, null or undefined");
12608
12727
  }
12609
12728
  if (!catalogFec) return INACTIVE["no-catalog-fec"];
@@ -13308,12 +13427,17 @@ var FECManager = class _FECManager {
13308
13427
  // per stream. Not only throws: the ordinary out-of-range case is detected by
13309
13428
  // arithmetic and never throws at all.
13310
13429
  this.#orderedHorizonWarnedFor = /* @__PURE__ */ new Set();
13311
- // Newest block start (SS_Start) seen per stream and when: the frontier for
13312
- // source-discontinuity detection and isoSpanResolution.
13430
+ // Newest block start (SS_Start) any symbol carried per stream and when: the
13431
+ // frontier isoSpanResolution reads.
13313
13432
  this.#highestSbn = /* @__PURE__ */ new Map();
13433
+ // The same from source symbols alone: the frontier a source is judged
13434
+ // against for a discontinuity. Repairs ride their own group, which can run
13435
+ // blocks ahead of the media they protect.
13436
+ this.#sourceFrontiers = /* @__PURE__ */ new Map();
13314
13437
  // iso-ssbg1-v1 block location per stream (streamKey). A source belongs to a
13315
13438
  // block only once a repair symbol stated the block's (SS_Start, SSB_length).
13316
13439
  this.#isoLocators = /* @__PURE__ */ new Map();
13440
+ this.#deferIsoGaps = false;
13317
13441
  this.#isoRepairRefusedCount = 0;
13318
13442
  this.#isoSourceOversizeCount = 0;
13319
13443
  // Held sources a locator's capacity cap evicted (IsoBlockLocator.heldCapacity):
@@ -13328,8 +13452,8 @@ var FECManager = class _FECManager {
13328
13452
  // rate-limited like the other per-symbol warns here. Cumulative.
13329
13453
  this.#isoDecoderUnplacedRetireFailed = 0;
13330
13454
  // The latest source symbol per stream that carried its MMTP
13331
- // packet_sequence_number: the anchor that bounds how many blocks the
13332
- // producer can have started before a later source symbol.
13455
+ // packet_sequence_number, by its own SS_ID: the anchor that bounds how far
13456
+ // the producer's SS_IDs can have moved before or after another source symbol.
13333
13457
  this.#sourceAnchors = /* @__PURE__ */ new Map();
13334
13458
  // Catalog/reset epoch per packetId. Gap decisions carry it for fencing.
13335
13459
  this.#packetEpochs = /* @__PURE__ */ new Map();
@@ -13388,6 +13512,14 @@ var FECManager = class _FECManager {
13388
13512
  this.onBlockReclassified = null;
13389
13513
  /** A video stream's classifier mode was established or changed. */
13390
13514
  this.onClassifierMode = null;
13515
+ /**
13516
+ * A repair stated a block past a gap that is missing a source and whose
13517
+ * every repair was lost: a lost SS_ID in an undelimited span
13518
+ * (draft-ramadan-moq-fec §7.5). Set with `setUndelimitedLossHandler`; the
13519
+ * receiver keeps the gap as a pending hole until `closeIsoHoles` is called
13520
+ * for it, which it must be.
13521
+ */
13522
+ this.#onUndelimitedLoss = null;
13391
13523
  /** A block every symbol of which vanished was created by SBN evidence. */
13392
13524
  this.onBlockVanished = null;
13393
13525
  /** A block reached a terminal state (completed, recovered, or failed). */
@@ -13467,7 +13599,9 @@ var FECManager = class _FECManager {
13467
13599
  #materializedBlocks;
13468
13600
  #orderedHorizonWarnedFor;
13469
13601
  #highestSbn;
13602
+ #sourceFrontiers;
13470
13603
  #isoLocators;
13604
+ #deferIsoGaps;
13471
13605
  #isoRepairRefusedCount;
13472
13606
  #isoSourceOversizeCount;
13473
13607
  #isoHeldEvictedCount;
@@ -13481,6 +13615,7 @@ var FECManager = class _FECManager {
13481
13615
  #workerErrorCounts;
13482
13616
  #decoderUnavailableEvents;
13483
13617
  #repairSymbolSizeMismatchCount;
13618
+ #onUndelimitedLoss;
13484
13619
  #encodeTrackName(catalogTrackName) {
13485
13620
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
13486
13621
  if (encoded === void 0) {
@@ -14057,8 +14192,8 @@ var FECManager = class _FECManager {
14057
14192
  // Deliberately one block tighter than deriveFecRetentionBlocks over the same
14058
14193
  // inputs (that function's `+ 1`). Different question: the retention horizon
14059
14194
  // asks how long the decoder still ACCEPTS symbols for a block, this asks how
14060
- // many blocks a stream can live behind (or ahead of) its frontier before a
14061
- // source symbol there is a discontinuity rather than loss (see #noteSbnSeen).
14195
+ // many blocks a stream can jump ahead of its frontier before a source symbol
14196
+ // there is a discontinuity rather than loss (see #noteSbnSeen).
14062
14197
  // The extra block of retention is slack for a block still being fed; a block
14063
14198
  // nothing has been heard from does not get it. Not the units defect — but it
14064
14199
  // is the next place the two can drift, so change both or neither.
@@ -14068,55 +14203,72 @@ var FECManager = class _FECManager {
14068
14203
  }
14069
14204
  /**
14070
14205
  * Record that a symbol for block `sbn` (the block's SS_Start) arrived and
14071
- * advance the stream's frontier, the newest block start seen.
14206
+ * advance the stream's frontiers, the newest block start seen.
14072
14207
  *
14073
- * A SOURCE symbol whose block goes back further than one live window, or
14074
- * jumps further than the stream could have produced since its last symbol,
14075
- * is a source discontinuity, not loss. A repair symbol can only advance the
14208
+ * A SOURCE symbol is judged against the newest source block alone: repairs
14209
+ * ride their own group, which can run blocks ahead of the media. One whose
14210
+ * block goes back further than the blocks this manager retains, or that
14211
+ * cannot have been sent before the source it lies behind, or that jumps
14212
+ * further than the stream could have produced since its last symbol, is a
14213
+ * source discontinuity, not loss. A repair symbol can only advance the
14076
14214
  * frontier: a D-28 fetch legitimately answers for an old block, so it never
14077
14215
  * signals a discontinuity.
14078
14216
  *
14079
14217
  * The producer closes a block at its Dth media-unit boundary OR when K
14080
14218
  * source symbols filled it, so one interleave span can start several blocks
14081
- * (every large keyframe does). What bounds a forward jump is therefore
14082
- * packet evidence, not a block rate: SS_ID advances by one per FEC source
14083
- * packet (ISO/IEC 23008-1 C.5.2) and the MMTP packet_sequence_number by one
14084
- * per packet of the packet_id, so with both source symbols'
14085
- * packet_sequence_number a block start can move at most the packets sent
14086
- * between them plus the anchor's own offset into its block (< K). Without
14087
- * it, only the D-close rate is known.
14219
+ * (every large keyframe does). What bounds a jump is therefore packet
14220
+ * evidence, not a block rate: SS_ID advances by one per FEC source packet
14221
+ * (ISO/IEC 23008-1 C.5.2) and the MMTP packet_sequence_number by one per
14222
+ * packet of the packet_id, so with both source symbols'
14223
+ * packet_sequence_number their SS_IDs (`ssId`, not their block starts,
14224
+ * which a repair-less span can put far behind) can move at most the packets
14225
+ * sent between them, in either direction, plus K of slack for sources lost
14226
+ * before a hop that renumbers packets. Without it, only the D-close rate is
14227
+ * known.
14088
14228
  *
14089
14229
  * Vanished blocks are not enumerated here: their starts are unknown until a
14090
14230
  * repair states them. The SS_IDs between two stated blocks become one
14091
14231
  * repair-less span when the later block's repair arrives (placeIsoRepair).
14092
14232
  */
14093
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber) {
14233
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
14094
14234
  const streamKey = this.#streamKey(packetId, catalogTrackName);
14095
14235
  const now = performance.now();
14096
- const previous = this.#highestSbn.get(streamKey);
14236
+ const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
14097
14237
  const anchor = this.#sourceAnchors.get(streamKey);
14098
14238
  const psn = symbol === "source" && packetSequenceNumber !== void 0 && Number.isSafeInteger(packetSequenceNumber) && packetSequenceNumber >= 0 && packetSequenceNumber <= 4294967295 ? packetSequenceNumber : void 0;
14099
14239
  const anchorHere = () => {
14100
- if (psn !== void 0 && (anchor === void 0 || !this.#blockPrecedes(sbn, anchor.sbn))) {
14101
- this.#sourceAnchors.set(streamKey, { sbn, psn, atMs: now });
14240
+ if (psn !== void 0 && (anchor === void 0 || !serial32Precedes(ssId, anchor.ssId))) {
14241
+ this.#sourceAnchors.set(streamKey, { ssId, psn, atMs: now });
14242
+ }
14243
+ };
14244
+ const advance = () => {
14245
+ const highest = this.#highestSbn.get(streamKey);
14246
+ if (highest === void 0 || this.#blockPrecedes(highest.sbn, sbn)) {
14247
+ this.#highestSbn.set(streamKey, { sbn, atMs: now });
14102
14248
  }
14249
+ if (symbol === "source") this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
14250
+ anchorHere();
14103
14251
  };
14104
14252
  const discontinuity = () => {
14105
14253
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity();
14106
14254
  this.#highestSbn.set(streamKey, { sbn, atMs: now });
14255
+ this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
14107
14256
  if (psn === void 0) this.#sourceAnchors.delete(streamKey);
14108
- else this.#sourceAnchors.set(streamKey, { sbn, psn, atMs: now });
14257
+ else this.#sourceAnchors.set(streamKey, { ssId, psn, atMs: now });
14109
14258
  this.onSourceDiscontinuity?.(packetId, catalogTrackName);
14110
14259
  };
14111
14260
  if (previous === void 0) {
14112
- this.#highestSbn.set(streamKey, { sbn, atMs: now });
14113
- anchorHere();
14261
+ advance();
14114
14262
  return;
14115
14263
  }
14116
14264
  const config = this.#trackConfig(packetId);
14117
14265
  const window2 = this.#liveWindowBlocks(config);
14266
+ const sentInOrder = (from, to) => {
14267
+ const sent = to.psn - from.psn >>> 0;
14268
+ return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
14269
+ };
14118
14270
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
14119
- if (symbol === "source" && window2 !== null && this.#blocksBehind(sbn, previous.sbn, packetId) > window2) {
14271
+ 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))) {
14120
14272
  discontinuity();
14121
14273
  return;
14122
14274
  }
@@ -14126,9 +14278,8 @@ var FECManager = class _FECManager {
14126
14278
  const missing = this.#blocksBehind(previous.sbn, sbn, packetId) - 1;
14127
14279
  let plausible = true;
14128
14280
  if (window2 !== null) {
14129
- if (psn !== void 0 && anchor !== void 0 && this.#blockPrecedes(anchor.sbn, sbn) && psn !== anchor.psn) {
14130
- const sent = psn - anchor.psn >>> 0;
14131
- plausible = sent <= 2147483647 && serial32Distance(anchor.sbn, sbn) <= sent + config.k;
14281
+ if (psn !== void 0 && anchor !== void 0 && serial32Precedes(anchor.ssId, ssId) && psn !== anchor.psn) {
14282
+ plausible = sentInOrder(anchor, { ssId, psn });
14132
14283
  } else {
14133
14284
  plausible = missing <= window2 + Math.ceil((now - previous.atMs) / config.interleaveDepthMs);
14134
14285
  }
@@ -14138,8 +14289,7 @@ var FECManager = class _FECManager {
14138
14289
  discontinuity();
14139
14290
  return;
14140
14291
  }
14141
- this.#highestSbn.set(streamKey, { sbn, atMs: now });
14142
- anchorHere();
14292
+ advance();
14143
14293
  }
14144
14294
  /*
14145
14295
  * Block order for one stream (BLO-35597 iso:5). A block is keyed by its
@@ -14723,6 +14873,7 @@ var FECManager = class _FECManager {
14723
14873
  resetSet(this.#materializedBlocks);
14724
14874
  resetMap(this.#resolvedBlockClasses);
14725
14875
  resetMap(this.#highestSbn);
14876
+ resetMap(this.#sourceFrontiers);
14726
14877
  resetMap(this.#isoLocators);
14727
14878
  resetMap(this.#sourceAnchors);
14728
14879
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName));
@@ -14828,6 +14979,7 @@ var FECManager = class _FECManager {
14828
14979
  dropMap(this.#orderedPendingBlocks);
14829
14980
  dropMap(this.#resolvedBlockClasses);
14830
14981
  dropMap(this.#highestSbn);
14982
+ dropMap(this.#sourceFrontiers);
14831
14983
  dropMap(this.#isoLocators);
14832
14984
  dropMap(this.#sourceAnchors);
14833
14985
  dropMap(this.#classifiers);
@@ -14920,7 +15072,13 @@ var FECManager = class _FECManager {
14920
15072
  if (isSourceSymbol && esi === 0) {
14921
15073
  this.#startupPartialBlocks.delete(blockKey);
14922
15074
  this.#startupAlignedPackets.add(streamKey);
14923
- } else if (isStartupPartial && !isReadyMulticastRepair || !this.#startupAlignedPackets.has(streamKey) && !isReadyMulticastRepair) {
15075
+ } else if (
15076
+ // A ready multicast repair opens a block the join has not seen yet, never
15077
+ // a join partial: its sources were refused, so its repairs alone open a
15078
+ // block that cannot decode and fails at its deadline, once per packet ID
15079
+ // per join (BLO-48308).
15080
+ isStartupPartial || !this.#startupAlignedPackets.has(streamKey) && !isReadyMulticastRepair
15081
+ ) {
14924
15082
  this.#markStartupPartial(blockKey);
14925
15083
  return false;
14926
15084
  }
@@ -15202,6 +15360,7 @@ var FECManager = class _FECManager {
15202
15360
  let locator = this.#isoLocators.get(streamKey);
15203
15361
  if (!locator) {
15204
15362
  locator = new IsoBlockLocator(this.#trackConfig(packetId).k, this.#isoRetentionBlocks(packetId));
15363
+ locator.deferIncompleteGaps = this.#deferIsoGaps;
15205
15364
  this.#isoLocators.set(streamKey, locator);
15206
15365
  }
15207
15366
  return locator;
@@ -15245,6 +15404,10 @@ var FECManager = class _FECManager {
15245
15404
  }
15246
15405
  return blocks;
15247
15406
  }
15407
+ /** The iso-ssbg1-v1 locator horizon of a configured packetId, in blocks (#isoRetentionBlocks). */
15408
+ isoRetentionBlocksForPacket(packetId) {
15409
+ return this.#hasBlockProfile(packetId) ? this.#isoRetentionBlocks(packetId) : void 0;
15410
+ }
15248
15411
  /** Whether an iso-ssbg1-v1 protected packet fits one ssbg_mode1 symbol (len + 2 <= T). */
15249
15412
  isoSourceFits(packetId, packetLength) {
15250
15413
  const symbolSize = this.#trackConfigs.get(packetId)?.symbolSize;
@@ -15294,15 +15457,61 @@ var FECManager = class _FECManager {
15294
15457
  }
15295
15458
  return placement;
15296
15459
  }
15297
- if (placement.span !== void 0) {
15298
- const key = this.#blockKey(placement.span.block.start, packetId, catalogTrackName);
15299
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, placement.span.block.length);
15300
- }
15301
- if (placement.span !== void 0 && placement.span.placed.length === 0) {
15302
- this.#materializeBlock(placement.span.block.start, packetId, catalogTrackName, true);
15460
+ if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
15461
+ if (placement.hole !== void 0) {
15462
+ const locator = this.#isoLocatorFor(packetId, catalogTrackName);
15463
+ const hole = placement.hole.block;
15464
+ const previous = locator.blockEndingAt(hole.start);
15465
+ const loss = {
15466
+ packetId,
15467
+ catalogTrackName,
15468
+ holeStart: hole.start,
15469
+ holeLength: hole.length,
15470
+ lostSsId: placement.hole.lostSsId,
15471
+ kMax: this.#trackConfig(packetId).k,
15472
+ ...previous === void 0 ? {} : { previousBlockStart: previous.start }
15473
+ };
15474
+ this.#onUndelimitedLoss(loss);
15303
15475
  }
15304
15476
  return placement;
15305
15477
  }
15478
+ /**
15479
+ * Keep an iso-ssbg1-v1 gap missing a source as a pending hole, reported to
15480
+ * `handler`, instead of a repair-less span; null restores spans. Set by the
15481
+ * range repair scheduler; applies to every stream from its next gap. The
15482
+ * handler and the deferral are one setting, so no hole is ever created with
15483
+ * nobody to close it.
15484
+ */
15485
+ setUndelimitedLossHandler(handler) {
15486
+ this.#onUndelimitedLoss = handler;
15487
+ this.#deferIsoGaps = handler !== null;
15488
+ for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
15489
+ }
15490
+ /**
15491
+ * The range repair for a hole ended: every hole still pending inside
15492
+ * `[start, start + length)` becomes a repair-less span. Returns those spans
15493
+ * with the held sources they placed, for the caller to feed (MmtpRouter).
15494
+ */
15495
+ closeIsoHoles(packetId, catalogTrackName, start, length) {
15496
+ const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
15497
+ if (locator === void 0) return [];
15498
+ const spans = locator.closeHolesWithin(start, length);
15499
+ for (const span of spans) this.#openIsoSpan(span, packetId, catalogTrackName);
15500
+ return spans;
15501
+ }
15502
+ /**
15503
+ * A repair-less span has no repair to state its length, so it is known
15504
+ * here: its sources make it clean exactly when all of them arrived. A
15505
+ * stated block learns its SSB_length from its own repair symbol, fed after
15506
+ * its placed sources exactly as on the wire (feedRepairSymbol). A span every
15507
+ * SS_ID of which vanished resolves through its deadline like any vanished
15508
+ * block.
15509
+ */
15510
+ #openIsoSpan(span, packetId, catalogTrackName) {
15511
+ const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
15512
+ if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
15513
+ if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
15514
+ }
15306
15515
  /**
15307
15516
  * Resolution of the SS_IDs strictly between two released frames' SS_IDs on
15308
15517
  * an iso-ssbg1-v1 stream, for in-order frame release: null while a block
@@ -15826,20 +16035,37 @@ var FECManager = class _FECManager {
15826
16035
  * Caller is responsible for routing recovered data and updating
15827
16036
  * block completion state via `markBlockCompleted()`.
15828
16037
  */
15829
- feedRepairSymbol(packetId, ssStart, ssbLength, rsId, repairData, catalogTrackName) {
15830
- this.#fecStats.repairPackets++;
15831
- this.#statsForPacket(packetId).repairPackets++;
15832
- if (!this.#hasBlockProfile(packetId)) return null;
16038
+ /**
16039
+ * Whether a repair symbol of `byteLength` bytes is a valid member of a
16040
+ * `packetId` block: every repair symbol is exactly the track's T. A symbol of
16041
+ * any other size is counted on `repairSymbolSizeMismatches`, warned (rate
16042
+ * limited) and refused. The router calls this before the symbol takes any
16043
+ * other part in block state (placement, first-arrival dedup, completed-block
16044
+ * accounting), so a malformed repair is counted whatever its arrival order:
16045
+ * judged after dedup, one landing on an already-complete block, or behind a
16046
+ * valid copy from the other transport, was swallowed as a duplicate and never
16047
+ * counted (BLO-48306). A packetId with no configured block profile admits
16048
+ * nothing here; its repair is dropped upstream as unreadable.
16049
+ */
16050
+ admitRepairSymbolSize(packetId, ssStart, ssbLength, rsId, byteLength) {
16051
+ if (!this.#hasBlockProfile(packetId)) return false;
15833
16052
  const symbolSize = this.#trackConfig(packetId).symbolSize;
15834
- if (symbolSize > 0 && repairData.byteLength !== symbolSize) {
16053
+ if (symbolSize > 0 && byteLength !== symbolSize) {
15835
16054
  this.#repairSymbolSizeMismatchCount++;
15836
16055
  if (this.#repairSymbolSizeMismatchCount <= 5 || this.#repairSymbolSizeMismatchCount % 100 === 0) {
15837
16056
  console.warn(
15838
- `[FECManager] Dropping repair symbol with invalid size: got ${repairData.byteLength}B, expected ${symbolSize}B (packetId=${packetId}, ssStart=${ssStart}, ssbLength=${ssbLength}, rsId=${rsId})`
16057
+ `[FECManager] Dropping repair symbol with invalid size: got ${byteLength}B, expected ${symbolSize}B (packetId=${packetId}, ssStart=${ssStart}, ssbLength=${ssbLength}, rsId=${rsId})`
15839
16058
  );
15840
16059
  }
15841
- return null;
16060
+ return false;
15842
16061
  }
16062
+ return true;
16063
+ }
16064
+ feedRepairSymbol(packetId, ssStart, ssbLength, rsId, repairData, catalogTrackName) {
16065
+ this.#fecStats.repairPackets++;
16066
+ this.#statsForPacket(packetId).repairPackets++;
16067
+ if (!this.#hasBlockProfile(packetId)) return null;
16068
+ if (!this.admitRepairSymbolSize(packetId, ssStart, ssbLength, rsId, repairData.byteLength)) return null;
15843
16069
  const fecData = repairData;
15844
16070
  const k = this.#trackConfig(packetId).k;
15845
16071
  const block = this.#isoLocatorFor(packetId, catalogTrackName).blockAt(ssStart);
@@ -15992,7 +16218,14 @@ var FECManager = class _FECManager {
15992
16218
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
15993
16219
  const k = trackConfig.k;
15994
16220
  if (this.#completedBlocks.has(key)) return;
15995
- this.#noteSbnSeen(sbn, packetId, catalogTrackName, "source", evidence.packetSequenceNumber);
16221
+ this.#noteSbnSeen(
16222
+ sbn,
16223
+ packetId,
16224
+ catalogTrackName,
16225
+ "source",
16226
+ evidence.packetSequenceNumber,
16227
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
16228
+ );
15996
16229
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
15997
16230
  if (Number.isInteger(esi) && esi >= authoredLength) {
15998
16231
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -16243,6 +16476,7 @@ var FECManager = class _FECManager {
16243
16476
  this.#repairedBlocks.clear();
16244
16477
  this.#materializedBlocks.clear();
16245
16478
  this.#highestSbn.clear();
16479
+ this.#sourceFrontiers.clear();
16246
16480
  this.#isoLocators.clear();
16247
16481
  this.#sourceAnchors.clear();
16248
16482
  this.#trackConfigs.clear();
@@ -17332,6 +17566,7 @@ function isFmp4Box(data) {
17332
17566
  const type = String.fromCharCode(data[4], data[5], data[6], data[7]);
17333
17567
  return FMPU_BOX_TYPES.has(type);
17334
17568
  }
17569
+ var MAX_AWAITING_TIMING_HEADS = 8;
17335
17570
  var MmtpContainerParser = class _MmtpContainerParser {
17336
17571
  constructor(config) {
17337
17572
  this.#tracks = /* @__PURE__ */ new Map();
@@ -17390,6 +17625,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
17390
17625
  * reordering into the parser. */
17391
17626
  this.#reliableMoqStartupGate = /* @__PURE__ */ new Map();
17392
17627
  this.#disposed = false;
17628
+ this.#replayingAwaitingTiming = false;
17393
17629
  this.#fedObjects = 0;
17394
17630
  this.#reassemblerFragmentsFed = 0;
17395
17631
  this.#reassemblerDataUnitsReturned = 0;
@@ -17482,6 +17718,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
17482
17718
  #reorderStats;
17483
17719
  #reliableMoqStartupGate;
17484
17720
  #disposed;
17721
+ #replayingAwaitingTiming;
17485
17722
  #fedObjects;
17486
17723
  #reassemblerFragmentsFed;
17487
17724
  #reassemblerDataUnitsReturned;
@@ -17731,7 +17968,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
17731
17968
  * a single failure bucket. Returns null so call sites stay `return this.#drop(...)`.
17732
17969
  */
17733
17970
  #drop(reason) {
17734
- this.#countOutcome(`drop:${reason}`);
17971
+ if (this.#replayingAwaitingTiming) this.#countDeferredOutcome(reason);
17972
+ else this.#countOutcome(`drop:${reason}`);
17735
17973
  return null;
17736
17974
  }
17737
17975
  get reorderDiagnostics() {
@@ -17754,6 +17992,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
17754
17992
  for (const combiner of this.#sampleCombiners.values()) {
17755
17993
  combiner.cleanupTimeouts(timeoutMs);
17756
17994
  }
17995
+ const now = Date.now();
17996
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
17997
+ while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
17998
+ awaitingTiming.shift();
17999
+ }
18000
+ }
17757
18001
  }
17758
18002
  /**
17759
18003
  * Phase 1 of two-phase parsing. Returns structured header info for FEC feeding.
@@ -17834,7 +18078,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
17834
18078
  byteLength: packet.byteLength
17835
18079
  };
17836
18080
  }
17837
- if (info.fecPayloadId !== null && this.#sourceSymbolCb) {
18081
+ if (info.fecPayloadId !== null && this.#sourceSymbolCb && !this.#replayingAwaitingTiming) {
17838
18082
  const rawSymbol = packet.subarray(0, packet.length - 4);
17839
18083
  try {
17840
18084
  this.#sourceSymbolCb(info.packetId, info.fecPayloadId.ssId, rawSymbol);
@@ -17882,6 +18126,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
17882
18126
  }
17883
18127
  return this.#drop("fragment-timing-refused");
17884
18128
  }
18129
+ this.#replayAwaitingTiming(streamKey, resolver2);
17885
18130
  return {
17886
18131
  kind: "fragment",
17887
18132
  packet: info,
@@ -17905,7 +18150,18 @@ var MmtpContainerParser = class _MmtpContainerParser {
17905
18150
  mfuDuHeader.movieFragmentSequenceNumber,
17906
18151
  mfuDuHeader.sampleNumber
17907
18152
  );
17908
- if (!headTiming) return this.#drop("mfu-sample-timing-missing");
18153
+ if (!headTiming) {
18154
+ this.#awaitTiming(streamKey, {
18155
+ packet,
18156
+ options,
18157
+ parsed,
18158
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
18159
+ movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
18160
+ sampleNumber: mfuDuHeader.sampleNumber,
18161
+ arrivedAt: Date.now()
18162
+ });
18163
+ return this.#drop("mfu-sample-timing-missing");
18164
+ }
17909
18165
  const offset = mfuDuHeader.offset;
17910
18166
  if (!Number.isSafeInteger(offset) || offset < 0 || offset >= headTiming.size)
17911
18167
  return this.#drop("mfu-offset-out-of-range");
@@ -17981,16 +18237,17 @@ var MmtpContainerParser = class _MmtpContainerParser {
17981
18237
  const sampleNumber = assembled.sampleNumber;
17982
18238
  if (movieFragmentSequenceNumber === void 0 || sampleNumber === void 0)
17983
18239
  return this.#drop("assembled-identity-missing");
17984
- if (!resolver.sampleTiming(
18240
+ const assembledTiming = resolver.sampleTiming(
17985
18241
  assembled.mpuSequenceNumber,
17986
18242
  movieFragmentSequenceNumber,
17987
18243
  sampleNumber
17988
- )) return this.#drop("assembled-timing-missing");
18244
+ );
18245
+ if (!assembledTiming) return this.#drop("assembled-timing-missing");
17989
18246
  if (assembled.mpuSequenceNumber !== mpu.mpuSequenceNumber)
17990
18247
  return this.#drop("assembled-mpu-mismatch");
17991
18248
  let combined;
17992
18249
  try {
17993
- combined = this.#sampleCombinerFor(streamKey).addMfu(assembled);
18250
+ combined = this.#sampleCombinerFor(streamKey).addMfu(assembled, assembledTiming.size);
17994
18251
  } catch (error) {
17995
18252
  if (!(error instanceof SampleCombineError)) throw error;
17996
18253
  console.warn(
@@ -18299,9 +18556,37 @@ var MmtpContainerParser = class _MmtpContainerParser {
18299
18556
  if (existing) return existing.resolver;
18300
18557
  if (!create) return null;
18301
18558
  const resolver = new IsoBmffTimingResolver(this.#maxPendingTimingSamples);
18302
- this.#timingStreams.set(streamKey, { packetId, resolver });
18559
+ this.#timingStreams.set(streamKey, { packetId, resolver, awaitingTiming: [] });
18303
18560
  return resolver;
18304
18561
  }
18562
+ #awaitTiming(streamKey, head) {
18563
+ const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
18564
+ if (!awaitingTiming) return;
18565
+ awaitingTiming.push(head);
18566
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
18567
+ }
18568
+ /**
18569
+ * Feed again the heads whose timing the FT=1 just admitted declares. That
18570
+ * FT=1 can be an FEC recovery landing after its sample's FI=1, and neither
18571
+ * FEC path routes a source symbol that already arrived a second time.
18572
+ */
18573
+ #replayAwaitingTiming(streamKey, resolver) {
18574
+ const state = this.#timingStreams.get(streamKey);
18575
+ if (!state || state.awaitingTiming.length === 0) return;
18576
+ const ready = state.awaitingTiming.filter((head) => resolver.sampleTiming(
18577
+ head.mpuSequenceNumber,
18578
+ head.movieFragmentSequenceNumber,
18579
+ head.sampleNumber
18580
+ ));
18581
+ if (ready.length === 0) return;
18582
+ state.awaitingTiming = state.awaitingTiming.filter((head) => !ready.includes(head));
18583
+ this.#replayingAwaitingTiming = true;
18584
+ try {
18585
+ for (const head of ready) this.#feed(head.packet, head.options, head.parsed);
18586
+ } finally {
18587
+ this.#replayingAwaitingTiming = false;
18588
+ }
18589
+ }
18305
18590
  #dropTimingStream(streamKey) {
18306
18591
  const state = this.#timingStreams.get(streamKey);
18307
18592
  if (!state) return;
@@ -18906,6 +19191,18 @@ var MmtpRouter = class {
18906
19191
  // MSE recovery routes through CmafBlockAssembler and can reorder by block; the
18907
19192
  // direct callback path has to preserve decode order before frames leave libmmt.
18908
19193
  #latestVideoSeqByStream = /* @__PURE__ */ new Map();
19194
+ /**
19195
+ * Per stream, SS_ID - packet_sequence_number (mod 2^32) of its latest
19196
+ * first-arrival FEC source packet. A recovered source symbol's wire
19197
+ * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
19198
+ */
19199
+ #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
19200
+ /**
19201
+ * Streams whose multicast leg delivered a RAP-flagged source packet that was
19202
+ * not parsed, typically because its overlap copy was parsed first
19203
+ * (BLO-49179). The next video keyframe emitted on the stream consumes it.
19204
+ */
19205
+ #multicastRapTwinByStream = /* @__PURE__ */ new Set();
18909
19206
  #lastDirectSourceVideoTsByStream = /* @__PURE__ */ new Map();
18910
19207
  #lastDirectEmittedVideoTsByStream = /* @__PURE__ */ new Map();
18911
19208
  #pendingDirectRecoveredVideoByStream = /* @__PURE__ */ new Map();
@@ -18980,6 +19277,7 @@ var MmtpRouter = class {
18980
19277
  */
18981
19278
  #onPublisherRestart;
18982
19279
  #publisherRestarts = 0;
19280
+ #restampedRecoveredSeqs = 0;
18983
19281
  /** Inits delivered with no onTrackInit handler for their packetId (MOQT-01). */
18984
19282
  #unmappedInitDeliveries = 0;
18985
19283
  // FEC Payload IDs left unread because their (owner) packetId had no
@@ -19038,6 +19336,12 @@ var MmtpRouter = class {
19038
19336
  ...meta.catalogTrackName === void 0 ? {} : { catalogTrackName: meta.catalogTrackName }
19039
19337
  };
19040
19338
  if (meta.source) frameMeta.source = meta.source;
19339
+ if (isVideo && frameMeta.keyframe) {
19340
+ const twinSeen = this.#multicastRapTwinByStream.delete(
19341
+ this.#mediaStreamKey(packetId, frameMeta.catalogTrackName)
19342
+ );
19343
+ if (twinSeen && frameMeta.source === "moq") frameMeta.source = "multicast";
19344
+ }
19041
19345
  if (meta.deliveryProvenance !== void 0)
19042
19346
  frameMeta.deliveryProvenance = meta.deliveryProvenance;
19043
19347
  if (meta.recovered) frameMeta.recovered = true;
@@ -19200,6 +19504,14 @@ var MmtpRouter = class {
19200
19504
  get publisherRestartCount() {
19201
19505
  return this.#publisherRestarts;
19202
19506
  }
19507
+ /**
19508
+ * FEC-recovered source symbols whose reconstructed header named a
19509
+ * packet_sequence_number other than the wire sequence their SS_ID maps to:
19510
+ * a hop re-stamped the sequence after the sender protected the packet.
19511
+ */
19512
+ get restampedRecoveredSequenceCount() {
19513
+ return this.#restampedRecoveredSeqs;
19514
+ }
19203
19515
  /**
19204
19516
  * Packets whose Source or Repair FEC Payload ID was left unread because
19205
19517
  * their (owner) packetId had no configured `fec.blockProfile`: FEC not
@@ -19715,6 +20027,13 @@ var MmtpRouter = class {
19715
20027
  `[MmtpRouter] packetId=${ownerPacketId} is iso-ssbg1-v1 but its FEC manager cannot place ISO blocks`
19716
20028
  );
19717
20029
  }
20030
+ if (fec.admitRepairSymbolSize && !fec.admitRepairSymbolSize(
20031
+ ownerPacketId,
20032
+ repair.ssStart,
20033
+ repair.ssbLength,
20034
+ repair.rsId,
20035
+ repair.symbolData.byteLength
20036
+ )) return;
19718
20037
  const placement = fec.placeIsoRepair(ownerPacketId, catalogTrackName, repair.ssStart, repair.ssbLength);
19719
20038
  if (placement.status !== "placed") return;
19720
20039
  const blockStart = placement.block.start;
@@ -19749,6 +20068,17 @@ var MmtpRouter = class {
19749
20068
  this.#routeRecoveredBlock(blockStart, recovered, ownerPacketId, catalogTrackName);
19750
20069
  }
19751
20070
  }
20071
+ /**
20072
+ * The range repair FETCH for an undelimited hole ended (draft-ramadan-moq-fec
20073
+ * §7.5): what no repair stated becomes repair-less spans, whose held sources
20074
+ * are fed exactly as a span a repair closed.
20075
+ */
20076
+ closeIsoHoles(ownerPacketId, catalogTrackName, start, length) {
20077
+ const spans = this.#fecManager?.closeIsoHoles?.(ownerPacketId, catalogTrackName, start, length) ?? [];
20078
+ for (const span of spans) {
20079
+ this.#replayIsoSources(ownerPacketId, catalogTrackName, span.block.start, span.placed);
20080
+ }
20081
+ }
19752
20082
  /**
19753
20083
  * Feed iso-ssbg1-v1 sources a repair just placed, in SS_ID order, exactly as
19754
20084
  * a first-arrival source is fed once its block is known: transport
@@ -19844,6 +20174,8 @@ var MmtpRouter = class {
19844
20174
  this.#trackSynced.delete(streamKey);
19845
20175
  this.#droppedPreSyncVideo.delete(streamKey);
19846
20176
  this.#latestVideoSeqByStream.delete(streamKey);
20177
+ this.#ssIdSeqOffsetByStream.delete(streamKey);
20178
+ this.#multicastRapTwinByStream.delete(streamKey);
19847
20179
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
19848
20180
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
19849
20181
  this.#pendingDirectRecoveredVideoByStream.delete(streamKey);
@@ -20614,6 +20946,12 @@ var MmtpRouter = class {
20614
20946
  } else if (fecUnreadable && info.fecPayloadId) {
20615
20947
  parseSourceSymbol = !duplicates.parsedSymbols.has(info.fecPayloadId.ssId);
20616
20948
  }
20949
+ if (fecPayloadId && !overlapCopy) {
20950
+ this.#ssIdSeqOffsetByStream.set(
20951
+ this.#mediaStreamKey(info.packetId, catalogTrackName),
20952
+ fecPayloadId.ssId - info.sequenceNumber >>> 0
20953
+ );
20954
+ }
20617
20955
  if (!this.#fecManager || !info.fecPayloadId || parseSourceSymbol) {
20618
20956
  if (this.#fecManager && info.fecPayloadId) {
20619
20957
  duplicates.parsedSymbols.add(info.fecPayloadId.ssId);
@@ -20624,6 +20962,8 @@ var MmtpRouter = class {
20624
20962
  catalogTrackName
20625
20963
  );
20626
20964
  this.#routeTrackPacket(packet, info.packetId, info.sequenceNumber, {
20965
+ mmtpTimestamp: parsed.header.timestamp,
20966
+ rap: info.rapFlag,
20627
20967
  recovered: false,
20628
20968
  skipFecPayloadId: false,
20629
20969
  catalogTrackName
@@ -20634,6 +20974,10 @@ var MmtpRouter = class {
20634
20974
  // An FEC source frame is anchored by its own SS_ID (C.5.2).
20635
20975
  ...fecSource && fecPayloadId ? { fecSbn: fecPayloadId.ssId } : {}
20636
20976
  }, parsed);
20977
+ } else if (source === "multicast" && info.rapFlag) {
20978
+ this.#multicastRapTwinByStream.add(
20979
+ this.#mediaStreamKey(info.packetId, catalogTrackName)
20980
+ );
20637
20981
  }
20638
20982
  if (this.#classifyPacketId(info.packetId) === null) return;
20639
20983
  if (this.#fecManager && fecPayloadId && coords && sourceSymbolAccepted && sourceSymbolTrackable) {
@@ -20811,6 +21155,8 @@ var MmtpRouter = class {
20811
21155
  callback(packet, {
20812
21156
  packetId,
20813
21157
  packetSequenceNumber,
21158
+ mmtpTimestamp: meta.mmtpTimestamp,
21159
+ rap: meta.rap,
20814
21160
  recovered: meta.recovered,
20815
21161
  skipFecPayloadId: meta.skipFecPayloadId,
20816
21162
  ...meta.catalogTrackName === void 0 ? {} : { catalogTrackName: meta.catalogTrackName },
@@ -21186,6 +21532,20 @@ var MmtpRouter = class {
21186
21532
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName) {
21187
21533
  if (ownerPacketId == null) return;
21188
21534
  if (this.#classifyPacketId(ownerPacketId) === null) return;
21535
+ const ssIdSeqOffset = this.#ssIdSeqOffsetByStream.get(
21536
+ this.#mediaStreamKey(ownerPacketId, catalogTrackName)
21537
+ );
21538
+ if (ssIdSeqOffset !== void 0) {
21539
+ result = {
21540
+ ...result,
21541
+ symbols: result.symbols.map((sym) => {
21542
+ const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
21543
+ if (wire === sym.packetSequenceNumber) return sym;
21544
+ this.#restampedRecoveredSeqs++;
21545
+ return { ...sym, packetSequenceNumber: wire };
21546
+ })
21547
+ };
21548
+ }
21189
21549
  this.#stream(ownerPacketId, catalogTrackName).duplicates.advance(blockId);
21190
21550
  const deliveryProvenance = this.#fecManager?.blockDeliveryProvenance?.(
21191
21551
  blockId,
@@ -21194,6 +21554,8 @@ var MmtpRouter = class {
21194
21554
  ) ?? "unknown";
21195
21555
  for (const sym of result.symbols) {
21196
21556
  this.#routeTrackPacket(sym.rawSymbol, ownerPacketId, sym.packetSequenceNumber, {
21557
+ mmtpTimestamp: sym.fragment.timestamp,
21558
+ rap: sym.fragment.rapFlag,
21197
21559
  recovered: true,
21198
21560
  skipFecPayloadId: true,
21199
21561
  catalogTrackName,
@@ -22009,7 +22371,7 @@ function sameIds(a, b) {
22009
22371
  for (const id of a) if (!b.has(id)) return false;
22010
22372
  return true;
22011
22373
  }
22012
- var MulticastTransport = class _MulticastTransport {
22374
+ var MulticastTransport = class {
22013
22375
  #onPacket;
22014
22376
  #subscription = null;
22015
22377
  #packetListener = null;
@@ -22081,8 +22443,11 @@ var MulticastTransport = class _MulticastTransport {
22081
22443
  // droppedPacketIds.
22082
22444
  #unadvertisedPacketIds = /* @__PURE__ */ new Set();
22083
22445
  #joinGeneration = 0;
22084
- constructor(onPacket) {
22446
+ // The provider to subscribe through; window.multicast when unset.
22447
+ #gateway;
22448
+ constructor(onPacket, options = {}) {
22085
22449
  this.#onPacket = onPacket;
22450
+ this.#gateway = options.gateway;
22086
22451
  }
22087
22452
  static isAvailable() {
22088
22453
  return hasMulticastGateway();
@@ -22092,7 +22457,8 @@ var MulticastTransport = class _MulticastTransport {
22092
22457
  this.#releaseSubscription();
22093
22458
  this.#dataPlaneLive = false;
22094
22459
  if (this.#disposed) return this.#declined(generation, "disposed");
22095
- if (!_MulticastTransport.isAvailable()) {
22460
+ const gateway = this.#gateway ?? getMulticastGlobals().multicast;
22461
+ if (typeof gateway?.subscribe !== "function") {
22096
22462
  console.warn("[MulticastTransport] Multicast API not available");
22097
22463
  return this.#declined(generation, "unavailable");
22098
22464
  }
@@ -22109,11 +22475,12 @@ var MulticastTransport = class _MulticastTransport {
22109
22475
  mode: config.mode,
22110
22476
  amtRelay: config.amtRelay,
22111
22477
  amtRelayPort: config.amtRelayPort,
22478
+ amtDiscovery: config.amtDiscovery,
22112
22479
  packetIds: config.packetIds,
22113
22480
  tracks: config.tracks
22114
22481
  });
22115
22482
  failure = "provider-rejected";
22116
- const subscription = await getMulticastGlobals().multicast.subscribe(subscribeConfig);
22483
+ const subscription = await gateway.subscribe(subscribeConfig);
22117
22484
  failure = "invalid-subscription";
22118
22485
  console.log(`[MulticastTransport] window.multicast.subscribe returned:`, !!subscription);
22119
22486
  if (this.#disposed || generation !== this.#joinGeneration) {
@@ -22769,28 +23136,28 @@ function joinedRepairSymbolCount(params, joinedRepairTrackNames) {
22769
23136
  }
22770
23137
  return total;
22771
23138
  }
22772
- function recordOf2(value) {
23139
+ function recordOf3(value) {
22773
23140
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
22774
23141
  }
22775
23142
  function msfTracks(catalog) {
22776
23143
  const raw = catalog.tracks;
22777
23144
  if (!Array.isArray(raw)) return void 0;
22778
- return { tracks: raw.map((t) => recordOf2(t) ?? {}) };
23145
+ return { tracks: raw.map((t) => recordOf3(t) ?? {}) };
22779
23146
  }
22780
23147
  function resolveRepairLayers(catalog, source) {
22781
23148
  if (!catalog) return void 0;
22782
23149
  const sourceName = typeof source === "string" ? source : source.name;
22783
23150
  const hang = catalog;
22784
23151
  const roles = typeof source === "string" ? ["video", "audio"] : source.type === "audio" ? ["audio"] : source.type === "video" ? ["video"] : ["video", "audio"];
22785
- const role = roles.find((r) => recordOf2(hang[r]?.renditions?.[sourceName]) !== void 0);
22786
- if (role !== void 0) {
22787
- const renditionPath = `$.${role}.renditions[${JSON.stringify(sourceName)}]`;
22788
- const rendition = recordOf2(hang[role].renditions[sourceName]);
23152
+ const located = locateCatalogFecSource(catalog, sourceName, roles);
23153
+ if (located?.dialect === "hang") {
23154
+ const renditionPath = `$.${located.role}.renditions[${JSON.stringify(sourceName)}]`;
23155
+ const rendition = located.entry;
22789
23156
  rejectRepairFieldsOnMediaTrack(renditionPath, rendition, throwRepairContractError);
22790
- const repairRenditions = recordOf2(hang.repair?.renditions) ?? {};
23157
+ const repairRenditions = recordOf3(hang.repair?.renditions) ?? {};
22791
23158
  const descriptors2 = Object.entries(repairRenditions).map(([name, entry]) => {
22792
23159
  const path = `$.repair.renditions[${JSON.stringify(name)}]`;
22793
- const fields = recordOf2(entry);
23160
+ const fields = recordOf3(entry);
22794
23161
  if (fields === void 0) {
22795
23162
  throwRepairContractError("track_repair_layer", path, "a repair rendition must be an object");
22796
23163
  }
@@ -22798,14 +23165,14 @@ function resolveRepairLayers(catalog, source) {
22798
23165
  return describeRepairTrack(name, path, fields);
22799
23166
  });
22800
23167
  const fecOfRendition = (entry) => {
22801
- const fec2 = recordOf2(recordOf2(entry)?.["fec"]);
23168
+ const fec2 = recordOf3(recordOf3(entry)?.["fec"]);
22802
23169
  return fec2 !== void 0 && fec2["algorithm"] !== "none" ? fec2 : void 0;
22803
23170
  };
22804
23171
  const mediaRenditions = [
22805
- ...Object.values(recordOf2(hang.video?.renditions) ?? {}),
22806
- ...Object.values(recordOf2(hang.audio?.renditions) ?? {})
23172
+ ...Object.values(recordOf3(hang.video?.renditions) ?? {}),
23173
+ ...Object.values(recordOf3(hang.audio?.renditions) ?? {})
22807
23174
  ];
22808
- const reachability2 = repairReachability(mediaRenditions.map((entry) => recordOf2(entry)?.["fec"]));
23175
+ const reachability2 = repairReachability(mediaRenditions.map((entry) => recordOf3(entry)?.["fec"]));
22809
23176
  for (const d of descriptors2) {
22810
23177
  validateRepairTrackFields(d, throwRepairContractError);
22811
23178
  assertRepairTrackReachable(d, reachability2, throwRepairContractError);
@@ -22821,20 +23188,20 @@ function resolveRepairLayers(catalog, source) {
22821
23188
  }
22822
23189
  }
22823
23190
  const layers2 = assembleRepairLayers(
22824
- geometryOf(sourceName, `${renditionPath}.fec`, recordOf2(rendition["fec"])),
23191
+ geometryOf(sourceName, `${renditionPath}.fec`, recordOf3(rendition["fec"])),
22825
23192
  descriptors2,
22826
23193
  throwRepairContractError
22827
23194
  );
22828
23195
  return catalogFecUnavailable(rendition["fec"], `${renditionPath}.fec`) === void 0 ? layers2 : void 0;
22829
23196
  }
22830
23197
  const msf = msfTracks(catalog);
22831
- const msfIndex = msf ? msf.tracks.findIndex((t) => t["name"] === sourceName) : -1;
22832
- if (!msf || msfIndex < 0) return void 0;
23198
+ if (!msf || located?.dialect !== "msf") return void 0;
23199
+ const msfIndex = located.index;
22833
23200
  const track = msf.tracks[msfIndex];
22834
- const fec = recordOf2(track["fec"]);
23201
+ const fec = recordOf3(track["fec"]);
22835
23202
  const packagingOf = (t) => t["packaging"];
22836
23203
  const fecOfTrack = (t) => {
22837
- const trackFec = recordOf2(t?.["fec"]);
23204
+ const trackFec = recordOf3(t?.["fec"]);
22838
23205
  return trackFec !== void 0 && trackFec["algorithm"] !== "none" ? trackFec : void 0;
22839
23206
  };
22840
23207
  const descriptors = [];
@@ -22884,8 +23251,8 @@ function catalogRepairTarget(catalog, source) {
22884
23251
  const entry = msf?.tracks.find((t) => t["name"] === sourceName);
22885
23252
  const hang = catalog;
22886
23253
  const roles = typeof source === "string" ? ["video", "audio"] : source.type === "video" ? ["video"] : source.type === "audio" ? ["audio"] : ["video", "audio"];
22887
- const rendition = roles.map((role) => hang[role]?.renditions?.[sourceName]).find((r) => recordOf2(r) !== void 0);
22888
- const fec = rendition === void 0 ? recordOf2(entry?.["fec"]) : recordOf2(rendition.fec);
23254
+ const rendition = roles.map((role) => hang[role]?.renditions?.[sourceName]).find((r) => recordOf3(r) !== void 0);
23255
+ const fec = rendition === void 0 ? recordOf3(entry?.["fec"]) : recordOf3(rendition.fec);
22889
23256
  if (!fec || !(catalogFecInterleaveMs(fec) ?? 0)) return null;
22890
23257
  const sourcePriority = entry === void 0 ? null : moqtPriority2(entry["priority"]);
22891
23258
  return { repairTrack: layerZero.repairTrackName, sourcePriority, repairPriority: layerZero.priority };
@@ -22928,10 +23295,14 @@ function isoSpanUnavailable(fec, path, declaresFecInstance) {
22928
23295
  });
22929
23296
  }
22930
23297
  function catalogFecUnavailable(fec, fecPath) {
22931
- const block = recordOf2(fec);
22932
- if (block === void 0) return void 0;
23298
+ if (catalogFecAvailable(fec)) return void 0;
23299
+ const block = recordOf3(fec);
22933
23300
  const declaresFecInstance = block["algorithm"] !== "none";
22934
- return blockProfileUnavailable(block["blockProfile"], `${fecPath}.blockProfile`, declaresFecInstance) ?? isoSpanUnavailable(block, `${fecPath}.interleaveDepthMs`, declaresFecInstance);
23301
+ const reason = blockProfileUnavailable(block["blockProfile"], `${fecPath}.blockProfile`, declaresFecInstance) ?? isoSpanUnavailable(block, `${fecPath}.interleaveDepthMs`, declaresFecInstance);
23302
+ if (reason === void 0) {
23303
+ throw new Error(`catalogFecUnavailable: ${fecPath} is unavailable but no reason applies (rule drift)`);
23304
+ }
23305
+ return reason;
22935
23306
  }
22936
23307
  function fecParams(catalog, track, rendition, fps, sampleRate) {
22937
23308
  const mediaRate = sampleRate === void 0 ? { fps } : { fps, sampleRate };
@@ -22940,14 +23311,12 @@ function fecParams(catalog, track, rendition, fps, sampleRate) {
22940
23311
  const repair = resolveRepairLayers(catalog, track);
22941
23312
  const fecPath = `$.${track.type}.renditions[${JSON.stringify(track.name)}].fec`;
22942
23313
  if (!catalogDeclaresFec(fec)) {
22943
- const declaresFecInstance = fec.algorithm !== "none";
22944
- const kValid = Number.isSafeInteger(fec.sourceSymbols) && (fec.sourceSymbols ?? 0) > 0;
22945
- const tValid = Number.isSafeInteger(fec.symbolSize) && (fec.symbolSize ?? 0) > 0;
22946
- if (declaresFecInstance && !(kValid && tValid)) {
23314
+ if (catalogFecDeclaresUnconfigurableInstance(fec)) {
23315
+ const kValid = Number.isSafeInteger(fec.sourceSymbols) && (fec.sourceSymbols ?? 0) > 0;
22947
23316
  throwRepairContractError(
22948
23317
  "track_fec",
22949
23318
  `${fecPath}.${kValid ? "symbolSize" : "sourceSymbols"}`,
22950
- "must be a positive integer"
23319
+ 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"
22951
23320
  );
22952
23321
  }
22953
23322
  const fecUnavailable = catalogFecUnavailable(fec, fecPath);
@@ -23052,8 +23421,10 @@ function newBlockPolicyStats(packetId, catalogTrackName, epoch) {
23052
23421
  repairsSkippedRttUnmeasured: 0,
23053
23422
  repairsSkippedRttExceedsBudget: 0,
23054
23423
  repairsSkippedPresentationDelayUnavailable: 0,
23424
+ repairsSkippedRangeNoAnchor: 0,
23055
23425
  lastRepairSkip: null,
23056
23426
  keyframeRepairFetchesSent: 0,
23427
+ rangeRepairFetchesSent: 0,
23057
23428
  keyframeBudgetHolds: 0,
23058
23429
  keyframeBudgetHoldMs: 0,
23059
23430
  deltaBlocksFailed: 0,
@@ -23132,6 +23503,12 @@ var REPAIR_PRIORITY_REASONS = /* @__PURE__ */ new Set([
23132
23503
  "repair-priority-absent",
23133
23504
  "repair-priority-invalid"
23134
23505
  ]);
23506
+ var REPAIR_SKIP_REASONS = /* @__PURE__ */ new Set([
23507
+ "rtt-unmeasured",
23508
+ "rtt-exceeds-budget",
23509
+ "presentation-delay-unavailable"
23510
+ ]);
23511
+ var REPAIR_DEADLINE_BOUNDS = /* @__PURE__ */ new Set(["wait", "presentation", "keyframe", "retention"]);
23135
23512
  var GAP_REASONS = {
23136
23513
  "rap-lost": "stall",
23137
23514
  "rap-unknown": "stall",
@@ -23154,6 +23531,9 @@ function isSymbolCounts(value) {
23154
23531
  function isNullableNonNegative(value) {
23155
23532
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
23156
23533
  }
23534
+ function isFiniteNumber(value) {
23535
+ return typeof value === "number" && Number.isFinite(value);
23536
+ }
23157
23537
  function isRepairLifecycleEvent(value) {
23158
23538
  if (!isRecord(value) || value["version"] !== 2) return false;
23159
23539
  const block = value["block"];
@@ -23171,6 +23551,20 @@ function isRepairLifecycleEvent(value) {
23171
23551
  case "repair-preempted":
23172
23552
  case "repair-deferred":
23173
23553
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
23554
+ case "repair-sent":
23555
+ return hasExactKeys(value, [
23556
+ "version",
23557
+ "type",
23558
+ "block",
23559
+ "priority",
23560
+ "rttMs",
23561
+ "budgetMs",
23562
+ "delayMs",
23563
+ "blockAgeMs",
23564
+ "bound"
23565
+ ]) && 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"]);
23566
+ case "repair-skipped":
23567
+ return hasExactKeys(value, ["version", "type", "block", "reason", "rttMs", "budgetMs"]) && isRepairBlockIdentity(block) && REPAIR_SKIP_REASONS.has(value["reason"]) && isNullableNonNegative(value["rttMs"]) && isFiniteNumber(value["budgetMs"]);
23174
23568
  case "repair-priority": {
23175
23569
  const blockClass = value["blockClass"];
23176
23570
  const action = value["action"];
@@ -23350,6 +23744,9 @@ var MulticastManager = class {
23350
23744
  #router;
23351
23745
  #hostMfuTimeoutMs;
23352
23746
  #transport;
23747
+ /** Live joinRepairEndpoints() releases → the repair owners they registered,
23748
+ * re-applied after configureMultiTrack() clears catalog-derived owners. */
23749
+ #repairReleases = /* @__PURE__ */ new Map();
23353
23750
  #reportedFecDiagnosticsFailure = false;
23354
23751
  // ── Stream-global FEC timing reduction ──
23355
23752
  //
@@ -23613,7 +24010,9 @@ var MulticastManager = class {
23613
24010
  catalogTrackName
23614
24011
  );
23615
24012
  this.#configureTrackMapper(packetId, config);
23616
- this.#router.setPacketIdType(packetId, trackType);
24013
+ if (this.#router.trackKindFor(packetId) !== trackType) {
24014
+ this.#router.setPacketIdType(packetId, trackType);
24015
+ }
23617
24016
  }
23618
24017
  /**
23619
24018
  * Stop routing a stream's symbols to its Worker decoder. Returns false when
@@ -23694,6 +24093,14 @@ var MulticastManager = class {
23694
24093
  );
23695
24094
  }
23696
24095
  }
24096
+ for (const [packetId, c] of this.#trackFecTiming) {
24097
+ if (c.deliveryWindowMs === void 0) continue;
24098
+ mfuTimeoutMs = Math.max(
24099
+ mfuTimeoutMs ?? 0,
24100
+ this.#fec.terminalRetentionMsForPacket(packetId) ?? 0,
24101
+ this.#hostMfuTimeoutMs ?? 0
24102
+ );
24103
+ }
23697
24104
  const failbackWindowMs = deliveryWindowMs === void 0 ? minimumFailbackWindowMs : Math.max(deliveryWindowMs, minimumFailbackWindowMs ?? 0);
23698
24105
  this.#transport.setFailbackWindowMs(failbackWindowMs ?? null);
23699
24106
  this.#router.setMfuTimeoutMs(mfuTimeoutMs ?? this.#hostMfuTimeoutMs);
@@ -23877,6 +24284,7 @@ var MulticastManager = class {
23877
24284
  setMfuTimeoutMs(ms) {
23878
24285
  this.#router.setMfuTimeoutMs(ms);
23879
24286
  this.#hostMfuTimeoutMs = this.#router.reassembler.timeoutMs;
24287
+ if (this.#trackFecTiming.size > 0) this.#applyStreamGlobalFecTiming();
23880
24288
  }
23881
24289
  setTrackCodec(packetId, codec) {
23882
24290
  this.#router.setTrackCodec(packetId, codec);
@@ -23997,11 +24405,80 @@ var MulticastManager = class {
23997
24405
  // through whatever the relay looks like, since dropping it would be the
23998
24406
  // worse behaviour.
23999
24407
  amtRelayPort: config.amtRelayPort ?? config.relayPort ?? (amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : void 0),
24408
+ amtDiscovery: config.amtDiscovery,
24000
24409
  packetIds: config.packetIds,
24001
24410
  tracks: catalogTracks?.map(({ name, packetId }) => ({ name, packetId }))
24002
24411
  };
24003
24412
  return ingress === void 0 ? this.#transport.join(transportConfig) : this.#transport.join(transportConfig, ingress);
24004
24413
  }
24414
+ /**
24415
+ * Join the selected rung's dedicated repair groups beside the media join
24416
+ * (pim #3898): one subscription per endpoint, through `provider` when given
24417
+ * (a `window.multicast`-shaped gateway or a subscribe callback), otherwise a
24418
+ * new MulticastTransport on `window.multicast`. Returns the call that
24419
+ * releases every one of them; dispose() releases them too.
24420
+ *
24421
+ * Packets go straight to the router with the endpoint's ingress, never
24422
+ * through feedPacket(): repair arriving on its own group is not media
24423
+ * liveness, so it must not hold off the media leg's failback watchdog. The
24424
+ * repair roles and owners are registered here; in-band owners stay the
24425
+ * caller's. Joining is best effort: a group that fails to join is logged
24426
+ * and leaves the media join as it was.
24427
+ */
24428
+ joinRepairEndpoints(endpoints, provider) {
24429
+ const releases = [];
24430
+ let released = false;
24431
+ const safely = (each) => {
24432
+ try {
24433
+ each();
24434
+ } catch (error) {
24435
+ console.warn("[MulticastManager] repair group release failed", error);
24436
+ }
24437
+ };
24438
+ const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners);
24439
+ this.#applyRepairOwners(repairOwners);
24440
+ for (const endpoint of endpoints) {
24441
+ const ingress = {
24442
+ tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId })))
24443
+ };
24444
+ const onPacket = (packet) => {
24445
+ if (!released) this.#router.feedPacket(packet, "multicast", void 0, ingress);
24446
+ };
24447
+ const fail = (error) => console.warn(`[MulticastManager] repair group ${endpoint.group}:${endpoint.port} not joined`, error);
24448
+ if (typeof provider === "function") {
24449
+ Promise.resolve().then(() => provider(endpoint, onPacket)).then((release2) => released ? safely(release2) : releases.push(release2), fail);
24450
+ continue;
24451
+ }
24452
+ const transport = new MulticastTransport((packet) => onPacket(packet), { gateway: provider });
24453
+ releases.push(() => transport.dispose());
24454
+ void transport.join({
24455
+ sourceAddress: endpoint.source,
24456
+ groupAddress: endpoint.group,
24457
+ port: endpoint.port,
24458
+ mode: endpoint.mode,
24459
+ amtRelay: endpoint.amtRelay,
24460
+ amtRelayPort: endpoint.amtRelayPort ?? (endpoint.amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : void 0),
24461
+ packetIds: endpoint.packetIds,
24462
+ tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId }))
24463
+ }).then((joined) => {
24464
+ if (!joined && !released) fail(transport.lastJoinOutcome);
24465
+ });
24466
+ }
24467
+ const release = () => {
24468
+ if (released) return;
24469
+ released = true;
24470
+ this.#repairReleases.delete(release);
24471
+ for (const each of releases.splice(0)) safely(each);
24472
+ };
24473
+ this.#repairReleases.set(release, repairOwners);
24474
+ return release;
24475
+ }
24476
+ #applyRepairOwners(owners) {
24477
+ for (const { packetId, ownerPacketId } of owners) {
24478
+ this.#router.setPacketIdRole(packetId, "repair");
24479
+ this.#router.setRepairPacketIdOwner(packetId, ownerPacketId);
24480
+ }
24481
+ }
24005
24482
  // ---------------------------------------------------------------------------
24006
24483
  // In-place rendition switch
24007
24484
  // ---------------------------------------------------------------------------
@@ -24277,7 +24754,7 @@ var MulticastManager = class {
24277
24754
  *
24278
24755
  * D-04: Validates completeness via validateSwitchingSet — throws if incomplete.
24279
24756
  * D-07: Applies per-track FEC configs (base+delta get decoders; repair does not).
24280
- * D-17: Builds altGroup → track-name index for getSwitchingSet().
24757
+ * D-17: Builds altGroup → track-name index for getSwitchingSet() (repair legs excluded).
24281
24758
  * D-26: Registers packetId → TrackRole on MmtpRouter for block-complete fanout.
24282
24759
  *
24283
24760
  * FEC availability is per track (draft-ramadan-moq-fec §5.1). A media track
@@ -24328,11 +24805,9 @@ var MulticastManager = class {
24328
24805
  }
24329
24806
  }
24330
24807
  const repairOwnerGroup = /* @__PURE__ */ new Map();
24331
- const repairOwnerAltGroup = /* @__PURE__ */ new Map();
24332
24808
  for (const track of catalog.tracks) {
24333
24809
  for (const repairName of repairNamesBySource.get(track.name) ?? []) {
24334
24810
  repairOwnerGroup.set(repairName, altGroupKey(track));
24335
- repairOwnerAltGroup.set(repairName, track.altGroup);
24336
24811
  }
24337
24812
  }
24338
24813
  const groupKeyFor = (track) => repairOwnerGroup.get(track.name) ?? altGroupKey(track);
@@ -24363,11 +24838,7 @@ var MulticastManager = class {
24363
24838
  for (const [groupKey, roles] of resolvedRolesByGroup) {
24364
24839
  if (!(hasSwitchingSetByGroup.get(groupKey) ?? false)) continue;
24365
24840
  const presentRoles = new Set(roles.filter((r) => r !== "single"));
24366
- const required = [
24367
- "base",
24368
- "delta",
24369
- "repair"
24370
- ];
24841
+ const required = ["base", "repair"];
24371
24842
  const missing = required.filter((r) => !presentRoles.has(r));
24372
24843
  if (missing.length > 0) {
24373
24844
  throw new Error(
@@ -24414,6 +24885,7 @@ var MulticastManager = class {
24414
24885
  this.#switchingSets.clear();
24415
24886
  this.#repairPacketIds.clear();
24416
24887
  this.#router.clearRepairPacketIdOwners();
24888
+ for (const owners of this.#repairReleases.values()) this.#applyRepairOwners(owners);
24417
24889
  const fecPacketIds = new Set([...fecDecoders.keys()].map((i) => catalog.tracks[i].packetId));
24418
24890
  for (const [packetId, catalogTrackName] of this.#multiTrackFecTracks) {
24419
24891
  if (fecPacketIds.has(packetId)) continue;
@@ -24434,11 +24906,10 @@ var MulticastManager = class {
24434
24906
  for (let i = 0; i < catalog.tracks.length; i++) {
24435
24907
  const track = catalog.tracks[i];
24436
24908
  const role = resolvedRoles[i];
24437
- const altGroup = repairOwnerAltGroup.has(track.name) ? repairOwnerAltGroup.get(track.name) : track.altGroup;
24438
- if (altGroup !== void 0) {
24439
- const existing = this.#switchingSets.get(altGroup) ?? [];
24909
+ if (role !== "repair" && track.altGroup !== void 0) {
24910
+ const existing = this.#switchingSets.get(track.altGroup) ?? [];
24440
24911
  existing.push(track.name);
24441
- this.#switchingSets.set(altGroup, existing);
24912
+ this.#switchingSets.set(track.altGroup, existing);
24442
24913
  }
24443
24914
  if (track.packetId !== void 0) {
24444
24915
  this.#router.setPacketIdRole(track.packetId, role);
@@ -24513,7 +24984,7 @@ var MulticastManager = class {
24513
24984
  #multiTrackFecTracks = /* @__PURE__ */ new Map();
24514
24985
  /**
24515
24986
  * Return the track names belonging to the given altGroup switching set.
24516
- * D-17: altGroup groups base+delta+repair into one switching set.
24987
+ * D-17: tracks with equal altGroup form one switching set; repair legs are in none.
24517
24988
  *
24518
24989
  * @param altGroup - The altGroup number to look up.
24519
24990
  * @returns Array of track names in that switching set (empty if none).
@@ -24541,6 +25012,19 @@ var MulticastManager = class {
24541
25012
  this.requestRepairForBlock(sbn, packetId, catalogTrackName, blockClass);
24542
25013
  };
24543
25014
  }
25015
+ /**
25016
+ * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
25017
+ * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
25018
+ * pending hole and reported here, and `closeIsoHoles` must be called for it
25019
+ * once its range FETCH ends (or none is sent).
25020
+ */
25021
+ onUndelimitedLoss(cb) {
25022
+ this.#fec.setUndelimitedLossHandler(cb);
25023
+ }
25024
+ /** End a pending hole's range repair: feed what no repair stated as spans. */
25025
+ closeIsoHoles(packetId, catalogTrackName, start, length) {
25026
+ this.#router.closeIsoHoles(packetId, catalogTrackName, start, length);
25027
+ }
24544
25028
  /**
24545
25029
  * Record a repair request whose SUBSCRIBER_PRIORITY the catalog could not
24546
25030
  * supply (draft-ramadan-moq-fec §11.4.5): sent without the parameter, or
@@ -24562,6 +25046,7 @@ var MulticastManager = class {
24562
25046
  stats.repairsSkipped++;
24563
25047
  if (reason === "rtt-unmeasured") stats.repairsSkippedRttUnmeasured++;
24564
25048
  else if (reason === "rtt-exceeds-budget") stats.repairsSkippedRttExceedsBudget++;
25049
+ else if (reason === "range-no-anchor") stats.repairsSkippedRangeNoAnchor++;
24565
25050
  else stats.repairsSkippedPresentationDelayUnavailable++;
24566
25051
  stats.lastRepairSkip = {
24567
25052
  reason,
@@ -24593,8 +25078,20 @@ var MulticastManager = class {
24593
25078
  stats.keyframeBudgetHoldMs += extensionMs;
24594
25079
  }
24595
25080
  /** Record a repair FETCH the scheduler admitted and sent. */
24596
- noteRepairFetchSent(priority, _sbn, packetId, catalogTrackName) {
25081
+ noteRepairFetchSent(priority, sbn, packetId, catalogTrackName, measurement) {
24597
25082
  if (priority === 0) this.#statsFor(packetId, catalogTrackName).keyframeRepairFetchesSent++;
25083
+ if (measurement.range) this.#statsFor(packetId, catalogTrackName).rangeRepairFetchesSent++;
25084
+ this.#emitRepairLifecycle({
25085
+ version: 2,
25086
+ type: "repair-sent",
25087
+ block: repairBlockIdentity(packetId, sbn, catalogTrackName),
25088
+ priority,
25089
+ rttMs: measurement.rttMs,
25090
+ budgetMs: measurement.budgetMs,
25091
+ delayMs: measurement.delayMs,
25092
+ blockAgeMs: measurement.blockAgeMs,
25093
+ bound: measurement.bound
25094
+ });
24598
25095
  }
24599
25096
  /**
24600
25097
  * Record a repair-scheduler decision about a delta block: preempted for
@@ -24745,6 +25242,7 @@ var MulticastManager = class {
24745
25242
  this.#trackResetObservers.clear();
24746
25243
  this.#repairLifecycleObservers.clear();
24747
25244
  this.#transport.dispose();
25245
+ for (const release of [...this.#repairReleases.keys()]) release();
24748
25246
  this.#router.dispose();
24749
25247
  this.#fec.dispose();
24750
25248
  }
@@ -24834,7 +25332,6 @@ async function setupFecWorkerForTrack(opts) {
24834
25332
  repairTrack: opts.repairTrackName,
24835
25333
  relayBlockSigEnabled: false
24836
25334
  };
24837
- client.configure(fecTrackConfig, rqWasm);
24838
25335
  try {
24839
25336
  opts.multicastManager.setFecWorker(opts.packetId, client, opts.trackType, {
24840
25337
  blockProfile,
@@ -24854,6 +25351,14 @@ async function setupFecWorkerForTrack(opts) {
24854
25351
  }
24855
25352
  throw e;
24856
25353
  }
25354
+ fecTrackConfig.interleaveDepth = Math.min(
25355
+ MAX_FEC_RETENTION_BLOCKS,
25356
+ Math.max(
25357
+ interleaveDepthBlocks,
25358
+ opts.multicastManager.fecManager.isoRetentionBlocksForPacket(opts.packetId) ?? 0
25359
+ )
25360
+ );
25361
+ client.configure(fecTrackConfig, rqWasm);
24857
25362
  let disposed = false;
24858
25363
  return {
24859
25364
  client,
@@ -25503,7 +26008,7 @@ function asSeconds(n) {
25503
26008
  }
25504
26009
  return n;
25505
26010
  }
25506
- function groupIdForTicks(ticks, groupDurationTicks) {
26011
+ function groupIdForTicks(ticks, groupDurationTicks, presentationAnchorTicks = 0) {
25507
26012
  if (!Number.isInteger(ticks)) {
25508
26013
  throw new Error(
25509
26014
  `[align] groupIdForTicks: ticks must be an integer, got ${ticks}`
@@ -25514,8 +26019,23 @@ function groupIdForTicks(ticks, groupDurationTicks) {
25514
26019
  `[align] groupIdForTicks: groupDurationTicks must be a positive integer, got ${groupDurationTicks}`
25515
26020
  );
25516
26021
  }
25517
- if (ticks < 0) return 0;
25518
- return Math.floor(ticks / groupDurationTicks);
26022
+ if (!Number.isInteger(presentationAnchorTicks)) {
26023
+ throw new Error(
26024
+ `[align] groupIdForTicks: presentationAnchorTicks must be an integer, got ${presentationAnchorTicks}`
26025
+ );
26026
+ }
26027
+ const relativeTicks = ticks - presentationAnchorTicks;
26028
+ if (!Number.isSafeInteger(relativeTicks)) {
26029
+ throw new Error(
26030
+ `[align] groupIdForTicks: ticks - presentationAnchorTicks = ${relativeTicks} is not a safe integer`
26031
+ );
26032
+ }
26033
+ if (relativeTicks < 0) {
26034
+ throw new Error(
26035
+ `[align] groupIdForTicks: ticks ${ticks} precede presentationAnchorTicks ${presentationAnchorTicks}; the publisher must reject this MPU (moq-mmt-01 4.4.1)`
26036
+ );
26037
+ }
26038
+ return Math.floor(relativeTicks / groupDurationTicks);
25519
26039
  }
25520
26040
  function groupIdFor(mediaTimeSec, groupDurationSec) {
25521
26041
  if (!Number.isFinite(mediaTimeSec)) {
@@ -25528,7 +26048,11 @@ function groupIdFor(mediaTimeSec, groupDurationSec) {
25528
26048
  `[align] groupIdFor: groupDurationSec must be a positive finite number, got ${groupDurationSec}`
25529
26049
  );
25530
26050
  }
25531
- if (mediaTimeSec < 0) return 0;
26051
+ if (mediaTimeSec < 0) {
26052
+ throw new Error(
26053
+ `[align] groupIdFor: mediaTimeSec ${mediaTimeSec} precedes presentationAnchorTicks 0; the publisher must reject this MPU (moq-mmt-01 4.4.1)`
26054
+ );
26055
+ }
25532
26056
  const TS = 1e9;
25533
26057
  const ticks = Math.round(mediaTimeSec * TS);
25534
26058
  const durTicks = Math.round(groupDurationSec * TS);
@@ -26499,6 +27023,337 @@ var CmcdProducer = class {
26499
27023
  }
26500
27024
  };
26501
27025
 
27026
+ // src/mmtp-fec-session.ts
27027
+ var PATH_BITS = { moq: 1, multicast: 2 };
27028
+ var MIXED_PATHS = PATH_BITS.moq | PATH_BITS.multicast;
27029
+ var MmtpFecSession = class {
27030
+ #decoder;
27031
+ /** Blocks a repair has defined and that are not settled yet, by SS_Start. */
27032
+ #blocks = /* @__PURE__ */ new Map();
27033
+ /** SS_Starts of settled blocks, so a later repair for one is refused. */
27034
+ #settled = /* @__PURE__ */ new Set();
27035
+ /**
27036
+ * SS_IDs whose packet the parser has, with the PATH_BITS of the path it was
27037
+ * received on, or 0 for one the session recovered.
27038
+ */
27039
+ #have = /* @__PURE__ */ new Map();
27040
+ #newest;
27041
+ /** The newest SS_ID when the remembered SS_IDs were last pruned. */
27042
+ #prunedAt;
27043
+ #repairPacketId;
27044
+ #stats = {
27045
+ sourceSymbols: 0,
27046
+ repairSymbols: 0,
27047
+ blocksClean: 0,
27048
+ blocksRecovered: 0,
27049
+ blocksFailed: 0,
27050
+ blocksReleased: 0,
27051
+ packetsRecovered: 0,
27052
+ packetsLost: 0,
27053
+ dropped: {},
27054
+ sourceSymbolsByPath: { moq: 0, multicast: 0 },
27055
+ repairSymbolsByPath: { moq: 0, multicast: 0 },
27056
+ mixedPath: { clean: 0, recovered: 0, failed: 0, released: 0 }
27057
+ };
27058
+ /**
27059
+ * @throws when the catalog block lacks or misstates a field the session
27060
+ * needs: the block profile, K, T, `interleaveDepthMs` or
27061
+ * `reorderToleranceMs`. None is defaulted.
27062
+ */
27063
+ constructor(config) {
27064
+ const fec = config?.fec;
27065
+ if (!fec || typeof fec !== "object") {
27066
+ throw new Error("MmtpFecSession: the catalog fec block is required");
27067
+ }
27068
+ this.blockProfile = parseFecBlockProfile(fec.blockProfile, "fec.blockProfile");
27069
+ this.sourceSymbols = requirePositiveInteger(fec.sourceSymbols, "fec.sourceSymbols");
27070
+ this.symbolSize = requirePositiveInteger(fec.symbolSize, "fec.symbolSize");
27071
+ const interleaveDepthMs = requireNumber(fec.interleaveDepthMs, "fec.interleaveDepthMs");
27072
+ const reorderToleranceMs = requireNumber(fec.reorderToleranceMs, "fec.reorderToleranceMs");
27073
+ this.retentionBlocks = deriveFecRetentionBlocks(
27074
+ fecBlockBudgetMs(interleaveDepthMs, reorderToleranceMs),
27075
+ interleaveDepthMs
27076
+ );
27077
+ if (typeof config.Decoder !== "function") {
27078
+ throw new Error("MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required");
27079
+ }
27080
+ const decoder = new config.Decoder(this.retentionBlocks, this.blockProfile);
27081
+ try {
27082
+ decoder.configure_params(this.sourceSymbols, this.symbolSize);
27083
+ } catch (error) {
27084
+ decoder.free();
27085
+ throw error;
27086
+ }
27087
+ this.#decoder = decoder;
27088
+ }
27089
+ /** True once release() ran. */
27090
+ get released() {
27091
+ return this.#decoder === null;
27092
+ }
27093
+ get stats() {
27094
+ return {
27095
+ ...this.#stats,
27096
+ dropped: { ...this.#stats.dropped },
27097
+ sourceSymbolsByPath: { ...this.#stats.sourceSymbolsByPath },
27098
+ repairSymbolsByPath: { ...this.#stats.repairSymbolsByPath },
27099
+ mixedPath: { ...this.#stats.mixedPath }
27100
+ };
27101
+ }
27102
+ /**
27103
+ * Feeds one received source packet: the MMTP packet without its four-byte
27104
+ * Source FEC Payload ID, under the SS_ID that ID stated. This is what
27105
+ * MmtpContainerParser's onSourceSymbol() hands over. `path` is where it
27106
+ * was received; a caller that only subscribes over MoQT can leave it out.
27107
+ *
27108
+ * @returns the protected packets of this packet's block that it recovered,
27109
+ * in SS_ID order, for the caller to feed to its parser with
27110
+ * `{skipFecPayloadId: true, recovered: true}`. Usually empty.
27111
+ */
27112
+ addSource(ssId, packet, path = "moq") {
27113
+ const decoder = this.#decoder;
27114
+ if (!decoder) return this.#drop("source:released");
27115
+ const pathBit = PATH_BITS[path];
27116
+ if (!pathBit) return this.#drop("source:unknown-path");
27117
+ if (!Number.isInteger(ssId) || ssId < 0 || ssId > 4294967295) return this.#drop("source:bad-ss-id");
27118
+ if (!ssbg1FitsSymbol(packet.byteLength, this.symbolSize)) return this.#drop("source:exceeds-symbol");
27119
+ if (this.#have.has(ssId)) return this.#drop("source:duplicate");
27120
+ this.#have.set(ssId, pathBit);
27121
+ this.#stats.sourceSymbols++;
27122
+ this.#stats.sourceSymbolsByPath[path]++;
27123
+ this.#noteNewest(ssId);
27124
+ const start = this.#blockStartOf(ssId);
27125
+ const block = start === void 0 ? void 0 : this.#blocks.get(start);
27126
+ if (block) {
27127
+ block.received++;
27128
+ block.paths |= pathBit;
27129
+ }
27130
+ let output;
27131
+ try {
27132
+ output = decoder.add_source(ssId, packet, 0);
27133
+ } catch {
27134
+ this.#drop("source:decoder-refused");
27135
+ output = void 0;
27136
+ }
27137
+ const recovered = [];
27138
+ if (start !== void 0 && block) {
27139
+ if (output) {
27140
+ recovered.push(...this.#settleDecoded(start, block, output));
27141
+ } else if (block.received >= block.ssbLength) {
27142
+ this.#settleClean(start);
27143
+ }
27144
+ }
27145
+ this.#retireBehindHorizon();
27146
+ return recovered;
27147
+ }
27148
+ /**
27149
+ * Feeds one object of the repair track: a whole MMTP repair packet (ISO/IEC
27150
+ * 23008-1 C.5.3). A repair track carries one repair flow, so the first
27151
+ * repair packet fixes its packet ID and a packet of any other is refused.
27152
+ * `path` is where it was received, as for addSource().
27153
+ *
27154
+ * @returns the protected packets this repair symbol recovered, as for
27155
+ * addSource().
27156
+ */
27157
+ addRepair(packet, path = "moq") {
27158
+ const decoder = this.#decoder;
27159
+ if (!decoder) return this.#drop("repair:released");
27160
+ const pathBit = PATH_BITS[path];
27161
+ if (!pathBit) return this.#drop("repair:unknown-path");
27162
+ let header;
27163
+ try {
27164
+ header = parseMMTPHeader(packet);
27165
+ } catch {
27166
+ return this.#drop("repair:malformed");
27167
+ }
27168
+ const frame = parseMoqRepairFrameWithHeader(packet, header);
27169
+ if (!frame) return this.#drop("repair:malformed");
27170
+ if (this.#repairPacketId === void 0) {
27171
+ this.#repairPacketId = frame.packetId;
27172
+ } else if (frame.packetId !== this.#repairPacketId) {
27173
+ return this.#drop("repair:foreign-packet-id");
27174
+ }
27175
+ if (frame.symbolData.byteLength !== this.symbolSize) return this.#drop("repair:symbol-size");
27176
+ if (frame.ssbLength > this.sourceSymbols) return this.#drop("repair:ssb-length");
27177
+ const start = frame.ssStart;
27178
+ let block = this.#blocks.get(start);
27179
+ if (block && block.ssbLength !== frame.ssbLength) return this.#drop("repair:conflicting-ssb-length");
27180
+ if (!block) {
27181
+ if (this.#settled.has(start)) return this.#drop("repair:block-settled");
27182
+ if (this.#behindHorizon(start)) return this.#drop("repair:behind-horizon");
27183
+ block = { ssbLength: frame.ssbLength, received: 0, paths: 0 };
27184
+ this.#countHeld(start, block);
27185
+ this.#blocks.set(start, block);
27186
+ }
27187
+ this.#noteNewest(serial32Add(start, frame.ssbLength - 1));
27188
+ if (block.received >= block.ssbLength) {
27189
+ this.#settleClean(start);
27190
+ this.#retireBehindHorizon();
27191
+ return [];
27192
+ }
27193
+ let output;
27194
+ try {
27195
+ output = decoder.add_repair(start, frame.ssbLength, frame.rsId, frame.symbolData, 0);
27196
+ } catch {
27197
+ return this.#drop("repair:decoder-refused");
27198
+ }
27199
+ this.#stats.repairSymbols++;
27200
+ this.#stats.repairSymbolsByPath[path]++;
27201
+ block.paths |= pathBit;
27202
+ const recovered = output ? this.#settleDecoded(start, block, output) : [];
27203
+ this.#retireBehindHorizon();
27204
+ return recovered;
27205
+ }
27206
+ /**
27207
+ * Frees the decoder and every block. Blocks still unsettled are counted as
27208
+ * released, not failed: nothing proved them unrecoverable. Idempotent;
27209
+ * returns whether this call released anything.
27210
+ */
27211
+ release() {
27212
+ const decoder = this.#decoder;
27213
+ if (!decoder) return false;
27214
+ this.#decoder = null;
27215
+ this.#stats.blocksReleased += this.#blocks.size;
27216
+ for (const block of this.#blocks.values()) this.#noteMixed(block, "released");
27217
+ this.#blocks.clear();
27218
+ this.#settled.clear();
27219
+ this.#have.clear();
27220
+ decoder.free();
27221
+ return true;
27222
+ }
27223
+ #drop(reason) {
27224
+ this.#stats.dropped[reason] = (this.#stats.dropped[reason] ?? 0) + 1;
27225
+ return [];
27226
+ }
27227
+ #noteNewest(ssId) {
27228
+ if (this.#newest === void 0 || serial32Precedes(this.#newest, ssId)) this.#newest = ssId;
27229
+ }
27230
+ #blockStartOf(ssId) {
27231
+ for (const [start, block] of this.#blocks) {
27232
+ if (isoBlockContains(start, block.ssbLength, ssId)) return start;
27233
+ }
27234
+ return void 0;
27235
+ }
27236
+ /** Counts the sources of a new block the parser already has, and their paths. */
27237
+ #countHeld(start, block) {
27238
+ for (let i = 0; i < block.ssbLength; i++) {
27239
+ const pathBit = this.#have.get(serial32Add(start, i));
27240
+ if (pathBit === void 0) continue;
27241
+ block.received++;
27242
+ block.paths |= pathBit;
27243
+ }
27244
+ }
27245
+ #noteMixed(block, outcome) {
27246
+ if ((block.paths & MIXED_PATHS) === MIXED_PATHS) this.#stats.mixedPath[outcome]++;
27247
+ }
27248
+ /** The decoder's own rule: more than its retention behind, counted from below. */
27249
+ #behindHorizon(start) {
27250
+ const newest = this.#newest;
27251
+ if (newest === void 0) return false;
27252
+ return isoBlocksBehindLowerBound(start, newest, this.sourceSymbols) > this.retentionBlocks;
27253
+ }
27254
+ #settle(start) {
27255
+ this.#blocks.delete(start);
27256
+ this.#settled.add(start);
27257
+ }
27258
+ #settleClean(start) {
27259
+ const block = this.#blocks.get(start);
27260
+ if (!block) return;
27261
+ this.#settle(start);
27262
+ this.#stats.blocksClean++;
27263
+ this.#noteMixed(block, "clean");
27264
+ try {
27265
+ this.#decoder?.cleanup_blocks_detailed(Uint32Array.of(start));
27266
+ } catch {
27267
+ }
27268
+ }
27269
+ /**
27270
+ * The decoder returns a completed block as its K' ssbg_mode1 symbols,
27271
+ * concatenated: split by T, trim by each symbol's length field, and hand
27272
+ * back the packets the parser does not have yet.
27273
+ */
27274
+ #settleDecoded(start, block, output) {
27275
+ this.#settle(start);
27276
+ if (output.byteLength !== block.ssbLength * this.symbolSize) {
27277
+ this.#stats.blocksFailed++;
27278
+ this.#stats.packetsLost += block.ssbLength - block.received;
27279
+ this.#noteMixed(block, "failed");
27280
+ this.#drop("block:decoded-length");
27281
+ return [];
27282
+ }
27283
+ const recovered = [];
27284
+ let refused = 0;
27285
+ for (let i = 0; i < block.ssbLength; i++) {
27286
+ const ssId = serial32Add(start, i);
27287
+ if (this.#have.has(ssId)) continue;
27288
+ const symbol = output.subarray(i * this.symbolSize, (i + 1) * this.symbolSize);
27289
+ const packet = trimSsbg1SourceSymbol(symbol);
27290
+ if (!packet) {
27291
+ refused++;
27292
+ continue;
27293
+ }
27294
+ this.#have.set(ssId, 0);
27295
+ recovered.push(packet.slice());
27296
+ }
27297
+ if (refused > 0) {
27298
+ this.#stats.blocksFailed++;
27299
+ this.#stats.packetsLost += refused;
27300
+ this.#noteMixed(block, "failed");
27301
+ this.#drop("block:bad-ssbg1-symbol");
27302
+ } else if (recovered.length === 0) {
27303
+ this.#stats.blocksClean++;
27304
+ this.#noteMixed(block, "clean");
27305
+ } else {
27306
+ this.#stats.blocksRecovered++;
27307
+ this.#noteMixed(block, "recovered");
27308
+ }
27309
+ this.#stats.packetsRecovered += recovered.length;
27310
+ return recovered;
27311
+ }
27312
+ /**
27313
+ * Retires every block, and every SS_ID the session remembers, that the
27314
+ * newest SS_ID has moved past the retention. An unsettled block retired
27315
+ * here is a failure: more of its sources were lost than its repair could
27316
+ * restore, or its repair never arrived.
27317
+ */
27318
+ #retireBehindHorizon() {
27319
+ const decoder = this.#decoder;
27320
+ const newest = this.#newest;
27321
+ if (!decoder || newest === void 0) return;
27322
+ try {
27323
+ decoder.cleanup_by_ss_start(newest);
27324
+ } catch {
27325
+ }
27326
+ for (const [start, block] of this.#blocks) {
27327
+ if (!this.#behindHorizon(start)) continue;
27328
+ this.#settle(start);
27329
+ this.#stats.blocksFailed++;
27330
+ this.#stats.packetsLost += block.ssbLength - block.received;
27331
+ this.#noteMixed(block, "failed");
27332
+ }
27333
+ const prunedAt = this.#prunedAt;
27334
+ if (prunedAt !== void 0 && serial32Distance(prunedAt, newest) < this.sourceSymbols) return;
27335
+ this.#prunedAt = newest;
27336
+ for (const ssId of this.#have.keys()) {
27337
+ if (this.#behindHorizon(ssId)) this.#have.delete(ssId);
27338
+ }
27339
+ for (const start of this.#settled) {
27340
+ if (this.#behindHorizon(start)) this.#settled.delete(start);
27341
+ }
27342
+ }
27343
+ };
27344
+ function requirePositiveInteger(value, path) {
27345
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
27346
+ throw new Error(`MmtpFecSession: ${path} must be a positive integer (got ${String(value)})`);
27347
+ }
27348
+ return value;
27349
+ }
27350
+ function requireNumber(value, path) {
27351
+ if (typeof value !== "number") {
27352
+ throw new Error(`MmtpFecSession: ${path} is required (got ${String(value)}); it is never defaulted`);
27353
+ }
27354
+ return value;
27355
+ }
27356
+
26502
27357
  // src/repair-fetch.ts
26503
27358
  var MOQT_PRIORITY_MAX = 255;
26504
27359
  var SOURCE_MEDIA_PRIORITY_MAX = REPAIR_PRIORITY_MIN - 1;
@@ -26533,6 +27388,9 @@ function wireRepairFetch(mc, opts) {
26533
27388
  if (typeof opts.presentationDelayMs !== "function") {
26534
27389
  throw new Error("[RepairFetch] presentationDelayMs is required: a repair FETCH is due by the block's presentation deadline");
26535
27390
  }
27391
+ if (opts.rangeTransport !== void 0 && (typeof opts.repairEpochReference !== "function" || !mc.onUndelimitedLoss || !mc.closeIsoHoles)) {
27392
+ throw new Error("[RepairFetch] rangeTransport needs repairEpochReference and a host that reports undelimited losses");
27393
+ }
26536
27394
  const entries = /* @__PURE__ */ new Map();
26537
27395
  const warnedNoTarget = /* @__PURE__ */ new Set();
26538
27396
  let disposed = false;
@@ -26546,7 +27404,12 @@ function wireRepairFetch(mc, opts) {
26546
27404
  const note = (type, entry) => {
26547
27405
  mc.noteRepairScheduling(type, entry.sbn, entry.packetId, entry.catalogTrackName);
26548
27406
  };
27407
+ const clearEntry = (entry) => {
27408
+ if (entry.range) mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, entry.range.holeLength);
27409
+ else clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27410
+ };
26549
27411
  const releaseHold = (entry) => {
27412
+ if (entry.range) return;
26550
27413
  if (entry.catalogTrackName === void 0) mc.fecManager.releaseRepairHold(entry.sbn, entry.packetId);
26551
27414
  else mc.fecManager.releaseRepairHold(entry.sbn, entry.packetId, entry.catalogTrackName);
26552
27415
  };
@@ -26579,10 +27442,10 @@ function wireRepairFetch(mc, opts) {
26579
27442
  const admit = (entry, now) => {
26580
27443
  const budgetMs = entry.deadlineAt - now;
26581
27444
  const rttMs = readRtt();
26582
- if (rttMs !== null && rttMs < budgetMs) return true;
27445
+ if (rttMs !== null && rttMs < budgetMs) return rttMs;
26583
27446
  retire(entry);
26584
27447
  releaseHold(entry);
26585
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27448
+ clearEntry(entry);
26586
27449
  mc.noteRepairSkipped(
26587
27450
  rttMs === null ? "rtt-unmeasured" : "rtt-exceeds-budget",
26588
27451
  { rttMs, budgetMs, priority: entry.priority },
@@ -26590,10 +27453,11 @@ function wireRepairFetch(mc, opts) {
26590
27453
  entry.packetId,
26591
27454
  entry.catalogTrackName
26592
27455
  );
26593
- return false;
27456
+ return null;
26594
27457
  };
26595
27458
  const retire = (entry) => {
26596
27459
  if (entries.get(entry.key) === entry) entries.delete(entry.key);
27460
+ if (entry.expiry !== void 0) clearTimeout(entry.expiry);
26597
27461
  };
26598
27462
  const urgentOutstanding = () => {
26599
27463
  for (const entry of entries.values()) {
@@ -26622,17 +27486,28 @@ function wireRepairFetch(mc, opts) {
26622
27486
  return derived.kind === "omit" ? { subscriberPriority: void 0 } : null;
26623
27487
  };
26624
27488
  const start = (entry, counted = true) => {
26625
- if (!admit(entry, performance.now())) return;
27489
+ const now = performance.now();
27490
+ const rttMs = admit(entry, now);
27491
+ if (rttMs === null) return;
26626
27492
  if (counted) entry.attempts++;
26627
- mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName);
27493
+ mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName, {
27494
+ rttMs,
27495
+ budgetMs: entry.deadlineAt - now,
27496
+ delayMs: entry.delayMs,
27497
+ blockAgeMs: entry.anchorAt === null ? null : Math.max(0, now - entry.anchorAt),
27498
+ bound: entry.bound,
27499
+ ...entry.range ? { range: true } : {}
27500
+ });
26628
27501
  const run = { controller: new AbortController(), stopped: null };
26629
27502
  entry.running = run;
26630
- mc.fecManager.holdBlockForRepair(
26631
- entry.sbn,
26632
- entry.packetId,
26633
- entry.catalogTrackName,
26634
- entry.deadlineAt
26635
- );
27503
+ if (!entry.range) {
27504
+ mc.fecManager.holdBlockForRepair(
27505
+ entry.sbn,
27506
+ entry.packetId,
27507
+ entry.catalogTrackName,
27508
+ entry.deadlineAt
27509
+ );
27510
+ }
26636
27511
  void execute(entry, run);
26637
27512
  };
26638
27513
  const dispatch = () => {
@@ -26644,14 +27519,14 @@ function wireRepairFetch(mc, opts) {
26644
27519
  if (entry.deadlineAt <= now) {
26645
27520
  stop(entry, "expired");
26646
27521
  retire(entry);
26647
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27522
+ clearEntry(entry);
26648
27523
  }
26649
27524
  continue;
26650
27525
  }
26651
27526
  if (entry.deadlineAt <= now) {
26652
27527
  retire(entry);
26653
27528
  if (entry.priority === 2 && entry.attempts === 0) note("repair-deferred", entry);
26654
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27529
+ clearEntry(entry);
26655
27530
  continue;
26656
27531
  }
26657
27532
  queued.push(entry);
@@ -26688,9 +27563,9 @@ function wireRepairFetch(mc, opts) {
26688
27563
  entry.running = null;
26689
27564
  if (error === void 0) {
26690
27565
  retire(entry);
26691
- if (fed === 0 || !decodable(entry)) {
27566
+ if (entry.range || fed === 0 || !decodable(entry)) {
26692
27567
  releaseHold(entry);
26693
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27568
+ clearEntry(entry);
26694
27569
  }
26695
27570
  dispatch();
26696
27571
  return;
@@ -26702,7 +27577,7 @@ function wireRepairFetch(mc, opts) {
26702
27577
  }
26703
27578
  retire(entry);
26704
27579
  if (fed === 0) releaseHold(entry);
26705
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27580
+ clearEntry(entry);
26706
27581
  console.warn(
26707
27582
  `[RepairFetch] fetch failed pid=${entry.packetId} sbn=${entry.sbn} track=${entry.repairTrack}:`,
26708
27583
  error
@@ -26718,15 +27593,21 @@ function wireRepairFetch(mc, opts) {
26718
27593
  };
26719
27594
  const execute = async (entry, run) => {
26720
27595
  let fed = 0;
27596
+ const common = {
27597
+ repairTrack: entry.repairTrack,
27598
+ blockProfile: entry.blockProfile,
27599
+ packetId: entry.packetId,
27600
+ signal: run.controller.signal,
27601
+ subscriberPriority: entry.subscriberPriority
27602
+ };
26721
27603
  try {
26722
- for await (const packet of opts.transport({
26723
- repairTrack: entry.repairTrack,
26724
- sbn: entry.sbn,
26725
- blockProfile: entry.blockProfile,
26726
- packetId: entry.packetId,
26727
- signal: run.controller.signal,
26728
- subscriberPriority: entry.subscriberPriority
26729
- })) {
27604
+ const packets = entry.range ? opts.rangeTransport({
27605
+ ...common,
27606
+ startGroup: entry.range.startGroup,
27607
+ endGroup: entry.range.endGroup,
27608
+ lostSsId: entry.range.lostSsId
27609
+ }) : opts.transport({ ...common, sbn: entry.sbn });
27610
+ for await (const packet of packets) {
26730
27611
  if (run.stopped !== null || entry.running !== run) break;
26731
27612
  fed++;
26732
27613
  if (entry.catalogTrackName === void 0) {
@@ -26745,6 +27626,7 @@ function wireRepairFetch(mc, opts) {
26745
27626
  if (entry.packetId !== packetId || entry.catalogTrackName !== catalogTrackName) continue;
26746
27627
  retire(entry);
26747
27628
  stop(entry, "reset");
27629
+ if (entry.range) clearEntry(entry);
26748
27630
  }
26749
27631
  warnedNoTarget.delete(noTargetKey(packetId, catalogTrackName));
26750
27632
  dispatch();
@@ -26771,6 +27653,9 @@ function wireRepairFetch(mc, opts) {
26771
27653
  );
26772
27654
  if (promotedDeadline !== null && promotedDeadline.deadlineAt > entry2.deadlineAt) {
26773
27655
  entry2.deadlineAt = promotedDeadline.deadlineAt;
27656
+ entry2.anchorAt = promotedDeadline.anchorAt;
27657
+ entry2.delayMs = promotedDeadline.delayMs;
27658
+ entry2.bound = promotedDeadline.bound;
26774
27659
  noteBudget(entry2, promotedDeadline.extensionMs);
26775
27660
  }
26776
27661
  if (entry2.running) {
@@ -26796,7 +27681,9 @@ function wireRepairFetch(mc, opts) {
26796
27681
  if (waitMs === void 0) return null;
26797
27682
  const waitDeadlineAt = now + waitMs;
26798
27683
  const anchor = mc.fecManager.blockAnchorAtMs(sbn, packetId, catalogTrackName);
26799
- if (anchor === void 0) return { deadlineAt: waitDeadlineAt, extensionMs: 0 };
27684
+ if (anchor === void 0) {
27685
+ return { deadlineAt: waitDeadlineAt, extensionMs: 0, anchorAt: null, delayMs: null, bound: "wait" };
27686
+ }
26800
27687
  let delayMs;
26801
27688
  try {
26802
27689
  delayMs = opts.presentationDelayMs(packetId, catalogTrackName);
@@ -26807,12 +27694,21 @@ function wireRepairFetch(mc, opts) {
26807
27694
  const retentionMs = mc.fecManager.terminalRetentionMsForPacket(packetId);
26808
27695
  if (retentionMs === void 0) return null;
26809
27696
  const ceilingAt = Math.min(anchor, earliestGatedFrameAt(packetId, catalogTrackName) ?? anchor) + retentionMs;
26810
- const deadlineAt = (delay) => Math.max(waitDeadlineAt, Math.min(anchor + delay, ceilingAt));
26811
- const base = deadlineAt(delayMs);
27697
+ const at = (delay, delayBound) => {
27698
+ const presentAt = Math.min(anchor + delay, ceilingAt);
27699
+ if (waitDeadlineAt >= presentAt) return { deadlineAt: waitDeadlineAt, bound: "wait" };
27700
+ return { deadlineAt: presentAt, bound: anchor + delay <= ceilingAt ? delayBound : "retention" };
27701
+ };
27702
+ const base = at(delayMs, "presentation");
26812
27703
  const budgetMs = keyframeBudgetEligible(blockClass, classifierMode(packetId, catalogTrackName)) && groupCanComplete(sbn, packetId, catalogTrackName) ? readKeyframeBudget(packetId, catalogTrackName) : null;
26813
- if (budgetMs === null || budgetMs <= delayMs) return { deadlineAt: base, extensionMs: 0 };
26814
- const extended = deadlineAt(budgetMs);
26815
- return { deadlineAt: extended, extensionMs: extended - base };
27704
+ if (budgetMs === null || budgetMs <= delayMs) return { ...base, extensionMs: 0, anchorAt: anchor, delayMs };
27705
+ const extended = at(budgetMs, "keyframe");
27706
+ return {
27707
+ ...extended,
27708
+ extensionMs: extended.deadlineAt - base.deadlineAt,
27709
+ anchorAt: anchor,
27710
+ delayMs: budgetMs
27711
+ };
26816
27712
  };
26817
27713
  const earliestGatedFrameAt = (packetId, catalogTrackName) => {
26818
27714
  try {
@@ -26889,6 +27785,9 @@ function wireRepairFetch(mc, opts) {
26889
27785
  priority,
26890
27786
  subscriberPriority: wire.subscriberPriority,
26891
27787
  deadlineAt: deadline.deadlineAt,
27788
+ anchorAt: deadline.anchorAt,
27789
+ delayMs: deadline.delayMs,
27790
+ bound: deadline.bound,
26892
27791
  order: enqueueOrder++,
26893
27792
  attempts: 0,
26894
27793
  running: null
@@ -26898,14 +27797,92 @@ function wireRepairFetch(mc, opts) {
26898
27797
  if (entry.priority < 2) preemptDeltas();
26899
27798
  dispatch();
26900
27799
  });
27800
+ const rangeFor = (loss, repairTrack) => {
27801
+ let reference;
27802
+ try {
27803
+ reference = opts.repairEpochReference(repairTrack);
27804
+ } catch {
27805
+ return null;
27806
+ }
27807
+ if (reference === void 0) return null;
27808
+ try {
27809
+ const anchor = loss.previousBlockStart === void 0 ? { reference } : { previousBlockStart: extendSsId(reference, loss.previousBlockStart) };
27810
+ return repairFetchRange(loss.lostSsId, loss.kMax, anchor);
27811
+ } catch (error) {
27812
+ if (error instanceof RangeError) return null;
27813
+ throw error;
27814
+ }
27815
+ };
27816
+ if (opts.rangeTransport !== void 0) {
27817
+ mc.onUndelimitedLoss((loss) => {
27818
+ const { packetId, catalogTrackName, holeStart, holeLength } = loss;
27819
+ const close = () => mc.closeIsoHoles(packetId, catalogTrackName, holeStart, holeLength);
27820
+ if (disposed) return close();
27821
+ const blockProfile = blockProfileOf(packetId);
27822
+ const target = opts.resolveTarget(packetId, catalogTrackName);
27823
+ if (!target) return close();
27824
+ const priority = repairPriorityForClass("unknown");
27825
+ const range = rangeFor(loss, target.repairTrack);
27826
+ if (range === null) {
27827
+ close();
27828
+ mc.noteRepairSkipped("range-no-anchor", { rttMs: readRtt(), budgetMs: 0, priority }, holeStart, packetId, catalogTrackName);
27829
+ return;
27830
+ }
27831
+ const identity = {
27832
+ target,
27833
+ sbn: holeStart,
27834
+ packetId,
27835
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
27836
+ };
27837
+ const wire = wirePriority(identity, "unknown");
27838
+ const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, performance.now(), "unknown");
27839
+ if (deadline === null) {
27840
+ close();
27841
+ mc.noteRepairSkipped(
27842
+ "presentation-delay-unavailable",
27843
+ { rttMs: readRtt(), budgetMs: 0, priority },
27844
+ holeStart,
27845
+ packetId,
27846
+ catalogTrackName
27847
+ );
27848
+ return;
27849
+ }
27850
+ const entry = {
27851
+ key: JSON.stringify(["range", packetId, catalogTrackName ?? null, holeStart]),
27852
+ ...identity,
27853
+ repairTrack: target.repairTrack,
27854
+ blockProfile,
27855
+ priority,
27856
+ subscriberPriority: wire.subscriberPriority,
27857
+ deadlineAt: deadline.deadlineAt,
27858
+ anchorAt: deadline.anchorAt,
27859
+ delayMs: deadline.delayMs,
27860
+ bound: deadline.bound,
27861
+ order: enqueueOrder++,
27862
+ attempts: 0,
27863
+ running: null,
27864
+ range: { ...range, lostSsId: loss.lostSsId, holeLength }
27865
+ };
27866
+ const previous = entries.get(entry.key);
27867
+ if (previous) {
27868
+ retire(previous);
27869
+ stop(previous, "reset");
27870
+ }
27871
+ entries.set(entry.key, entry);
27872
+ entry.expiry = setTimeout(dispatch, Math.max(0, entry.deadlineAt - performance.now()) + 1);
27873
+ preemptDeltas();
27874
+ dispatch();
27875
+ });
27876
+ }
26901
27877
  return () => {
26902
27878
  disposed = true;
26903
27879
  removeResetObserver();
26904
27880
  removeLifecycleObserver();
26905
27881
  for (const entry of [...entries.values()]) {
26906
- clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
27882
+ clearEntry(entry);
26907
27883
  if (entry.running) releaseHold(entry);
26908
27884
  stop(entry, "disposed");
27885
+ if (entry.expiry !== void 0) clearTimeout(entry.expiry);
26909
27886
  }
26910
27887
  entries.clear();
26911
27888
  };
@@ -26944,6 +27921,7 @@ export {
26944
27921
  MfuReassemblyError,
26945
27922
  MmtpContainerParser,
26946
27923
  MmtpDecodePipeline,
27924
+ MmtpFecSession,
26947
27925
  MmtpRouter,
26948
27926
  MmtpToCmaf,
26949
27927
  MulticastContainerContractError,
@@ -26979,6 +27957,8 @@ export {
26979
27957
  buildVideoInitSegment,
26980
27958
  catalogAmtNetworkSource,
26981
27959
  catalogDeclaresFec,
27960
+ catalogFecAvailable,
27961
+ catalogFecDeclaresUnconfigurableInstance,
26982
27962
  catalogFecInterleaveMs,
26983
27963
  catalogFecMediaUnitsPerSecond,
26984
27964
  catalogFecUnavailable,
@@ -27053,6 +28033,7 @@ export {
27053
28033
  isTrackTimingConfig,
27054
28034
  joinedRepairSymbolCount,
27055
28035
  keyframeIntervalMediaTicks,
28036
+ locateCatalogFecSource,
27056
28037
  mergeOverrideIntoCmsfTracks,
27057
28038
  mergeOverrideIntoHangRenditions,
27058
28039
  mfuReassemblyTimeoutMs,