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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/README.md +36 -20
  2. package/dist/align.d.ts +24 -18
  3. package/dist/align.d.ts.map +1 -1
  4. package/dist/align.js +23 -4
  5. package/dist/align.js.map +2 -2
  6. package/dist/browser-runtime.js +1904 -692
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +76 -39
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +321 -205
  11. package/dist/carp-catalog.js.map +3 -3
  12. package/dist/catalog-fec-params.d.ts +12 -4
  13. package/dist/catalog-fec-params.d.ts.map +1 -1
  14. package/dist/catalog-fec-params.js +40 -17
  15. package/dist/catalog-fec-params.js.map +3 -3
  16. package/dist/catalog-network-source.d.ts +28 -7
  17. package/dist/catalog-network-source.d.ts.map +1 -1
  18. package/dist/catalog-network-source.js +21 -1
  19. package/dist/catalog-network-source.js.map +2 -2
  20. package/dist/catalog-validator.d.ts +4 -3
  21. package/dist/catalog-validator.d.ts.map +1 -1
  22. package/dist/catalog-validator.js +0 -29
  23. package/dist/catalog-validator.js.map +3 -3
  24. package/dist/cmcd-producer.d.ts +8 -0
  25. package/dist/cmcd-producer.d.ts.map +1 -1
  26. package/dist/cmcd-producer.js +14 -0
  27. package/dist/cmcd-producer.js.map +2 -2
  28. package/dist/delivery-catalog.js +98 -234
  29. package/dist/delivery-catalog.js.map +4 -4
  30. package/dist/fec-manager.d.ts +108 -1
  31. package/dist/fec-manager.d.ts.map +1 -1
  32. package/dist/fec-manager.js +452 -66
  33. package/dist/fec-manager.js.map +4 -4
  34. package/dist/fec-state.d.ts +2 -1
  35. package/dist/fec-state.d.ts.map +1 -1
  36. package/dist/fec-state.js +18 -3
  37. package/dist/fec-state.js.map +3 -3
  38. package/dist/fec-worker-setup.d.ts +10 -0
  39. package/dist/fec-worker-setup.d.ts.map +1 -1
  40. package/dist/fec-worker-setup.js +15 -4
  41. package/dist/fec-worker-setup.js.map +2 -2
  42. package/dist/held-layer-admission.d.ts +58 -0
  43. package/dist/held-layer-admission.d.ts.map +1 -0
  44. package/dist/held-layer-admission.js +105 -0
  45. package/dist/held-layer-admission.js.map +7 -0
  46. package/dist/index.d.ts +5 -5
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +8 -8
  49. package/dist/index.js.map +2 -2
  50. package/dist/iso-block-locator.d.ts +39 -1
  51. package/dist/iso-block-locator.d.ts.map +1 -1
  52. package/dist/iso-block-locator.js +109 -17
  53. package/dist/iso-block-locator.js.map +3 -3
  54. package/dist/manifest-auth-plan.d.ts +26 -25
  55. package/dist/manifest-auth-plan.d.ts.map +1 -1
  56. package/dist/manifest-auth-plan.js +331 -1171
  57. package/dist/manifest-auth-plan.js.map +4 -4
  58. package/dist/mfu-reassembler.js +21 -13
  59. package/dist/mfu-reassembler.js.map +2 -2
  60. package/dist/mmtp-container-parser.d.ts.map +1 -1
  61. package/dist/mmtp-container-parser.js +93 -22
  62. package/dist/mmtp-container-parser.js.map +2 -2
  63. package/dist/mmtp-container-parser.no-modules.js +1250 -317
  64. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  65. package/dist/mmtp-decode-pipeline.js +93 -22
  66. package/dist/mmtp-decode-pipeline.js.map +2 -2
  67. package/dist/mmtp-fec-session.d.ts +192 -0
  68. package/dist/mmtp-fec-session.d.ts.map +1 -0
  69. package/dist/mmtp-fec-session.js +640 -0
  70. package/dist/mmtp-fec-session.js.map +7 -0
  71. package/dist/mmtp-router.d.ts +39 -6
  72. package/dist/mmtp-router.d.ts.map +1 -1
  73. package/dist/mmtp-router.js +184 -27
  74. package/dist/mmtp-router.js.map +2 -2
  75. package/dist/multicast-auth-catalog.d.ts +86 -92
  76. package/dist/multicast-auth-catalog.d.ts.map +1 -1
  77. package/dist/multicast-auth-catalog.js +347 -132
  78. package/dist/multicast-auth-catalog.js.map +4 -4
  79. package/dist/multicast-input.d.ts +31 -8
  80. package/dist/multicast-input.d.ts.map +1 -1
  81. package/dist/multicast-input.js +299 -35
  82. package/dist/multicast-input.js.map +3 -3
  83. package/dist/multicast-manager.d.ts +94 -5
  84. package/dist/multicast-manager.d.ts.map +1 -1
  85. package/dist/multicast-manager.js +908 -357
  86. package/dist/multicast-manager.js.map +4 -4
  87. package/dist/multicast-transport.d.ts +12 -2
  88. package/dist/multicast-transport.d.ts.map +1 -1
  89. package/dist/multicast-transport.js +108 -238
  90. package/dist/multicast-transport.js.map +4 -4
  91. package/dist/multicast-unwrap.js +21 -13
  92. package/dist/multicast-unwrap.js.map +2 -2
  93. package/dist/no-modules.d.ts +4 -1
  94. package/dist/no-modules.d.ts.map +1 -1
  95. package/dist/no-modules.js +1195 -301
  96. package/dist/no-modules.js.map +4 -4
  97. package/dist/phase14-catalog-override.d.ts +1 -1
  98. package/dist/phase14-catalog-override.d.ts.map +1 -1
  99. package/dist/phase14-catalog-override.js +2 -2
  100. package/dist/phase14-catalog-override.js.map +2 -2
  101. package/dist/repair-fetch.d.ts +81 -6
  102. package/dist/repair-fetch.d.ts.map +1 -1
  103. package/dist/repair-fetch.js +156 -31
  104. package/dist/repair-fetch.js.map +3 -3
  105. package/dist/repair-layers.d.ts +2 -0
  106. package/dist/repair-layers.d.ts.map +1 -1
  107. package/dist/repair-layers.js +19 -2
  108. package/dist/repair-layers.js.map +2 -2
  109. package/dist/sample-combiner.d.ts +7 -1
  110. package/dist/sample-combiner.d.ts.map +1 -1
  111. package/dist/sample-combiner.js +14 -2
  112. package/dist/sample-combiner.js.map +2 -2
  113. package/dist/signaling.d.ts +2 -2
  114. package/dist/signaling.d.ts.map +1 -1
  115. package/dist/signaling.js +3 -3
  116. package/dist/signaling.js.map +2 -2
  117. package/dist/source-auth.js +2710 -7
  118. package/dist/source-auth.js.map +4 -4
  119. package/dist/switching-set-alignment.d.ts +1 -1
  120. package/dist/switching-set-alignment.js.map +1 -1
  121. package/dist/timestamp-codec.js +21 -13
  122. package/dist/timestamp-codec.js.map +2 -2
  123. package/dist/wasm-mfu-reassembler.js.map +1 -1
  124. package/dist/wasm-mmtp-container-parser.js +93 -22
  125. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  126. package/package.json +6 -9
  127. package/schemas/catalog.schema.json +133 -38
  128. package/src/align.ts +52 -21
  129. package/src/carp-catalog.ts +188 -68
  130. package/src/catalog-fec-params.ts +28 -3
  131. package/src/catalog-network-source.ts +49 -7
  132. package/src/catalog-validator.ts +4 -11
  133. package/src/cmcd-producer.ts +17 -0
  134. package/src/fec-manager.ts +366 -63
  135. package/src/fec-state.ts +11 -4
  136. package/src/fec-worker-setup.ts +30 -2
  137. package/src/held-layer-admission.ts +161 -0
  138. package/src/index.ts +27 -10
  139. package/src/iso-block-locator.ts +110 -7
  140. package/src/manifest-auth-plan.ts +39 -91
  141. package/src/mmtp-container-parser.ts +75 -7
  142. package/src/mmtp-fec-session.ts +606 -0
  143. package/src/mmtp-router.ts +166 -7
  144. package/src/multicast-auth-catalog.ts +131 -238
  145. package/src/multicast-input.ts +148 -124
  146. package/src/multicast-manager.ts +267 -21
  147. package/src/multicast-transport.ts +17 -3
  148. package/src/no-modules.ts +7 -1
  149. package/src/phase14-catalog-override.ts +3 -3
  150. package/src/repair-fetch.ts +283 -39
  151. package/src/repair-layers.ts +22 -2
  152. package/src/sample-combiner.ts +15 -2
  153. package/src/signaling.ts +2 -2
  154. package/src/switching-set-alignment.ts +1 -1
  155. package/test-vectors/align.json +108 -32
  156. package/test-vectors/bc-provenance-v2.json +1526 -0
  157. package/test-vectors/catalog/README.md +71 -4
  158. package/test-vectors/catalog/negative/fec-block-profile-missing.json +1 -1
  159. package/test-vectors/catalog/negative/fec-block-profile-retired.json +1 -1
  160. package/test-vectors/catalog/negative/fec-block-profile-unknown.json +1 -1
  161. package/test-vectors/catalog/negative/fec-iso-symbol-size-below-floor.json +28 -0
  162. package/test-vectors/catalog/negative/fec-reed-solomon-iso-symbol-size-13.json +28 -0
  163. package/test-vectors/catalog/negative/fec-reed-solomon-k-plus-p-over-255.json +39 -0
  164. package/test-vectors/catalog/negative/fec-reed-solomon-overlay-over-255.json +40 -0
  165. package/test-vectors/catalog/negative/fec-repair-overlay-source-symbols-zero.json +43 -0
  166. package/test-vectors/catalog/negative/fec-repair-symbols-zero.json +28 -0
  167. package/test-vectors/catalog/negative/fec-source-symbols-zero.json +28 -0
  168. package/test-vectors/catalog/negative/fec-symbol-size-zero.json +28 -0
  169. package/test-vectors/catalog/negative/init-data-inline-without-data.json +22 -0
  170. package/test-vectors/catalog/negative/mmtp-mode-mpu.json +15 -0
  171. package/test-vectors/catalog/negative/multicast-amt-dns-without-relay.json +37 -0
  172. package/test-vectors/catalog/negative/multicast-amt-driad-with-relay.json +38 -0
  173. package/test-vectors/catalog/negative/multicast-auth-asm-missing-sender-address.json +77 -0
  174. package/test-vectors/catalog/negative/multicast-auth-duplicate-first-epoch.json +56 -0
  175. package/test-vectors/catalog/negative/multicast-auth-duplicate-kid.json +56 -0
  176. package/test-vectors/catalog/negative/multicast-auth-endpoint-auth-without-object-auth.json +38 -0
  177. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-auth.json +49 -0
  178. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-bandwidth.json +55 -0
  179. package/test-vectors/catalog/negative/multicast-auth-manifest-port-equals-port.json +56 -0
  180. package/test-vectors/catalog/negative/multicast-auth-manifest-timer-out-of-range.json +56 -0
  181. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-above-max.json +56 -0
  182. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-below-min.json +56 -0
  183. package/test-vectors/catalog/negative/multicast-auth-root-dotted-key.json +55 -0
  184. package/test-vectors/catalog/negative/multicast-auth-sender-address-on-ssm.json +57 -0
  185. package/test-vectors/catalog/negative/multicast-auth-version-1.json +56 -0
  186. package/test-vectors/catalog/negative/multicast-auth-version-3.json +56 -0
  187. package/test-vectors/catalog/negative/multicast-auth-version-missing.json +55 -0
  188. package/test-vectors/catalog/negative/multicast-endpoint-foreign-namespace-track.json +44 -0
  189. package/test-vectors/catalog/negative/multicast-endpoint-protocol-amt.json +38 -0
  190. package/test-vectors/catalog/negative/multicast-endpoint-protocol-atsc3.json +38 -0
  191. package/test-vectors/catalog/negative/presentation-anchor-unsafe.json +16 -0
  192. package/test-vectors/catalog/positive/fec-algorithm-unimplemented.json +29 -0
  193. package/test-vectors/catalog/positive/fec-iso-ssbg1.json +1 -1
  194. package/test-vectors/catalog/positive/fec-multicast.json +1 -1
  195. package/test-vectors/catalog/positive/fec-reed-solomon-layered.json +50 -0
  196. package/test-vectors/catalog/positive/mmt01-12-1-init-ref-anchor.json +29 -0
  197. package/test-vectors/catalog/positive/multicast-amt-discovery-omitted.json +37 -0
  198. package/test-vectors/catalog/positive/multicast-amt-dns-relay.json +38 -0
  199. package/test-vectors/catalog/positive/multicast-amt-manual-relay.json +3 -3
  200. package/test-vectors/catalog/{negative/multicast-endpoint-missing-protocol-and-source.json → positive/multicast-asm-unprotected.json} +10 -5
  201. package/test-vectors/catalog/positive/multicast-auth-asm-sender.json +78 -0
  202. package/test-vectors/catalog/positive/multicast-auth-rotation.json +39 -38
  203. package/test-vectors/catalog/positive/multicast-draft01-4-1-example.json +81 -0
  204. package/test-vectors/catalog/positive/multicast-draft01-7-2-6-example.json +70 -0
  205. package/test-vectors/catalog/positive/presentation-anchor-negative.json +27 -0
  206. package/test-vectors/catalog/section-codes.json +31 -1
  207. package/test-vectors/catalog-multicast-auth-v1.json +38 -20
  208. package/test-vectors/catalog-validation.json +101 -5
  209. package/test-vectors/catalog-validator-public-api.mjs +14 -9
  210. package/test-vectors/generate-bc-provenance-v2.mjs +252 -0
  211. package/dist/fec-codec.d.ts +0 -32
  212. package/dist/fec-codec.d.ts.map +0 -1
  213. package/dist/fec-codec.js +0 -47
  214. package/dist/fec-codec.js.map +0 -7
  215. package/src/fec-codec.ts +0 -61
@@ -171,26 +171,30 @@ function isEmptyOrExactLegacyTrailer(payload, start, end) {
171
171
  const authLength = view2.getUint16(2, false);
172
172
  return start + LEGACY_TRAILER_HEADER_SIZE + authLength === end;
173
173
  }
174
- function resolveDeclaredTrailers(payload, declaredEnd, fecType, options) {
174
+ function resolveDeclaredTrailers(payload, declaredEnd, fecType, options, rapFlag = false) {
175
175
  if (declaredEnd > payload.length)
176
176
  return null;
177
177
  if (options?.skipFecId) {
178
- return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false } : null;
178
+ return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false, hasOverlayFecId: false } : null;
179
179
  }
180
+ const overlay = options?.overlayDeclared === true && rapFlag;
180
181
  if (fecType === 1) {
181
- const fecStart = payload.length - SOURCE_FEC_PAYLOAD_ID_SIZE;
182
+ const fecStart = payload.length - sourceFecTrailerSize(overlay);
182
183
  if (fecStart < declaredEnd || !isEmptyOrExactLegacyTrailer(payload, declaredEnd, fecStart)) {
183
184
  return null;
184
185
  }
185
- return { hasFecId: true };
186
+ return { hasFecId: true, hasOverlayFecId: overlay };
186
187
  }
187
- if (fecType !== 0)
188
+ if (fecType !== 0 || overlay)
188
189
  return null;
189
190
  if (isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)) {
190
- return { hasFecId: false };
191
+ return { hasFecId: false, hasOverlayFecId: false };
191
192
  }
192
193
  return null;
193
194
  }
