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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/README.md +37 -21
  2. package/dist/align.d.ts +24 -18
  3. package/dist/align.d.ts.map +1 -1
  4. package/dist/align.js +23 -4
  5. package/dist/align.js.map +2 -2
  6. package/dist/browser-runtime.js +2037 -881
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +76 -39
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +321 -205
  11. package/dist/carp-catalog.js.map +3 -3
  12. package/dist/catalog-fec-params.d.ts +12 -4
  13. package/dist/catalog-fec-params.d.ts.map +1 -1
  14. package/dist/catalog-fec-params.js +40 -17
  15. package/dist/catalog-fec-params.js.map +3 -3
  16. package/dist/catalog-network-source.d.ts +28 -7
  17. package/dist/catalog-network-source.d.ts.map +1 -1
  18. package/dist/catalog-network-source.js +21 -1
  19. package/dist/catalog-network-source.js.map +2 -2
  20. package/dist/catalog-validator.d.ts +4 -3
  21. package/dist/catalog-validator.d.ts.map +1 -1
  22. package/dist/catalog-validator.js +0 -29
  23. package/dist/catalog-validator.js.map +3 -3
  24. package/dist/cmcd-producer.d.ts +13 -1
  25. package/dist/cmcd-producer.d.ts.map +1 -1
  26. package/dist/cmcd-producer.js +14 -0
  27. package/dist/cmcd-producer.js.map +2 -2
  28. package/dist/delivery-catalog.js +98 -234
  29. package/dist/delivery-catalog.js.map +4 -4
  30. package/dist/fec-manager.d.ts +108 -1
  31. package/dist/fec-manager.d.ts.map +1 -1
  32. package/dist/fec-manager.js +452 -66
  33. package/dist/fec-manager.js.map +4 -4
  34. package/dist/fec-state.d.ts +2 -1
  35. package/dist/fec-state.d.ts.map +1 -1
  36. package/dist/fec-state.js +18 -3
  37. package/dist/fec-state.js.map +3 -3
  38. package/dist/fec-worker-setup.d.ts +10 -0
  39. package/dist/fec-worker-setup.d.ts.map +1 -1
  40. package/dist/fec-worker-setup.js +15 -4
  41. package/dist/fec-worker-setup.js.map +2 -2
  42. package/dist/held-layer-admission.d.ts +58 -0
  43. package/dist/held-layer-admission.d.ts.map +1 -0
  44. package/dist/held-layer-admission.js +105 -0
  45. package/dist/held-layer-admission.js.map +7 -0
  46. package/dist/index.d.ts +5 -5
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +8 -8
  49. package/dist/index.js.map +2 -2
  50. package/dist/iso-block-locator.d.ts +39 -1
  51. package/dist/iso-block-locator.d.ts.map +1 -1
  52. package/dist/iso-block-locator.js +109 -17
  53. package/dist/iso-block-locator.js.map +3 -3
  54. package/dist/mfu-reassembler.js +21 -13
  55. package/dist/mfu-reassembler.js.map +2 -2
  56. package/dist/mmtp-container-parser.d.ts.map +1 -1
  57. package/dist/mmtp-container-parser.js +93 -22
  58. package/dist/mmtp-container-parser.js.map +2 -2
  59. package/dist/mmtp-container-parser.no-modules.js +3677 -1213
  60. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  61. package/dist/mmtp-decode-pipeline.js +93 -22
  62. package/dist/mmtp-decode-pipeline.js.map +2 -2
  63. package/dist/mmtp-fec-session.d.ts +192 -0
  64. package/dist/mmtp-fec-session.d.ts.map +1 -0
  65. package/dist/mmtp-fec-session.js +640 -0
  66. package/dist/mmtp-fec-session.js.map +7 -0
  67. package/dist/mmtp-router.d.ts +69 -32
  68. package/dist/mmtp-router.d.ts.map +1 -1
  69. package/dist/mmtp-router.js +296 -192
  70. package/dist/mmtp-router.js.map +2 -2
  71. package/dist/multicast-auth-catalog.d.ts +86 -92
  72. package/dist/multicast-auth-catalog.d.ts.map +1 -1
  73. package/dist/multicast-auth-catalog.js +313 -124
  74. package/dist/multicast-auth-catalog.js.map +3 -3
  75. package/dist/multicast-input.d.ts +31 -8
  76. package/dist/multicast-input.d.ts.map +1 -1
  77. package/dist/multicast-input.js +299 -35
  78. package/dist/multicast-input.js.map +3 -3
  79. package/dist/multicast-manager.d.ts +97 -11
  80. package/dist/multicast-manager.d.ts.map +1 -1
  81. package/dist/multicast-manager.js +1022 -527
  82. package/dist/multicast-manager.js.map +4 -4
  83. package/dist/multicast-transport.d.ts +12 -2
  84. package/dist/multicast-transport.d.ts.map +1 -1
  85. package/dist/multicast-transport.js +108 -238
  86. package/dist/multicast-transport.js.map +4 -4
  87. package/dist/multicast-unwrap.js +21 -13
  88. package/dist/multicast-unwrap.js.map +2 -2
  89. package/dist/no-modules.d.ts +5 -3
  90. package/dist/no-modules.d.ts.map +1 -1
  91. package/dist/no-modules.js +3625 -1194
  92. package/dist/no-modules.js.map +4 -4
  93. package/dist/phase14-catalog-override.d.ts +1 -1
  94. package/dist/phase14-catalog-override.d.ts.map +1 -1
  95. package/dist/phase14-catalog-override.js +2 -2
  96. package/dist/phase14-catalog-override.js.map +2 -2
  97. package/dist/repair-fetch.d.ts +81 -6
  98. package/dist/repair-fetch.d.ts.map +1 -1
  99. package/dist/repair-fetch.js +156 -31
  100. package/dist/repair-fetch.js.map +3 -3
  101. package/dist/repair-layers.d.ts +2 -0
  102. package/dist/repair-layers.d.ts.map +1 -1
  103. package/dist/repair-layers.js +19 -2
  104. package/dist/repair-layers.js.map +2 -2
  105. package/dist/sample-combiner.d.ts +7 -1
  106. package/dist/sample-combiner.d.ts.map +1 -1
  107. package/dist/sample-combiner.js +14 -2
  108. package/dist/sample-combiner.js.map +2 -2
  109. package/dist/signaling.d.ts +2 -2
  110. package/dist/signaling.d.ts.map +1 -1
  111. package/dist/signaling.js +3 -3
  112. package/dist/signaling.js.map +2 -2
  113. package/dist/switching-set-alignment.d.ts +1 -1
  114. package/dist/switching-set-alignment.js.map +1 -1
  115. package/dist/timestamp-codec.js +21 -13
  116. package/dist/timestamp-codec.js.map +2 -2
  117. package/dist/wasm-mfu-reassembler.js.map +1 -1
  118. package/dist/wasm-mmtp-container-parser.js +93 -22
  119. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  120. package/package.json +6 -18
  121. package/schemas/catalog.schema.json +133 -38
  122. package/src/align.ts +52 -21
  123. package/src/carp-catalog.ts +188 -68
  124. package/src/catalog-fec-params.ts +28 -3
  125. package/src/catalog-network-source.ts +49 -7
  126. package/src/catalog-validator.ts +4 -11
  127. package/src/cmcd-producer.ts +23 -1
  128. package/src/fec-manager.ts +366 -63
  129. package/src/fec-state.ts +11 -4
  130. package/src/fec-worker-setup.ts +30 -2
  131. package/src/held-layer-admission.ts +161 -0
  132. package/src/index.ts +32 -19
  133. package/src/iso-block-locator.ts +110 -7
  134. package/src/mmtp-container-parser.ts +75 -7
  135. package/src/mmtp-fec-session.ts +606 -0
  136. package/src/mmtp-router.ts +301 -240
  137. package/src/multicast-auth-catalog.ts +134 -238
  138. package/src/multicast-input.ts +148 -124
  139. package/src/multicast-manager.ts +271 -40
  140. package/src/multicast-transport.ts +17 -3
  141. package/src/no-modules.ts +8 -7
  142. package/src/phase14-catalog-override.ts +3 -3
  143. package/src/repair-fetch.ts +283 -39
  144. package/src/repair-layers.ts +22 -2
  145. package/src/sample-combiner.ts +15 -2
  146. package/src/signaling.ts +2 -2
  147. package/src/switching-set-alignment.ts +1 -1
  148. package/test-vectors/align.json +108 -32
  149. package/test-vectors/bc-provenance-v2.json +1526 -0
  150. package/test-vectors/catalog/README.md +71 -4
  151. package/test-vectors/catalog/negative/fec-block-profile-missing.json +1 -1
  152. package/test-vectors/catalog/negative/fec-block-profile-retired.json +1 -1
  153. package/test-vectors/catalog/negative/fec-block-profile-unknown.json +1 -1
  154. package/test-vectors/catalog/negative/fec-iso-symbol-size-below-floor.json +28 -0
  155. package/test-vectors/catalog/negative/fec-reed-solomon-iso-symbol-size-13.json +28 -0
  156. package/test-vectors/catalog/negative/fec-reed-solomon-k-plus-p-over-255.json +39 -0
  157. package/test-vectors/catalog/negative/fec-reed-solomon-overlay-over-255.json +40 -0
  158. package/test-vectors/catalog/negative/fec-repair-overlay-source-symbols-zero.json +43 -0
  159. package/test-vectors/catalog/negative/fec-repair-symbols-zero.json +28 -0
  160. package/test-vectors/catalog/negative/fec-source-symbols-zero.json +28 -0
  161. package/test-vectors/catalog/negative/fec-symbol-size-zero.json +28 -0
  162. package/test-vectors/catalog/negative/init-data-inline-without-data.json +22 -0
  163. package/test-vectors/catalog/negative/mmtp-mode-mpu.json +15 -0
  164. package/test-vectors/catalog/negative/multicast-amt-dns-without-relay.json +37 -0
  165. package/test-vectors/catalog/negative/multicast-amt-driad-with-relay.json +38 -0
  166. package/test-vectors/catalog/negative/multicast-auth-asm-missing-sender-address.json +77 -0
  167. package/test-vectors/catalog/negative/multicast-auth-duplicate-first-epoch.json +56 -0
  168. package/test-vectors/catalog/negative/multicast-auth-duplicate-kid.json +56 -0
  169. package/test-vectors/catalog/negative/multicast-auth-endpoint-auth-without-object-auth.json +38 -0
  170. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-auth.json +49 -0
  171. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-bandwidth.json +55 -0
  172. package/test-vectors/catalog/negative/multicast-auth-manifest-port-equals-port.json +56 -0
  173. package/test-vectors/catalog/negative/multicast-auth-manifest-timer-out-of-range.json +56 -0
  174. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-above-max.json +56 -0
  175. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-below-min.json +56 -0
  176. package/test-vectors/catalog/negative/multicast-auth-root-dotted-key.json +55 -0
  177. package/test-vectors/catalog/negative/multicast-auth-sender-address-on-ssm.json +57 -0
  178. package/test-vectors/catalog/negative/multicast-auth-version-1.json +56 -0
  179. package/test-vectors/catalog/negative/multicast-auth-version-3.json +56 -0
  180. package/test-vectors/catalog/negative/multicast-auth-version-missing.json +55 -0
  181. package/test-vectors/catalog/negative/multicast-endpoint-foreign-namespace-track.json +44 -0
  182. package/test-vectors/catalog/negative/multicast-endpoint-protocol-amt.json +38 -0
  183. package/test-vectors/catalog/negative/multicast-endpoint-protocol-atsc3.json +38 -0
  184. package/test-vectors/catalog/negative/presentation-anchor-unsafe.json +16 -0
  185. package/test-vectors/catalog/positive/fec-algorithm-unimplemented.json +29 -0
  186. package/test-vectors/catalog/positive/fec-iso-ssbg1.json +1 -1
  187. package/test-vectors/catalog/positive/fec-multicast.json +1 -1
  188. package/test-vectors/catalog/positive/fec-reed-solomon-layered.json +50 -0
  189. package/test-vectors/catalog/positive/mmt01-12-1-init-ref-anchor.json +29 -0
  190. package/test-vectors/catalog/positive/multicast-amt-discovery-omitted.json +37 -0
  191. package/test-vectors/catalog/positive/multicast-amt-dns-relay.json +38 -0
  192. package/test-vectors/catalog/positive/multicast-amt-manual-relay.json +3 -3
  193. package/test-vectors/catalog/{negative/multicast-endpoint-missing-protocol-and-source.json → positive/multicast-asm-unprotected.json} +10 -5
  194. package/test-vectors/catalog/positive/multicast-auth-asm-sender.json +78 -0
  195. package/test-vectors/catalog/positive/multicast-auth-rotation.json +39 -38
  196. package/test-vectors/catalog/positive/multicast-draft01-4-1-example.json +81 -0
  197. package/test-vectors/catalog/positive/multicast-draft01-7-2-6-example.json +70 -0
  198. package/test-vectors/catalog/positive/presentation-anchor-negative.json +27 -0
  199. package/test-vectors/catalog/section-codes.json +31 -1
  200. package/test-vectors/catalog-multicast-auth-v1.json +38 -20
  201. package/test-vectors/catalog-validation.json +101 -5
  202. package/test-vectors/catalog-validator-public-api.mjs +14 -9
  203. package/test-vectors/generate-bc-provenance-v2.mjs +252 -0
  204. package/dist/fec-codec.d.ts +0 -32
  205. package/dist/fec-codec.d.ts.map +0 -1
  206. package/dist/fec-codec.js +0 -47
  207. package/dist/fec-codec.js.map +0 -7
  208. package/dist/manifest-auth-plan.d.ts +0 -30
  209. package/dist/manifest-auth-plan.d.ts.map +0 -1
  210. package/dist/manifest-auth-plan.js +0 -1266
  211. package/dist/manifest-auth-plan.js.map +0 -7
  212. package/dist/source-auth.d.ts +0 -2
  213. package/dist/source-auth.d.ts.map +0 -1
  214. package/dist/source-auth.js +0 -1209
  215. package/dist/source-auth.js.map +0 -7
  216. package/src/fec-codec.ts +0 -61
  217. package/src/manifest-auth-plan.ts +0 -107
  218. package/src/source-auth.ts +0 -1
  219. package/test-vectors/generate-source-auth-fixture.mjs +0 -114
  220. package/test-vectors/source-auth-v1.json +0 -61