195
+ function sourceFecTrailerSize(overlay) {
196
+ return overlay ? 2 * SOURCE_FEC_PAYLOAD_ID_SIZE : SOURCE_FEC_PAYLOAD_ID_SIZE;
197
+ }
194
198
  function planMfuExtraction(mmtpPacket, options, parsedHeader) {
195
199
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) {
196
200
  return {
@@ -243,15 +247,16 @@ function planMfuExtraction(mmtpPacket, options, parsedHeader) {
243
247
  if ("rejection" in layoutResult)
244
248
  return layoutResult;
245
249
  const { layout } = layoutResult;
246
- const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options);
250
+ const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options, header.rapFlag);
247
251
  if (!trailerLayout) {
248
252
  if (!options?.skipFecId && header.fecType === 1) {
249
253
  const observed = payload.length - layout.dataEnd;
250
- if (observed !== SOURCE_FEC_PAYLOAD_ID_SIZE) {
254
+ const expected = sourceFecTrailerSize(options?.overlayDeclared === true && header.rapFlag);
255
+ if (observed !== expected) {
251
256
  return {
252
257
  rejection: {
253
258
  gate: "source-fec-payload-id-width-mismatch",
254
- 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})`
259
+ 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})`
255
260
  }
256
261
  };
257
262
  }
@@ -278,10 +283,13 @@ function extractPlannedMfu(mmtpPacket, result) {
278
283
  const mfuDuHeader = mfuDuHeaderPresent && mpu.timedFlag === 1 ? parseTimedMfuDuHeader(payload, MPU_HEADER_SIZE) : null;
279
284
  const itemId = mfuDuHeaderPresent && mpu.timedFlag === 0 ? new DataView(payload.buffer, payload.byteOffset + MPU_HEADER_SIZE, 4).getUint32(0, false) : null;
280
285
  const data = payload.subarray(mfuOffset, dataEnd);
281
- const fecPayloadId = trailerLayout.hasFecId ? {
282
- ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE, SOURCE_FEC_PAYLOAD_ID_SIZE).getUint32(0, false)
283
- } : null;
284
- return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId };
286
+ const trailerStart = mmtpPacket.length - sourceFecTrailerSize(trailerLayout.hasOverlayFecId);
287
+ const ssIdAt = (offset) => ({
288
+ ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + offset, 4).getUint32(0, false)
289
+ });
290
+ const fecPayloadId = trailerLayout.hasFecId ? ssIdAt(trailerStart) : null;
291
+ const overlayFecPayloadId = trailerLayout.hasOverlayFecId ? ssIdAt(trailerStart + SOURCE_FEC_PAYLOAD_ID_SIZE) : null;
292
+ return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId, overlayFecPayloadId };
285
293
  }
286
294
  function sourceFecPayloadIdOf(mmtpPacket, header) {
287
295
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE)
@@ -433,11 +441,16 @@ function catalogFecAvailable(fec) {
433
441
  const block = recordOf(fec);
434
442
  if (block === void 0)
435
443
  return true;
444
+ if (fecAlgorithmUnimplemented(block["algorithm"]))
445
+ return false;
436
446
  const declaresFecInstance = block["algorithm"] !== "none";
437
447
  const profile = block["blockProfile"];
438
448
  const profileOk = isFecBlockProfile(profile) || profile === void 0 && !declaresFecInstance;
439
449
  return profileOk && (!declaresFecInstance || isoBlockSpanUsable(block));
440
450
  }
451
+ function fecAlgorithmUnimplemented(algorithm) {
452
+ return typeof algorithm === "string" && algorithm !== "none" && algorithm !== "raptorq" && algorithm !== "reed-solomon";
453
+ }
441
454
 
442
455
  // src/track-session.ts
443
456
  import { fecBlockBudgetMs } from "@blockcast/mmt-fec";