@@ -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 });
2285
2493
  }
2286
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 });
2499
+ }
2500
+ if (symbol === "source") this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
2501
+ anchorHere();
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;
@@ -12415,11 +12877,14 @@ var MmtpRouter = class {
12415
12877
  #fecManager;
12416
12878
  #defaultFecMapper;
12417
12879
  #fecMappersByPacketId = /* @__PURE__ */ new Map();
12418
- #manifestVerifier;
12419
- #ownsManifestVerifier;
12420
- #resolveManifestIdentity;
12421
- #resolveManifestIdentityForRoute;
12422
- #manifestRecoveryQueues = /* @__PURE__ */ new Map();
12880
+ /** Protected flows: one 7.2.7 receiver each, and the ingress its datagrams arrive with. */
12881
+ #provenance = /* @__PURE__ */ new Map();
12882
+ /** The ingress a held datagram arrived with; the receiver returns the same bytes on release. */
12883
+ #heldIngress = /* @__PURE__ */ new WeakMap();
12884
+ /** The flow whose receiver admitted a stream's source datagrams, by packetId then catalog track name: recovered packets answer to it. */
12885
+ #provenanceStreamFlow = /* @__PURE__ */ new Map();
12886
+ #unregisteredFlowDrops = 0;
12887
+ #ambiguousRecoveredDrops = 0;
12423
12888
  // Temp state set by #processMMTP before calling parser.feed(),
12424
12889
  // read by the parser's onFrame callback for CMAF assembly + dedup.
12425
12890
  #currentFecInfo;
@@ -12453,6 +12918,18 @@ var MmtpRouter = class {
12453
12918
  // MSE recovery routes through CmafBlockAssembler and can reorder by block; the
12454
12919
  // direct callback path has to preserve decode order before frames leave libmmt.
12455
12920
  #latestVideoSeqByStream = /* @__PURE__ */ new Map();
12921
+ /**
12922
+ * Per stream, SS_ID - packet_sequence_number (mod 2^32) of its latest
12923
+ * first-arrival FEC source packet. A recovered source symbol's wire
12924
+ * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
12925
+ */
12926
+ #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
12927
+ /**
12928
+ * Streams whose multicast leg delivered a RAP-flagged source packet that was
12929
+ * not parsed, typically because its overlap copy was parsed first
12930
+ * (BLO-49179). The next video keyframe emitted on the stream consumes it.
12931
+ */
12932
+ #multicastRapTwinByStream = /* @__PURE__ */ new Set();
12456
12933
  #lastDirectSourceVideoTsByStream = /* @__PURE__ */ new Map();
12457
12934
  #lastDirectEmittedVideoTsByStream = /* @__PURE__ */ new Map();
12458
12935
  #pendingDirectRecoveredVideoByStream = /* @__PURE__ */ new Map();
@@ -12527,11 +13004,14 @@ var MmtpRouter = class {
12527
13004
  */
12528
13005
  #onPublisherRestart;
12529
13006
  #publisherRestarts = 0;
13007
+ #restampedRecoveredSeqs = 0;
12530
13008
  /** Inits delivered with no onTrackInit handler for their packetId (MOQT-01). */
12531
13009
  #unmappedInitDeliveries = 0;
12532
13010
  // FEC Payload IDs left unread because their (owner) packetId had no
12533
13011
  // configured fec.blockProfile (see #noteUnreadableFecPayloadId).
12534
13012
  #fecPayloadIdsWithoutProfile = 0;
13013
+ // Repair packets discarded by the fec-01 4.5 block-length rule.
13014
+ #repairBlockLengthDiscards = 0;
12535
13015
  /** The staged in-place stream switch, if any (stageStreamSwitch). */
12536
13016
  #staged = null;
12537
13017
  #disposed = false;
@@ -12541,10 +13021,6 @@ var MmtpRouter = class {
12541
13021
  this.#fecManager = config?.fecManager ?? null;
12542
13022
  this.#onFrameGap = config?.onFrameGap ?? null;
12543
13023
  this.#defaultFecMapper = config?.fecMapper ?? null;
12544
- this.#manifestVerifier = config?.manifestVerifier ?? null;
12545
- this.#ownsManifestVerifier = config?.manifestVerifierOwnership !== "caller";
12546
- this.#resolveManifestIdentity = config?.resolveManifestIdentity ?? null;
12547
- this.#resolveManifestIdentityForRoute = config?.resolveManifestIdentityForRoute ?? null;
12548
13024
  this.#parser = new MmtpContainerParser({
12549
13025
  mfuTimeoutMs: config?.mfuTimeoutMs,
12550
13026
  reassemblyPolicy: config?.reassemblyPolicy,
@@ -12585,6 +13061,12 @@ var MmtpRouter = class {
12585
13061
  ...meta.catalogTrackName === void 0 ? {} : { catalogTrackName: meta.catalogTrackName }
12586
13062
  };
12587
13063
  if (meta.source) frameMeta.source = meta.source;
13064
+ if (isVideo && frameMeta.keyframe) {
13065
+ const twinSeen = this.#multicastRapTwinByStream.delete(
13066
+ this.#mediaStreamKey(packetId, frameMeta.catalogTrackName)
13067
+ );
13068
+ if (twinSeen && frameMeta.source === "moq") frameMeta.source = "multicast";
13069
+ }
12588
13070
  if (meta.deliveryProvenance !== void 0)
12589
13071
  frameMeta.deliveryProvenance = meta.deliveryProvenance;
12590
13072
  if (meta.recovered) frameMeta.recovered = true;
@@ -12747,6 +13229,14 @@ var MmtpRouter = class {
12747
13229
  get publisherRestartCount() {
12748
13230
  return this.#publisherRestarts;
12749
13231
  }
13232
+ /**
13233
+ * FEC-recovered source symbols whose reconstructed header named a
13234
+ * packet_sequence_number other than the wire sequence their SS_ID maps to:
13235
+ * a hop re-stamped the sequence after the sender protected the packet.
13236
+ */
13237
+ get restampedRecoveredSequenceCount() {
13238
+ return this.#restampedRecoveredSeqs;
13239
+ }
12750
13240
  /**
12751
13241
  * Packets whose Source or Repair FEC Payload ID was left unread because
12752
13242
  * their (owner) packetId had no configured `fec.blockProfile`: FEC not
@@ -12758,6 +13248,14 @@ var MmtpRouter = class {
12758
13248
  get fecPayloadIdsWithoutProfile() {
12759
13249
  return this.#fecPayloadIdsWithoutProfile;
12760
13250
  }
13251
+ /**
13252
+ * Repair packets discarded at admission by the fec-01 4.5 rule (RS_ID not
13253
+ * below RSB_length, or a reed-solomon SSB_length + RSB_length above 255),
13254
+ * before they touched any block state.
13255
+ */
13256
+ get repairBlockLengthDiscards() {
13257
+ return this.#repairBlockLengthDiscards;
13258
+ }
12761
13259
  get reassembler() {
12762
13260
  return this.#parser.reassembler;
12763
13261
  }
@@ -13054,29 +13552,51 @@ var MmtpRouter = class {
13054
13552
  }
13055
13553
  });
13056
13554
  }
13057
- registerManifestTrack(context) {
13058
- if (!this.#manifestVerifier) throw new Error("manifest verifier is not configured");
13059
- this.#manifestVerifier.registerTrack(context);
13060
- }
13061
- feedManifestFrame(trackName, frame) {
13062
- this.#manifestVerifier?.ingestManifestFrame(trackName, frame);
13063
- }
13064
- setManifestAuthMode(mode) {
13065
- this.#manifestVerifier?.setMode(mode);
13066
- if (mode !== "enforce") {
13067
- for (const queue of this.#manifestRecoveryQueues.values()) {
13068
- for (const item of queue) {
13069
- this.#routeProcessedFecSymbols(
13070
- item.blockId,
13071
- item.result,
13072
- item.ownerPacketId,
13073
- item.catalogTrackName
13074
- );
13555
+ /**
13556
+ * Protect a flow (draft-ramadan-moq-multicast-01 7.2.7): every multicast
13557
+ * datagram whose ingress names `ingress.flow`, source and repair alike, is
13558
+ * admitted by `receiver` before anything reads it, and an unadmitted one is
13559
+ * held or dropped. The caller owns the receiver's configuration; the router
13560
+ * releases it on `releaseProvenanceFlow` and on dispose.
13561
+ */
13562
+ registerProvenanceFlow(ingress, receiver) {
13563
+ this.#provenance.get(ingress.flow)?.receiver.release();
13564
+ this.#provenance.set(ingress.flow, { receiver, ingress });
13565
+ }
13566
+ /**
13567
+ * Feed one bc-provenance record of `flow`: a datagram from `manifestPort`
13568
+ * (`multicast`) or an object of the manifest track (`mirror`). Held
13569
+ * datagrams the record admits are routed before this returns.
13570
+ */
13571
+ feedProvenanceRecord(flow, record, path) {
13572
+ const entry = this.#provenance.get(flow);
13573
+ if (!entry || this.#disposed) return "unregistered";
13574
+ const result = entry.receiver.onRecord(record, path);
13575
+ if (result.admitted.length > 0) {
13576
+ this.#withDeferredFecPokes(() => {
13577
+ for (const datagram of result.admitted) {
13578
+ this.#processMMTP(datagram, "multicast", true, this.#heldIngress.get(datagram) ?? entry.ingress, false, true);
13075
13579
  }
13076
- }
13077
- this.#manifestRecoveryQueues.clear();
13580
+ });
13581
+ }
13582
+ return result.verdict;
13583
+ }
13584
+ /** The receiver ceased to hold the flow: its hold queues are dropped, not expired. */
13585
+ releaseProvenanceFlow(flow) {
13586
+ this.#provenance.get(flow)?.receiver.release();
13587
+ this.#provenance.delete(flow);
13588
+ for (const byName of this.#provenanceStreamFlow.values()) {
13589
+ for (const [name, bound] of byName) if (bound === flow) byName.delete(name);
13078
13590
  }
13079
13591
  }
13592
+ /** Multicast datagrams dropped because their ingress names a flow with no registered receiver. */
13593
+ get unregisteredFlowDropCount() {
13594
+ return this.#unregisteredFlowDrops;
13595
+ }
13596
+ /** Recovered packets dropped because more than one protected flow could own their stream. */
13597
+ get ambiguousRecoveredDropCount() {
13598
+ return this.#ambiguousRecoveredDrops;
13599
+ }
13080
13600
  /**
13081
13601
  * Main entry point: feed a raw MMTP packet for processing.
13082
13602
  *
@@ -13091,10 +13611,10 @@ var MmtpRouter = class {
13091
13611
  * they may never have crossed — and that attribution is what the physical-
13092
13612
  * delivery evidence path is built on. Absence is not multicast; say which.
13093
13613
  */
13094
- feedPacket(packet, source, manifestIdentity, ingress) {
13614
+ feedPacket(packet, source, ingress) {
13095
13615
  if (this.#disposed) return;
13096
13616
  this.#withDeferredFecPokes(() => {
13097
- this.#processMMTP(packet, source, manifestIdentity, false, ingress);
13617
+ this.#processMMTP(packet, source, false, ingress);
13098
13618
  });
13099
13619
  }
13100
13620
  /**
@@ -13129,20 +13649,20 @@ var MmtpRouter = class {
13129
13649
  feedOverlapCopy(packet, ingress) {
13130
13650
  if (this.#disposed) return;
13131
13651
  this.#withDeferredFecPokes(() => {
13132
- this.#processMMTP(packet, "moq", void 0, false, ingress, true);
13652
+ this.#processMMTP(packet, "moq", false, ingress, true);
13133
13653
  });
13134
13654
  }
13135
13655
  /**
13136
13656
  * Feed a repair packet from MoQ (reliable QUIC) — parses MMTP repair
13137
13657
  * header and delegates to FECManager for FEC recovery.
13138
13658
  */
13139
- feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName) {
13659
+ feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName) {
13140
13660
  if (this.#disposed) return;
13141
13661
  this.#withDeferredFecPokes(() => {
13142
- this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName);
13662
+ this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName);
13143
13663
  });
13144
13664
  }
13145
- #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName) {
13665
+ #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName) {
13146
13666
  let header;
13147
13667
  try {
13148
13668
  header = parseMMTPHeader(packet);
@@ -13173,7 +13693,7 @@ var MmtpRouter = class {
13173
13693
  this.#noteUnreadableFecPayloadId(ownerPacketId, "repair");
13174
13694
  return;
13175
13695
  }
13176
- this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, "moq");
13696
+ this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, "moq", repairTrackName);
13177
13697
  }
13178
13698
  }
13179
13699
  // ── Packet FEC geometry and block profile ───────────────────────
@@ -13255,13 +13775,25 @@ var MmtpRouter = class {
13255
13775
  * the repair, the order they had on the wire, so a loss-free block completes
13256
13776
  * clean on its repair. A repair contradicting a known block is dropped.
13257
13777
  */
13258
- #handleIsoRepair(ownerPacketId, catalogTrackName, repair, source) {
13778
+ #handleIsoRepair(ownerPacketId, catalogTrackName, repair, source, repairTrackName) {
13259
13779
  const fec = this.#fecManager;
13260
13780
  if (!fec?.placeIsoRepair) {
13261
13781
  throw new Error(
13262
13782
  `[MmtpRouter] packetId=${ownerPacketId} is iso-ssbg1-v1 but its FEC manager cannot place ISO blocks`
13263
13783
  );
13264
13784
  }
13785
+ if (fec.admitRepairBlockLength && !fec.admitRepairBlockLength(ownerPacketId, repair.ssbLength, repair.rsbLength, repair.rsId)) {
13786
+ this.#repairBlockLengthDiscards++;
13787
+ return;
13788
+ }
13789
+ if (fec.admitRepairSymbolSize && !fec.admitRepairSymbolSize(
13790
+ ownerPacketId,
13791
+ repair.ssStart,
13792
+ repair.ssbLength,
13793
+ repair.rsId,
13794
+ repair.symbolData.byteLength
13795
+ )) return;
13796
+ if (fec.admitRepairLayerTotal && !fec.admitRepairLayerTotal(ownerPacketId, catalogTrackName, repairTrackName, repair.ssStart, repair.rsbLength)) return;
13265
13797
  const placement = fec.placeIsoRepair(ownerPacketId, catalogTrackName, repair.ssStart, repair.ssbLength);
13266
13798
  if (placement.status !== "placed") return;
13267
13799
  const blockStart = placement.block.start;
@@ -13296,6 +13828,17 @@ var MmtpRouter = class {
13296
13828
  this.#routeRecoveredBlock(blockStart, recovered, ownerPacketId, catalogTrackName);
13297
13829
  }
13298
13830
  }
13831
+ /**
13832
+ * The range repair FETCH for an undelimited hole ended (draft-ramadan-moq-fec
13833
+ * §7.5): what no repair stated becomes repair-less spans, whose held sources
13834
+ * are fed exactly as a span a repair closed.
13835
+ */
13836
+ closeIsoHoles(ownerPacketId, catalogTrackName, start, length) {
13837
+ const spans = this.#fecManager?.closeIsoHoles?.(ownerPacketId, catalogTrackName, start, length) ?? [];
13838
+ for (const span of spans) {
13839
+ this.#replayIsoSources(ownerPacketId, catalogTrackName, span.block.start, span.placed);
13840
+ }
13841
+ }
13299
13842
  /**
13300
13843
  * Feed iso-ssbg1-v1 sources a repair just placed, in SS_ID order, exactly as
13301
13844
  * a first-arrival source is fed once its block is known: transport
@@ -13391,13 +13934,14 @@ var MmtpRouter = class {
13391
13934
  this.#trackSynced.delete(streamKey);
13392
13935
  this.#droppedPreSyncVideo.delete(streamKey);
13393
13936
  this.#latestVideoSeqByStream.delete(streamKey);
13937
+ this.#ssIdSeqOffsetByStream.delete(streamKey);
13938
+ this.#multicastRapTwinByStream.delete(streamKey);
13394
13939
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
13395
13940
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
13396
13941
  this.#pendingDirectRecoveredVideoByStream.delete(streamKey);
13397
13942
  this.#lastDirectSourceAudioCursorByStream.delete(streamKey);
13398
13943
  this.#lastDirectEmittedAudioCursorByStream.delete(streamKey);
13399
13944
  this.#pendingDirectRecoveredAudioByStream.delete(streamKey);
13400
- this.#manifestRecoveryQueues.delete(streamKey);
13401
13945
  this.#deliveredVideoHighWaterByStream.delete(streamKey);
13402
13946
  this.#stream(packetId, catalogTrackName).duplicates.clear();
13403
13947
  const assemblersToReset = /* @__PURE__ */ new Set();