@@ -556,16 +569,6 @@ import {
556
569
 
557
570
  // src/iso-block-locator.ts
558
571
  var IsoBlockLocator = class _IsoBlockLocator {
559
- /** Known blocks and spans, in serial order of their start. */
560
- #blocks = [];
561
- /** Held first-arrival sources whose block no repair has stated yet. */
562
- #held = /* @__PURE__ */ new Map();
563
- /** End of contiguous coverage: the SS_ID the next unknown block starts at. */
564
- #coverageEnd;
565
- #kMax;
566
- #retentionBlocks;
567
- #heldEvicted = 0;
568
- #newest;
569
572
  /**
570
573
  * @param kMax the catalog maximum K (`sourceSymbols`), the bound on SSB_length.
571
574
  * @param retentionBlocks how many blocks behind the newest position the
@@ -573,12 +576,35 @@ var IsoBlockLocator = class _IsoBlockLocator {
573
576
  * no locator exists without retention.
574
577
  */
575
578
  constructor(kMax, retentionBlocks) {
579
+ /** Known blocks and spans, in serial order of their start. */
580
+ this.#blocks = [];
581
+ /** Held first-arrival sources whose block no repair has stated yet. */
582
+ this.#held = /* @__PURE__ */ new Map();
583
+ this.#heldEvicted = 0;
584
+ /** Pending holes (see `deferIncompleteGaps`): unstated, sources still held. */
585
+ this.#holes = [];
586
+ /**
587
+ * Keep a gap that is missing a source as a pending hole rather than a span,
588
+ * so a repair FETCHed for it (draft-ramadan-moq-fec §7.5) can still state
589
+ * its blocks. Set only while a range repair scheduler is wired; its owner
590
+ * must close every hole it is told about (`closeHolesWithin`).
591
+ */
592
+ this.deferIncompleteGaps = false;
576
593
  if (!Number.isSafeInteger(kMax) || kMax <= 0) {
577
594
  throw new Error(`[IsoBlockLocator] maximum K must be a positive integer (got ${kMax})`);
578
595
  }
579
596
  this.#kMax = kMax;
580
597
  this.#retentionBlocks = _IsoBlockLocator.#checkedRetention(retentionBlocks);
581
598
  }
599
+ #blocks;
600
+ #held;
601
+ /** End of contiguous coverage: the SS_ID the next unknown block starts at. */
602
+ #coverageEnd;
603
+ #kMax;
604
+ #retentionBlocks;
605
+ #heldEvicted;
606
+ #newest;
607
+ #holes;
582
608
  static #checkedRetention(retentionBlocks) {
583
609
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
584
610
  throw new Error(
@@ -641,6 +667,14 @@ var IsoBlockLocator = class _IsoBlockLocator {
641
667
  }
642
668
  return null;
643
669
  }
670
+ /** Number of pending holes. */
671
+ get holeCount() {
672
+ return this.#holes.length;
673
+ }
674
+ /** The stated block (never a span) ending exactly at `end`. */
675
+ blockEndingAt(end) {
676
+ return this.#blocks.find((block) => !block.span && isoBlockEnd(block.start, block.length) === end);
677
+ }
644
678
  /** The known block or span starting exactly at `start`. */
645
679
  blockAt(start) {
646
680
  return this.#blocks.find((block) => block.start === start);
@@ -663,6 +697,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
663
697
  coversBetween(a, b) {
664
698
  if (this.#coverageEnd === void 0) return false;
665
699
  if (!serial32Precedes(a, b) || serial32Distance(a, b) <= 1) return true;
700
+ const first = a + 1 >>> 0;
701
+ const count = serial32Distance(a, b) - 1;
702
+ if (this.#holes.some((hole) => isoRangesOverlap(first, count, hole.start, hole.length))) return false;
666
703
  return serial32Precedes(b - 1 >>> 0, this.#coverageEnd);
667
704
  }
668
705
  /**
@@ -692,6 +729,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
692
729
  * known block (a different length, or an overlap with another block or a
693
730
  * span) fails closed: the repair symbol is dropped and no block changes.
694
731
  * A newly stated block retires behind its SS_Start (see the class note).
732
+ * A block so far past `newest` that stating it would retire the position
733
+ * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
734
+ * this is slightly conservative (retirement measures that block from its
735
+ * last SS_ID), dropping up to one block-length of repairs past the horizon
736
+ * until a source moves `newest`. Placing it would turn everything
737
+ * between into a repair-less span and leave every real repair behind it
738
+ * `stale`. Sources move `newest` (`hold`, `observe`), so after a real outage
739
+ * the first source back brings the next repair inside the horizon; until one
740
+ * arrives, a stream's repairs alone cannot pass it.
695
741
  */
696
742
  placeRepair(start, length) {
697
743
  if (!Number.isSafeInteger(length) || length <= 0 || length > this.#kMax) {
@@ -710,6 +756,22 @@ var IsoBlockLocator = class _IsoBlockLocator {
710
756
  }
711
757
  return { status: "placed", block: known, placed: [] };
712
758
  }
759
+ const pending = this.#holes.find((h) => isoBlockContains(h.start, h.length, start));
760
+ if (pending !== void 0) {
761
+ if (!isoBlockContains(pending.start, pending.length, serial32Add(start, length - 1))) {
762
+ return { status: "overlap", reason: `repair block ${start}+${length} runs past pending hole ${pending.start}+${pending.length}` };
763
+ }
764
+ this.#holes.splice(this.#holes.indexOf(pending), 1);
765
+ const before = serial32Distance(pending.start, start);
766
+ const afterStart = isoBlockEnd(start, length);
767
+ const after = pending.length - before - length;
768
+ if (before > 0) this.#holes.push({ start: pending.start, length: before, span: false });
769
+ if (after > 0) this.#holes.push({ start: afterStart, length: after, span: false });
770
+ const block2 = { start, length, span: false };
771
+ const placed2 = this.#claim(block2);
772
+ this.#blocks.push(block2);
773
+ return { status: "placed", block: block2, placed: placed2 };
774
+ }
713
775
  for (const block2 of this.#blocks) {
714
776
  if (isoBlockContains(block2.start, block2.length, start) || isoBlockContains(start, length, block2.start)) {
715
777
  return {
@@ -718,7 +780,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
718
780
  };
719
781
  }
720
782
  }
783
+ if (this.#newest !== void 0 && isoBlocksBehindLowerBound(this.#newest, start, this.#kMax) > this.#retentionBlocks) {
784
+ return { status: "ahead", reason: `repair block ${start}+${length} is past the retention horizon ahead of ${this.#newest}` };
785
+ }
721
786
  let span;
787
+ let hole;
722
788
  if (this.#coverageEnd === void 0) {
723
789
  for (const ssId of this.#held.keys()) {
724
790
  if (serial32Precedes(ssId, start)) this.#held.delete(ssId);
@@ -727,21 +793,51 @@ var IsoBlockLocator = class _IsoBlockLocator {
727
793
  } else if (serial32Precedes(start, this.#coverageEnd)) {
728
794
  return { status: "stale", reason: `repair block ${start}+${length} precedes known coverage` };
729
795
  } else if (start !== this.#coverageEnd) {
730
- const spanBlock = {
731
- start: this.#coverageEnd,
732
- length: serial32Distance(this.#coverageEnd, start),
733
- span: true
734
- };
735
- span = { block: spanBlock, placed: this.#claim(spanBlock) };
736
- this.#blocks.push(spanBlock);
796
+ const gap = { start: this.#coverageEnd, length: serial32Distance(this.#coverageEnd, start) };
797
+ const lostSsId = this.deferIncompleteGaps ? this.#highestMissing(gap.start, gap.length) : void 0;
798
+ if (lostSsId !== void 0) {
799
+ const holeBlock = { ...gap, span: false };
800
+ this.#holes.push(holeBlock);
801
+ hole = { block: holeBlock, lostSsId };
802
+ } else {
803
+ const spanBlock = { ...gap, span: true };
804
+ span = { block: spanBlock, placed: this.#claim(spanBlock) };
805
+ this.#blocks.push(spanBlock);
806
+ }
737
807
  }
738
808
  const block = { start, length, span: false };
739
809
  const placed = this.#claim(block);
740
810
  this.#blocks.push(block);
741
811
  this.#coverageEnd = isoBlockEnd(start, length);
742
812
  this.retireBehind(start);
813
+ if (hole !== void 0) return { status: "placed", block, placed, hole };
743
814
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
744
815
  }
816
+ /**
817
+ * Turn every pending hole inside `[start, start + length)` into a
818
+ * repair-less span, claiming its held sources: its range FETCH ended, so
819
+ * nothing more will state its blocks. Returns the spans, in SS_ID order.
820
+ */
821
+ closeHolesWithin(start, length) {
822
+ const closed = [];
823
+ for (const hole of [...this.#holes]) {
824
+ if (!isoBlockContains(start, length, hole.start)) continue;
825
+ this.#holes.splice(this.#holes.indexOf(hole), 1);
826
+ const spanBlock = { start: hole.start, length: hole.length, span: true };
827
+ closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
828
+ this.#blocks.push(spanBlock);
829
+ }
830
+ return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
831
+ }
832
+ /** The highest SS_ID in the range no source is held for, or undefined when all are. */
833
+ #highestMissing(start, length) {
834
+ const steps = Math.min(length, this.#held.size + 1);
835
+ for (let i = 1; i <= steps; i++) {
836
+ const ssId = serial32Add(start, length - i);
837
+ if (!this.#held.has(ssId)) return ssId;
838
+ }
839
+ return void 0;
840
+ }
745
841
  /**
746
842
  * Retire every block and span whose last SS_ID, and every held source,
747
843
  * lies more than `retentionBlocks` blocks behind `position`, with the shared
@@ -760,6 +856,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
760
856
  this.#blocks.splice(i, 1);
761
857
  }
762
858
  }
859
+ for (let i = this.#holes.length - 1; i >= 0; i--) {
860
+ const hole = this.#holes[i];
861
+ const last = serial32Add(hole.start, hole.length - 1);
862
+ if (isoBlocksBehindLowerBound(last, position, this.#kMax) > horizon) this.#holes.splice(i, 1);
863
+ }
763
864
  for (const ssId of [...this.#held.keys()]) {
764
865
  if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon) this.#held.delete(ssId);
765
866
  }
@@ -768,6 +869,7 @@ var IsoBlockLocator = class _IsoBlockLocator {
768
869
  /** Forget everything (publisher restart, track reset). */
769
870
  reset() {
770
871
  this.#blocks.length = 0;
872
+ this.#holes.length = 0;
771
873
  this.#held.clear();
772
874
  this.#coverageEnd = void 0;
773
875
  this.#newest = void 0;
@@ -783,6 +885,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
783
885
  return placed;
784
886
  }
785
887
  };
888
+ function isoRangesOverlap(aStart, aLength, bStart, bLength) {
889
+ return serial32Distance(aStart, bStart) < aLength || serial32Distance(bStart, aStart) < bLength;
890
+ }
786
891
 
787
892
  // src/fec-state.ts
788
893
  var MIN_INTERLEAVE_DEPTH_MS = 1;
@@ -1256,7 +1361,81 @@ function decideGap(input) {
1256
1361
  });
1257
1362
  }
1258
1363
 
1364
+ // src/held-layer-admission.ts
1365
+ var HORIZON_CAP = 1073741824;
1366
+ function heldLayerAnchorHorizon(retentionBlocks, k) {
1367
+ return retentionBlocks === void 0 || k <= 0 ? HORIZON_CAP : Math.min(HORIZON_CAP, retentionBlocks * k);
1368
+ }
1369
+ var HeldLayerAdmission = class {
1370
+ #layerNames;
1371
+ #states;
1372
+ constructor(layers, heldLayers = [0]) {
1373
+ const held = new Set(heldLayers);
1374
+ this.#layerNames = new Set(layers.map((l) => l.repairTrackName));
1375
+ this.#states = layers.filter((l) => held.has(l.layer)).map((l) => ({ layer: l.layer, repairTrackName: l.repairTrackName, total: l.rsIdOffset + l.repairSymbols }));
1376
+ }
1377
+ /**
1378
+ * Judges one repair packet, after the 4.5 discards and the size check and
1379
+ * before it places a block. `repairTrackName` is the subscribed repair
1380
+ * track, never inferred from RS_ID; without it only (b) runs. A packet on a
1381
+ * repair track the catalog does not list is `'discard'` and anchors nothing.
1382
+ * `sourceFrontier` is the newest source SS_ID, if any: a repair more than
1383
+ * `horizon` past it is judged without moving the anchored state.
1384
+ *
1385
+ * @returns undefined to admit, `'discard'`, or the fail-closed reason.
1386
+ */
1387
+ admit(repairTrackName, ssStart, rsbLength, horizon, sourceFrontier) {
1388
+ if (repairTrackName !== void 0 && !this.#layerNames.has(repairTrackName)) return "discard";
1389
+ const farAhead = sourceFrontier !== void 0 && serial32Precedes(sourceFrontier, ssStart) && serial32Distance(sourceFrontier, ssStart) > horizon;
1390
+ for (const state of this.#states) {
1391
+ let code;
1392
+ if (farAhead) {
1393
+ if (rsbLength < state.total) {
1394
+ if (state.layer > 0 && repairTrackName === state.repairTrackName) code = "below_own_track_total";
1395
+ else if (state.anchor !== void 0 || state.settled) code = "below_anchored_total";
1396
+ }
1397
+ } else {
1398
+ if (state.newest === void 0 || serial32Precedes(state.newest, ssStart)) state.newest = ssStart;
1399
+ const stale = (s) => serial32Distance(s, state.newest) > horizon;
1400
+ if (state.latestBelow !== void 0 && stale(state.latestBelow)) {
1401
+ delete state.latestBelow;
1402
+ delete state.latestBelowRsb;
1403
+ }
1404
+ if (state.anchor !== void 0 && stale(state.anchor)) state.settled = true;
1405
+ if (rsbLength < state.total) {
1406
+ if (state.layer > 0 && repairTrackName === state.repairTrackName) code = "below_own_track_total";
1407
+ else if (stale(ssStart)) continue;
1408
+ else if (state.settled || state.anchor !== void 0 && !serial32Precedes(ssStart, state.anchor)) code = "below_anchored_total";
1409
+ else if (state.latestBelow === void 0 || serial32Precedes(state.latestBelow, ssStart)) {
1410
+ state.latestBelow = ssStart;
1411
+ state.latestBelowRsb = rsbLength;
1412
+ }
1413
+ } else if (!state.settled && !stale(ssStart)) {
1414
+ if (state.anchor === void 0 || serial32Precedes(ssStart, state.anchor)) state.anchor = ssStart;
1415
+ if (state.latestBelow !== void 0 && !serial32Precedes(state.latestBelow, state.anchor)) {
1416
+ code = "below_anchored_total";
1417
+ ssStart = state.latestBelow;
1418
+ rsbLength = state.latestBelowRsb;
1419
+ }
1420
+ }
1421
+ }
1422
+ if (code !== void 0) {
1423
+ return {
1424
+ code,
1425
+ layer: state.layer,
1426
+ total: state.total,
1427
+ rsbLength,
1428
+ ssStart,
1429
+ ...state.anchor === void 0 ? {} : { anchor: state.anchor }
1430
+ };
1431
+ }
1432
+ }
1433
+ return void 0;
1434
+ }
1435
+ };
1436
+
1259
1437
  // src/fec-manager.ts
1438
+ var RS_MAX_BLOCK_SYMBOLS = 255;
1260
1439
  var WORKER_ERROR_LOG_CAP = 5;
1261
1440
  var WORKER_ERROR_KIND_CAP = 32;
1262
1441
  var WORKER_ERROR_OVERFLOW_KIND = "other";
@@ -1371,6 +1550,11 @@ var FECManager = class _FECManager {
1371
1550
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
1372
1551
  // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
1373
1552
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
1553
+ /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
1554
+ this.#heldLayerStates = /* @__PURE__ */ new Map();
1555
+ /** Streams whose FEC failed closed at runtime (fec-01 6.3.9). */
1556
+ this.#fecFailClosed = /* @__PURE__ */ new Map();
1557
+ this.#onFecFailClosed = null;
1374
1558
  // Blocks already recovered — prevents late source symbols from restarting timeouts.
1375
1559
  // WASM removes blocks after recovery; late symbols create empty blocks returning null,
1376
1560
  // which would falsely start new timeouts without this guard.
@@ -1491,12 +1675,17 @@ var FECManager = class _FECManager {
1491
1675
  // per stream. Not only throws: the ordinary out-of-range case is detected by
1492
1676
  // arithmetic and never throws at all.
1493
1677
  this.#orderedHorizonWarnedFor = /* @__PURE__ */ new Set();
1494
- // Newest block start (SS_Start) seen per stream and when: the frontier for
1495
- // source-discontinuity detection and isoSpanResolution.
1678
+ // Newest block start (SS_Start) any symbol carried per stream and when: the
1679
+ // frontier isoSpanResolution reads.
1496
1680
  this.#highestSbn = /* @__PURE__ */ new Map();
1681
+ // The same from source symbols alone: the frontier a source is judged
1682
+ // against for a discontinuity. Repairs ride their own group, which can run
1683
+ // blocks ahead of the media they protect.
1684
+ this.#sourceFrontiers = /* @__PURE__ */ new Map();
1497
1685
  // iso-ssbg1-v1 block location per stream (streamKey). A source belongs to a
1498
1686
  // block only once a repair symbol stated the block's (SS_Start, SSB_length).
1499
1687
  this.#isoLocators = /* @__PURE__ */ new Map();
1688
+ this.#deferIsoGaps = false;
1500
1689
  this.#isoRepairRefusedCount = 0;
1501
1690
  this.#isoSourceOversizeCount = 0;
1502
1691
  // Held sources a locator's capacity cap evicted (IsoBlockLocator.heldCapacity):
@@ -1511,8 +1700,8 @@ var FECManager = class _FECManager {
1511
1700
  // rate-limited like the other per-symbol warns here. Cumulative.
1512
1701
  this.#isoDecoderUnplacedRetireFailed = 0;
1513
1702
  // The latest source symbol per stream that carried its MMTP
1514
- // packet_sequence_number: the anchor that bounds how many blocks the
1515
- // producer can have started before a later source symbol.
1703
+ // packet_sequence_number, by its own SS_ID: the anchor that bounds how far
1704
+ // the producer's SS_IDs can have moved before or after another source symbol.
1516
1705
  this.#sourceAnchors = /* @__PURE__ */ new Map();
1517
1706
  // Catalog/reset epoch per packetId. Gap decisions carry it for fencing.
1518
1707
  this.#packetEpochs = /* @__PURE__ */ new Map();
@@ -1571,6 +1760,14 @@ var FECManager = class _FECManager {
1571
1760
  this.onBlockReclassified = null;
1572
1761
  /** A video stream's classifier mode was established or changed. */
1573
1762
  this.onClassifierMode = null;
1763
+ /**
1764
+ * A repair stated a block past a gap that is missing a source and whose
1765
+ * every repair was lost: a lost SS_ID in an undelimited span
1766
+ * (draft-ramadan-moq-fec §7.5). Set with `setUndelimitedLossHandler`; the
1767
+ * receiver keeps the gap as a pending hole until `closeIsoHoles` is called
1768
+ * for it, which it must be.
1769
+ */
1770
+ this.#onUndelimitedLoss = null;
1574
1771
  /** A block every symbol of which vanished was created by SBN evidence. */
1575
1772
  this.onBlockVanished = null;
1576
1773
  /** A block reached a terminal state (completed, recovered, or failed). */
@@ -1612,6 +1809,9 @@ var FECManager = class _FECManager {
1612
1809
  #ssbLengthConflictCount;
1613
1810
  #blockRepairRsIds;
1614
1811
  #blockRsbLengths;
1812
+ #heldLayerStates;
1813
+ #fecFailClosed;
1814
+ #onFecFailClosed;
1615
1815
  #completedBlocks;
1616
1816
  #terminalExpiryMs;
1617
1817
  #terminalQueues;
@@ -1650,7 +1850,9 @@ var FECManager = class _FECManager {
1650
1850
  #materializedBlocks;
1651
1851
  #orderedHorizonWarnedFor;
1652
1852
  #highestSbn;
1853
+ #sourceFrontiers;
1653
1854
  #isoLocators;
1855
+ #deferIsoGaps;
1654
1856
  #isoRepairRefusedCount;
1655
1857
  #isoSourceOversizeCount;
1656
1858
  #isoHeldEvictedCount;
@@ -1664,6 +1866,7 @@ var FECManager = class _FECManager {
1664
1866
  #workerErrorCounts;
1665
1867
  #decoderUnavailableEvents;
1666
1868
  #repairSymbolSizeMismatchCount;
1869
+ #onUndelimitedLoss;
1667
1870
  #encodeTrackName(catalogTrackName) {
1668
1871
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
1669
1872
  if (encoded === void 0) {
@@ -2240,8 +2443,8 @@ var FECManager = class _FECManager {
2240
2443
  // Deliberately one block tighter than deriveFecRetentionBlocks over the same
2241
2444
  // inputs (that function's `+ 1`). Different question: the retention horizon
2242
2445
  // asks how long the decoder still ACCEPTS symbols for a block, this asks how
2243
- // many blocks a stream can live behind (or ahead of) its frontier before a
2244
- // source symbol there is a discontinuity rather than loss (see #noteSbnSeen).
2446
+ // many blocks a stream can jump ahead of its frontier before a source symbol
2447
+ // there is a discontinuity rather than loss (see #noteSbnSeen).
2245
2448
  // The extra block of retention is slack for a block still being fed; a block
2246
2449
  // nothing has been heard from does not get it. Not the units defect — but it
2247
2450
  // is the next place the two can drift, so change both or neither.
@@ -2251,55 +2454,72 @@ var FECManager = class _FECManager {
2251
2454
  }
2252
2455
  /**
2253
2456
  * Record that a symbol for block `sbn` (the block's SS_Start) arrived and
2254
- * advance the stream's frontier, the newest block start seen.
2457
+ * advance the stream's frontiers, the newest block start seen.
2255
2458
  *
2256
- * A SOURCE symbol whose block goes back further than one live window, or
2257
- * jumps further than the stream could have produced since its last symbol,
2258
- * is a source discontinuity, not loss. A repair symbol can only advance the
2459
+ * A SOURCE symbol is judged against the newest source block alone: repairs
2460
+ * ride their own group, which can run blocks ahead of the media. One whose
2461
+ * block goes back further than the blocks this manager retains, or that
2462
+ * cannot have been sent before the source it lies behind, or that jumps
2463
+ * further than the stream could have produced since its last symbol, is a
2464
+ * source discontinuity, not loss. A repair symbol can only advance the
2259
2465
  * frontier: a D-28 fetch legitimately answers for an old block, so it never
2260
2466
  * signals a discontinuity.
2261
2467
  *
2262
2468
  * The producer closes a block at its Dth media-unit boundary OR when K
2263
2469
  * source symbols filled it, so one interleave span can start several blocks
2264
- * (every large keyframe does). What bounds a forward jump is therefore
2265
- * packet evidence, not a block rate: SS_ID advances by one per FEC source
2266
- * packet (ISO/IEC 23008-1 C.5.2) and the MMTP packet_sequence_number by one
2267
- * per packet of the packet_id, so with both source symbols'
2268
- * packet_sequence_number a block start can move at most the packets sent
2269
- * between them plus the anchor's own offset into its block (< K). Without
2270
- * it, only the D-close rate is known.
2470
+ * (every large keyframe does). What bounds a jump is therefore packet
2471
+ * evidence, not a block rate: SS_ID advances by one per FEC source packet
2472
+ * (ISO/IEC 23008-1 C.5.2) and the MMTP packet_sequence_number by one per
2473
+ * packet of the packet_id, so with both source symbols'
2474
+ * packet_sequence_number their SS_IDs (`ssId`, not their block starts,
2475
+ * which a repair-less span can put far behind) can move at most the packets
2476
+ * sent between them, in either direction, plus K of slack for sources lost
2477
+ * before a hop that renumbers packets. Without it, only the D-close rate is
2478
+ * known.
2271
2479
  *
2272
2480
  * Vanished blocks are not enumerated here: their starts are unknown until a
2273
2481
  * repair states them. The SS_IDs between two stated blocks become one
2274
2482
  * repair-less span when the later block's repair arrives (placeIsoRepair).
2275
2483
  */
2276
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber) {
2484
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
2277
2485
  const streamKey = this.#streamKey(packetId, catalogTrackName);
2278
2486
  const now = performance.now();
2279
- const previous = this.#highestSbn.get(streamKey);
2487
+ const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
2280
2488
  const anchor = this.#sourceAnchors.get(streamKey);
2281
2489
  const psn = symbol === "source" && packetSequenceNumber !== void 0 && Number.isSafeInteger(packetSequenceNumber) && packetSequenceNumber >= 0 && packetSequenceNumber <= 4294967295 ? packetSequenceNumber : void 0;
2282
2490
  const anchorHere = () => {
2283
- if (psn !== void 0 && (anchor === void 0 || !this.#blockPrecedes(sbn, anchor.sbn))) {
2284
- this.#sourceAnchors.set(streamKey, { sbn, psn, atMs: now });
2491
+ if (psn !== void 0 && (anchor === void 0 || !serial32Precedes(ssId, anchor.ssId))) {
2492
+ this.#sourceAnchors.set(streamKey, { ssId, psn, atMs: now });
2493
+ }
2494
+ };
2495
+ const advance = () => {
2496
+ const highest = this.#highestSbn.get(streamKey);
2497
+ if (highest === void 0 || this.#blockPrecedes(highest.sbn, sbn)) {
2498
+ this.#highestSbn.set(streamKey, { sbn, atMs: now });
2285
2499
  }
2500
+ if (symbol === "source") this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
2501
+ anchorHere();
2286
2502
  };
2287
2503
  const discontinuity = () => {
2288
2504
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity();
2289
2505
  this.#highestSbn.set(streamKey, { sbn, atMs: now });
2506
+ this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
2290
2507
  if (psn === void 0) this.#sourceAnchors.delete(streamKey);
2291
- else this.#sourceAnchors.set(streamKey, { sbn, psn, atMs: now });
2508
+ else this.#sourceAnchors.set(streamKey, { ssId, psn, atMs: now });
2292
2509
  this.onSourceDiscontinuity?.(packetId, catalogTrackName);
2293
2510
  };
2294
2511
  if (previous === void 0) {
2295
- this.#highestSbn.set(streamKey, { sbn, atMs: now });
2296
- anchorHere();
2512
+ advance();
2297
2513
  return;
2298
2514
  }
2299
2515
  const config = this.#trackConfig(packetId);
2300
2516
  const window2 = this.#liveWindowBlocks(config);
2517
+ const sentInOrder = (from, to) => {
2518
+ const sent = to.psn - from.psn >>> 0;
2519
+ return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
2520
+ };
2301
2521
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
2302
- if (symbol === "source" && window2 !== null && this.#blocksBehind(sbn, previous.sbn, packetId) > window2) {
2522
+ 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))) {
2303
2523
  discontinuity();
2304
2524
  return;
2305
2525
  }
@@ -2309,9 +2529,8 @@ var FECManager = class _FECManager {
2309
2529
  const missing = this.#blocksBehind(previous.sbn, sbn, packetId) - 1;
2310
2530
  let plausible = true;
2311
2531
  if (window2 !== null) {
2312
- if (psn !== void 0 && anchor !== void 0 && this.#blockPrecedes(anchor.sbn, sbn) && psn !== anchor.psn) {
2313
- const sent = psn - anchor.psn >>> 0;
2314
- plausible = sent <= 2147483647 && serial32Distance(anchor.sbn, sbn) <= sent + config.k;
2532
+ if (psn !== void 0 && anchor !== void 0 && serial32Precedes(anchor.ssId, ssId) && psn !== anchor.psn) {
2533
+ plausible = sentInOrder(anchor, { ssId, psn });
2315
2534
  } else {
2316
2535
  plausible = missing <= window2 + Math.ceil((now - previous.atMs) / config.interleaveDepthMs);
2317
2536
  }
@@ -2321,8 +2540,7 @@ var FECManager = class _FECManager {
2321
2540
  discontinuity();
2322
2541
  return;
2323
2542
  }
2324
- this.#highestSbn.set(streamKey, { sbn, atMs: now });
2325
- anchorHere();
2543
+ advance();
2326
2544
  }
2327
2545
  /*
2328
2546
  * Block order for one stream (BLO-35597 iso:5). A block is keyed by its
@@ -2639,8 +2857,10 @@ var FECManager = class _FECManager {
2639
2857
  );
2640
2858
  }
2641
2859
  const hasCatalogTiming = _FECManager.#hasCatalogTiming({ interleaveDepthMs: ownInterleaveDepthMs });
2860
+ const algorithm = config.algorithm ?? previous.algorithm;
2642
2861
  const next = {
2643
2862
  blockProfile,
2863
+ ...algorithm === void 0 ? {} : { algorithm },
2644
2864
  k,
2645
2865
  symbolSize: config.symbolSize != null && config.symbolSize > 0 ? config.symbolSize : previousTrack?.symbolSize ?? 0,
2646
2866
  interleaveDepthMs: ownInterleaveDepthMs,
@@ -2648,8 +2868,19 @@ var FECManager = class _FECManager {
2648
2868
  timeoutMs: config.timeoutMs ?? (timingChanged ? 0 : previous.timeoutMs ?? 0),
2649
2869
  ...(config.trackKind ?? previous.trackKind) === void 0 ? {} : { trackKind: config.trackKind ?? previous.trackKind },
2650
2870
  ...(config.codec ?? previous.codec) === void 0 ? {} : { codec: config.codec ?? previous.codec },
2651
- ...(config.geometry ?? previous.geometry) === void 0 ? {} : { geometry: config.geometry ?? previous.geometry }
2871
+ ...(config.geometry ?? previous.geometry) === void 0 ? {} : { geometry: config.geometry ?? previous.geometry },
2872
+ ...(config.repairLayers ?? previous.repairLayers) === void 0 ? {} : { repairLayers: config.repairLayers ?? previous.repairLayers },
2873
+ ...(config.heldLayers ?? previous.heldLayers) === void 0 ? {} : { heldLayers: config.heldLayers ?? previous.heldLayers }
2652
2874
  };
2875
+ if (
2876
+ // By content: a catalog refresh rebuilds equal arrays, and forgetting
2877
+ // the anchors on one would fail open.
2878
+ JSON.stringify(next.repairLayers) !== JSON.stringify(previous.repairLayers) || JSON.stringify(next.heldLayers) !== JSON.stringify(previous.heldLayers)
2879
+ ) {
2880
+ for (const key of [...this.#heldLayerStates.keys()]) {
2881
+ if (this.#belongsToPacket(key, packetId)) this.#heldLayerStates.delete(key);
2882
+ }
2883
+ }
2653
2884
  if (!hasCatalogTiming) {
2654
2885
  next.timeoutMs = config.timeoutMs !== void 0 && config.timeoutMs > 0 ? config.timeoutMs : previousTrack !== void 0 && previousTrack.interleaveDepthMs === 0 ? previousTrack.timeoutMs : LOCAL_FEC_TIMEOUT_MS;
2655
2886
  } else {
@@ -2884,6 +3115,8 @@ var FECManager = class _FECManager {
2884
3115
  resetMap(this.#blockAuthoredLengths);
2885
3116
  resetMap(this.#blockRepairRsIds);
2886
3117
  resetMap(this.#blockRsbLengths);
3118
+ resetMap(this.#heldLayerStates);
3119
+ resetMap(this.#fecFailClosed);
2887
3120
  resetMap(this.#blockPathCounts);
2888
3121
  resetMap(this.#blockAnchorsMs);
2889
3122
  resetMap(this.#blockCatalogTrackNames);
@@ -2906,6 +3139,7 @@ var FECManager = class _FECManager {
2906
3139
  resetSet(this.#materializedBlocks);
2907
3140
  resetMap(this.#resolvedBlockClasses);
2908
3141
  resetMap(this.#highestSbn);
3142
+ resetMap(this.#sourceFrontiers);
2909
3143
  resetMap(this.#isoLocators);
2910
3144
  resetMap(this.#sourceAnchors);
2911
3145
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName));
@@ -3011,6 +3245,7 @@ var FECManager = class _FECManager {
3011
3245
  dropMap(this.#orderedPendingBlocks);
3012
3246
  dropMap(this.#resolvedBlockClasses);
3013
3247
  dropMap(this.#highestSbn);
3248
+ dropMap(this.#sourceFrontiers);
3014
3249
  dropMap(this.#isoLocators);
3015
3250
  dropMap(this.#sourceAnchors);
3016
3251
  dropMap(this.#classifiers);
@@ -3103,7 +3338,13 @@ var FECManager = class _FECManager {
3103
3338
  if (isSourceSymbol && esi === 0) {
3104
3339
  this.#startupPartialBlocks.delete(blockKey);
3105
3340
  this.#startupAlignedPackets.add(streamKey);
3106
- } else if (isStartupPartial && !isReadyMulticastRepair || !this.#startupAlignedPackets.has(streamKey) && !isReadyMulticastRepair) {
3341
+ } else if (
3342
+ // A ready multicast repair opens a block the join has not seen yet, never
3343
+ // a join partial: its sources were refused, so its repairs alone open a
3344
+ // block that cannot decode and fails at its deadline, once per packet ID
3345
+ // per join (BLO-48308).
3346
+ isStartupPartial || !this.#startupAlignedPackets.has(streamKey) && !isReadyMulticastRepair
3347
+ ) {
3107
3348
  this.#markStartupPartial(blockKey);
3108
3349
  return false;
3109
3350
  }
@@ -3385,6 +3626,7 @@ var FECManager = class _FECManager {
3385
3626
  let locator = this.#isoLocators.get(streamKey);
3386
3627
  if (!locator) {
3387
3628
  locator = new IsoBlockLocator(this.#trackConfig(packetId).k, this.#isoRetentionBlocks(packetId));
3629
+ locator.deferIncompleteGaps = this.#deferIsoGaps;
3388
3630
  this.#isoLocators.set(streamKey, locator);
3389
3631
  }
3390
3632
  return locator;
@@ -3428,6 +3670,10 @@ var FECManager = class _FECManager {
3428
3670
  }
3429
3671
  return blocks;
3430
3672
  }
3673
+ /** The iso-ssbg1-v1 locator horizon of a configured packetId, in blocks (#isoRetentionBlocks). */
3674
+ isoRetentionBlocksForPacket(packetId) {
3675
+ return this.#hasBlockProfile(packetId) ? this.#isoRetentionBlocks(packetId) : void 0;
3676
+ }
3431
3677
  /** Whether an iso-ssbg1-v1 protected packet fits one ssbg_mode1 symbol (len + 2 <= T). */
3432
3678
  isoSourceFits(packetId, packetLength) {
3433
3679
  const symbolSize = this.#trackConfigs.get(packetId)?.symbolSize;
@@ -3477,15 +3723,61 @@ var FECManager = class _FECManager {
3477
3723
  }
3478
3724
  return placement;
3479
3725
  }
3480
- if (placement.span !== void 0) {
3481
- const key = this.#blockKey(placement.span.block.start, packetId, catalogTrackName);
3482
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, placement.span.block.length);
3483
- }
3484
- if (placement.span !== void 0 && placement.span.placed.length === 0) {
3485
- this.#materializeBlock(placement.span.block.start, packetId, catalogTrackName, true);
3726
+ if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
3727
+ if (placement.hole !== void 0) {
3728
+ const locator = this.#isoLocatorFor(packetId, catalogTrackName);
3729
+ const hole = placement.hole.block;
3730
+ const previous = locator.blockEndingAt(hole.start);
3731
+ const loss = {
3732
+ packetId,
3733
+ catalogTrackName,
3734
+ holeStart: hole.start,
3735
+ holeLength: hole.length,
3736
+ lostSsId: placement.hole.lostSsId,
3737
+ kMax: this.#trackConfig(packetId).k,
3738
+ ...previous === void 0 ? {} : { previousBlockStart: previous.start }
3739
+ };
3740
+ this.#onUndelimitedLoss(loss);
3486
3741
  }
3487
3742
  return placement;
3488
3743
  }
3744
+ /**
3745
+ * Keep an iso-ssbg1-v1 gap missing a source as a pending hole, reported to
3746
+ * `handler`, instead of a repair-less span; null restores spans. Set by the
3747
+ * range repair scheduler; applies to every stream from its next gap. The
3748
+ * handler and the deferral are one setting, so no hole is ever created with
3749
+ * nobody to close it.
3750
+ */
3751
+ setUndelimitedLossHandler(handler) {
3752
+ this.#onUndelimitedLoss = handler;
3753
+ this.#deferIsoGaps = handler !== null;
3754
+ for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
3755
+ }
3756
+ /**
3757
+ * The range repair for a hole ended: every hole still pending inside
3758
+ * `[start, start + length)` becomes a repair-less span. Returns those spans
3759
+ * with the held sources they placed, for the caller to feed (MmtpRouter).
3760
+ */
3761
+ closeIsoHoles(packetId, catalogTrackName, start, length) {
3762
+ const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
3763
+ if (locator === void 0) return [];
3764
+ const spans = locator.closeHolesWithin(start, length);
3765
+ for (const span of spans) this.#openIsoSpan(span, packetId, catalogTrackName);
3766
+ return spans;
3767
+ }
3768
+ /**
3769
+ * A repair-less span has no repair to state its length, so it is known
3770
+ * here: its sources make it clean exactly when all of them arrived. A
3771
+ * stated block learns its SSB_length from its own repair symbol, fed after
3772
+ * its placed sources exactly as on the wire (feedRepairSymbol). A span every
3773
+ * SS_ID of which vanished resolves through its deadline like any vanished
3774
+ * block.
3775
+ */
3776
+ #openIsoSpan(span, packetId, catalogTrackName) {
3777
+ const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
3778
+ if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
3779
+ if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
3780
+ }
3489
3781
  /**
3490
3782
  * Resolution of the SS_IDs strictly between two released frames' SS_IDs on
3491
3783
  * an iso-ssbg1-v1 stream, for in-order frame release: null while a block
@@ -4002,6 +4294,112 @@ var FECManager = class _FECManager {
4002
4294
  }
4003
4295
  return recovered;
4004
4296
  }
4297
+ /**
4298
+ * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
4299
+ * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
4300
+ * block state unchanged. The router calls this before the repair places a
4301
+ * block or takes any other part in block bookkeeping. A RaptorQ track admits
4302
+ * every header that parsed (its RS_ID < RSB_length check is in the parser).
4303
+ */
4304
+ admitRepairBlockLength(packetId, ssbLength, rsbLength, rsId) {
4305
+ if (rsId >= rsbLength) return false;
4306
+ if (this.#trackConfigs.get(packetId)?.algorithm !== "reed-solomon") return true;
4307
+ return ssbLength + rsbLength <= RS_MAX_BLOCK_SYMBOLS;
4308
+ }
4309
+ /**
4310
+ * Whether a repair symbol of `byteLength` bytes is a valid member of a
4311
+ * `packetId` block: every repair symbol is exactly the track's T. A symbol of
4312
+ * any other size is counted on `repairSymbolSizeMismatches`, warned (rate
4313
+ * limited) and refused. The router calls this before the symbol takes any
4314
+ * other part in block state (placement, first-arrival dedup, completed-block
4315
+ * accounting), so a malformed repair is counted whatever its arrival order:
4316
+ * judged after dedup, one landing on an already-complete block, or behind a
4317
+ * valid copy from the other transport, was swallowed as a duplicate and never
4318
+ * counted (BLO-48306). A packetId with no configured block profile admits
4319
+ * nothing here; its repair is dropped upstream as unreadable.
4320
+ */
4321
+ admitRepairSymbolSize(packetId, ssStart, ssbLength, rsId, byteLength) {
4322
+ if (!this.#hasBlockProfile(packetId)) return false;
4323
+ const symbolSize = this.#trackConfig(packetId).symbolSize;
4324
+ if (symbolSize > 0 && byteLength !== symbolSize) {
4325
+ this.#repairSymbolSizeMismatchCount++;
4326
+ if (this.#repairSymbolSizeMismatchCount <= 5 || this.#repairSymbolSizeMismatchCount % 100 === 0) {
4327
+ console.warn(
4328
+ `[FECManager] Dropping repair symbol with invalid size: got ${byteLength}B, expected ${symbolSize}B (packetId=${packetId}, ssStart=${ssStart}, ssbLength=${ssbLength}, rsId=${rsId})`
4329
+ );
4330
+ }
4331
+ return false;
4332
+ }
4333
+ return true;
4334
+ }
4335
+ /**
4336
+ * fec-01 6.3.9 receiver check, run on a repair packet after the 4.5 discard
4337
+ * and the size check, before it places a block. For each held layer i with
4338
+ * total B_i = O_i + P_i: the anchor is the earliest block, in SS_Start
4339
+ * serial order, whose repair carried RSB_length >= B_i. The source track
4340
+ * fails closed on (a) a packet on layer i's own repair track (i > 0) below
4341
+ * B_i, or (b) any packet of the instance at or after the anchor below B_i.
4342
+ * Blocks before the anchor (pre-append) stay valid at the previous total. A
4343
+ * packet on a repair track the catalog does not list is discarded and
4344
+ * anchors nothing. `repairTrackName` is the subscribed repair track, never
4345
+ * inferred from RS_ID; without it only (b) runs. Returns false when the
4346
+ * repair must be dropped, including every repair once the track failed.
4347
+ */
4348
+ admitRepairLayerTotal(packetId, catalogTrackName, repairTrackName, ssStart, rsbLength) {
4349
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
4350
+ if (this.#fecFailClosed.has(streamKey)) return false;
4351
+ const config = this.#trackConfigs.get(packetId);
4352
+ const layers = config?.repairLayers;
4353
+ if (layers === void 0 || layers.length === 0) return true;
4354
+ let admission = this.#heldLayerStates.get(streamKey);
4355
+ if (admission === void 0) {
4356
+ admission = new HeldLayerAdmission(layers, config.heldLayers);
4357
+ this.#heldLayerStates.set(streamKey, admission);
4358
+ }
4359
+ const verdict = admission.admit(
4360
+ repairTrackName,
4361
+ ssStart,
4362
+ rsbLength,
4363
+ this.#layerAnchorHorizon(packetId),
4364
+ this.#sourceFrontiers.get(streamKey)?.sbn
4365
+ );
4366
+ if (verdict === "discard") return false;
4367
+ if (verdict !== void 0) {
4368
+ this.#fecFailClosed.set(streamKey, verdict);
4369
+ this.#onFecFailClosed?.({ ...verdict, packetId, catalogTrackName });
4370
+ console.warn(
4371
+ `[FECManager] FEC failed closed (fec-01 6.3.9) packetId=${packetId} track=${catalogTrackName ?? "-"}: ${JSON.stringify(verdict)}`
4372
+ );
4373
+ return false;
4374
+ }
4375
+ return true;
4376
+ }
4377
+ /**
4378
+ * How far (in SS_Start symbols) behind the newest block a 6.3.9 anchor or
4379
+ * below-total block can still matter: the iso locator's retention in blocks
4380
+ * times K, capped at 2^30 so compared serials stay inside one half-window.
4381
+ */
4382
+ #layerAnchorHorizon(packetId) {
4383
+ let blocks;
4384
+ try {
4385
+ blocks = this.isoRetentionBlocksForPacket(packetId);
4386
+ } catch {
4387
+ blocks = void 0;
4388
+ }
4389
+ return heldLayerAnchorHorizon(blocks, this.#trackConfigs.get(packetId)?.k ?? 0);
4390
+ }
4391
+ /**
4392
+ * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), once,
4393
+ * when it does; null stops reporting. The player wiring forwards it to
4394
+ * CmcdProducer.updateFecFailClosed.
4395
+ */
4396
+ setFecFailClosedHandler(handler) {
4397
+ this.#onFecFailClosed = handler;
4398
+ }
4399
+ /** The runtime fail-closed reason of a stream's FEC (fec-01 6.3.9), if any. */
4400
+ fecFailClosedReason(packetId, catalogTrackName) {
4401
+ return this.#fecFailClosed.get(this.#streamKey(packetId, catalogTrackName));
4402
+ }
4005
4403
  /**
4006
4404
  * Feed a repair symbol to the WASM FEC decoder.
4007
4405
  *
@@ -4013,16 +4411,7 @@ var FECManager = class _FECManager {
4013
4411
  this.#fecStats.repairPackets++;
4014
4412
  this.#statsForPacket(packetId).repairPackets++;
4015
4413
  if (!this.#hasBlockProfile(packetId)) return null;
4016
- const symbolSize = this.#trackConfig(packetId).symbolSize;
4017
- if (symbolSize > 0 && repairData.byteLength !== symbolSize) {
4018
- this.#repairSymbolSizeMismatchCount++;
4019
- if (this.#repairSymbolSizeMismatchCount <= 5 || this.#repairSymbolSizeMismatchCount % 100 === 0) {
4020
- console.warn(
4021
- `[FECManager] Dropping repair symbol with invalid size: got ${repairData.byteLength}B, expected ${symbolSize}B (packetId=${packetId}, ssStart=${ssStart}, ssbLength=${ssbLength}, rsId=${rsId})`
4022
- );
4023
- }
4024
- return null;
4025
- }
4414
+ if (!this.admitRepairSymbolSize(packetId, ssStart, ssbLength, rsId, repairData.byteLength)) return null;
4026
4415
  const fecData = repairData;
4027
4416
  const k = this.#trackConfig(packetId).k;
4028
4417
  const block = this.#isoLocatorFor(packetId, catalogTrackName).blockAt(ssStart);
@@ -4175,7 +4564,14 @@ var FECManager = class _FECManager {
4175
4564
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
4176
4565
  const k = trackConfig.k;
4177
4566
  if (this.#completedBlocks.has(key)) return;
4178
- this.#noteSbnSeen(sbn, packetId, catalogTrackName, "source", evidence.packetSequenceNumber);
4567
+ this.#noteSbnSeen(
4568
+ sbn,
4569
+ packetId,
4570
+ catalogTrackName,
4571
+ "source",
4572
+ evidence.packetSequenceNumber,
4573
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
4574
+ );
4179
4575
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
4180
4576
  if (Number.isInteger(esi) && esi >= authoredLength) {
4181
4577
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -4402,6 +4798,8 @@ var FECManager = class _FECManager {
4402
4798
  this.#blockAuthoredLengths.clear();
4403
4799
  this.#blockRepairRsIds.clear();
4404
4800
  this.#blockRsbLengths.clear();
4801
+ this.#heldLayerStates.clear();
4802
+ this.#fecFailClosed.clear();
4405
4803
  this.#completedBlocks.clear();
4406
4804
  this.#cleanlyCompletedBlocks.clear();
4407
4805
  this.#repairRequestedBlocks.clear();
@@ -4426,6 +4824,7 @@ var FECManager = class _FECManager {
4426
4824
  this.#repairedBlocks.clear();
4427
4825
  this.#materializedBlocks.clear();
4428
4826
  this.#highestSbn.clear();
4827
+ this.#sourceFrontiers.clear();
4429
4828
  this.#isoLocators.clear();
4430
4829
  this.#sourceAnchors.clear();
4431
4830
  this.#trackConfigs.clear();
@@ -9325,8 +9724,14 @@ var SampleCombiner = class {
9325
9724
  /**
9326
9725
  * Add one reassembled data unit. Returns the combined sample once every
9327
9726
  * constituent data unit has arrived and totals the authored size.
9727
+ *
9728
+ * `sampleSize` is the authored size the host resolves for the sample as the
9729
+ * data unit completes. It stands in only when no size was registered, which
9730
+ * happens when the data unit's FI=0/FI=1 reached the reassembler without the
9731
+ * host's own FT=2 parse: an FEC-recovered first fragment completed by source
9732
+ * fragments, or one decoded before its source copy arrived.
9328
9733
  */
9329
- addMfu(mfu) {
9734
+ addMfu(mfu, sampleSize) {
9330
9735
  if (mfu.movieFragmentSequenceNumber === void 0 || mfu.sampleNumber === void 0) {
9331
9736
  this.#stats.passthroughSamples++;
9332
9737
  return fromPassthrough(mfu);
@@ -9342,7 +9747,7 @@ var SampleCombiner = class {
9342
9747
  return null;
9343
9748
  }
9344
9749
  const dataLen = mfu.data.byteLength;
9345
- const authoredSize = this.#authoredSizes.get(key);
9750
+ const authoredSize = this.#authoredSizes.get(key) ?? sampleSize;
9346
9751
  if (offset === 0 && !this.#pending.has(key)) {
9347
9752
  const passesThrough = authoredSize === void 0 ? !this.#requireAuthoredSize : dataLen === authoredSize;
9348
9753
  if (passesThrough) {
@@ -9636,6 +10041,12 @@ if (void 0) {
9636
10041
  const out = c.addMfu(mfu(1, 9, 17, 5, [6, 7, 8, 9, 10], 1001n, false));
9637
10042
  expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
9638
10043
  });
10044
+ test("a size handed with the data unit completes a sample no head registered", () => {
10045
+ const c = combiner({ requireAuthoredSize: true });
10046
+ const out = c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5);
10047
+ expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5]));
10048
+ expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5)).toBeNull();
10049
+ });
9639
10050
  test("duplicate offset is rejected", () => {
9640
10051
  const c = combiner();
9641
10052
  c.registerAuthoredSize(void 0, 1, 9, 17, 10);
@@ -10880,6 +11291,7 @@ function isFmp4Box(data) {
10880
11291
  const type = String.fromCharCode(data[4], data[5], data[6], data[7]);
10881
11292
  return FMPU_BOX_TYPES.has(type);
10882
11293
  }
11294
+ var MAX_AWAITING_TIMING_HEADS = 8;
10883
11295
  var MmtpContainerParser = class _MmtpContainerParser {
10884
11296
  constructor(config) {
10885
11297
  this.#tracks = /* @__PURE__ */ new Map();
@@ -10938,6 +11350,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
10938
11350
  * reordering into the parser. */
10939
11351
  this.#reliableMoqStartupGate = /* @__PURE__ */ new Map();
10940
11352
  this.#disposed = false;
11353
+ this.#replayingAwaitingTiming = false;
10941
11354
  this.#fedObjects = 0;
10942
11355
  this.#reassemblerFragmentsFed = 0;
10943
11356
  this.#reassemblerDataUnitsReturned = 0;
@@ -11030,6 +11443,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
11030
11443
  #reorderStats;
11031
11444
  #reliableMoqStartupGate;
11032
11445
  #disposed;
11446
+ #replayingAwaitingTiming;
11033
11447
  #fedObjects;
11034
11448
  #reassemblerFragmentsFed;
11035
11449
  #reassemblerDataUnitsReturned;
@@ -11279,7 +11693,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
11279
11693
  * a single failure bucket. Returns null so call sites stay `return this.#drop(...)`.
11280
11694
  */
11281
11695
  #drop(reason) {
11282
- this.#countOutcome(`drop:${reason}`);
11696
+ if (this.#replayingAwaitingTiming) this.#countDeferredOutcome(reason);
11697
+ else this.#countOutcome(`drop:${reason}`);
11283
11698
  return null;
11284
11699
  }
11285
11700
  get reorderDiagnostics() {
@@ -11302,6 +11717,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
11302
11717
  for (const combiner of this.#sampleCombiners.values()) {
11303
11718
  combiner.cleanupTimeouts(timeoutMs);
11304
11719
  }
11720
+ const now = Date.now();
11721
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
11722
+ while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
11723
+ awaitingTiming.shift();
11724
+ }
11725
+ }
11305
11726
  }
11306
11727
  /**
11307
11728
  * Phase 1 of two-phase parsing. Returns structured header info for FEC feeding.
@@ -11382,7 +11803,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
11382
11803
  byteLength: packet.byteLength
11383
11804
  };
11384
11805
  }
11385
- if (info.fecPayloadId !== null && this.#sourceSymbolCb) {
11806
+ if (info.fecPayloadId !== null && this.#sourceSymbolCb && !this.#replayingAwaitingTiming) {
11386
11807
  const rawSymbol = packet.subarray(0, packet.length - 4);
11387
11808
  try {
11388
11809
  this.#sourceSymbolCb(info.packetId, info.fecPayloadId.ssId, rawSymbol);
@@ -11430,6 +11851,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
11430
11851
  }
11431
11852
  return this.#drop("fragment-timing-refused");
11432
11853
  }
11854
+ this.#replayAwaitingTiming(streamKey, resolver2);
11433
11855
  return {
11434
11856
  kind: "fragment",
11435
11857
  packet: info,
@@ -11453,7 +11875,18 @@ var MmtpContainerParser = class _MmtpContainerParser {
11453
11875
  mfuDuHeader.movieFragmentSequenceNumber,
11454
11876
  mfuDuHeader.sampleNumber
11455
11877
  );
11456
- if (!headTiming) return this.#drop("mfu-sample-timing-missing");
11878
+ if (!headTiming) {
11879
+ this.#awaitTiming(streamKey, {
11880
+ packet,
11881
+ options,
11882
+ parsed,
11883
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
11884
+ movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
11885
+ sampleNumber: mfuDuHeader.sampleNumber,
11886
+ arrivedAt: Date.now()
11887
+ });
11888
+ return this.#drop("mfu-sample-timing-missing");
11889
+ }
11457
11890
  const offset = mfuDuHeader.offset;
11458
11891
  if (!Number.isSafeInteger(offset) || offset < 0 || offset >= headTiming.size)
11459
11892
  return this.#drop("mfu-offset-out-of-range");
@@ -11529,16 +11962,17 @@ var MmtpContainerParser = class _MmtpContainerParser {
11529
11962
  const sampleNumber = assembled.sampleNumber;
11530
11963
  if (movieFragmentSequenceNumber === void 0 || sampleNumber === void 0)
11531
11964
  return this.#drop("assembled-identity-missing");
11532
- if (!resolver.sampleTiming(
11965
+ const assembledTiming = resolver.sampleTiming(
11533
11966
  assembled.mpuSequenceNumber,
11534
11967
  movieFragmentSequenceNumber,
11535
11968
  sampleNumber
11536
- )) return this.#drop("assembled-timing-missing");
11969
+ );
11970
+ if (!assembledTiming) return this.#drop("assembled-timing-missing");
11537
11971
  if (assembled.mpuSequenceNumber !== mpu.mpuSequenceNumber)
11538
11972
  return this.#drop("assembled-mpu-mismatch");
11539
11973
  let combined;
11540
11974
  try {
11541
- combined = this.#sampleCombinerFor(streamKey).addMfu(assembled);
11975
+ combined = this.#sampleCombinerFor(streamKey).addMfu(assembled, assembledTiming.size);
11542
11976
  } catch (error) {
11543
11977
  if (!(error instanceof SampleCombineError)) throw error;
11544
11978
  console.warn(
@@ -11847,9 +12281,37 @@ var MmtpContainerParser = class _MmtpContainerParser {
11847
12281
  if (existing) return existing.resolver;
11848
12282
  if (!create) return null;
11849
12283
  const resolver = new IsoBmffTimingResolver(this.#maxPendingTimingSamples);
11850
- this.#timingStreams.set(streamKey, { packetId, resolver });
12284
+ this.#timingStreams.set(streamKey, { packetId, resolver, awaitingTiming: [] });
11851
12285
  return resolver;
11852
12286
  }
12287
+ #awaitTiming(streamKey, head) {
12288
+ const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
12289
+ if (!awaitingTiming) return;
12290
+ awaitingTiming.push(head);
12291
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
12292
+ }
12293
+ /**
12294
+ * Feed again the heads whose timing the FT=1 just admitted declares. That
12295
+ * FT=1 can be an FEC recovery landing after its sample's FI=1, and neither
12296
+ * FEC path routes a source symbol that already arrived a second time.
12297
+ */
12298
+ #replayAwaitingTiming(streamKey, resolver) {
12299
+ const state = this.#timingStreams.get(streamKey);
12300
+ if (!state || state.awaitingTiming.length === 0) return;
12301
+ const ready = state.awaitingTiming.filter((head) => resolver.sampleTiming(
12302
+ head.mpuSequenceNumber,
12303
+ head.movieFragmentSequenceNumber,
12304
+ head.sampleNumber
12305
+ ));
12306
+ if (ready.length === 0) return;
12307
+ state.awaitingTiming = state.awaitingTiming.filter((head) => !ready.includes(head));
12308
+ this.#replayingAwaitingTiming = true;
12309
+ try {
12310
+ for (const head of ready) this.#feed(head.packet, head.options, head.parsed);
12311
+ } finally {
12312
+ this.#replayingAwaitingTiming = false;
12313
+ }
12314
+ }
11853
12315
  #dropTimingStream(streamKey) {
11854
12316
  const state = this.#timingStreams.get(streamKey);
11855
12317
  if (!state) return;
@@ -12453,6 +12915,18 @@ var MmtpRouter = class {
12453
12915
  // MSE recovery routes through CmafBlockAssembler and can reorder by block; the
12454
12916
  // direct callback path has to preserve decode order before frames leave libmmt.
12455
12917
  #latestVideoSeqByStream = /* @__PURE__ */ new Map();
12918
+ /**
12919
+ * Per stream, SS_ID - packet_sequence_number (mod 2^32) of its latest
12920
+ * first-arrival FEC source packet. A recovered source symbol's wire
12921
+ * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
12922
+ */
12923
+ #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
12924
+ /**
12925
+ * Streams whose multicast leg delivered a RAP-flagged source packet that was
12926
+ * not parsed, typically because its overlap copy was parsed first
12927
+ * (BLO-49179). The next video keyframe emitted on the stream consumes it.
12928
+ */
12929
+ #multicastRapTwinByStream = /* @__PURE__ */ new Set();
12456
12930
  #lastDirectSourceVideoTsByStream = /* @__PURE__ */ new Map();
12457
12931
  #lastDirectEmittedVideoTsByStream = /* @__PURE__ */ new Map();
12458
12932
  #pendingDirectRecoveredVideoByStream = /* @__PURE__ */ new Map();
@@ -12527,11 +13001,14 @@ var MmtpRouter = class {
12527
13001
  */
12528
13002
  #onPublisherRestart;
12529
13003
  #publisherRestarts = 0;
13004
+ #restampedRecoveredSeqs = 0;
12530
13005
  /** Inits delivered with no onTrackInit handler for their packetId (MOQT-01). */
12531
13006
  #unmappedInitDeliveries = 0;
12532
13007
  // FEC Payload IDs left unread because their (owner) packetId had no
12533
13008
  // configured fec.blockProfile (see #noteUnreadableFecPayloadId).
12534
13009
  #fecPayloadIdsWithoutProfile = 0;
13010
+ // Repair packets discarded by the fec-01 4.5 block-length rule.
13011
+ #repairBlockLengthDiscards = 0;
12535
13012
  /** The staged in-place stream switch, if any (stageStreamSwitch). */
12536
13013
  #staged = null;
12537
13014
  #disposed = false;
@@ -12585,6 +13062,12 @@ var MmtpRouter = class {
12585
13062
  ...meta.catalogTrackName === void 0 ? {} : { catalogTrackName: meta.catalogTrackName }
12586
13063
  };
12587
13064
  if (meta.source) frameMeta.source = meta.source;
13065
+ if (isVideo && frameMeta.keyframe) {
13066
+ const twinSeen = this.#multicastRapTwinByStream.delete(
13067
+ this.#mediaStreamKey(packetId, frameMeta.catalogTrackName)
13068
+ );
13069
+ if (twinSeen && frameMeta.source === "moq") frameMeta.source = "multicast";
13070
+ }
12588
13071
  if (meta.deliveryProvenance !== void 0)
12589
13072
  frameMeta.deliveryProvenance = meta.deliveryProvenance;
12590
13073
  if (meta.recovered) frameMeta.recovered = true;
@@ -12747,6 +13230,14 @@ var MmtpRouter = class {
12747
13230
  get publisherRestartCount() {
12748
13231
  return this.#publisherRestarts;
12749
13232
  }
13233
+ /**
13234
+ * FEC-recovered source symbols whose reconstructed header named a
13235
+ * packet_sequence_number other than the wire sequence their SS_ID maps to:
13236
+ * a hop re-stamped the sequence after the sender protected the packet.
13237
+ */
13238
+ get restampedRecoveredSequenceCount() {
13239
+ return this.#restampedRecoveredSeqs;
13240
+ }
12750
13241
  /**
12751
13242
  * Packets whose Source or Repair FEC Payload ID was left unread because
12752
13243
  * their (owner) packetId had no configured `fec.blockProfile`: FEC not
@@ -12758,6 +13249,14 @@ var MmtpRouter = class {
12758
13249
  get fecPayloadIdsWithoutProfile() {
12759
13250
  return this.#fecPayloadIdsWithoutProfile;
12760
13251
  }
13252
+ /**
13253
+ * Repair packets discarded at admission by the fec-01 4.5 rule (RS_ID not
13254
+ * below RSB_length, or a reed-solomon SSB_length + RSB_length above 255),
13255
+ * before they touched any block state.
13256
+ */
13257
+ get repairBlockLengthDiscards() {
13258
+ return this.#repairBlockLengthDiscards;
13259
+ }
12761
13260
  get reassembler() {
12762
13261
  return this.#parser.reassembler;
12763
13262
  }
@@ -13136,13 +13635,13 @@ var MmtpRouter = class {
13136
13635
  * Feed a repair packet from MoQ (reliable QUIC) — parses MMTP repair
13137
13636
  * header and delegates to FECManager for FEC recovery.
13138
13637
  */
13139
- feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName) {
13638
+ feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName) {
13140
13639
  if (this.#disposed) return;
13141
13640
  this.#withDeferredFecPokes(() => {
13142
- this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName);
13641
+ this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName);
13143
13642
  });
13144
13643
  }
13145
- #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName) {
13644
+ #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName) {
13146
13645
  let header;
13147
13646
  try {
13148
13647
  header = parseMMTPHeader(packet);
@@ -13173,7 +13672,7 @@ var MmtpRouter = class {
13173
13672
  this.#noteUnreadableFecPayloadId(ownerPacketId, "repair");
13174
13673
  return;
13175
13674
  }
13176
- this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, "moq");
13675
+ this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, "moq", repairTrackName);
13177
13676
  }
13178
13677
  }
13179
13678
  // ── Packet FEC geometry and block profile ───────────────────────
@@ -13255,13 +13754,25 @@ var MmtpRouter = class {
13255
13754
  * the repair, the order they had on the wire, so a loss-free block completes
13256
13755
  * clean on its repair. A repair contradicting a known block is dropped.
13257
13756
  */
13258
- #handleIsoRepair(ownerPacketId, catalogTrackName, repair, source) {
13757
+ #handleIsoRepair(ownerPacketId, catalogTrackName, repair, source, repairTrackName) {
13259
13758
  const fec = this.#fecManager;
13260
13759
  if (!fec?.placeIsoRepair) {
13261
13760
  throw new Error(
13262
13761
  `[MmtpRouter] packetId=${ownerPacketId} is iso-ssbg1-v1 but its FEC manager cannot place ISO blocks`
13263
13762
  );
13264
13763
  }
13764
+ if (fec.admitRepairBlockLength && !fec.admitRepairBlockLength(ownerPacketId, repair.ssbLength, repair.rsbLength, repair.rsId)) {
13765
+ this.#repairBlockLengthDiscards++;
13766
+ return;
13767
+ }
13768
+ if (fec.admitRepairSymbolSize && !fec.admitRepairSymbolSize(
13769
+ ownerPacketId,
13770
+ repair.ssStart,
13771
+ repair.ssbLength,
13772
+ repair.rsId,
13773
+ repair.symbolData.byteLength
13774
+ )) return;
13775
+ if (fec.admitRepairLayerTotal && !fec.admitRepairLayerTotal(ownerPacketId, catalogTrackName, repairTrackName, repair.ssStart, repair.rsbLength)) return;
13265
13776
  const placement = fec.placeIsoRepair(ownerPacketId, catalogTrackName, repair.ssStart, repair.ssbLength);
13266
13777
  if (placement.status !== "placed") return;
13267
13778
  const blockStart = placement.block.start;
@@ -13296,6 +13807,17 @@ var MmtpRouter = class {
13296
13807
  this.#routeRecoveredBlock(blockStart, recovered, ownerPacketId, catalogTrackName);
13297
13808
  }
13298
13809
  }
13810
+ /**
13811
+ * The range repair FETCH for an undelimited hole ended (draft-ramadan-moq-fec
13812
+ * §7.5): what no repair stated becomes repair-less spans, whose held sources
13813
+ * are fed exactly as a span a repair closed.
13814
+ */
13815
+ closeIsoHoles(ownerPacketId, catalogTrackName, start, length) {
13816
+ const spans = this.#fecManager?.closeIsoHoles?.(ownerPacketId, catalogTrackName, start, length) ?? [];
13817
+ for (const span of spans) {
13818
+ this.#replayIsoSources(ownerPacketId, catalogTrackName, span.block.start, span.placed);
13819
+ }
13820
+ }
13299
13821
  /**
13300
13822
  * Feed iso-ssbg1-v1 sources a repair just placed, in SS_ID order, exactly as
13301
13823
  * a first-arrival source is fed once its block is known: transport
@@ -13391,6 +13913,8 @@ var MmtpRouter = class {
13391
13913
  this.#trackSynced.delete(streamKey);
13392
13914
  this.#droppedPreSyncVideo.delete(streamKey);
13393
13915
  this.#latestVideoSeqByStream.delete(streamKey);
13916
+ this.#ssIdSeqOffsetByStream.delete(streamKey);
13917
+ this.#multicastRapTwinByStream.delete(streamKey);
13394
13918
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
13395
13919
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
13396
13920
  this.#pendingDirectRecoveredVideoByStream.delete(streamKey);
@@ -14161,6 +14685,12 @@ var MmtpRouter = class {
14161
14685
  } else if (fecUnreadable && info.fecPayloadId) {
14162
14686
  parseSourceSymbol = !duplicates.parsedSymbols.has(info.fecPayloadId.ssId);
14163
14687
  }
14688
+ if (fecPayloadId && !overlapCopy) {
14689
+ this.#ssIdSeqOffsetByStream.set(
14690
+ this.#mediaStreamKey(info.packetId, catalogTrackName),
14691
+ fecPayloadId.ssId - info.sequenceNumber >>> 0
14692
+ );
14693
+ }
14164
14694
  if (!this.#fecManager || !info.fecPayloadId || parseSourceSymbol) {
14165
14695
  if (this.#fecManager && info.fecPayloadId) {
14166
14696
  duplicates.parsedSymbols.add(info.fecPayloadId.ssId);
@@ -14183,6 +14713,10 @@ var MmtpRouter = class {
14183
14713
  // An FEC source frame is anchored by its own SS_ID (C.5.2).
14184
14714
  ...fecSource && fecPayloadId ? { fecSbn: fecPayloadId.ssId } : {}
14185
14715
  }, parsed);
14716
+ } else if (source === "multicast" && info.rapFlag) {
14717
+ this.#multicastRapTwinByStream.add(
14718
+ this.#mediaStreamKey(info.packetId, catalogTrackName)
14719
+ );
14186
14720
  }
14187
14721
  if (this.#classifyPacketId(info.packetId) === null) return;
14188
14722
  if (this.#fecManager && fecPayloadId && coords && sourceSymbolAccepted && sourceSymbolTrackable) {
@@ -14737,6 +15271,20 @@ var MmtpRouter = class {
14737
15271
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName) {
14738
15272
  if (ownerPacketId == null) return;
14739
15273
  if (this.#classifyPacketId(ownerPacketId) === null) return;
15274
+ const ssIdSeqOffset = this.#ssIdSeqOffsetByStream.get(
15275
+ this.#mediaStreamKey(ownerPacketId, catalogTrackName)
15276
+ );
15277
+ if (ssIdSeqOffset !== void 0) {
15278
+ result = {
15279
+ ...result,
15280
+ symbols: result.symbols.map((sym) => {
15281
+ const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
15282
+ if (wire === sym.packetSequenceNumber) return sym;
15283
+ this.#restampedRecoveredSeqs++;
15284
+ return { ...sym, packetSequenceNumber: wire };
15285
+ })
15286
+ };
15287
+ }
14740
15288
  this.#stream(ownerPacketId, catalogTrackName).duplicates.advance(blockId);
14741
15289
  const deliveryProvenance = this.#fecManager?.blockDeliveryProvenance?.(
14742
15290
  blockId,
@@ -15222,189 +15770,6 @@ var MmtpRouter = class {
15222
15770
  }
15223
15771
  };
15224
15772
 
15225
- // node_modules/@blockcast/mmt-transport/dist/types.js
15226
- var MoqFecAlgorithm;
15227
- (function(MoqFecAlgorithm2) {
15228
- MoqFecAlgorithm2[MoqFecAlgorithm2["None"] = 0] = "None";
15229
- MoqFecAlgorithm2[MoqFecAlgorithm2["Xor"] = 1] = "Xor";
15230
- MoqFecAlgorithm2[MoqFecAlgorithm2["RaptorQ"] = 2] = "RaptorQ";
15231
- })(MoqFecAlgorithm || (MoqFecAlgorithm = {}));
15232
-
15233
- // node_modules/@blockcast/mmt-base/dist/mmtp.js
15234
- var MPU_HEADER_SIZE2 = 8;
15235
- var MPU_LENGTH_FIELD_SIZE2 = 2;
15236
- var MPU_HEADER_REMAINDER_SIZE2 = MPU_HEADER_SIZE2 - MPU_LENGTH_FIELD_SIZE2;
15237
- var MMTP_SIGNALING_PACKET_ID2 = 0;
15238
- var MMTP_PACKET_ID_MAX2 = 65535;
15239
-
15240
- // node_modules/@blockcast/mmt-base/dist/net-constants.js
15241
- var DEFAULT_AMT_RELAY_PORT2 = 2268;
15242
-
15243
- // node_modules/@blockcast/mmt-base/dist/ntp-short.js
15244
- var NTP_SHORT_BITS2 = 32;
15245
- var NTP_SHORT_MODULUS2 = 2 ** NTP_SHORT_BITS2;
15246
- var NTP_SHORT_HALF_RANGE2 = 2 ** (NTP_SHORT_BITS2 - 1);
15247
- function isNtpShort(value) {
15248
- return Number.isInteger(value) && value >= 0 && value < NTP_SHORT_MODULUS2;
15249
- }
15250
- function compareNtpShort(a, b) {
15251
- if (!isNtpShort(a) || !isNtpShort(b)) {
15252
- throw new RangeError(`NTP-short values must be integers in [0, 2^${NTP_SHORT_BITS2}), got ${String(a)} and ${String(b)}`);
15253
- }
15254
- if (a === b)
15255
- return "equal";
15256
- const forward = (a - b + NTP_SHORT_MODULUS2) % NTP_SHORT_MODULUS2;
15257
- if (forward < NTP_SHORT_HALF_RANGE2)
15258
- return "after";
15259
- if (forward > NTP_SHORT_HALF_RANGE2)
15260
- return "before";
15261
- return "unordered";
15262
- }
15263
-
15264
- // node_modules/@blockcast/mmt-base/dist/fec-block-profile.js
15265
- var FEC_BLOCK_PROFILES2 = Object.freeze([
15266
- "iso-ssbg1-v1"
15267
- ]);
15268
-
15269
- // node_modules/@blockcast/mmt-base/dist/catalog-fec-source.js
15270
- var ALL_ROLES2 = Object.freeze(["video", "audio"]);
15271
-
15272
- // node_modules/@blockcast/mmt-transport/dist/driad-discovery.js
15273
- var DRIADDiscovery = class {
15274
- cache = /* @__PURE__ */ new Map();
15275
- cacheExpiry = 3e5;
15276
- // 5 minutes
15277
- /**
15278
- * Discover AMT relays for a multicast source address (RFC 8777)
15279
- *
15280
- * @param source - The multicast source IP address (NOT the group!)
15281
- * @returns Array of discovered AMT relays that can tunnel traffic from this source
15282
- */
15283
- async discoverRelays(source) {
15284
- const cached = this.cache.get(source);
15285
- if (cached) {
15286
- return cached;
15287
- }
15288
- try {
15289
- const reversedSource = source.split(".").reverse().join(".");
15290
- const queryDomain = `${reversedSource}.amt.in-addr.arpa`;
15291
- console.log(`[DRIAD] Discovering relays for source ${source} via ${queryDomain}`);
15292
- const relays = await this.queryDRIADProxy(source);
15293
- if (relays.length > 0) {
15294
- this.cache.set(source, relays);
15295
- setTimeout(() => this.cache.delete(source), this.cacheExpiry);
15296
- }
15297
- return relays;
15298
- } catch (error) {
15299
- console.warn(`[DRIAD] Discovery failed for source ${source}:`, error);
15300
- return [];
15301
- }
15302
- }
15303
- /**
15304
- * Query DRIAD proxy service (browser-compatible)
15305
- */
15306
- async queryDRIADProxy(source) {
15307
- const proxyEndpoints = [
15308
- "https://driad.amt.net/api/v1/relays",
15309
- "https://multicast-gateway.cloudflare.com/driad"
15310
- ];
15311
- for (const endpoint of proxyEndpoints) {
15312
- try {
15313
- const response = await fetch(`${endpoint}?source=${encodeURIComponent(source)}`, {
15314
- method: "GET",
15315
- headers: { Accept: "application/json" },
15316
- signal: AbortSignal.timeout(5e3)
15317
- });
15318
- if (response.ok) {
15319
- const data = await response.json();
15320
- return data.relays || [];
15321
- }
15322
- } catch {
15323
- }
15324
- }
15325
- const dohRelay = await this.queryDNSOverHTTPS(source);
15326
- if (dohRelay) {
15327
- return [dohRelay];
15328
- }
15329
- return [];
15330
- }
15331
- /**
15332
- * Query DNS-over-HTTPS for DRIAD relay based on source address (RFC 8777)
15333
- */
15334
- async queryDNSOverHTTPS(source) {
15335
- try {
15336
- const reversedSource = source.split(".").reverse().join(".");
15337
- const queryName = `${reversedSource}.amt.in-addr.arpa`;
15338
- const dohUrl = `https://cloudflare-dns.com/dns-query?name=${queryName}&type=A`;
15339
- const response = await fetch(dohUrl, {
15340
- headers: { Accept: "application/dns-json" },
15341
- signal: AbortSignal.timeout(3e3)
15342
- });
15343
- if (!response.ok) {
15344
- return null;
15345
- }
15346
- const result = await response.json();
15347
- if (result.Answer && result.Answer.length > 0) {
15348
- return {
15349
- host: result.Answer[0].data,
15350
- port: DEFAULT_AMT_RELAY_PORT2,
15351
- priority: 10,
15352
- weight: 100,
15353
- asn: 0
15354
- };
15355
- }
15356
- return null;
15357
- } catch (error) {
15358
- console.warn("[DRIAD] DNS-over-HTTPS query failed:", error);
15359
- return null;
15360
- }
15361
- }
15362
- /**
15363
- * Select best relay based on RTT measurements
15364
- */
15365
- async selectBestRelay(relays) {
15366
- if (relays.length === 0)
15367
- return null;
15368
- const measured = await Promise.all(relays.map(async (relay) => {
15369
- const rtt = await this.measureRTT(relay.host, relay.port);
15370
- return { ...relay, rtt };
15371
- }));
15372
- measured.sort((a, b) => {
15373
- if (a.priority !== b.priority)
15374
- return a.priority - b.priority;
15375
- return (a.rtt || Infinity) - (b.rtt || Infinity);
15376
- });
15377
- console.log(`[DRIAD] Selected relay: ${measured[0].host} (RTT: ${measured[0].rtt}ms)`);
15378
- return measured[0];
15379
- }
15380
- async measureRTT(host, _port) {
15381
- const start = performance.now();
15382
- try {
15383
- await fetch(`https://${host}/health`, {
15384
- method: "HEAD",
15385
- signal: AbortSignal.timeout(2e3),
15386
- mode: "no-cors"
15387
- });
15388
- return performance.now() - start;
15389
- } catch {
15390
- return Infinity;
15391
- }
15392
- }
15393
- /**
15394
- * Clear the relay cache
15395
- */
15396
- clearCache() {
15397
- this.cache.clear();
15398
- }
15399
- /**
15400
- * Get cached relays for a source address
15401
- */
15402
- getCached(source) {
15403
- return this.cache.get(source);
15404
- }
15405
- };
15406
- var driadDiscovery = new DRIADDiscovery();
15407
-
15408
15773
  // node_modules/@blockcast/mmt-transport/dist/multicast-tier.js
15409
15774
  function endpointKey(endpoint) {
15410
15775
  return `${endpoint.sourceAddress ?? ""}|${endpoint.groupAddress}|${endpoint.port}`;
@@ -15535,8 +15900,8 @@ var AdaptiveBitrateController = class {
15535
15900
  /**
15536
15901
  * Update FEC statistics for ABR decisions
15537
15902
  *
15538
- * Per draft-ramadan-moq-fec-00, ABR should use the effective loss rate
15539
- * (after FEC recovery) rather than raw transport loss rate.
15903
+ * ABR uses the effective loss rate (after FEC recovery) rather than the
15904
+ * raw transport loss rate.
15540
15905
  *
15541
15906
  * @param stats - FEC statistics from the FEC decoder
15542
15907
  */
@@ -15612,6 +15977,45 @@ var AdaptiveBitrateController = class {
15612
15977
  }
15613
15978
  };
15614
15979
 
15980
+ // node_modules/@blockcast/mmt-base/dist/mmtp.js
15981
+ var MPU_HEADER_SIZE2 = 8;
15982
+ var MPU_LENGTH_FIELD_SIZE2 = 2;
15983
+ var MPU_HEADER_REMAINDER_SIZE2 = MPU_HEADER_SIZE2 - MPU_LENGTH_FIELD_SIZE2;
15984
+ var MMTP_SIGNALING_PACKET_ID2 = 0;
15985
+ var MMTP_PACKET_ID_MAX2 = 65535;
15986
+
15987
+ // node_modules/@blockcast/mmt-base/dist/net-constants.js
15988
+ var DEFAULT_AMT_RELAY_PORT2 = 2268;
15989
+
15990
+ // node_modules/@blockcast/mmt-base/dist/ntp-short.js
15991
+ var NTP_SHORT_BITS2 = 32;
15992
+ var NTP_SHORT_MODULUS2 = 2 ** NTP_SHORT_BITS2;
15993
+ var NTP_SHORT_HALF_RANGE2 = 2 ** (NTP_SHORT_BITS2 - 1);
15994
+ function isNtpShort(value) {
15995
+ return Number.isInteger(value) && value >= 0 && value < NTP_SHORT_MODULUS2;
15996
+ }
15997
+ function compareNtpShort(a, b) {
15998
+ if (!isNtpShort(a) || !isNtpShort(b)) {
15999
+ throw new RangeError(`NTP-short values must be integers in [0, 2^${NTP_SHORT_BITS2}), got ${String(a)} and ${String(b)}`);
16000
+ }
16001
+ if (a === b)
16002
+ return "equal";
16003
+ const forward = (a - b + NTP_SHORT_MODULUS2) % NTP_SHORT_MODULUS2;
16004
+ if (forward < NTP_SHORT_HALF_RANGE2)
16005
+ return "after";
16006
+ if (forward > NTP_SHORT_HALF_RANGE2)
16007
+ return "before";
16008
+ return "unordered";
16009
+ }
16010
+
16011
+ // node_modules/@blockcast/mmt-base/dist/fec-block-profile.js
16012
+ var FEC_BLOCK_PROFILES2 = Object.freeze([
16013
+ "iso-ssbg1-v1"
16014
+ ]);
16015
+
16016
+ // node_modules/@blockcast/mmt-base/dist/catalog-fec-source.js
16017
+ var ALL_ROLES2 = Object.freeze(["video", "audio"]);
16018
+
15615
16019
  // node_modules/@blockcast/mmt-transport/dist/multicast-orchestrator.js
15616
16020
  var DEFAULT_DWELL_MS = 3e3;
15617
16021
  var DEFAULT_JOIN_DEADLINE_MS = 5e3;
@@ -15849,8 +16253,23 @@ function toWindowMulticastSubscribeConfig(input) {
15849
16253
  consume: "bytes",
15850
16254
  ...input.packetIds?.length ? { packetIds: [...input.packetIds] } : {}
15851
16255
  };
16256
+ if (input.atsc3) {
16257
+ const { frequency, plpId, serviceId } = input.atsc3;
16258
+ if (!Number.isInteger(frequency) || frequency < 1) {
16259
+ throw new TypeError(`ATSC3 tuning requires a positive integer frequency in kHz, got ${String(frequency)}`);
16260
+ }
16261
+ return {
16262
+ ...base,
16263
+ origin: "tuner",
16264
+ standard: "atsc3",
16265
+ frequency,
16266
+ ...plpId !== void 0 ? { plpId } : {},
16267
+ ...serviceId !== void 0 ? { serviceId } : {}
16268
+ };
16269
+ }
15852
16270
  const relay = input.amtRelay?.trim();
15853
- const wantsAmt = input.mode === "tunnel" || input.mode !== "native" && relay !== void 0 && relay !== "";
16271
+ const driad = !relay && input.amtDiscovery === "driad";
16272
+ const wantsAmt = input.mode === "tunnel" || input.mode !== "native" && (relay !== void 0 && relay !== "" || driad);
15854
16273
  if (!wantsAmt) {
15855
16274
  const native = {
15856
16275
  ...base,
@@ -15860,6 +16279,20 @@ function toWindowMulticastSubscribeConfig(input) {
15860
16279
  return native;
15861
16280
  }
15862
16281
  const relayPort = input.amtRelayPort;
16282
+ if (driad) {
16283
+ if (!base.source)
16284
+ throw new TypeError("AMT DRIAD discovery requires a source address");
16285
+ if (relayPort !== void 0 && !isPositivePort(relayPort)) {
16286
+ throw new TypeError("AMT DRIAD discovery requires a valid relay port when one is given");
16287
+ }
16288
+ return {
16289
+ ...base,
16290
+ source: base.source,
16291
+ origin: "amt",
16292
+ discovery: "driad",
16293
+ ...relayPort !== void 0 ? { relayPort } : {}
16294
+ };
16295
+ }
15863
16296
  if (!relay || relayPort === void 0 || !isPositivePort(relayPort)) {
15864
16297
  throw new TypeError("AMT requires a resolved relay and a valid relay port");
15865
16298
  }
@@ -15903,7 +16336,8 @@ function normalizeMulticastEndpoint(endpoint) {
15903
16336
  port: endpoint.port,
15904
16337
  ...endpoint.mode ? { mode: endpoint.mode } : {},
15905
16338
  ...amtRelay ? { amtRelay } : {},
15906
- ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
16339
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {},
16340
+ ...endpoint.amtDiscovery === "driad" ? { amtDiscovery: "driad" } : {}
15907
16341
  };
15908
16342
  }
15909
16343
  function multicastEndpointKey(endpoint) {
@@ -15916,7 +16350,9 @@ function multicastEndpointKey(endpoint) {
15916
16350
  normalized.port,
15917
16351
  normalized.mode ?? "auto",
15918
16352
  normalized.amtRelay ?? "",
15919
- normalized.amtRelayPort ?? ""
16353
+ normalized.amtRelayPort ?? "",
16354
+ // A DRIAD join is a different gateway subscription from a native one.
16355
+ ...normalized.amtDiscovery ? [normalized.amtDiscovery] : []
15920
16356
  ]);
15921
16357
  }
15922
16358
  function isMulticastTrackPacketId(value) {
@@ -15956,7 +16392,8 @@ var MulticastSubscriptionPool = class {
15956
16392
  port: config.port,
15957
16393
  mode: config.mode,
15958
16394
  amtRelay: config.amtRelay,
15959
- amtRelayPort: config.amtRelayPort
16395
+ amtRelayPort: config.amtRelayPort,
16396
+ amtDiscovery: config.amtDiscovery
15960
16397
  });
15961
16398
  if (!endpoint)
15962
16399
  throw new Error("Invalid multicast endpoint");
@@ -16022,7 +16459,8 @@ var MulticastSubscriptionPool = class {
16022
16459
  port: endpoint.port,
16023
16460
  ...endpoint.mode ? { mode: endpoint.mode } : {},
16024
16461
  ...endpoint.amtRelay ? { amtRelay: endpoint.amtRelay } : {},
16025
- ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
16462
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {},
16463
+ ...endpoint.amtDiscovery ? { amtDiscovery: endpoint.amtDiscovery } : {}
16026
16464
  }));
16027
16465
  const consumers = /* @__PURE__ */ new Map();
16028
16466
  let entry;
@@ -16102,7 +16540,6 @@ var TransportManager = class {
16102
16540
  };
16103
16541
  capabilities = null;
16104
16542
  subscription = null;
16105
- driad = new DRIADDiscovery();
16106
16543
  /** Built by `connect()` from the caller's ladder; there is no built-in one. */
16107
16544
  abr = null;
16108
16545
  multicastOrchestrator = null;
@@ -16152,8 +16589,8 @@ var TransportManager = class {
16152
16589
  nativeIGMP: hasGatewayBytes,
16153
16590
  directSockets: typeof win?.UDPSocket !== "undefined",
16154
16591
  amt: false,
16155
- driad: true,
16156
- // DRIAD uses HTTP proxy, always available
16592
+ driad: hasGatewayBytes,
16593
+ // the gateway runs RFC 8777 discovery
16157
16594
  fecDecode: false
16158
16595
  };
16159
16596
  console.log("[Transport] Capabilities:", this.capabilities);
@@ -16164,7 +16601,7 @@ var TransportManager = class {
16164
16601
  *
16165
16602
  * Promotion hierarchy:
16166
16603
  * 1. window.multicast gateway bytes
16167
- * 2. AMT proxy (specified or discovered via DRIAD)
16604
+ * 2. AMT: a configured relay via the AMT proxy, else gateway DRIAD discovery
16168
16605
  * 3. MOQ WebTransport (final fallback)
16169
16606
  *
16170
16607
  * The ABR ladder (`abrLadder`) and initial rendition (`initialQuality`)
@@ -16258,7 +16695,7 @@ var TransportManager = class {
16258
16695
  /**
16259
16696
  * Connect via the lowercase window.multicast bytes gateway.
16260
16697
  */
16261
- async connectWindowMulticast(config, generation) {
16698
+ async connectWindowMulticast(config, generation, mode = "multicast") {
16262
16699
  try {
16263
16700
  const gateway = this.getWindowMulticastGateway();
16264
16701
  if (typeof gateway?.subscribe !== "function")
@@ -16293,7 +16730,7 @@ var TransportManager = class {
16293
16730
  }
16294
16731
  };
16295
16732
  this.state = {
16296
- mode: "multicast",
16733
+ mode,
16297
16734
  connected: true,
16298
16735
  group: config.group,
16299
16736
  source: config.source,
@@ -16311,29 +16748,19 @@ var TransportManager = class {
16311
16748
  }
16312
16749
  }
16313
16750
  /**
16314
- * Connect via AMT proxy (with optional DRIAD discovery)
16751
+ * Connect via AMT: a configured relay goes through the AMT proxy; with no
16752
+ * relay, the window.multicast gateway discovers one per RFC 8777 (DRIAD).
16315
16753
  */
16316
16754
  async connectAmt(config, generation) {
16317
16755
  try {
16318
- let amtRelay = config.amtRelay;
16319
- if (!amtRelay && config.driadEnabled !== false && config.source) {
16320
- console.log(`[Transport] Discovering AMT relay via DRIAD for source ${config.source}...`);
16321
- const relays = await this.driad.discoverRelays(config.source);
16322
- if (generation !== this.connectionGeneration)
16323
- return false;
16324
- const bestRelay = await this.driad.selectBestRelay(relays);
16325
- if (generation !== this.connectionGeneration)
16326
- return false;
16327
- if (bestRelay) {
16328
- amtRelay = bestRelay.host;
16329
- this.state.amtRelay = amtRelay;
16330
- }
16331
- }
16332
- if (!amtRelay) {
16756
+ if (config.amtRelay)
16757
+ return await this.connectAmtProxy(config, config.amtRelay, generation);
16758
+ if (config.driadEnabled === false || !config.source || config.mode === "native") {
16333
16759
  console.warn("[Transport] No AMT relay available (DRIAD requires source address for SSM)");
16334
16760
  return false;
16335
16761
  }
16336
- return await this.connectAmtProxy(config, amtRelay, generation);
16762
+ console.log(`[Transport] Asking the gateway for a DRIAD relay for source ${config.source}...`);
16763
+ return await this.connectWindowMulticast({ ...config, amtDiscovery: "driad" }, generation, "amt");
16337
16764
  } catch (error) {
16338
16765
  console.warn("[Transport] AMT connection failed:", error);
16339
16766
  return false;
@@ -16564,7 +16991,6 @@ var AMTGatewayManager = class {
16564
16991
  subscriptions = /* @__PURE__ */ new Map();
16565
16992
  messageHandler;
16566
16993
  pendingPackets = /* @__PURE__ */ new Map();
16567
- driad = new DRIADDiscovery();
16568
16994
  constructor() {
16569
16995
  this.messageHandler = (event) => {
16570
16996
  const data = event.data;
@@ -16595,26 +17021,12 @@ var AMTGatewayManager = class {
16595
17021
  return keyStr;
16596
17022
  }
16597
17023
  try {
16598
- let relayAddress;
16599
- let discoveryMethod;
17024
+ const relayAddress = config.relayAddress;
16600
17025
  const relayPort = config.relayPort || DEFAULT_AMT_RELAY_PORT2;
16601
- if (config.relayAddress) {
16602
- relayAddress = config.relayAddress;
16603
- discoveryMethod = "manual";
16604
- console.log(`[AMT] Using configured relay ${relayAddress}:${relayPort}`);
16605
- } else if (key.source) {
16606
- console.log(`[AMT] No relay configured, discovering via DRIAD for source ${key.source}...`);
16607
- const relays = await this.driad.discoverRelays(key.source);
16608
- const bestRelay = await this.driad.selectBestRelay(relays);
16609
- if (!bestRelay) {
16610
- throw new Error(`AMT relay discovery failed for source ${key.source}. Please specify a relay address in the subscription configuration.`);
16611
- }
16612
- relayAddress = bestRelay.host;
16613
- discoveryMethod = "driad";
16614
- console.log(`[AMT] Discovered relay via DRIAD: ${relayAddress}:${relayPort}`);
16615
- } else {
16616
- throw new Error(`AMT relay discovery requires a source address for SSM (RFC 8777). Please specify either a relay address or source address.`);
17026
+ if (!relayAddress) {
17027
+ 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".`);
16617
17028
  }
17029
+ console.log(`[AMT] Using configured relay ${relayAddress}:${relayPort}`);
16618
17030
  const subscriptionId = keyStr;
16619
17031
  this.pendingPackets.set(subscriptionId, []);
16620
17032
  const subscription = {
@@ -16625,7 +17037,7 @@ var AMTGatewayManager = class {
16625
17037
  relay: {
16626
17038
  address: relayAddress,
16627
17039
  port: relayPort,
16628
- discoveryMethod,
17040
+ discoveryMethod: "manual",
16629
17041
  discoveredAt: Date.now()
16630
17042
  }
16631
17043
  };
@@ -16781,7 +17193,7 @@ function sameIds(a, b) {
16781
17193
  for (const id of a) if (!b.has(id)) return false;
16782
17194
  return true;
16783
17195
  }
16784
- var MulticastTransport = class _MulticastTransport {
17196
+ var MulticastTransport = class {
16785
17197
  #onPacket;
16786
17198
  #subscription = null;
16787
17199
  #packetListener = null;
@@ -16853,8 +17265,11 @@ var MulticastTransport = class _MulticastTransport {
16853
17265
  // droppedPacketIds.
16854
17266
  #unadvertisedPacketIds = /* @__PURE__ */ new Set();
16855
17267
  #joinGeneration = 0;
16856
- constructor(onPacket) {
17268
+ // The provider to subscribe through; window.multicast when unset.
17269
+ #gateway;
17270
+ constructor(onPacket, options = {}) {
16857
17271
  this.#onPacket = onPacket;
17272
+ this.#gateway = options.gateway;
16858
17273
  }
16859
17274
  static isAvailable() {
16860
17275
  return hasMulticastGateway();
@@ -16864,7 +17279,8 @@ var MulticastTransport = class _MulticastTransport {
16864
17279
  this.#releaseSubscription();
16865
17280
  this.#dataPlaneLive = false;
16866
17281
  if (this.#disposed) return this.#declined(generation, "disposed");
16867
- if (!_MulticastTransport.isAvailable()) {
17282
+ const gateway = this.#gateway ?? getMulticastGlobals().multicast;
17283
+ if (typeof gateway?.subscribe !== "function") {
16868
17284
  console.warn("[MulticastTransport] Multicast API not available");
16869
17285
  return this.#declined(generation, "unavailable");
16870
17286
  }
@@ -16881,11 +17297,13 @@ var MulticastTransport = class _MulticastTransport {
16881
17297
  mode: config.mode,
16882
17298
  amtRelay: config.amtRelay,
16883
17299
  amtRelayPort: config.amtRelayPort,
17300
+ amtDiscovery: config.amtDiscovery,
16884
17301
  packetIds: config.packetIds,
16885
- tracks: config.tracks
17302
+ tracks: config.tracks,
17303
+ atsc3: config.atsc3
16886
17304
  });
16887
17305
  failure = "provider-rejected";
16888
- const subscription = await getMulticastGlobals().multicast.subscribe(subscribeConfig);
17306
+ const subscription = await gateway.subscribe(subscribeConfig);
16889
17307
  failure = "invalid-subscription";
16890
17308
  console.log(`[MulticastTransport] window.multicast.subscribe returned:`, !!subscription);
16891
17309
  if (this.#disposed || generation !== this.#joinGeneration) {
@@ -17472,16 +17890,6 @@ var MulticastTransport = class _MulticastTransport {
17472
17890
  // src/multicast-manager.ts
17473
17891
  import { deriveFecInterleaveDepth as deriveFecInterleaveDepth3, FecBlockMapper as FecBlockMapper2 } from "@blockcast/mmt-fec";
17474
17892
 
17475
- // src/multicast-auth-catalog.ts
17476
- var BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
17477
- var BASE64URL_DECODE_TABLE = (() => {
17478
- const table = new Int8Array(128).fill(-1);
17479
- for (let i = 0; i < BASE64URL_ALPHABET.length; i++) {
17480
- table[BASE64URL_ALPHABET.charCodeAt(i)] = i;
17481
- }
17482
- return table;
17483
- })();
17484
-
17485
17893
  // src/repair-layers.ts
17486
17894
  var RepairContractError = class extends Error {
17487
17895
  constructor(code, path, message) {
@@ -17555,7 +17963,7 @@ function isFecCatalogGeometry(obj) {
17555
17963
  const o = obj;
17556
17964
  const algorithm = o["algorithm"];
17557
17965
  const symbolSize = o["symbolSize"];
17558
- return typeof algorithm === "string" && (algorithm === "none" || algorithm === "raptorq" || algorithm === "reed-solomon") && typeof o["sourceSymbols"] === "number" && o["sourceSymbols"] >= 1 && typeof o["repairSymbols"] === "number" && o["repairSymbols"] >= 1 && typeof symbolSize === "number" && symbolSize >= 1 && (algorithm !== "raptorq" || symbolSize % 8 === 0) && typeof o["repairTrack"] === "string" && o["repairTrack"].length > 0;
17966
+ return typeof algorithm === "string" && algorithm.length > 0 && typeof o["sourceSymbols"] === "number" && o["sourceSymbols"] >= 1 && typeof o["repairSymbols"] === "number" && o["repairSymbols"] >= 1 && typeof symbolSize === "number" && symbolSize >= 1 && (algorithm !== "raptorq" || symbolSize % 8 === 0) && typeof o["repairTrack"] === "string" && o["repairTrack"].length > 0;
17559
17967
  }
17560
17968
  function isFecCatalogConfig(obj) {
17561
17969
  if (!isFecCatalogGeometry(obj)) return false;
@@ -17591,6 +17999,13 @@ function isoSpanUnavailable(fec, path, declaresFecInstance) {
17591
17999
  function catalogFecUnavailable(fec, fecPath) {
17592
18000
  if (catalogFecAvailable(fec)) return void 0;
17593
18001
  const block = recordOf2(fec);
18002
+ if (fecAlgorithmUnimplemented(block["algorithm"])) {
18003
+ return Object.freeze({
18004
+ code: "track_fec_algorithm_unimplemented",
18005
+ path: `${fecPath}.algorithm`,
18006
+ message: `algorithm ${JSON.stringify(block["algorithm"])} is not implemented: the track plays without FEC`
18007
+ });
18008
+ }
17594
18009
  const declaresFecInstance = block["algorithm"] !== "none";
17595
18010
  const reason = blockProfileUnavailable(block["blockProfile"], `${fecPath}.blockProfile`, declaresFecInstance) ?? isoSpanUnavailable(block, `${fecPath}.interleaveDepthMs`, declaresFecInstance);
17596
18011
  if (reason === void 0) {
@@ -17633,8 +18048,10 @@ function newBlockPolicyStats(packetId, catalogTrackName, epoch) {
17633
18048
  repairsSkippedRttUnmeasured: 0,
17634
18049
  repairsSkippedRttExceedsBudget: 0,
17635
18050
  repairsSkippedPresentationDelayUnavailable: 0,
18051
+ repairsSkippedRangeNoAnchor: 0,
17636
18052
  lastRepairSkip: null,
17637
18053
  keyframeRepairFetchesSent: 0,
18054
+ rangeRepairFetchesSent: 0,
17638
18055
  keyframeBudgetHolds: 0,
17639
18056
  keyframeBudgetHoldMs: 0,
17640
18057
  deltaBlocksFailed: 0,
@@ -17713,6 +18130,12 @@ var REPAIR_PRIORITY_REASONS = /* @__PURE__ */ new Set([
17713
18130
  "repair-priority-absent",
17714
18131
  "repair-priority-invalid"
17715
18132
  ]);
18133
+ var REPAIR_SKIP_REASONS = /* @__PURE__ */ new Set([
18134
+ "rtt-unmeasured",
18135
+ "rtt-exceeds-budget",
18136
+ "presentation-delay-unavailable"
18137
+ ]);
18138
+ var REPAIR_DEADLINE_BOUNDS = /* @__PURE__ */ new Set(["wait", "presentation", "keyframe", "retention"]);
17716
18139
  var GAP_REASONS = {
17717
18140
  "rap-lost": "stall",
17718
18141
  "rap-unknown": "stall",
@@ -17735,6 +18158,9 @@ function isSymbolCounts(value) {
17735
18158
  function isNullableNonNegative(value) {
17736
18159
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
17737
18160
  }
18161
+ function isFiniteNumber(value) {
18162
+ return typeof value === "number" && Number.isFinite(value);
18163
+ }
17738
18164
  function isRepairLifecycleEvent(value) {
17739
18165
  if (!isRecord(value) || value["version"] !== 2) return false;
17740
18166
  const block = value["block"];
@@ -17752,6 +18178,20 @@ function isRepairLifecycleEvent(value) {
17752
18178
  case "repair-preempted":
17753
18179
  case "repair-deferred":
17754
18180
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
18181
+ case "repair-sent":
18182
+ return hasExactKeys(value, [
18183
+ "version",
18184
+ "type",
18185
+ "block",
18186
+ "priority",
18187
+ "rttMs",
18188
+ "budgetMs",
18189
+ "delayMs",
18190
+ "blockAgeMs",
18191
+ "bound"
18192
+ ]) && 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"]);
18193
+ case "repair-skipped":
18194
+ return hasExactKeys(value, ["version", "type", "block", "reason", "rttMs", "budgetMs"]) && isRepairBlockIdentity(block) && REPAIR_SKIP_REASONS.has(value["reason"]) && isNullableNonNegative(value["rttMs"]) && isFiniteNumber(value["budgetMs"]);
17755
18195
  case "repair-priority": {
17756
18196
  const blockClass = value["blockClass"];
17757
18197
  const action = value["action"];
@@ -17931,6 +18371,9 @@ var MulticastManager = class {
17931
18371
  #router;
17932
18372
  #hostMfuTimeoutMs;
17933
18373
  #transport;
18374
+ /** Live joinRepairEndpoints() releases → the repair owners they registered,
18375
+ * re-applied after configureMultiTrack() clears catalog-derived owners. */
18376
+ #repairReleases = /* @__PURE__ */ new Map();
17934
18377
  #reportedFecDiagnosticsFailure = false;
17935
18378
  // ── Stream-global FEC timing reduction ──
17936
18379
  //
@@ -18194,7 +18637,9 @@ var MulticastManager = class {
18194
18637
  catalogTrackName
18195
18638
  );
18196
18639
  this.#configureTrackMapper(packetId, config);
18197
- this.#router.setPacketIdType(packetId, trackType);
18640
+ if (this.#router.trackKindFor(packetId) !== trackType) {
18641
+ this.#router.setPacketIdType(packetId, trackType);
18642
+ }
18198
18643
  }
18199
18644
  /**
18200
18645
  * Stop routing a stream's symbols to its Worker decoder. Returns false when
@@ -18275,6 +18720,14 @@ var MulticastManager = class {
18275
18720
  );
18276
18721
  }
18277
18722
  }
18723
+ for (const [packetId, c] of this.#trackFecTiming) {
18724
+ if (c.deliveryWindowMs === void 0) continue;
18725
+ mfuTimeoutMs = Math.max(
18726
+ mfuTimeoutMs ?? 0,
18727
+ this.#fec.terminalRetentionMsForPacket(packetId) ?? 0,
18728
+ this.#hostMfuTimeoutMs ?? 0
18729
+ );
18730
+ }
18278
18731
  const failbackWindowMs = deliveryWindowMs === void 0 ? minimumFailbackWindowMs : Math.max(deliveryWindowMs, minimumFailbackWindowMs ?? 0);
18279
18732
  this.#transport.setFailbackWindowMs(failbackWindowMs ?? null);
18280
18733
  this.#router.setMfuTimeoutMs(mfuTimeoutMs ?? this.#hostMfuTimeoutMs);
@@ -18458,6 +18911,7 @@ var MulticastManager = class {
18458
18911
  setMfuTimeoutMs(ms) {
18459
18912
  this.#router.setMfuTimeoutMs(ms);
18460
18913
  this.#hostMfuTimeoutMs = this.#router.reassembler.timeoutMs;
18914
+ if (this.#trackFecTiming.size > 0) this.#applyStreamGlobalFecTiming();
18461
18915
  }
18462
18916
  setTrackCodec(packetId, codec) {
18463
18917
  this.#router.setTrackCodec(packetId, codec);
@@ -18578,11 +19032,80 @@ var MulticastManager = class {
18578
19032
  // through whatever the relay looks like, since dropping it would be the
18579
19033
  // worse behaviour.
18580
19034
  amtRelayPort: config.amtRelayPort ?? config.relayPort ?? (amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : void 0),
19035
+ amtDiscovery: config.amtDiscovery,
18581
19036
  packetIds: config.packetIds,
18582
19037
  tracks: catalogTracks?.map(({ name, packetId }) => ({ name, packetId }))
18583
19038
  };
18584
19039
  return ingress === void 0 ? this.#transport.join(transportConfig) : this.#transport.join(transportConfig, ingress);
18585
19040
  }
19041
+ /**
19042
+ * Join the selected rung's dedicated repair groups beside the media join
19043
+ * (pim #3898): one subscription per endpoint, through `provider` when given
19044
+ * (a `window.multicast`-shaped gateway or a subscribe callback), otherwise a
19045
+ * new MulticastTransport on `window.multicast`. Returns the call that
19046
+ * releases every one of them; dispose() releases them too.
19047
+ *
19048
+ * Packets go straight to the router with the endpoint's ingress, never
19049
+ * through feedPacket(): repair arriving on its own group is not media
19050
+ * liveness, so it must not hold off the media leg's failback watchdog. The
19051
+ * repair roles and owners are registered here; in-band owners stay the
19052
+ * caller's. Joining is best effort: a group that fails to join is logged
19053
+ * and leaves the media join as it was.
19054
+ */
19055
+ joinRepairEndpoints(endpoints, provider) {
19056
+ const releases = [];
19057
+ let released = false;
19058
+ const safely = (each) => {
19059
+ try {
19060
+ each();
19061
+ } catch (error) {
19062
+ console.warn("[MulticastManager] repair group release failed", error);
19063
+ }
19064
+ };
19065
+ const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners);
19066
+ this.#applyRepairOwners(repairOwners);
19067
+ for (const endpoint of endpoints) {
19068
+ const ingress = {
19069
+ tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId })))
19070
+ };
19071
+ const onPacket = (packet) => {
19072
+ if (!released) this.#router.feedPacket(packet, "multicast", void 0, ingress);
19073
+ };
19074
+ const fail = (error) => console.warn(`[MulticastManager] repair group ${endpoint.group}:${endpoint.port} not joined`, error);
19075
+ if (typeof provider === "function") {
19076
+ Promise.resolve().then(() => provider(endpoint, onPacket)).then((release2) => released ? safely(release2) : releases.push(release2), fail);
19077
+ continue;
19078
+ }
19079
+ const transport = new MulticastTransport((packet) => onPacket(packet), { gateway: provider });
19080
+ releases.push(() => transport.dispose());
19081
+ void transport.join({
19082
+ sourceAddress: endpoint.source,
19083
+ groupAddress: endpoint.group,
19084
+ port: endpoint.port,
19085
+ mode: endpoint.mode,
19086
+ amtRelay: endpoint.amtRelay,
19087
+ amtRelayPort: endpoint.amtRelayPort ?? (endpoint.amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : void 0),
19088
+ packetIds: endpoint.packetIds,
19089
+ tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId }))
19090
+ }).then((joined) => {
19091
+ if (!joined && !released) fail(transport.lastJoinOutcome);
19092
+ });
19093
+ }
19094
+ const release = () => {
19095
+ if (released) return;
19096
+ released = true;
19097
+ this.#repairReleases.delete(release);
19098
+ for (const each of releases.splice(0)) safely(each);
19099
+ };
19100
+ this.#repairReleases.set(release, repairOwners);
19101
+ return release;
19102
+ }
19103
+ #applyRepairOwners(owners) {
19104
+ for (const { packetId, ownerPacketId } of owners) {
19105
+ this.#router.setPacketIdRole(packetId, "repair");
19106
+ this.#router.setRepairPacketIdOwner(packetId, ownerPacketId);
19107
+ }
19108
+ }
18586
19109
  // ---------------------------------------------------------------------------
18587
19110
  // In-place rendition switch
18588
19111
  // ---------------------------------------------------------------------------
@@ -18858,7 +19381,7 @@ var MulticastManager = class {
18858
19381
  *
18859
19382
  * D-04: Validates completeness via validateSwitchingSet — throws if incomplete.
18860
19383
  * D-07: Applies per-track FEC configs (base+delta get decoders; repair does not).
18861
- * D-17: Builds altGroup → track-name index for getSwitchingSet().
19384
+ * D-17: Builds altGroup → track-name index for getSwitchingSet() (repair legs excluded).
18862
19385
  * D-26: Registers packetId → TrackRole on MmtpRouter for block-complete fanout.
18863
19386
  *
18864
19387
  * FEC availability is per track (draft-ramadan-moq-fec §5.1). A media track
@@ -18909,11 +19432,9 @@ var MulticastManager = class {
18909
19432
  }
18910
19433
  }
18911
19434
  const repairOwnerGroup = /* @__PURE__ */ new Map();
18912
- const repairOwnerAltGroup = /* @__PURE__ */ new Map();
18913
19435
  for (const track of catalog.tracks) {
18914
19436
  for (const repairName of repairNamesBySource.get(track.name) ?? []) {
18915
19437
  repairOwnerGroup.set(repairName, altGroupKey(track));
18916
- repairOwnerAltGroup.set(repairName, track.altGroup);
18917
19438
  }
18918
19439
  }
18919
19440
  const groupKeyFor = (track) => repairOwnerGroup.get(track.name) ?? altGroupKey(track);
@@ -18944,11 +19465,7 @@ var MulticastManager = class {
18944
19465
  for (const [groupKey, roles] of resolvedRolesByGroup) {
18945
19466
  if (!(hasSwitchingSetByGroup.get(groupKey) ?? false)) continue;
18946
19467
  const presentRoles = new Set(roles.filter((r) => r !== "single"));
18947
- const required = [
18948
- "base",
18949
- "delta",
18950
- "repair"
18951
- ];
19468
+ const required = ["base", "repair"];
18952
19469
  const missing = required.filter((r) => !presentRoles.has(r));
18953
19470
  if (missing.length > 0) {
18954
19471
  throw new Error(
@@ -18995,6 +19512,7 @@ var MulticastManager = class {
18995
19512
  this.#switchingSets.clear();
18996
19513
  this.#repairPacketIds.clear();
18997
19514
  this.#router.clearRepairPacketIdOwners();
19515
+ for (const owners of this.#repairReleases.values()) this.#applyRepairOwners(owners);
18998
19516
  const fecPacketIds = new Set([...fecDecoders.keys()].map((i) => catalog.tracks[i].packetId));
18999
19517
  for (const [packetId, catalogTrackName] of this.#multiTrackFecTracks) {
19000
19518
  if (fecPacketIds.has(packetId)) continue;
@@ -19015,11 +19533,10 @@ var MulticastManager = class {
19015
19533
  for (let i = 0; i < catalog.tracks.length; i++) {
19016
19534
  const track = catalog.tracks[i];
19017
19535
  const role = resolvedRoles[i];
19018
- const altGroup = repairOwnerAltGroup.has(track.name) ? repairOwnerAltGroup.get(track.name) : track.altGroup;
19019
- if (altGroup !== void 0) {
19020
- const existing = this.#switchingSets.get(altGroup) ?? [];
19536
+ if (role !== "repair" && track.altGroup !== void 0) {
19537
+ const existing = this.#switchingSets.get(track.altGroup) ?? [];
19021
19538
  existing.push(track.name);
19022
- this.#switchingSets.set(altGroup, existing);
19539
+ this.#switchingSets.set(track.altGroup, existing);
19023
19540
  }
19024
19541
  if (track.packetId !== void 0) {
19025
19542
  this.#router.setPacketIdRole(track.packetId, role);
@@ -19094,7 +19611,7 @@ var MulticastManager = class {
19094
19611
  #multiTrackFecTracks = /* @__PURE__ */ new Map();
19095
19612
  /**
19096
19613
  * Return the track names belonging to the given altGroup switching set.
19097
- * D-17: altGroup groups base+delta+repair into one switching set.
19614
+ * D-17: tracks with equal altGroup form one switching set; repair legs are in none.
19098
19615
  *
19099
19616
  * @param altGroup - The altGroup number to look up.
19100
19617
  * @returns Array of track names in that switching set (empty if none).
@@ -19122,6 +19639,26 @@ var MulticastManager = class {
19122
19639
  this.requestRepairForBlock(sbn, packetId, catalogTrackName, blockClass);
19123
19640
  };
19124
19641
  }
19642
+ /**
19643
+ * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
19644
+ * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
19645
+ * pending hole and reported here, and `closeIsoHoles` must be called for it
19646
+ * once its range FETCH ends (or none is sent).
19647
+ */
19648
+ onUndelimitedLoss(cb) {
19649
+ this.#fec.setUndelimitedLossHandler(cb);
19650
+ }
19651
+ /**
19652
+ * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
19653
+ * to CmcdProducer.updateFecFailClosed.
19654
+ */
19655
+ onFecFailClosed(cb) {
19656
+ this.#fec.setFecFailClosedHandler(cb);
19657
+ }
19658
+ /** End a pending hole's range repair: feed what no repair stated as spans. */
19659
+ closeIsoHoles(packetId, catalogTrackName, start, length) {
19660
+ this.#router.closeIsoHoles(packetId, catalogTrackName, start, length);
19661
+ }
19125
19662
  /**
19126
19663
  * Record a repair request whose SUBSCRIBER_PRIORITY the catalog could not
19127
19664
  * supply (draft-ramadan-moq-fec §11.4.5): sent without the parameter, or
@@ -19143,6 +19680,7 @@ var MulticastManager = class {
19143
19680
  stats.repairsSkipped++;
19144
19681
  if (reason === "rtt-unmeasured") stats.repairsSkippedRttUnmeasured++;
19145
19682
  else if (reason === "rtt-exceeds-budget") stats.repairsSkippedRttExceedsBudget++;
19683
+ else if (reason === "range-no-anchor") stats.repairsSkippedRangeNoAnchor++;
19146
19684
  else stats.repairsSkippedPresentationDelayUnavailable++;
19147
19685
  stats.lastRepairSkip = {
19148
19686
  reason,
@@ -19174,8 +19712,20 @@ var MulticastManager = class {
19174
19712
  stats.keyframeBudgetHoldMs += extensionMs;
19175
19713
  }
19176
19714
  /** Record a repair FETCH the scheduler admitted and sent. */
19177
- noteRepairFetchSent(priority, _sbn, packetId, catalogTrackName) {
19715
+ noteRepairFetchSent(priority, sbn, packetId, catalogTrackName, measurement) {
19178
19716
  if (priority === 0) this.#statsFor(packetId, catalogTrackName).keyframeRepairFetchesSent++;
19717
+ if (measurement.range) this.#statsFor(packetId, catalogTrackName).rangeRepairFetchesSent++;
19718
+ this.#emitRepairLifecycle({
19719
+ version: 2,
19720
+ type: "repair-sent",
19721
+ block: repairBlockIdentity(packetId, sbn, catalogTrackName),
19722
+ priority,
19723
+ rttMs: measurement.rttMs,
19724
+ budgetMs: measurement.budgetMs,
19725
+ delayMs: measurement.delayMs,
19726
+ blockAgeMs: measurement.blockAgeMs,
19727
+ bound: measurement.bound
19728
+ });
19179
19729
  }
19180
19730
  /**
19181
19731
  * Record a repair-scheduler decision about a delta block: preempted for
@@ -19326,6 +19876,7 @@ var MulticastManager = class {
19326
19876
  this.#trackResetObservers.clear();
19327
19877
  this.#repairLifecycleObservers.clear();
19328
19878
  this.#transport.dispose();
19879
+ for (const release of [...this.#repairReleases.keys()]) release();
19329
19880
  this.#router.dispose();
19330
19881
  this.#fec.dispose();
19331
19882
  }