@@ -13447,7 +13991,6 @@ var MmtpRouter = class {
13447
13991
  this.#lastDirectSourceAudioCursorByStream.delete(key);
13448
13992
  this.#lastDirectEmittedAudioCursorByStream.delete(key);
13449
13993
  this.#pendingDirectRecoveredAudioByStream.delete(key);
13450
- this.#manifestRecoveryQueues.delete(key);
13451
13994
  this.#trackInitDelivered.delete(key);
13452
13995
  this.#parserDiagnostics.delete(key);
13453
13996
  this.#pendingFecPokes.delete(key);
@@ -13708,8 +14251,9 @@ var MmtpRouter = class {
13708
14251
  this.#parserDiagnostics.clear();
13709
14252
  this.#catalogTrackNamesByPacketId.clear();
13710
14253
  this.#repairOwnersByPacketId.clear();
13711
- if (this.#ownsManifestVerifier) this.#manifestVerifier?.dispose();
13712
- this.#manifestRecoveryQueues.clear();
14254
+ for (const { receiver } of this.#provenance.values()) receiver.release();
14255
+ this.#provenance.clear();
14256
+ this.#provenanceStreamFlow.clear();
13713
14257
  for (const assembler of this.#mseAssemblers.values()) assembler.dispose();
13714
14258
  this.#mseAssemblers.clear();
13715
14259
  }
@@ -13986,7 +14530,7 @@ var MmtpRouter = class {
13986
14530
  * 1. parseHeader() → extract packetId + fecPayloadId for FEC feeding
13987
14531
  * 2. feed() → MFU extraction, reassembly, keyframe detection, emit via callbacks
13988
14532
  */
13989
- #processMMTP(packet, source, manifestIdentity, manifestAdmitted = false, ingress, overlapCopy = false, releasedFromQuarantine = false) {
14533
+ #processMMTP(packet, source, manifestAdmitted = false, ingress, overlapCopy = false, releasedFromQuarantine = false) {
13990
14534
  const parsed = this.#parser.parsePacket(packet);
13991
14535
  if (!parsed) return;
13992
14536
  const info = parsed.info;
@@ -14011,45 +14555,22 @@ var MmtpRouter = class {
14011
14555
  }
14012
14556
  const fecUnreadable = !info.isRepair && info.fecPayloadId != null && this.#fecManager !== null && this.#classifyPacketId(info.packetId) !== null && this.#configuredBlockProfile(info.packetId) === void 0;
14013
14557
  if (fecUnreadable && !manifestAdmitted) this.#noteUnreadableFecPayloadId(info.packetId, "source");
14014
- if (!info.isRepair && this.#manifestVerifier && !manifestAdmitted) {
14015
- let identity = manifestIdentity;
14016
- if (!identity && info.fecPayloadId && !fecUnreadable && (this.#resolveManifestIdentityForRoute || this.#resolveManifestIdentity)) {
14017
- const catalogTrackName = catalogTrackNameForPacket(ingress, info.packetId);
14018
- const coordinates = this.#locateFecSource(info.packetId, catalogTrackName, info.fecPayloadId.ssId);
14019
- identity = coordinates === null ? void 0 : (this.#resolveManifestIdentityForRoute ? this.#resolveManifestIdentityForRoute({
14020
- packetId: info.packetId,
14021
- sbn: coordinates.sbn,
14022
- esi: coordinates.esi,
14023
- ...catalogTrackName === void 0 ? {} : { catalogTrackName },
14024
- recovered: false,
14025
- sourceSymbolFormat: "full-mmtp-packet"
14026
- }) : this.#resolveManifestIdentity(
14027
- info.packetId,
14028
- coordinates.sbn,
14029
- coordinates.esi,
14030
- catalogTrackName
14031
- )) ?? void 0;
14032
- }
14033
- if (identity) {
14034
- identity = {
14035
- ...identity,
14036
- packetId: info.packetId,
14037
- ...info.fecPayloadId ? { ssId: info.fecPayloadId.ssId } : {}
14038
- };
14039
- const authenticated = info.fecPayloadId ? packet.subarray(0, packet.length - 4) : packet;
14040
- let quarantined = false;
14041
- const admission = this.#manifestVerifier.admitObject(identity, authenticated, () => {
14042
- if (!this.#disposed) {
14043
- this.#processMMTP(packet, source, identity, true, ingress, overlapCopy, quarantined);
14044
- }
14045
- });
14046
- quarantined = admission.action === "stall";
14047
- return;
14048
- }
14049
- if (this.#manifestVerifier.config.mode === "enforce" && this.#manifestVerifier.config.onMissingManifest === "stall") {
14050
- console.warn(`[MmtpRouter] manifest identity absent; stalling packetId=${info.packetId}`);
14558
+ if (source === "multicast" && manifestAdmitted && !info.isRepair && ingress?.flow !== void 0) {
14559
+ let byName = this.#provenanceStreamFlow.get(info.packetId);
14560
+ if (!byName) this.#provenanceStreamFlow.set(info.packetId, byName = /* @__PURE__ */ new Map());
14561
+ byName.set(catalogTrackNameForPacket(ingress, info.packetId), ingress.flow);
14562
+ }
14563
+ if (source === "multicast" && !manifestAdmitted && ingress?.flow !== void 0) {
14564
+ const protectedFlow = this.#provenance.get(ingress.flow);
14565
+ if (!protectedFlow) {
14566
+ this.#unregisteredFlowDrops++;
14567
+ debugRouter(`[MmtpRouter] Dropping multicast packet pid=${info.packetId}: flow ${ingress.flow} has no receiver`);
14051
14568
  return;
14052
14569
  }
14570
+ const { verdict } = protectedFlow.receiver.onDatagram(packet, "multicast");
14571
+ if (verdict === "admitted") this.#processMMTP(packet, source, true, ingress, overlapCopy);
14572
+ else if (verdict === "held") this.#heldIngress.set(packet, ingress);
14573
+ return;
14053
14574
  }
14054
14575
  if (info.isRepair) {
14055
14576
  const repair = parseMoqRepairFrameWithHeader(packet, parsed.header);
@@ -14161,6 +14682,12 @@ var MmtpRouter = class {
14161
14682
  } else if (fecUnreadable && info.fecPayloadId) {
14162
14683
  parseSourceSymbol = !duplicates.parsedSymbols.has(info.fecPayloadId.ssId);
14163
14684
  }
14685
+ if (fecPayloadId && !overlapCopy) {
14686
+ this.#ssIdSeqOffsetByStream.set(
14687
+ this.#mediaStreamKey(info.packetId, catalogTrackName),
14688
+ fecPayloadId.ssId - info.sequenceNumber >>> 0
14689
+ );
14690
+ }
14164
14691
  if (!this.#fecManager || !info.fecPayloadId || parseSourceSymbol) {
14165
14692
  if (this.#fecManager && info.fecPayloadId) {
14166
14693
  duplicates.parsedSymbols.add(info.fecPayloadId.ssId);
@@ -14183,6 +14710,10 @@ var MmtpRouter = class {
14183
14710
  // An FEC source frame is anchored by its own SS_ID (C.5.2).
14184
14711
  ...fecSource && fecPayloadId ? { fecSbn: fecPayloadId.ssId } : {}
14185
14712
  }, parsed);
14713
+ } else if (source === "multicast" && info.rapFlag) {
14714
+ this.#multicastRapTwinByStream.add(
14715
+ this.#mediaStreamKey(info.packetId, catalogTrackName)
14716
+ );
14186
14717
  }
14187
14718
  if (this.#classifyPacketId(info.packetId) === null) return;
14188
14719
  if (this.#fecManager && fecPayloadId && coords && sourceSymbolAccepted && sourceSymbolTrackable) {
@@ -14638,105 +15169,69 @@ var MmtpRouter = class {
14638
15169
  });
14639
15170
  this.#routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
14640
15171
  }
15172
+ /**
15173
+ * A recovered source packet of a protected flow is admitted on its own
15174
+ * digest: its bytes with the SS_ID it was sent with (SS_Start + ESI)
15175
+ * appended are the datagram the record listed (7.2.7). One that no record
15176
+ * lists is dropped; holding it would let it out later as a multicast arrival.
15177
+ */
14641
15178
  #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName) {
14642
- if (!this.#manifestVerifier || ownerPacketId == null) {
14643
- this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
14644
- return;
14645
- }
14646
- if (!this.#resolveManifestIdentity && !this.#resolveManifestIdentityForRoute) {
14647
- console.warn(`[MmtpRouter] manifest identity resolver unavailable; recovered media is fail-open for packetId=${ownerPacketId} block=${blockId}`);
14648
- this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
14649
- return;
15179
+ const receiver = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
15180
+ if (receiver === "ambiguous") {
15181
+ this.#ambiguousRecoveredDrops += result.symbols.length;
15182
+ result = { ...result, symbols: [] };
15183
+ } else if (receiver) {
15184
+ result = {
15185
+ ...result,
15186
+ symbols: result.symbols.filter((sym) => {
15187
+ const wire = new Uint8Array(sym.rawSymbol.byteLength + 4);
15188
+ wire.set(sym.rawSymbol);
15189
+ new DataView(wire.buffer).setUint32(sym.rawSymbol.byteLength, this.#fecAnchorForRecovered(blockId, sym.index));
15190
+ return receiver.admitRecovered(wire);
15191
+ })
15192
+ };
14650
15193
  }
14651
- const queueKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
14652
- const queue = this.#manifestRecoveryQueues.get(queueKey) ?? [];
14653
- queue.push({ blockId, result, ownerPacketId, catalogTrackName });
14654
- this.#manifestRecoveryQueues.set(queueKey, queue);
14655
- if (queue.length > 1) return;
14656
- const drain = () => {
14657
- const next = queue[0];
14658
- if (!next) {
14659
- this.#manifestRecoveryQueues.delete(queueKey);
14660
- return;
15194
+ this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
15195
+ }
15196
+ /**
15197
+ * The receiver a recovered packet of `packetId` answers to: the flow that
15198
+ * admitted the stream's source datagrams. Before any was admitted, the one
15199
+ * flow whose registration lists the stream; more than one (a repair flow
15200
+ * also lists its owners' source tracks) cannot be told apart, so none.
15201
+ */
15202
+ #provenanceFor(packetId, catalogTrackName) {
15203
+ const byName = this.#provenanceStreamFlow.get(packetId);
15204
+ const flows = new Set(
15205
+ catalogTrackName === void 0 || !byName ? byName?.values() : byName.has(catalogTrackName) ? [byName.get(catalogTrackName)] : []
15206
+ );
15207
+ if (flows.size > 1) return "ambiguous";
15208
+ for (const bound of flows) return this.#provenance.get(bound)?.receiver ?? "ambiguous";
15209
+ let match;
15210
+ for (const { receiver, ingress } of this.#provenance.values()) {
15211
+ if (ingress.tracks.some((t) => t.packetId === packetId && (catalogTrackName === void 0 || t.name === catalogTrackName))) {
15212
+ if (match) return "ambiguous";
15213
+ match = receiver;
14661
15214
  }
14662
- this.#admitRecoveredResult(
14663
- next.blockId,
14664
- next.result,
14665
- next.ownerPacketId,
14666
- next.catalogTrackName,
14667
- () => {
14668
- queue.shift();
14669
- drain();
14670
- }
14671
- );
14672
- };
14673
- drain();
14674
- }
14675
- #admitRecoveredResult(blockId, result, ownerPacketId, catalogTrackName, done) {
14676
- const verifier = this.#manifestVerifier;
14677
- const resolveIdentity = this.#resolveManifestIdentity;
14678
- const resolveIdentityForRoute = this.#resolveManifestIdentityForRoute;
14679
- if (!verifier) {
14680
- this.#routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName);
14681
- done();
14682
- return;
14683
15215
  }
14684
- if (!resolveIdentity && !resolveIdentityForRoute) throw new Error("manifest identity resolver disappeared during admission");
14685
- const symbols = result.symbols;
14686
- const admitNext = (index) => {
14687
- const symbol = symbols[index];
14688
- if (!symbol) {
14689
- done();
14690
- return;
14691
- }
14692
- const identity = resolveIdentityForRoute ? resolveIdentityForRoute({
14693
- packetId: ownerPacketId,
14694
- sbn: blockId,
14695
- esi: symbol.index,
14696
- ...catalogTrackName === void 0 ? {} : { catalogTrackName },
14697
- recovered: true,
14698
- sourceSymbolFormat: "fec-padded-recovery"
14699
- }) : resolveIdentity(ownerPacketId, blockId, symbol.index, catalogTrackName);
14700
- if (!identity) {
14701
- console.warn(`[MmtpRouter] manifest identity unresolved; recovered symbol is fail-open for packetId=${ownerPacketId} block=${blockId} esi=${symbol.index}`);
14702
- this.#routeProcessedFecSymbols(
14703
- blockId,
14704
- { ...result, symbols: [symbol] },
14705
- ownerPacketId,
14706
- catalogTrackName
14707
- );
14708
- admitNext(index + 1);
14709
- return;
14710
- }
14711
- const admission = verifier.admitObject(
14712
- {
14713
- ...identity,
14714
- packetId: ownerPacketId
14715
- },
14716
- symbol.rawSymbol,
14717
- () => {
14718
- if (!this.#disposed) {
14719
- this.#routeProcessedFecSymbols(
14720
- blockId,
14721
- { ...result, symbols: [symbol] },
14722
- ownerPacketId,
14723
- catalogTrackName
14724
- );
14725
- }
14726
- admitNext(index + 1);
14727
- },
14728
- // A stalled symbol that is later discarded instead of played must still
14729
- // advance this loop; enforce mode never calls the release callback for
14730
- // it (BLO-30095).
14731
- () => admitNext(index + 1)
14732
- );
14733
- if (admission.action === "drop") admitNext(index + 1);
14734
- };
14735
- admitNext(0);
15216
+ return match;
14736
15217
  }
14737
15218
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName) {
14738
15219
  if (ownerPacketId == null) return;
14739
15220
  if (this.#classifyPacketId(ownerPacketId) === null) return;
15221
+ const ssIdSeqOffset = this.#ssIdSeqOffsetByStream.get(
15222
+ this.#mediaStreamKey(ownerPacketId, catalogTrackName)
15223
+ );
15224
+ if (ssIdSeqOffset !== void 0) {
15225
+ result = {
15226
+ ...result,
15227
+ symbols: result.symbols.map((sym) => {
15228
+ const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
15229
+ if (wire === sym.packetSequenceNumber) return sym;
15230
+ this.#restampedRecoveredSeqs++;
15231
+ return { ...sym, packetSequenceNumber: wire };
15232
+ })
15233
+ };
15234
+ }
14740
15235
  this.#stream(ownerPacketId, catalogTrackName).duplicates.advance(blockId);
14741
15236
  const deliveryProvenance = this.#fecManager?.blockDeliveryProvenance?.(
14742
15237
  blockId,
@@ -15222,189 +15717,6 @@ var MmtpRouter = class {
15222
15717
  }
15223
15718
  };
15224
15719
 
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
15720
  // node_modules/@blockcast/mmt-transport/dist/multicast-tier.js
15409
15721
  function endpointKey(endpoint) {
15410
15722
  return `${endpoint.sourceAddress ?? ""}|${endpoint.groupAddress}|${endpoint.port}`;
@@ -15535,8 +15847,8 @@ var AdaptiveBitrateController = class {
15535
15847
  /**
15536
15848
  * Update FEC statistics for ABR decisions
15537
15849
  *
15538
- * Per draft-ramadan-moq-fec-00, ABR should use the effective loss rate
15539
- * (after FEC recovery) rather than raw transport loss rate.
15850
+ * ABR uses the effective loss rate (after FEC recovery) rather than the
15851
+ * raw transport loss rate.
15540
15852
  *
15541
15853
  * @param stats - FEC statistics from the FEC decoder
15542
15854
  */
@@ -15612,6 +15924,45 @@ var AdaptiveBitrateController = class {
15612
15924
  }
15613
15925
  };
15614
15926
 
15927
+ // node_modules/@blockcast/mmt-base/dist/mmtp.js
15928
+ var MPU_HEADER_SIZE2 = 8;
15929
+ var MPU_LENGTH_FIELD_SIZE2 = 2;
15930
+ var MPU_HEADER_REMAINDER_SIZE2 = MPU_HEADER_SIZE2 - MPU_LENGTH_FIELD_SIZE2;
15931
+ var MMTP_SIGNALING_PACKET_ID2 = 0;
15932
+ var MMTP_PACKET_ID_MAX2 = 65535;
15933
+
15934
+ // node_modules/@blockcast/mmt-base/dist/net-constants.js
15935
+ var DEFAULT_AMT_RELAY_PORT2 = 2268;
15936
+
15937
+ // node_modules/@blockcast/mmt-base/dist/ntp-short.js
15938
+ var NTP_SHORT_BITS2 = 32;
15939
+ var NTP_SHORT_MODULUS2 = 2 ** NTP_SHORT_BITS2;
15940
+ var NTP_SHORT_HALF_RANGE2 = 2 ** (NTP_SHORT_BITS2 - 1);
15941
+ function isNtpShort(value) {
15942
+ return Number.isInteger(value) && value >= 0 && value < NTP_SHORT_MODULUS2;
15943
+ }
15944
+ function compareNtpShort(a, b) {
15945
+ if (!isNtpShort(a) || !isNtpShort(b)) {
15946
+ throw new RangeError(`NTP-short values must be integers in [0, 2^${NTP_SHORT_BITS2}), got ${String(a)} and ${String(b)}`);
15947
+ }
15948
+ if (a === b)
15949
+ return "equal";
15950
+ const forward = (a - b + NTP_SHORT_MODULUS2) % NTP_SHORT_MODULUS2;
15951
+ if (forward < NTP_SHORT_HALF_RANGE2)
15952
+ return "after";
15953
+ if (forward > NTP_SHORT_HALF_RANGE2)
15954
+ return "before";
15955
+ return "unordered";
15956
+ }
15957
+
15958
+ // node_modules/@blockcast/mmt-base/dist/fec-block-profile.js
15959
+ var FEC_BLOCK_PROFILES2 = Object.freeze([
15960
+ "iso-ssbg1-v1"
15961
+ ]);
15962
+
15963
+ // node_modules/@blockcast/mmt-base/dist/catalog-fec-source.js
15964
+ var ALL_ROLES2 = Object.freeze(["video", "audio"]);
15965
+
15615
15966
  // node_modules/@blockcast/mmt-transport/dist/multicast-orchestrator.js
15616
15967
  var DEFAULT_DWELL_MS = 3e3;
15617
15968
  var DEFAULT_JOIN_DEADLINE_MS = 5e3;
@@ -15849,8 +16200,23 @@ function toWindowMulticastSubscribeConfig(input) {
15849
16200
  consume: "bytes",
15850
16201
  ...input.packetIds?.length ? { packetIds: [...input.packetIds] } : {}
15851
16202
  };
16203
+ if (input.atsc3) {
16204
+ const { frequency, plpId, serviceId } = input.atsc3;
16205
+ if (!Number.isInteger(frequency) || frequency < 1) {
16206
+ throw new TypeError(`ATSC3 tuning requires a positive integer frequency in kHz, got ${String(frequency)}`);
16207
+ }
16208
+ return {
16209
+ ...base,
16210
+ origin: "tuner",
16211
+ standard: "atsc3",
16212
+ frequency,
16213
+ ...plpId !== void 0 ? { plpId } : {},
16214
+ ...serviceId !== void 0 ? { serviceId } : {}
16215
+ };
16216
+ }
15852
16217
  const relay = input.amtRelay?.trim();
15853
- const wantsAmt = input.mode === "tunnel" || input.mode !== "native" && relay !== void 0 && relay !== "";
16218
+ const driad = !relay && input.amtDiscovery === "driad";
16219
+ const wantsAmt = input.mode === "tunnel" || input.mode !== "native" && (relay !== void 0 && relay !== "" || driad);
15854
16220
  if (!wantsAmt) {
15855
16221
  const native = {
15856
16222
  ...base,
@@ -15860,6 +16226,20 @@ function toWindowMulticastSubscribeConfig(input) {
15860
16226
  return native;
15861
16227
  }
15862
16228
  const relayPort = input.amtRelayPort;
16229
+ if (driad) {
16230
+ if (!base.source)
16231
+ throw new TypeError("AMT DRIAD discovery requires a source address");
16232
+ if (relayPort !== void 0 && !isPositivePort(relayPort)) {
16233
+ throw new TypeError("AMT DRIAD discovery requires a valid relay port when one is given");
16234
+ }
16235
+ return {
16236
+ ...base,
16237
+ source: base.source,
16238
+ origin: "amt",
16239
+ discovery: "driad",
16240
+ ...relayPort !== void 0 ? { relayPort } : {}
16241
+ };
16242
+ }
15863
16243
  if (!relay || relayPort === void 0 || !isPositivePort(relayPort)) {
15864
16244
  throw new TypeError("AMT requires a resolved relay and a valid relay port");
15865
16245
  }
@@ -15903,7 +16283,8 @@ function normalizeMulticastEndpoint(endpoint) {
15903
16283
  port: endpoint.port,
15904
16284
  ...endpoint.mode ? { mode: endpoint.mode } : {},
15905
16285
  ...amtRelay ? { amtRelay } : {},
15906
- ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
16286
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {},
16287
+ ...endpoint.amtDiscovery === "driad" ? { amtDiscovery: "driad" } : {}
15907
16288
  };
15908
16289
  }
15909
16290
  function multicastEndpointKey(endpoint) {
@@ -15916,7 +16297,9 @@ function multicastEndpointKey(endpoint) {
15916
16297
  normalized.port,
15917
16298
  normalized.mode ?? "auto",
15918
16299
  normalized.amtRelay ?? "",
15919
- normalized.amtRelayPort ?? ""
16300
+ normalized.amtRelayPort ?? "",
16301
+ // A DRIAD join is a different gateway subscription from a native one.
16302
+ ...normalized.amtDiscovery ? [normalized.amtDiscovery] : []
15920
16303
  ]);
15921
16304
  }
15922
16305
  function isMulticastTrackPacketId(value) {
@@ -15956,7 +16339,8 @@ var MulticastSubscriptionPool = class {
15956
16339
  port: config.port,
15957
16340
  mode: config.mode,
15958
16341
  amtRelay: config.amtRelay,
15959
- amtRelayPort: config.amtRelayPort
16342
+ amtRelayPort: config.amtRelayPort,
16343
+ amtDiscovery: config.amtDiscovery
15960
16344
  });
15961
16345
  if (!endpoint)
15962
16346
  throw new Error("Invalid multicast endpoint");
@@ -16022,7 +16406,8 @@ var MulticastSubscriptionPool = class {
16022
16406
  port: endpoint.port,
16023
16407
  ...endpoint.mode ? { mode: endpoint.mode } : {},
16024
16408
  ...endpoint.amtRelay ? { amtRelay: endpoint.amtRelay } : {},
16025
- ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
16409
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {},
16410
+ ...endpoint.amtDiscovery ? { amtDiscovery: endpoint.amtDiscovery } : {}
16026
16411
  }));
16027
16412
  const consumers = /* @__PURE__ */ new Map();
16028
16413
  let entry;
@@ -16102,7 +16487,6 @@ var TransportManager = class {
16102
16487
  };
16103
16488
  capabilities = null;
16104
16489
  subscription = null;
16105
- driad = new DRIADDiscovery();
16106
16490
  /** Built by `connect()` from the caller's ladder; there is no built-in one. */
16107
16491
  abr = null;
16108
16492
  multicastOrchestrator = null;
@@ -16152,8 +16536,8 @@ var TransportManager = class {
16152
16536
  nativeIGMP: hasGatewayBytes,
16153
16537
  directSockets: typeof win?.UDPSocket !== "undefined",
16154
16538
  amt: false,
16155
- driad: true,
16156
- // DRIAD uses HTTP proxy, always available
16539
+ driad: hasGatewayBytes,
16540
+ // the gateway runs RFC 8777 discovery
16157
16541
  fecDecode: false
16158
16542
  };
16159
16543
  console.log("[Transport] Capabilities:", this.capabilities);
@@ -16164,7 +16548,7 @@ var TransportManager = class {
16164
16548
  *
16165
16549
  * Promotion hierarchy:
16166
16550
  * 1. window.multicast gateway bytes
16167
- * 2. AMT proxy (specified or discovered via DRIAD)
16551
+ * 2. AMT: a configured relay via the AMT proxy, else gateway DRIAD discovery
16168
16552
  * 3. MOQ WebTransport (final fallback)
16169
16553
  *
16170
16554
  * The ABR ladder (`abrLadder`) and initial rendition (`initialQuality`)
@@ -16258,7 +16642,7 @@ var TransportManager = class {
16258
16642
  /**
16259
16643
  * Connect via the lowercase window.multicast bytes gateway.
16260
16644
  */
16261
- async connectWindowMulticast(config, generation) {
16645
+ async connectWindowMulticast(config, generation, mode = "multicast") {
16262
16646
  try {
16263
16647
  const gateway = this.getWindowMulticastGateway();
16264
16648
  if (typeof gateway?.subscribe !== "function")
@@ -16293,7 +16677,7 @@ var TransportManager = class {
16293
16677
  }
16294
16678
  };
16295
16679
  this.state = {
16296
- mode: "multicast",
16680
+ mode,
16297
16681
  connected: true,
16298
16682
  group: config.group,
16299
16683
  source: config.source,
@@ -16311,29 +16695,19 @@ var TransportManager = class {
16311
16695
  }
16312
16696
  }
16313
16697
  /**
16314
- * Connect via AMT proxy (with optional DRIAD discovery)
16698
+ * Connect via AMT: a configured relay goes through the AMT proxy; with no
16699
+ * relay, the window.multicast gateway discovers one per RFC 8777 (DRIAD).
16315
16700
  */
16316
16701
  async connectAmt(config, generation) {
16317
16702
  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) {
16703
+ if (config.amtRelay)
16704
+ return await this.connectAmtProxy(config, config.amtRelay, generation);
16705
+ if (config.driadEnabled === false || !config.source || config.mode === "native") {
16333
16706
  console.warn("[Transport] No AMT relay available (DRIAD requires source address for SSM)");
16334
16707
  return false;
16335
16708
  }
16336
- return await this.connectAmtProxy(config, amtRelay, generation);
16709
+ console.log(`[Transport] Asking the gateway for a DRIAD relay for source ${config.source}...`);
16710
+ return await this.connectWindowMulticast({ ...config, amtDiscovery: "driad" }, generation, "amt");
16337
16711
  } catch (error) {
16338
16712
  console.warn("[Transport] AMT connection failed:", error);
16339
16713
  return false;
@@ -16564,7 +16938,6 @@ var AMTGatewayManager = class {
16564
16938
  subscriptions = /* @__PURE__ */ new Map();
16565
16939
  messageHandler;
16566
16940
  pendingPackets = /* @__PURE__ */ new Map();
16567
- driad = new DRIADDiscovery();
16568
16941
  constructor() {
16569
16942
  this.messageHandler = (event) => {
16570
16943
  const data = event.data;
@@ -16595,26 +16968,12 @@ var AMTGatewayManager = class {
16595
16968
  return keyStr;
16596
16969
  }
16597
16970
  try {
16598
- let relayAddress;
16599
- let discoveryMethod;
16971
+ const relayAddress = config.relayAddress;
16600
16972
  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.`);
16973
+ if (!relayAddress) {
16974
+ 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
16975
  }
16976
+ console.log(`[AMT] Using configured relay ${relayAddress}:${relayPort}`);
16618
16977
  const subscriptionId = keyStr;
16619
16978
  this.pendingPackets.set(subscriptionId, []);
16620
16979
  const subscription = {
@@ -16625,7 +16984,7 @@ var AMTGatewayManager = class {
16625
16984
  relay: {
16626
16985
  address: relayAddress,
16627
16986
  port: relayPort,
16628
- discoveryMethod,
16987
+ discoveryMethod: "manual",
16629
16988
  discoveredAt: Date.now()
16630
16989
  }
16631
16990
  };
@@ -16781,7 +17140,7 @@ function sameIds(a, b) {
16781
17140
  for (const id of a) if (!b.has(id)) return false;
16782
17141
  return true;
16783
17142
  }
16784
- var MulticastTransport = class _MulticastTransport {
17143
+ var MulticastTransport = class {
16785
17144
  #onPacket;
16786
17145
  #subscription = null;
16787
17146
  #packetListener = null;
@@ -16853,8 +17212,11 @@ var MulticastTransport = class _MulticastTransport {
16853
17212
  // droppedPacketIds.
16854
17213
  #unadvertisedPacketIds = /* @__PURE__ */ new Set();
16855
17214
  #joinGeneration = 0;
16856
- constructor(onPacket) {
17215
+ // The provider to subscribe through; window.multicast when unset.
17216
+ #gateway;
17217
+ constructor(onPacket, options = {}) {
16857
17218
  this.#onPacket = onPacket;
17219
+ this.#gateway = options.gateway;
16858
17220
  }
16859
17221
  static isAvailable() {
16860
17222
  return hasMulticastGateway();
@@ -16864,7 +17226,8 @@ var MulticastTransport = class _MulticastTransport {
16864
17226
  this.#releaseSubscription();
16865
17227
  this.#dataPlaneLive = false;
16866
17228
  if (this.#disposed) return this.#declined(generation, "disposed");
16867
- if (!_MulticastTransport.isAvailable()) {
17229
+ const gateway = this.#gateway ?? getMulticastGlobals().multicast;
17230
+ if (typeof gateway?.subscribe !== "function") {
16868
17231
  console.warn("[MulticastTransport] Multicast API not available");
16869
17232
  return this.#declined(generation, "unavailable");
16870
17233
  }
@@ -16881,11 +17244,13 @@ var MulticastTransport = class _MulticastTransport {
16881
17244
  mode: config.mode,
16882
17245
  amtRelay: config.amtRelay,
16883
17246
  amtRelayPort: config.amtRelayPort,
17247
+ amtDiscovery: config.amtDiscovery,
16884
17248
  packetIds: config.packetIds,
16885
- tracks: config.tracks
17249
+ tracks: config.tracks,
17250
+ atsc3: config.atsc3
16886
17251
  });
16887
17252
  failure = "provider-rejected";
16888
- const subscription = await getMulticastGlobals().multicast.subscribe(subscribeConfig);
17253
+ const subscription = await gateway.subscribe(subscribeConfig);
16889
17254
  failure = "invalid-subscription";
16890
17255
  console.log(`[MulticastTransport] window.multicast.subscribe returned:`, !!subscription);
16891
17256
  if (this.#disposed || generation !== this.#joinGeneration) {
@@ -17472,16 +17837,6 @@ var MulticastTransport = class _MulticastTransport {
17472
17837
  // src/multicast-manager.ts
17473
17838
  import { deriveFecInterleaveDepth as deriveFecInterleaveDepth3, FecBlockMapper as FecBlockMapper2 } from "@blockcast/mmt-fec";
17474
17839
 
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
17840
  // src/repair-layers.ts
17486
17841
  var RepairContractError = class extends Error {
17487
17842
  constructor(code, path, message) {
@@ -17555,7 +17910,7 @@ function isFecCatalogGeometry(obj) {
17555
17910
  const o = obj;
17556
17911
  const algorithm = o["algorithm"];
17557
17912
  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;
17913
+ 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
17914
  }
17560
17915
  function isFecCatalogConfig(obj) {
17561
17916
  if (!isFecCatalogGeometry(obj)) return false;
@@ -17591,6 +17946,13 @@ function isoSpanUnavailable(fec, path, declaresFecInstance) {
17591
17946
  function catalogFecUnavailable(fec, fecPath) {
17592
17947
  if (catalogFecAvailable(fec)) return void 0;
17593
17948
  const block = recordOf2(fec);
17949
+ if (fecAlgorithmUnimplemented(block["algorithm"])) {
17950
+ return Object.freeze({
17951
+ code: "track_fec_algorithm_unimplemented",
17952
+ path: `${fecPath}.algorithm`,
17953
+ message: `algorithm ${JSON.stringify(block["algorithm"])} is not implemented: the track plays without FEC`
17954
+ });
17955
+ }
17594
17956
  const declaresFecInstance = block["algorithm"] !== "none";
17595
17957
  const reason = blockProfileUnavailable(block["blockProfile"], `${fecPath}.blockProfile`, declaresFecInstance) ?? isoSpanUnavailable(block, `${fecPath}.interleaveDepthMs`, declaresFecInstance);
17596
17958
  if (reason === void 0) {
@@ -17633,8 +17995,10 @@ function newBlockPolicyStats(packetId, catalogTrackName, epoch) {
17633
17995
  repairsSkippedRttUnmeasured: 0,
17634
17996
  repairsSkippedRttExceedsBudget: 0,
17635
17997
  repairsSkippedPresentationDelayUnavailable: 0,
17998
+ repairsSkippedRangeNoAnchor: 0,
17636
17999
  lastRepairSkip: null,
17637
18000
  keyframeRepairFetchesSent: 0,
18001
+ rangeRepairFetchesSent: 0,
17638
18002
  keyframeBudgetHolds: 0,
17639
18003
  keyframeBudgetHoldMs: 0,
17640
18004
  deltaBlocksFailed: 0,
@@ -17713,6 +18077,12 @@ var REPAIR_PRIORITY_REASONS = /* @__PURE__ */ new Set([
17713
18077
  "repair-priority-absent",
17714
18078
  "repair-priority-invalid"
17715
18079
  ]);
18080
+ var REPAIR_SKIP_REASONS = /* @__PURE__ */ new Set([
18081
+ "rtt-unmeasured",
18082
+ "rtt-exceeds-budget",
18083
+ "presentation-delay-unavailable"
18084
+ ]);
18085
+ var REPAIR_DEADLINE_BOUNDS = /* @__PURE__ */ new Set(["wait", "presentation", "keyframe", "retention"]);
17716
18086
  var GAP_REASONS = {
17717
18087
  "rap-lost": "stall",
17718
18088
  "rap-unknown": "stall",
@@ -17735,6 +18105,9 @@ function isSymbolCounts(value) {
17735
18105
  function isNullableNonNegative(value) {
17736
18106
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
17737
18107
  }
18108
+ function isFiniteNumber(value) {
18109
+ return typeof value === "number" && Number.isFinite(value);
18110
+ }
17738
18111
  function isRepairLifecycleEvent(value) {
17739
18112
  if (!isRecord(value) || value["version"] !== 2) return false;
17740
18113
  const block = value["block"];
@@ -17752,6 +18125,20 @@ function isRepairLifecycleEvent(value) {
17752
18125
  case "repair-preempted":
17753
18126
  case "repair-deferred":
17754
18127
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
18128
+ case "repair-sent":
18129
+ return hasExactKeys(value, [
18130
+ "version",
18131
+ "type",
18132
+ "block",
18133
+ "priority",
18134
+ "rttMs",
18135
+ "budgetMs",
18136
+ "delayMs",
18137
+ "blockAgeMs",
18138
+ "bound"
18139
+ ]) && 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"]);
18140
+ case "repair-skipped":
18141
+ return hasExactKeys(value, ["version", "type", "block", "reason", "rttMs", "budgetMs"]) && isRepairBlockIdentity(block) && REPAIR_SKIP_REASONS.has(value["reason"]) && isNullableNonNegative(value["rttMs"]) && isFiniteNumber(value["budgetMs"]);
17755
18142
  case "repair-priority": {
17756
18143
  const blockClass = value["blockClass"];
17757
18144
  const action = value["action"];
@@ -17931,6 +18318,9 @@ var MulticastManager = class {
17931
18318
  #router;
17932
18319
  #hostMfuTimeoutMs;
17933
18320
  #transport;
18321
+ /** Live joinRepairEndpoints() releases → the repair owners they registered,
18322
+ * re-applied after configureMultiTrack() clears catalog-derived owners. */
18323
+ #repairReleases = /* @__PURE__ */ new Map();
17934
18324
  #reportedFecDiagnosticsFailure = false;
17935
18325
  // ── Stream-global FEC timing reduction ──
17936
18326
  //
@@ -17980,10 +18370,6 @@ var MulticastManager = class {
17980
18370
  reassemblyPolicy: options?.reassemblyPolicy,
17981
18371
  reassembler: options?.reassembler,
17982
18372
  maxBufferedMfus: options?.maxBufferedMfus,
17983
- manifestVerifier: options?.manifestVerifier,
17984
- manifestVerifierOwnership: options?.manifestVerifierOwnership,
17985
- resolveManifestIdentity: options?.resolveManifestIdentity,
17986
- resolveManifestIdentityForRoute: options?.resolveManifestIdentityForRoute,
17987
18373
  // The router has reset its own state for the stream; reset the rest.
17988
18374
  onPublisherRestart: (packetId, catalogTrackName) => {
17989
18375
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
@@ -18030,7 +18416,7 @@ var MulticastManager = class {
18030
18416
  });
18031
18417
  this.#hostMfuTimeoutMs = this.#router.reassembler.timeoutMs;
18032
18418
  this.#transport = new MulticastTransport((packet, ingress) => {
18033
- this.#router.feedPacket(packet, "multicast", void 0, ingress);
18419
+ this.#router.feedPacket(packet, "multicast", ingress);
18034
18420
  });
18035
18421
  this.#transport.onDelivery((delivery) => {
18036
18422
  this.#fec.setMulticastSymbolDelivery(delivery);
@@ -18194,7 +18580,9 @@ var MulticastManager = class {
18194
18580
  catalogTrackName
18195
18581
  );
18196
18582
  this.#configureTrackMapper(packetId, config);
18197
- this.#router.setPacketIdType(packetId, trackType);
18583
+ if (this.#router.trackKindFor(packetId) !== trackType) {
18584
+ this.#router.setPacketIdType(packetId, trackType);
18585
+ }
18198
18586
  }
18199
18587
  /**
18200
18588
  * Stop routing a stream's symbols to its Worker decoder. Returns false when
@@ -18275,6 +18663,14 @@ var MulticastManager = class {
18275
18663
  );
18276
18664
  }
18277
18665
  }
18666
+ for (const [packetId, c] of this.#trackFecTiming) {
18667
+ if (c.deliveryWindowMs === void 0) continue;
18668
+ mfuTimeoutMs = Math.max(
18669
+ mfuTimeoutMs ?? 0,
18670
+ this.#fec.terminalRetentionMsForPacket(packetId) ?? 0,
18671
+ this.#hostMfuTimeoutMs ?? 0
18672
+ );
18673
+ }
18278
18674
  const failbackWindowMs = deliveryWindowMs === void 0 ? minimumFailbackWindowMs : Math.max(deliveryWindowMs, minimumFailbackWindowMs ?? 0);
18279
18675
  this.#transport.setFailbackWindowMs(failbackWindowMs ?? null);
18280
18676
  this.#router.setMfuTimeoutMs(mfuTimeoutMs ?? this.#hostMfuTimeoutMs);
@@ -18458,6 +18854,7 @@ var MulticastManager = class {
18458
18854
  setMfuTimeoutMs(ms) {
18459
18855
  this.#router.setMfuTimeoutMs(ms);
18460
18856
  this.#hostMfuTimeoutMs = this.#router.reassembler.timeoutMs;
18857
+ if (this.#trackFecTiming.size > 0) this.#applyStreamGlobalFecTiming();
18461
18858
  }
18462
18859
  setTrackCodec(packetId, codec) {
18463
18860
  this.#router.setTrackCodec(packetId, codec);
@@ -18578,11 +18975,81 @@ var MulticastManager = class {
18578
18975
  // through whatever the relay looks like, since dropping it would be the
18579
18976
  // worse behaviour.
18580
18977
  amtRelayPort: config.amtRelayPort ?? config.relayPort ?? (amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : void 0),
18978
+ amtDiscovery: config.amtDiscovery,
18581
18979
  packetIds: config.packetIds,
18582
18980
  tracks: catalogTracks?.map(({ name, packetId }) => ({ name, packetId }))
18583
18981
  };
18584
18982
  return ingress === void 0 ? this.#transport.join(transportConfig) : this.#transport.join(transportConfig, ingress);
18585
18983
  }
18984
+ /**
18985
+ * Join the selected rung's dedicated repair groups beside the media join
18986
+ * (pim #3898): one subscription per endpoint, through `provider` when given
18987
+ * (a `window.multicast`-shaped gateway or a subscribe callback), otherwise a
18988
+ * new MulticastTransport on `window.multicast`. Returns the call that
18989
+ * releases every one of them; dispose() releases them too.
18990
+ *
18991
+ * Packets go straight to the router with the endpoint's ingress, never
18992
+ * through feedPacket(): repair arriving on its own group is not media
18993
+ * liveness, so it must not hold off the media leg's failback watchdog. The
18994
+ * repair roles and owners are registered here; in-band owners stay the
18995
+ * caller's. Joining is best effort: a group that fails to join is logged
18996
+ * and leaves the media join as it was.
18997
+ */
18998
+ joinRepairEndpoints(endpoints, provider) {
18999
+ const releases = [];
19000
+ let released = false;
19001
+ const safely = (each) => {
19002
+ try {
19003
+ each();
19004
+ } catch (error) {
19005
+ console.warn("[MulticastManager] repair group release failed", error);
19006
+ }
19007
+ };
19008
+ const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners);
19009
+ this.#applyRepairOwners(repairOwners);
19010
+ for (const endpoint of endpoints) {
19011
+ const ingress = {
19012
+ tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
19013
+ ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
19014
+ };
19015
+ const onPacket = (packet) => {
19016
+ if (!released) this.#router.feedPacket(packet, "multicast", ingress);
19017
+ };
19018
+ const fail = (error) => console.warn(`[MulticastManager] repair group ${endpoint.group}:${endpoint.port} not joined`, error);
19019
+ if (typeof provider === "function") {
19020
+ Promise.resolve().then(() => provider(endpoint, onPacket)).then((release2) => released ? safely(release2) : releases.push(release2), fail);
19021
+ continue;
19022
+ }
19023
+ const transport = new MulticastTransport((packet) => onPacket(packet), { gateway: provider });
19024
+ releases.push(() => transport.dispose());
19025
+ void transport.join({
19026
+ sourceAddress: endpoint.source,
19027
+ groupAddress: endpoint.group,
19028
+ port: endpoint.port,
19029
+ mode: endpoint.mode,
19030
+ amtRelay: endpoint.amtRelay,
19031
+ amtRelayPort: endpoint.amtRelayPort ?? (endpoint.amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : void 0),
19032
+ packetIds: endpoint.packetIds,
19033
+ tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId }))
19034
+ }).then((joined) => {
19035
+ if (!joined && !released) fail(transport.lastJoinOutcome);
19036
+ });
19037
+ }
19038
+ const release = () => {
19039
+ if (released) return;
19040
+ released = true;
19041
+ this.#repairReleases.delete(release);
19042
+ for (const each of releases.splice(0)) safely(each);
19043
+ };
19044
+ this.#repairReleases.set(release, repairOwners);
19045
+ return release;
19046
+ }
19047
+ #applyRepairOwners(owners) {
19048
+ for (const { packetId, ownerPacketId } of owners) {
19049
+ this.#router.setPacketIdRole(packetId, "repair");
19050
+ this.#router.setRepairPacketIdOwner(packetId, ownerPacketId);
19051
+ }
19052
+ }
18586
19053
  // ---------------------------------------------------------------------------
18587
19054
  // In-place rendition switch
18588
19055
  // ---------------------------------------------------------------------------
@@ -18858,7 +19325,7 @@ var MulticastManager = class {
18858
19325
  *
18859
19326
  * D-04: Validates completeness via validateSwitchingSet — throws if incomplete.
18860
19327
  * D-07: Applies per-track FEC configs (base+delta get decoders; repair does not).
18861
- * D-17: Builds altGroup → track-name index for getSwitchingSet().
19328
+ * D-17: Builds altGroup → track-name index for getSwitchingSet() (repair legs excluded).
18862
19329
  * D-26: Registers packetId → TrackRole on MmtpRouter for block-complete fanout.
18863
19330
  *
18864
19331
  * FEC availability is per track (draft-ramadan-moq-fec §5.1). A media track
@@ -18909,11 +19376,9 @@ var MulticastManager = class {
18909
19376
  }
18910
19377
  }
18911
19378
  const repairOwnerGroup = /* @__PURE__ */ new Map();
18912
- const repairOwnerAltGroup = /* @__PURE__ */ new Map();
18913
19379
  for (const track of catalog.tracks) {
18914
19380
  for (const repairName of repairNamesBySource.get(track.name) ?? []) {
18915
19381
  repairOwnerGroup.set(repairName, altGroupKey(track));
18916
- repairOwnerAltGroup.set(repairName, track.altGroup);
18917
19382
  }
18918
19383
  }
18919
19384
  const groupKeyFor = (track) => repairOwnerGroup.get(track.name) ?? altGroupKey(track);
@@ -18944,11 +19409,7 @@ var MulticastManager = class {
18944
19409
  for (const [groupKey, roles] of resolvedRolesByGroup) {
18945
19410
  if (!(hasSwitchingSetByGroup.get(groupKey) ?? false)) continue;
18946
19411
  const presentRoles = new Set(roles.filter((r) => r !== "single"));
18947
- const required = [
18948
- "base",
18949
- "delta",
18950
- "repair"
18951
- ];
19412
+ const required = ["base", "repair"];
18952
19413
  const missing = required.filter((r) => !presentRoles.has(r));
18953
19414
  if (missing.length > 0) {
18954
19415
  throw new Error(
@@ -18995,6 +19456,7 @@ var MulticastManager = class {
18995
19456
  this.#switchingSets.clear();
18996
19457
  this.#repairPacketIds.clear();
18997
19458
  this.#router.clearRepairPacketIdOwners();
19459
+ for (const owners of this.#repairReleases.values()) this.#applyRepairOwners(owners);
18998
19460
  const fecPacketIds = new Set([...fecDecoders.keys()].map((i) => catalog.tracks[i].packetId));
18999
19461
  for (const [packetId, catalogTrackName] of this.#multiTrackFecTracks) {
19000
19462
  if (fecPacketIds.has(packetId)) continue;
@@ -19015,11 +19477,10 @@ var MulticastManager = class {
19015
19477
  for (let i = 0; i < catalog.tracks.length; i++) {
19016
19478
  const track = catalog.tracks[i];
19017
19479
  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) ?? [];
19480
+ if (role !== "repair" && track.altGroup !== void 0) {
19481
+ const existing = this.#switchingSets.get(track.altGroup) ?? [];
19021
19482
  existing.push(track.name);
19022
- this.#switchingSets.set(altGroup, existing);
19483
+ this.#switchingSets.set(track.altGroup, existing);
19023
19484
  }
19024
19485
  if (track.packetId !== void 0) {
19025
19486
  this.#router.setPacketIdRole(track.packetId, role);
@@ -19094,7 +19555,7 @@ var MulticastManager = class {
19094
19555
  #multiTrackFecTracks = /* @__PURE__ */ new Map();
19095
19556
  /**
19096
19557
  * Return the track names belonging to the given altGroup switching set.
19097
- * D-17: altGroup groups base+delta+repair into one switching set.
19558
+ * D-17: tracks with equal altGroup form one switching set; repair legs are in none.
19098
19559
  *
19099
19560
  * @param altGroup - The altGroup number to look up.
19100
19561
  * @returns Array of track names in that switching set (empty if none).
@@ -19122,6 +19583,26 @@ var MulticastManager = class {
19122
19583
  this.requestRepairForBlock(sbn, packetId, catalogTrackName, blockClass);
19123
19584
  };
19124
19585
  }
19586
+ /**
19587
+ * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
19588
+ * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
19589
+ * pending hole and reported here, and `closeIsoHoles` must be called for it
19590
+ * once its range FETCH ends (or none is sent).
19591
+ */
19592
+ onUndelimitedLoss(cb) {
19593
+ this.#fec.setUndelimitedLossHandler(cb);
19594
+ }
19595
+ /**
19596
+ * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
19597
+ * to CmcdProducer.updateFecFailClosed.
19598
+ */
19599
+ onFecFailClosed(cb) {
19600
+ this.#fec.setFecFailClosedHandler(cb);
19601
+ }
19602
+ /** End a pending hole's range repair: feed what no repair stated as spans. */
19603
+ closeIsoHoles(packetId, catalogTrackName, start, length) {
19604
+ this.#router.closeIsoHoles(packetId, catalogTrackName, start, length);
19605
+ }
19125
19606
  /**
19126
19607
  * Record a repair request whose SUBSCRIBER_PRIORITY the catalog could not
19127
19608
  * supply (draft-ramadan-moq-fec §11.4.5): sent without the parameter, or
@@ -19143,6 +19624,7 @@ var MulticastManager = class {
19143
19624
  stats.repairsSkipped++;
19144
19625
  if (reason === "rtt-unmeasured") stats.repairsSkippedRttUnmeasured++;
19145
19626
  else if (reason === "rtt-exceeds-budget") stats.repairsSkippedRttExceedsBudget++;
19627
+ else if (reason === "range-no-anchor") stats.repairsSkippedRangeNoAnchor++;
19146
19628
  else stats.repairsSkippedPresentationDelayUnavailable++;
19147
19629
  stats.lastRepairSkip = {
19148
19630
  reason,
@@ -19174,8 +19656,20 @@ var MulticastManager = class {
19174
19656
  stats.keyframeBudgetHoldMs += extensionMs;
19175
19657
  }
19176
19658
  /** Record a repair FETCH the scheduler admitted and sent. */
19177
- noteRepairFetchSent(priority, _sbn, packetId, catalogTrackName) {
19659
+ noteRepairFetchSent(priority, sbn, packetId, catalogTrackName, measurement) {
19178
19660
  if (priority === 0) this.#statsFor(packetId, catalogTrackName).keyframeRepairFetchesSent++;
19661
+ if (measurement.range) this.#statsFor(packetId, catalogTrackName).rangeRepairFetchesSent++;
19662
+ this.#emitRepairLifecycle({
19663
+ version: 2,
19664
+ type: "repair-sent",
19665
+ block: repairBlockIdentity(packetId, sbn, catalogTrackName),
19666
+ priority,
19667
+ rttMs: measurement.rttMs,
19668
+ budgetMs: measurement.budgetMs,
19669
+ delayMs: measurement.delayMs,
19670
+ blockAgeMs: measurement.blockAgeMs,
19671
+ bound: measurement.bound
19672
+ });
19179
19673
  }
19180
19674
  /**
19181
19675
  * Record a repair-scheduler decision about a delta block: preempted for
@@ -19326,6 +19820,7 @@ var MulticastManager = class {
19326
19820
  this.#trackResetObservers.clear();
19327
19821
  this.#repairLifecycleObservers.clear();
19328
19822
  this.#transport.dispose();
19823
+ for (const release of [...this.#repairReleases.keys()]) release();
19329
19824
  this.#router.dispose();
19330
19825
  this.#fec.dispose();
19331
19826
  }