@blockcast/mmt-container 0.4.0-main.bb90ce9247fa → 0.4.0-main.bbdfdbf39ded

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 (205) hide show
  1. package/README.md +36 -20
  2. package/dist/align.d.ts +24 -18
  3. package/dist/align.d.ts.map +1 -1
  4. package/dist/align.js +23 -4
  5. package/dist/align.js.map +2 -2
  6. package/dist/browser-runtime.js +1721 -705
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +72 -34
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +309 -204
  11. package/dist/carp-catalog.js.map +3 -3
  12. package/dist/catalog-fec-params.d.ts +15 -4
  13. package/dist/catalog-fec-params.d.ts.map +1 -1
  14. package/dist/catalog-fec-params.js +137 -50
  15. package/dist/catalog-fec-params.js.map +4 -4
  16. package/dist/catalog-network-source.d.ts +24 -2
  17. package/dist/catalog-network-source.d.ts.map +1 -1
  18. package/dist/catalog-network-source.js +24 -1
  19. package/dist/catalog-network-source.js.map +3 -3
  20. package/dist/catalog-validator.d.ts +4 -3
  21. package/dist/catalog-validator.d.ts.map +1 -1
  22. package/dist/catalog-validator.js +0 -29
  23. package/dist/catalog-validator.js.map +3 -3
  24. package/dist/delivery-catalog.js +100 -230
  25. package/dist/delivery-catalog.js.map +4 -4
  26. package/dist/fec-manager.d.ts +64 -1
  27. package/dist/fec-manager.d.ts.map +1 -1
  28. package/dist/fec-manager.js +275 -62
  29. package/dist/fec-manager.js.map +4 -4
  30. package/dist/fec-state.d.ts +5 -3
  31. package/dist/fec-state.d.ts.map +1 -1
  32. package/dist/fec-state.js +34 -12
  33. package/dist/fec-state.js.map +4 -4
  34. package/dist/fec-worker-setup.d.ts +2 -0
  35. package/dist/fec-worker-setup.d.ts.map +1 -1
  36. package/dist/fec-worker-setup.js +15 -3
  37. package/dist/fec-worker-setup.js.map +3 -3
  38. package/dist/index.d.ts +5 -5
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +14 -8
  41. package/dist/index.js.map +2 -2
  42. package/dist/iso-block-locator.d.ts +29 -0
  43. package/dist/iso-block-locator.d.ts.map +1 -1
  44. package/dist/iso-block-locator.js +100 -17
  45. package/dist/iso-block-locator.js.map +4 -4
  46. package/dist/manifest-auth-plan.d.ts +26 -25
  47. package/dist/manifest-auth-plan.d.ts.map +1 -1
  48. package/dist/manifest-auth-plan.js +331 -1171
  49. package/dist/manifest-auth-plan.js.map +4 -4
  50. package/dist/mfu-reassembler.js +24 -13
  51. package/dist/mfu-reassembler.js.map +3 -3
  52. package/dist/mmtp-container-parser.d.ts.map +1 -1
  53. package/dist/mmtp-container-parser.js +96 -22
  54. package/dist/mmtp-container-parser.js.map +3 -3
  55. package/dist/mmtp-container-parser.no-modules.js +1138 -325
  56. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  57. package/dist/mmtp-decode-pipeline.js +96 -22
  58. package/dist/mmtp-decode-pipeline.js.map +3 -3
  59. package/dist/mmtp-fec-session.d.ts +159 -0
  60. package/dist/mmtp-fec-session.d.ts.map +1 -0
  61. package/dist/mmtp-fec-session.js +531 -0
  62. package/dist/mmtp-fec-session.js.map +7 -0
  63. package/dist/mmtp-router.d.ts +31 -5
  64. package/dist/mmtp-router.d.ts.map +1 -1
  65. package/dist/mmtp-router.js +168 -22
  66. package/dist/mmtp-router.js.map +3 -3
  67. package/dist/multicast-auth-catalog.d.ts +86 -92
  68. package/dist/multicast-auth-catalog.d.ts.map +1 -1
  69. package/dist/multicast-auth-catalog.js +347 -132
  70. package/dist/multicast-auth-catalog.js.map +4 -4
  71. package/dist/multicast-input.d.ts +28 -6
  72. package/dist/multicast-input.d.ts.map +1 -1
  73. package/dist/multicast-input.js +293 -28
  74. package/dist/multicast-input.js.map +3 -3
  75. package/dist/multicast-manager.d.ts +89 -5
  76. package/dist/multicast-manager.d.ts.map +1 -1
  77. package/dist/multicast-manager.js +730 -356
  78. package/dist/multicast-manager.js.map +4 -4
  79. package/dist/multicast-transport.d.ts +12 -2
  80. package/dist/multicast-transport.d.ts.map +1 -1
  81. package/dist/multicast-transport.js +111 -235
  82. package/dist/multicast-transport.js.map +4 -4
  83. package/dist/multicast-unwrap.js +24 -13
  84. package/dist/multicast-unwrap.js.map +3 -3
  85. package/dist/no-modules.d.ts +4 -1
  86. package/dist/no-modules.d.ts.map +1 -1
  87. package/dist/no-modules.js +1087 -309
  88. package/dist/no-modules.js.map +4 -4
  89. package/dist/phase14-catalog-override.d.ts +1 -1
  90. package/dist/phase14-catalog-override.d.ts.map +1 -1
  91. package/dist/phase14-catalog-override.js +2 -2
  92. package/dist/phase14-catalog-override.js.map +2 -2
  93. package/dist/repair-fetch.d.ts +81 -6
  94. package/dist/repair-fetch.d.ts.map +1 -1
  95. package/dist/repair-fetch.js +159 -31
  96. package/dist/repair-fetch.js.map +3 -3
  97. package/dist/repair-layers.d.ts +2 -0
  98. package/dist/repair-layers.d.ts.map +1 -1
  99. package/dist/repair-layers.js +22 -2
  100. package/dist/repair-layers.js.map +3 -3
  101. package/dist/sample-combiner.d.ts +7 -1
  102. package/dist/sample-combiner.d.ts.map +1 -1
  103. package/dist/sample-combiner.js +14 -2
  104. package/dist/sample-combiner.js.map +2 -2
  105. package/dist/signaling.d.ts +2 -2
  106. package/dist/signaling.d.ts.map +1 -1
  107. package/dist/signaling.js +6 -3
  108. package/dist/signaling.js.map +3 -3
  109. package/dist/source-auth.js +2710 -7
  110. package/dist/source-auth.js.map +4 -4
  111. package/dist/switching-set-alignment.d.ts +1 -1
  112. package/dist/switching-set-alignment.js.map +1 -1
  113. package/dist/timestamp-codec.js +24 -13
  114. package/dist/timestamp-codec.js.map +3 -3
  115. package/dist/wasm-mfu-reassembler.js +3 -0
  116. package/dist/wasm-mfu-reassembler.js.map +3 -3
  117. package/dist/wasm-mmtp-container-parser.js +96 -22
  118. package/dist/wasm-mmtp-container-parser.js.map +3 -3
  119. package/package.json +6 -9
  120. package/schemas/catalog.schema.json +124 -37
  121. package/src/align.ts +52 -21
  122. package/src/carp-catalog.ts +163 -61
  123. package/src/catalog-fec-params.ts +66 -20
  124. package/src/catalog-network-source.ts +45 -2
  125. package/src/catalog-validator.ts +4 -11
  126. package/src/fec-manager.ts +239 -63
  127. package/src/fec-state.ts +14 -12
  128. package/src/fec-worker-setup.ts +20 -2
  129. package/src/index.ts +29 -10
  130. package/src/iso-block-locator.ts +97 -6
  131. package/src/manifest-auth-plan.ts +39 -91
  132. package/src/mmtp-container-parser.ts +75 -7
  133. package/src/mmtp-fec-session.ts +533 -0
  134. package/src/mmtp-router.ts +133 -5
  135. package/src/multicast-auth-catalog.ts +131 -238
  136. package/src/multicast-input.ts +119 -61
  137. package/src/multicast-manager.ts +258 -21
  138. package/src/multicast-transport.ts +17 -3
  139. package/src/no-modules.ts +7 -1
  140. package/src/phase14-catalog-override.ts +3 -3
  141. package/src/repair-fetch.ts +283 -39
  142. package/src/repair-layers.ts +22 -2
  143. package/src/sample-combiner.ts +15 -2
  144. package/src/signaling.ts +2 -2
  145. package/src/switching-set-alignment.ts +1 -1
  146. package/test-vectors/align.json +108 -32
  147. package/test-vectors/bc-provenance-v2.json +1526 -0
  148. package/test-vectors/catalog/README.md +65 -4
  149. package/test-vectors/catalog/negative/fec-block-profile-missing.json +1 -1
  150. package/test-vectors/catalog/negative/fec-block-profile-retired.json +1 -1
  151. package/test-vectors/catalog/negative/fec-block-profile-unknown.json +1 -1
  152. package/test-vectors/catalog/negative/fec-iso-symbol-size-below-floor.json +28 -0
  153. package/test-vectors/catalog/negative/fec-reed-solomon-iso-symbol-size-13.json +28 -0
  154. package/test-vectors/catalog/negative/fec-reed-solomon-k-plus-p-over-255.json +39 -0
  155. package/test-vectors/catalog/negative/fec-reed-solomon-overlay-over-255.json +40 -0
  156. package/test-vectors/catalog/negative/fec-repair-overlay-source-symbols-zero.json +43 -0
  157. package/test-vectors/catalog/negative/fec-repair-symbols-zero.json +28 -0
  158. package/test-vectors/catalog/negative/fec-source-symbols-zero.json +28 -0
  159. package/test-vectors/catalog/negative/fec-symbol-size-zero.json +28 -0
  160. package/test-vectors/catalog/negative/init-data-inline-without-data.json +22 -0
  161. package/test-vectors/catalog/negative/mmtp-mode-mpu.json +15 -0
  162. package/test-vectors/catalog/negative/multicast-amt-dns-without-relay.json +37 -0
  163. package/test-vectors/catalog/negative/multicast-auth-asm-missing-sender-address.json +77 -0
  164. package/test-vectors/catalog/negative/multicast-auth-duplicate-first-epoch.json +56 -0
  165. package/test-vectors/catalog/negative/multicast-auth-duplicate-kid.json +56 -0
  166. package/test-vectors/catalog/negative/multicast-auth-endpoint-auth-without-object-auth.json +38 -0
  167. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-auth.json +49 -0
  168. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-bandwidth.json +55 -0
  169. package/test-vectors/catalog/negative/multicast-auth-manifest-port-equals-port.json +56 -0
  170. package/test-vectors/catalog/negative/multicast-auth-manifest-timer-out-of-range.json +56 -0
  171. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-above-max.json +56 -0
  172. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-below-min.json +56 -0
  173. package/test-vectors/catalog/negative/multicast-auth-root-dotted-key.json +55 -0
  174. package/test-vectors/catalog/negative/multicast-auth-sender-address-on-ssm.json +57 -0
  175. package/test-vectors/catalog/negative/multicast-auth-version-1.json +56 -0
  176. package/test-vectors/catalog/negative/multicast-auth-version-3.json +56 -0
  177. package/test-vectors/catalog/negative/multicast-auth-version-missing.json +55 -0
  178. package/test-vectors/catalog/negative/multicast-endpoint-foreign-namespace-track.json +44 -0
  179. package/test-vectors/catalog/negative/multicast-endpoint-protocol-amt.json +38 -0
  180. package/test-vectors/catalog/negative/multicast-endpoint-protocol-atsc3.json +38 -0
  181. package/test-vectors/catalog/negative/presentation-anchor-unsafe.json +16 -0
  182. package/test-vectors/catalog/positive/fec-algorithm-unimplemented.json +29 -0
  183. package/test-vectors/catalog/positive/fec-iso-ssbg1.json +1 -1
  184. package/test-vectors/catalog/positive/fec-multicast.json +1 -1
  185. package/test-vectors/catalog/positive/fec-reed-solomon-layered.json +50 -0
  186. package/test-vectors/catalog/positive/mmt01-12-1-init-ref-anchor.json +29 -0
  187. package/test-vectors/catalog/positive/multicast-amt-discovery-omitted.json +37 -0
  188. package/test-vectors/catalog/positive/multicast-amt-dns-relay.json +38 -0
  189. package/test-vectors/catalog/positive/multicast-amt-manual-relay.json +2 -2
  190. package/test-vectors/catalog/{negative/multicast-endpoint-missing-protocol-and-source.json → positive/multicast-asm-unprotected.json} +10 -5
  191. package/test-vectors/catalog/positive/multicast-auth-asm-sender.json +78 -0
  192. package/test-vectors/catalog/positive/multicast-auth-rotation.json +39 -38
  193. package/test-vectors/catalog/positive/multicast-draft01-4-1-example.json +81 -0
  194. package/test-vectors/catalog/positive/multicast-draft01-7-2-6-example.json +70 -0
  195. package/test-vectors/catalog/positive/presentation-anchor-negative.json +27 -0
  196. package/test-vectors/catalog/section-codes.json +30 -1
  197. package/test-vectors/catalog-multicast-auth-v1.json +38 -20
  198. package/test-vectors/catalog-validation.json +101 -5
  199. package/test-vectors/catalog-validator-public-api.mjs +14 -9
  200. package/test-vectors/generate-bc-provenance-v2.mjs +252 -0
  201. package/dist/fec-codec.d.ts +0 -32
  202. package/dist/fec-codec.d.ts.map +0 -1
  203. package/dist/fec-codec.js +0 -47
  204. package/dist/fec-codec.js.map +0 -7
  205. package/src/fec-codec.ts +0 -61
@@ -171,26 +171,30 @@ function isEmptyOrExactLegacyTrailer(payload, start, end) {
171
171
  const authLength = view2.getUint16(2, false);
172
172
  return start + LEGACY_TRAILER_HEADER_SIZE + authLength === end;
173
173
  }
174
- function resolveDeclaredTrailers(payload, declaredEnd, fecType, options) {
174
+ function resolveDeclaredTrailers(payload, declaredEnd, fecType, options, rapFlag = false) {
175
175
  if (declaredEnd > payload.length)
176
176
  return null;
177
177
  if (options?.skipFecId) {
178
- return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false } : null;
178
+ return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false, hasOverlayFecId: false } : null;
179
179
  }
180
+ const overlay = options?.overlayDeclared === true && rapFlag;
180
181
  if (fecType === 1) {
181
- const fecStart = payload.length - SOURCE_FEC_PAYLOAD_ID_SIZE;
182
+ const fecStart = payload.length - sourceFecTrailerSize(overlay);
182
183
  if (fecStart < declaredEnd || !isEmptyOrExactLegacyTrailer(payload, declaredEnd, fecStart)) {
183
184
  return null;
184
185
  }
185
- return { hasFecId: true };
186
+ return { hasFecId: true, hasOverlayFecId: overlay };
186
187
  }
187
- if (fecType !== 0)
188
+ if (fecType !== 0 || overlay)
188
189
  return null;
189
190
  if (isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)) {
190
- return { hasFecId: false };
191
+ return { hasFecId: false, hasOverlayFecId: false };
191
192
  }
192
193
  return null;
193
194
  }
195
+ function sourceFecTrailerSize(overlay) {
196
+ return overlay ? 2 * SOURCE_FEC_PAYLOAD_ID_SIZE : SOURCE_FEC_PAYLOAD_ID_SIZE;
197
+ }
194
198
  function planMfuExtraction(mmtpPacket, options, parsedHeader) {
195
199
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) {
196
200
  return {
@@ -243,15 +247,16 @@ function planMfuExtraction(mmtpPacket, options, parsedHeader) {
243
247
  if ("rejection" in layoutResult)
244
248
  return layoutResult;
245
249
  const { layout } = layoutResult;
246
- const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options);
250
+ const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options, header.rapFlag);
247
251
  if (!trailerLayout) {
248
252
  if (!options?.skipFecId && header.fecType === 1) {
249
253
  const observed = payload.length - layout.dataEnd;
250
- if (observed !== SOURCE_FEC_PAYLOAD_ID_SIZE) {
254
+ const expected = sourceFecTrailerSize(options?.overlayDeclared === true && header.rapFlag);
255
+ if (observed !== expected) {
251
256
  return {
252
257
  rejection: {
253
258
  gate: "source-fec-payload-id-width-mismatch",
254
- detail: `producer wrote a ${observed}-byte Source FEC Payload ID, ISO/IEC 23008-1 \xA7C.5.2 requires ${SOURCE_FEC_PAYLOAD_ID_SIZE} (payload=${payload.length}, declaredEnd=${layout.dataEnd})`
259
+ detail: `producer wrote a ${observed}-byte Source FEC Payload ID, ISO/IEC 23008-1 \xA7C.5.2 requires ${expected} (payload=${payload.length}, declaredEnd=${layout.dataEnd})`
255
260
  }
256
261
  };
257
262
  }
@@ -278,10 +283,13 @@ function extractPlannedMfu(mmtpPacket, result) {
278
283
  const mfuDuHeader = mfuDuHeaderPresent && mpu.timedFlag === 1 ? parseTimedMfuDuHeader(payload, MPU_HEADER_SIZE) : null;
279
284
  const itemId = mfuDuHeaderPresent && mpu.timedFlag === 0 ? new DataView(payload.buffer, payload.byteOffset + MPU_HEADER_SIZE, 4).getUint32(0, false) : null;
280
285
  const data = payload.subarray(mfuOffset, dataEnd);
281
- const fecPayloadId = trailerLayout.hasFecId ? {
282
- ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE, SOURCE_FEC_PAYLOAD_ID_SIZE).getUint32(0, false)
283
- } : null;
284
- return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId };
286
+ const trailerStart = mmtpPacket.length - sourceFecTrailerSize(trailerLayout.hasOverlayFecId);
287
+ const ssIdAt = (offset) => ({
288
+ ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + offset, 4).getUint32(0, false)
289
+ });
290
+ const fecPayloadId = trailerLayout.hasFecId ? ssIdAt(trailerStart) : null;
291
+ const overlayFecPayloadId = trailerLayout.hasOverlayFecId ? ssIdAt(trailerStart + SOURCE_FEC_PAYLOAD_ID_SIZE) : null;
292
+ return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId, overlayFecPayloadId };
285
293
  }
286
294
  function sourceFecPayloadIdOf(mmtpPacket, header) {
287
295
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE)
@@ -417,6 +425,33 @@ function isoBlocksBehindLowerBound(a, b, kMax) {
417
425
  return serial32Precedes(a, b) ? Math.floor(serial32Distance(a, b) / kMax) : 0;
418
426
  }
419
427
 
428
+ // ../mmt-base/dist/catalog-fec-source.js
429
+ var ALL_ROLES = Object.freeze(["video", "audio"]);
430
+ function recordOf(value) {
431
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
432
+ }
433
+ function isoBlockSpanUsable(fec) {
434
+ const block = recordOf(fec);
435
+ if (block === void 0 || block["blockProfile"] !== "iso-ssbg1-v1")
436
+ return true;
437
+ const ms = block["interleaveDepthMs"];
438
+ return ms === void 0 || typeof ms === "number" && Number.isSafeInteger(ms) && ms >= 0;
439
+ }
440
+ function catalogFecAvailable(fec) {
441
+ const block = recordOf(fec);
442
+ if (block === void 0)
443
+ return true;
444
+ if (fecAlgorithmUnimplemented(block["algorithm"]))
445
+ return false;
446
+ const declaresFecInstance = block["algorithm"] !== "none";
447
+ const profile = block["blockProfile"];
448
+ const profileOk = isFecBlockProfile(profile) || profile === void 0 && !declaresFecInstance;
449
+ return profileOk && (!declaresFecInstance || isoBlockSpanUsable(block));
450
+ }
451
+ function fecAlgorithmUnimplemented(algorithm) {
452
+ return typeof algorithm === "string" && algorithm !== "none" && algorithm !== "raptorq" && algorithm !== "reed-solomon";
453
+ }
454
+
420
455
  // src/track-session.ts
421
456
  import { fecBlockBudgetMs } from "@blockcast/mmt-fec";
422
457
  function computeFecDeliveryWindowMs(config) {
@@ -534,16 +569,6 @@ import {
534
569
 
535
570
  // src/iso-block-locator.ts
536
571
  var IsoBlockLocator = class _IsoBlockLocator {
537
- /** Known blocks and spans, in serial order of their start. */
538
- #blocks = [];
539
- /** Held first-arrival sources whose block no repair has stated yet. */
540
- #held = /* @__PURE__ */ new Map();
541
- /** End of contiguous coverage: the SS_ID the next unknown block starts at. */
542
- #coverageEnd;
543
- #kMax;
544
- #retentionBlocks;
545
- #heldEvicted = 0;
546
- #newest;
547
572
  /**
548
573
  * @param kMax the catalog maximum K (`sourceSymbols`), the bound on SSB_length.
549
574
  * @param retentionBlocks how many blocks behind the newest position the
@@ -551,12 +576,35 @@ var IsoBlockLocator = class _IsoBlockLocator {
551
576
  * no locator exists without retention.
552
577
  */
553
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;
554
593
  if (!Number.isSafeInteger(kMax) || kMax <= 0) {
555
594
  throw new Error(`[IsoBlockLocator] maximum K must be a positive integer (got ${kMax})`);
556
595
  }
557
596
  this.#kMax = kMax;
558
597
  this.#retentionBlocks = _IsoBlockLocator.#checkedRetention(retentionBlocks);
559
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;
560
608
  static #checkedRetention(retentionBlocks) {
561
609
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
562
610
  throw new Error(
@@ -619,6 +667,14 @@ var IsoBlockLocator = class _IsoBlockLocator {
619
667
  }
620
668
  return null;
621
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
+ }
622
678
  /** The known block or span starting exactly at `start`. */
623
679
  blockAt(start) {
624
680
  return this.#blocks.find((block) => block.start === start);
@@ -641,6 +697,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
641
697
  coversBetween(a, b) {
642
698
  if (this.#coverageEnd === void 0) return false;
643
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;
644
703
  return serial32Precedes(b - 1 >>> 0, this.#coverageEnd);
645
704
  }
646
705
  /**
@@ -688,6 +747,22 @@ var IsoBlockLocator = class _IsoBlockLocator {
688
747
  }
689
748
  return { status: "placed", block: known, placed: [] };
690
749
  }
750
+ const pending = this.#holes.find((h) => isoBlockContains(h.start, h.length, start));
751
+ if (pending !== void 0) {
752
+ if (!isoBlockContains(pending.start, pending.length, serial32Add(start, length - 1))) {
753
+ return { status: "overlap", reason: `repair block ${start}+${length} runs past pending hole ${pending.start}+${pending.length}` };
754
+ }
755
+ this.#holes.splice(this.#holes.indexOf(pending), 1);
756
+ const before = serial32Distance(pending.start, start);
757
+ const afterStart = isoBlockEnd(start, length);
758
+ const after = pending.length - before - length;
759
+ if (before > 0) this.#holes.push({ start: pending.start, length: before, span: false });
760
+ if (after > 0) this.#holes.push({ start: afterStart, length: after, span: false });
761
+ const block2 = { start, length, span: false };
762
+ const placed2 = this.#claim(block2);
763
+ this.#blocks.push(block2);
764
+ return { status: "placed", block: block2, placed: placed2 };
765
+ }
691
766
  for (const block2 of this.#blocks) {
692
767
  if (isoBlockContains(block2.start, block2.length, start) || isoBlockContains(start, length, block2.start)) {
693
768
  return {
@@ -697,6 +772,7 @@ var IsoBlockLocator = class _IsoBlockLocator {
697
772
  }
698
773
  }
699
774
  let span;
775
+ let hole;
700
776
  if (this.#coverageEnd === void 0) {
701
777
  for (const ssId of this.#held.keys()) {
702
778
  if (serial32Precedes(ssId, start)) this.#held.delete(ssId);
@@ -705,21 +781,51 @@ var IsoBlockLocator = class _IsoBlockLocator {
705
781
  } else if (serial32Precedes(start, this.#coverageEnd)) {
706
782
  return { status: "stale", reason: `repair block ${start}+${length} precedes known coverage` };
707
783
  } else if (start !== this.#coverageEnd) {
708
- const spanBlock = {
709
- start: this.#coverageEnd,
710
- length: serial32Distance(this.#coverageEnd, start),
711
- span: true
712
- };
713
- span = { block: spanBlock, placed: this.#claim(spanBlock) };
714
- this.#blocks.push(spanBlock);
784
+ const gap = { start: this.#coverageEnd, length: serial32Distance(this.#coverageEnd, start) };
785
+ const lostSsId = this.deferIncompleteGaps ? this.#highestMissing(gap.start, gap.length) : void 0;
786
+ if (lostSsId !== void 0) {
787
+ const holeBlock = { ...gap, span: false };
788
+ this.#holes.push(holeBlock);
789
+ hole = { block: holeBlock, lostSsId };
790
+ } else {
791
+ const spanBlock = { ...gap, span: true };
792
+ span = { block: spanBlock, placed: this.#claim(spanBlock) };
793
+ this.#blocks.push(spanBlock);
794
+ }
715
795
  }
716
796
  const block = { start, length, span: false };
717
797
  const placed = this.#claim(block);
718
798
  this.#blocks.push(block);
719
799
  this.#coverageEnd = isoBlockEnd(start, length);
720
800
  this.retireBehind(start);
801
+ if (hole !== void 0) return { status: "placed", block, placed, hole };
721
802
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
722
803
  }
804
+ /**
805
+ * Turn every pending hole inside `[start, start + length)` into a
806
+ * repair-less span, claiming its held sources: its range FETCH ended, so
807
+ * nothing more will state its blocks. Returns the spans, in SS_ID order.
808
+ */
809
+ closeHolesWithin(start, length) {
810
+ const closed = [];
811
+ for (const hole of [...this.#holes]) {
812
+ if (!isoBlockContains(start, length, hole.start)) continue;
813
+ this.#holes.splice(this.#holes.indexOf(hole), 1);
814
+ const spanBlock = { start: hole.start, length: hole.length, span: true };
815
+ closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
816
+ this.#blocks.push(spanBlock);
817
+ }
818
+ return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
819
+ }
820
+ /** The highest SS_ID in the range no source is held for, or undefined when all are. */
821
+ #highestMissing(start, length) {
822
+ const steps = Math.min(length, this.#held.size + 1);
823
+ for (let i = 1; i <= steps; i++) {
824
+ const ssId = serial32Add(start, length - i);
825
+ if (!this.#held.has(ssId)) return ssId;
826
+ }
827
+ return void 0;
828
+ }
723
829
  /**
724
830
  * Retire every block and span whose last SS_ID, and every held source,
725
831
  * lies more than `retentionBlocks` blocks behind `position`, with the shared
@@ -738,6 +844,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
738
844
  this.#blocks.splice(i, 1);
739
845
  }
740
846
  }
847
+ for (let i = this.#holes.length - 1; i >= 0; i--) {
848
+ const hole = this.#holes[i];
849
+ const last = serial32Add(hole.start, hole.length - 1);
850
+ if (isoBlocksBehindLowerBound(last, position, this.#kMax) > horizon) this.#holes.splice(i, 1);
851
+ }
741
852
  for (const ssId of [...this.#held.keys()]) {
742
853
  if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon) this.#held.delete(ssId);
743
854
  }
@@ -746,6 +857,7 @@ var IsoBlockLocator = class _IsoBlockLocator {
746
857
  /** Forget everything (publisher restart, track reset). */
747
858
  reset() {
748
859
  this.#blocks.length = 0;
860
+ this.#holes.length = 0;
749
861
  this.#held.clear();
750
862
  this.#coverageEnd = void 0;
751
863
  this.#newest = void 0;
@@ -761,6 +873,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
761
873
  return placed;
762
874
  }
763
875
  };
876
+ function isoRangesOverlap(aStart, aLength, bStart, bLength) {
877
+ return serial32Distance(aStart, bStart) < aLength || serial32Distance(bStart, aStart) < bLength;
878
+ }
764
879
 
765
880
  // src/fec-state.ts
766
881
  var MIN_INTERLEAVE_DEPTH_MS = 1;
@@ -774,15 +889,6 @@ var INACTIVE = Object.freeze({
774
889
  "reliable-moq": Object.freeze({ state: "inactive", reason: "reliable-moq" }),
775
890
  "no-multicast-bridge": Object.freeze({ state: "inactive", reason: "no-multicast-bridge" })
776
891
  });
777
- function recordOf(value) {
778
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
779
- }
780
- function isoBlockSpanUsable(fec) {
781
- const block = recordOf(fec);
782
- if (block === void 0 || block["blockProfile"] !== "iso-ssbg1-v1") return true;
783
- const ms = block["interleaveDepthMs"];
784
- return ms === void 0 || typeof ms === "number" && Number.isSafeInteger(ms) && ms >= 0;
785
- }
786
892
 
787
893
  // src/block-policy.ts
788
894
  import { deriveFecInterleaveDepth } from "@blockcast/mmt-fec";
@@ -1244,6 +1350,7 @@ function decideGap(input) {
1244
1350
  }
1245
1351
 
1246
1352
  // src/fec-manager.ts
1353
+ var RS_MAX_BLOCK_SYMBOLS = 255;
1247
1354
  var WORKER_ERROR_LOG_CAP = 5;
1248
1355
  var WORKER_ERROR_KIND_CAP = 32;
1249
1356
  var WORKER_ERROR_OVERFLOW_KIND = "other";
@@ -1478,12 +1585,17 @@ var FECManager = class _FECManager {
1478
1585
  // per stream. Not only throws: the ordinary out-of-range case is detected by
1479
1586
  // arithmetic and never throws at all.
1480
1587
  this.#orderedHorizonWarnedFor = /* @__PURE__ */ new Set();
1481
- // Newest block start (SS_Start) seen per stream and when: the frontier for
1482
- // source-discontinuity detection and isoSpanResolution.
1588
+ // Newest block start (SS_Start) any symbol carried per stream and when: the
1589
+ // frontier isoSpanResolution reads.
1483
1590
  this.#highestSbn = /* @__PURE__ */ new Map();
1591
+ // The same from source symbols alone: the frontier a source is judged
1592
+ // against for a discontinuity. Repairs ride their own group, which can run
1593
+ // blocks ahead of the media they protect.
1594
+ this.#sourceFrontiers = /* @__PURE__ */ new Map();
1484
1595
  // iso-ssbg1-v1 block location per stream (streamKey). A source belongs to a
1485
1596
  // block only once a repair symbol stated the block's (SS_Start, SSB_length).
1486
1597
  this.#isoLocators = /* @__PURE__ */ new Map();
1598
+ this.#deferIsoGaps = false;
1487
1599
  this.#isoRepairRefusedCount = 0;
1488
1600
  this.#isoSourceOversizeCount = 0;
1489
1601
  // Held sources a locator's capacity cap evicted (IsoBlockLocator.heldCapacity):
@@ -1498,8 +1610,8 @@ var FECManager = class _FECManager {
1498
1610
  // rate-limited like the other per-symbol warns here. Cumulative.
1499
1611
  this.#isoDecoderUnplacedRetireFailed = 0;
1500
1612
  // The latest source symbol per stream that carried its MMTP
1501
- // packet_sequence_number: the anchor that bounds how many blocks the
1502
- // producer can have started before a later source symbol.
1613
+ // packet_sequence_number, by its own SS_ID: the anchor that bounds how far
1614
+ // the producer's SS_IDs can have moved before or after another source symbol.
1503
1615
  this.#sourceAnchors = /* @__PURE__ */ new Map();
1504
1616
  // Catalog/reset epoch per packetId. Gap decisions carry it for fencing.
1505
1617
  this.#packetEpochs = /* @__PURE__ */ new Map();
@@ -1558,6 +1670,14 @@ var FECManager = class _FECManager {
1558
1670
  this.onBlockReclassified = null;
1559
1671
  /** A video stream's classifier mode was established or changed. */
1560
1672
  this.onClassifierMode = null;
1673
+ /**
1674
+ * A repair stated a block past a gap that is missing a source and whose
1675
+ * every repair was lost: a lost SS_ID in an undelimited span
1676
+ * (draft-ramadan-moq-fec §7.5). Set with `setUndelimitedLossHandler`; the
1677
+ * receiver keeps the gap as a pending hole until `closeIsoHoles` is called
1678
+ * for it, which it must be.
1679
+ */
1680
+ this.#onUndelimitedLoss = null;
1561
1681
  /** A block every symbol of which vanished was created by SBN evidence. */
1562
1682
  this.onBlockVanished = null;
1563
1683
  /** A block reached a terminal state (completed, recovered, or failed). */
@@ -1637,7 +1757,9 @@ var FECManager = class _FECManager {
1637
1757
  #materializedBlocks;
1638
1758
  #orderedHorizonWarnedFor;
1639
1759
  #highestSbn;
1760
+ #sourceFrontiers;
1640
1761
  #isoLocators;
1762
+ #deferIsoGaps;
1641
1763
  #isoRepairRefusedCount;
1642
1764
  #isoSourceOversizeCount;
1643
1765
  #isoHeldEvictedCount;
@@ -1651,6 +1773,7 @@ var FECManager = class _FECManager {
1651
1773
  #workerErrorCounts;
1652
1774
  #decoderUnavailableEvents;
1653
1775
  #repairSymbolSizeMismatchCount;
1776
+ #onUndelimitedLoss;
1654
1777
  #encodeTrackName(catalogTrackName) {
1655
1778
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
1656
1779
  if (encoded === void 0) {
@@ -2227,8 +2350,8 @@ var FECManager = class _FECManager {
2227
2350
  // Deliberately one block tighter than deriveFecRetentionBlocks over the same
2228
2351
  // inputs (that function's `+ 1`). Different question: the retention horizon
2229
2352
  // asks how long the decoder still ACCEPTS symbols for a block, this asks how
2230
- // many blocks a stream can live behind (or ahead of) its frontier before a
2231
- // source symbol there is a discontinuity rather than loss (see #noteSbnSeen).
2353
+ // many blocks a stream can jump ahead of its frontier before a source symbol
2354
+ // there is a discontinuity rather than loss (see #noteSbnSeen).
2232
2355
  // The extra block of retention is slack for a block still being fed; a block
2233
2356
  // nothing has been heard from does not get it. Not the units defect — but it
2234
2357
  // is the next place the two can drift, so change both or neither.
@@ -2238,55 +2361,72 @@ var FECManager = class _FECManager {
2238
2361
  }
2239
2362
  /**
2240
2363
  * Record that a symbol for block `sbn` (the block's SS_Start) arrived and
2241
- * advance the stream's frontier, the newest block start seen.
2364
+ * advance the stream's frontiers, the newest block start seen.
2242
2365
  *
2243
- * A SOURCE symbol whose block goes back further than one live window, or
2244
- * jumps further than the stream could have produced since its last symbol,
2245
- * is a source discontinuity, not loss. A repair symbol can only advance the
2366
+ * A SOURCE symbol is judged against the newest source block alone: repairs
2367
+ * ride their own group, which can run blocks ahead of the media. One whose
2368
+ * block goes back further than the blocks this manager retains, or that
2369
+ * cannot have been sent before the source it lies behind, or that jumps
2370
+ * further than the stream could have produced since its last symbol, is a
2371
+ * source discontinuity, not loss. A repair symbol can only advance the
2246
2372
  * frontier: a D-28 fetch legitimately answers for an old block, so it never
2247
2373
  * signals a discontinuity.
2248
2374
  *
2249
2375
  * The producer closes a block at its Dth media-unit boundary OR when K
2250
2376
  * source symbols filled it, so one interleave span can start several blocks
2251
- * (every large keyframe does). What bounds a forward jump is therefore
2252
- * packet evidence, not a block rate: SS_ID advances by one per FEC source
2253
- * packet (ISO/IEC 23008-1 C.5.2) and the MMTP packet_sequence_number by one
2254
- * per packet of the packet_id, so with both source symbols'
2255
- * packet_sequence_number a block start can move at most the packets sent
2256
- * between them plus the anchor's own offset into its block (< K). Without
2257
- * it, only the D-close rate is known.
2377
+ * (every large keyframe does). What bounds a jump is therefore packet
2378
+ * evidence, not a block rate: SS_ID advances by one per FEC source packet
2379
+ * (ISO/IEC 23008-1 C.5.2) and the MMTP packet_sequence_number by one per
2380
+ * packet of the packet_id, so with both source symbols'
2381
+ * packet_sequence_number their SS_IDs (`ssId`, not their block starts,
2382
+ * which a repair-less span can put far behind) can move at most the packets
2383
+ * sent between them, in either direction, plus K of slack for sources lost
2384
+ * before a hop that renumbers packets. Without it, only the D-close rate is
2385
+ * known.
2258
2386
  *
2259
2387
  * Vanished blocks are not enumerated here: their starts are unknown until a
2260
2388
  * repair states them. The SS_IDs between two stated blocks become one
2261
2389
  * repair-less span when the later block's repair arrives (placeIsoRepair).
2262
2390
  */
2263
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber) {
2391
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
2264
2392
  const streamKey = this.#streamKey(packetId, catalogTrackName);
2265
2393
  const now = performance.now();
2266
- const previous = this.#highestSbn.get(streamKey);
2394
+ const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
2267
2395
  const anchor = this.#sourceAnchors.get(streamKey);
2268
2396
  const psn = symbol === "source" && packetSequenceNumber !== void 0 && Number.isSafeInteger(packetSequenceNumber) && packetSequenceNumber >= 0 && packetSequenceNumber <= 4294967295 ? packetSequenceNumber : void 0;
2269
2397
  const anchorHere = () => {
2270
- if (psn !== void 0 && (anchor === void 0 || !this.#blockPrecedes(sbn, anchor.sbn))) {
2271
- this.#sourceAnchors.set(streamKey, { sbn, psn, atMs: now });
2398
+ if (psn !== void 0 && (anchor === void 0 || !serial32Precedes(ssId, anchor.ssId))) {
2399
+ this.#sourceAnchors.set(streamKey, { ssId, psn, atMs: now });
2272
2400
  }
2273
2401
  };
2402
+ const advance = () => {
2403
+ const highest = this.#highestSbn.get(streamKey);
2404
+ if (highest === void 0 || this.#blockPrecedes(highest.sbn, sbn)) {
2405
+ this.#highestSbn.set(streamKey, { sbn, atMs: now });
2406
+ }
2407
+ if (symbol === "source") this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
2408
+ anchorHere();
2409
+ };
2274
2410
  const discontinuity = () => {
2275
2411
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity();
2276
2412
  this.#highestSbn.set(streamKey, { sbn, atMs: now });
2413
+ this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
2277
2414
  if (psn === void 0) this.#sourceAnchors.delete(streamKey);
2278
- else this.#sourceAnchors.set(streamKey, { sbn, psn, atMs: now });
2415
+ else this.#sourceAnchors.set(streamKey, { ssId, psn, atMs: now });
2279
2416
  this.onSourceDiscontinuity?.(packetId, catalogTrackName);
2280
2417
  };
2281
2418
  if (previous === void 0) {
2282
- this.#highestSbn.set(streamKey, { sbn, atMs: now });
2283
- anchorHere();
2419
+ advance();
2284
2420
  return;
2285
2421
  }
2286
2422
  const config = this.#trackConfig(packetId);
2287
2423
  const window2 = this.#liveWindowBlocks(config);
2424
+ const sentInOrder = (from, to) => {
2425
+ const sent = to.psn - from.psn >>> 0;
2426
+ return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
2427
+ };
2288
2428
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
2289
- if (symbol === "source" && window2 !== null && this.#blocksBehind(sbn, previous.sbn, packetId) > window2) {
2429
+ 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))) {
2290
2430
  discontinuity();
2291
2431
  return;
2292
2432
  }
@@ -2296,9 +2436,8 @@ var FECManager = class _FECManager {
2296
2436
  const missing = this.#blocksBehind(previous.sbn, sbn, packetId) - 1;
2297
2437
  let plausible = true;
2298
2438
  if (window2 !== null) {
2299
- if (psn !== void 0 && anchor !== void 0 && this.#blockPrecedes(anchor.sbn, sbn) && psn !== anchor.psn) {
2300
- const sent = psn - anchor.psn >>> 0;
2301
- plausible = sent <= 2147483647 && serial32Distance(anchor.sbn, sbn) <= sent + config.k;
2439
+ if (psn !== void 0 && anchor !== void 0 && serial32Precedes(anchor.ssId, ssId) && psn !== anchor.psn) {
2440
+ plausible = sentInOrder(anchor, { ssId, psn });
2302
2441
  } else {
2303
2442
  plausible = missing <= window2 + Math.ceil((now - previous.atMs) / config.interleaveDepthMs);
2304
2443
  }
@@ -2308,8 +2447,7 @@ var FECManager = class _FECManager {
2308
2447
  discontinuity();
2309
2448
  return;
2310
2449
  }
2311
- this.#highestSbn.set(streamKey, { sbn, atMs: now });
2312
- anchorHere();
2450
+ advance();
2313
2451
  }
2314
2452
  /*
2315
2453
  * Block order for one stream (BLO-35597 iso:5). A block is keyed by its
@@ -2626,8 +2764,10 @@ var FECManager = class _FECManager {
2626
2764
  );
2627
2765
  }
2628
2766
  const hasCatalogTiming = _FECManager.#hasCatalogTiming({ interleaveDepthMs: ownInterleaveDepthMs });
2767
+ const algorithm = config.algorithm ?? previous.algorithm;
2629
2768
  const next = {
2630
2769
  blockProfile,
2770
+ ...algorithm === void 0 ? {} : { algorithm },
2631
2771
  k,
2632
2772
  symbolSize: config.symbolSize != null && config.symbolSize > 0 ? config.symbolSize : previousTrack?.symbolSize ?? 0,
2633
2773
  interleaveDepthMs: ownInterleaveDepthMs,
@@ -2893,6 +3033,7 @@ var FECManager = class _FECManager {
2893
3033
  resetSet(this.#materializedBlocks);
2894
3034
  resetMap(this.#resolvedBlockClasses);
2895
3035
  resetMap(this.#highestSbn);
3036
+ resetMap(this.#sourceFrontiers);
2896
3037
  resetMap(this.#isoLocators);
2897
3038
  resetMap(this.#sourceAnchors);
2898
3039
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName));
@@ -2998,6 +3139,7 @@ var FECManager = class _FECManager {
2998
3139
  dropMap(this.#orderedPendingBlocks);
2999
3140
  dropMap(this.#resolvedBlockClasses);
3000
3141
  dropMap(this.#highestSbn);
3142
+ dropMap(this.#sourceFrontiers);
3001
3143
  dropMap(this.#isoLocators);
3002
3144
  dropMap(this.#sourceAnchors);
3003
3145
  dropMap(this.#classifiers);
@@ -3090,7 +3232,13 @@ var FECManager = class _FECManager {
3090
3232
  if (isSourceSymbol && esi === 0) {
3091
3233
  this.#startupPartialBlocks.delete(blockKey);
3092
3234
  this.#startupAlignedPackets.add(streamKey);
3093
- } else if (isStartupPartial && !isReadyMulticastRepair || !this.#startupAlignedPackets.has(streamKey) && !isReadyMulticastRepair) {
3235
+ } else if (
3236
+ // A ready multicast repair opens a block the join has not seen yet, never
3237
+ // a join partial: its sources were refused, so its repairs alone open a
3238
+ // block that cannot decode and fails at its deadline, once per packet ID
3239
+ // per join (BLO-48308).
3240
+ isStartupPartial || !this.#startupAlignedPackets.has(streamKey) && !isReadyMulticastRepair
3241
+ ) {
3094
3242
  this.#markStartupPartial(blockKey);
3095
3243
  return false;
3096
3244
  }
@@ -3372,6 +3520,7 @@ var FECManager = class _FECManager {
3372
3520
  let locator = this.#isoLocators.get(streamKey);
3373
3521
  if (!locator) {
3374
3522
  locator = new IsoBlockLocator(this.#trackConfig(packetId).k, this.#isoRetentionBlocks(packetId));
3523
+ locator.deferIncompleteGaps = this.#deferIsoGaps;
3375
3524
  this.#isoLocators.set(streamKey, locator);
3376
3525
  }
3377
3526
  return locator;
@@ -3415,6 +3564,10 @@ var FECManager = class _FECManager {
3415
3564
  }
3416
3565
  return blocks;
3417
3566
  }
3567
+ /** The iso-ssbg1-v1 locator horizon of a configured packetId, in blocks (#isoRetentionBlocks). */
3568
+ isoRetentionBlocksForPacket(packetId) {
3569
+ return this.#hasBlockProfile(packetId) ? this.#isoRetentionBlocks(packetId) : void 0;
3570
+ }
3418
3571
  /** Whether an iso-ssbg1-v1 protected packet fits one ssbg_mode1 symbol (len + 2 <= T). */
3419
3572
  isoSourceFits(packetId, packetLength) {
3420
3573
  const symbolSize = this.#trackConfigs.get(packetId)?.symbolSize;
@@ -3464,15 +3617,61 @@ var FECManager = class _FECManager {
3464
3617
  }
3465
3618
  return placement;
3466
3619
  }
3467
- if (placement.span !== void 0) {
3468
- const key = this.#blockKey(placement.span.block.start, packetId, catalogTrackName);
3469
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, placement.span.block.length);
3470
- }
3471
- if (placement.span !== void 0 && placement.span.placed.length === 0) {
3472
- this.#materializeBlock(placement.span.block.start, packetId, catalogTrackName, true);
3620
+ if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
3621
+ if (placement.hole !== void 0) {
3622
+ const locator = this.#isoLocatorFor(packetId, catalogTrackName);
3623
+ const hole = placement.hole.block;
3624
+ const previous = locator.blockEndingAt(hole.start);
3625
+ const loss = {
3626
+ packetId,
3627
+ catalogTrackName,
3628
+ holeStart: hole.start,
3629
+ holeLength: hole.length,
3630
+ lostSsId: placement.hole.lostSsId,
3631
+ kMax: this.#trackConfig(packetId).k,
3632
+ ...previous === void 0 ? {} : { previousBlockStart: previous.start }
3633
+ };
3634
+ this.#onUndelimitedLoss(loss);
3473
3635
  }
3474
3636
  return placement;
3475
3637
  }
3638
+ /**
3639
+ * Keep an iso-ssbg1-v1 gap missing a source as a pending hole, reported to
3640
+ * `handler`, instead of a repair-less span; null restores spans. Set by the
3641
+ * range repair scheduler; applies to every stream from its next gap. The
3642
+ * handler and the deferral are one setting, so no hole is ever created with
3643
+ * nobody to close it.
3644
+ */
3645
+ setUndelimitedLossHandler(handler) {
3646
+ this.#onUndelimitedLoss = handler;
3647
+ this.#deferIsoGaps = handler !== null;
3648
+ for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
3649
+ }
3650
+ /**
3651
+ * The range repair for a hole ended: every hole still pending inside
3652
+ * `[start, start + length)` becomes a repair-less span. Returns those spans
3653
+ * with the held sources they placed, for the caller to feed (MmtpRouter).
3654
+ */
3655
+ closeIsoHoles(packetId, catalogTrackName, start, length) {
3656
+ const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
3657
+ if (locator === void 0) return [];
3658
+ const spans = locator.closeHolesWithin(start, length);
3659
+ for (const span of spans) this.#openIsoSpan(span, packetId, catalogTrackName);
3660
+ return spans;
3661
+ }
3662
+ /**
3663
+ * A repair-less span has no repair to state its length, so it is known
3664
+ * here: its sources make it clean exactly when all of them arrived. A
3665
+ * stated block learns its SSB_length from its own repair symbol, fed after
3666
+ * its placed sources exactly as on the wire (feedRepairSymbol). A span every
3667
+ * SS_ID of which vanished resolves through its deadline like any vanished
3668
+ * block.
3669
+ */
3670
+ #openIsoSpan(span, packetId, catalogTrackName) {
3671
+ const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
3672
+ if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
3673
+ if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
3674
+ }
3476
3675
  /**
3477
3676
  * Resolution of the SS_IDs strictly between two released frames' SS_IDs on
3478
3677
  * an iso-ssbg1-v1 stream, for in-order frame release: null while a block
@@ -3996,20 +4195,49 @@ var FECManager = class _FECManager {
3996
4195
  * Caller is responsible for routing recovered data and updating
3997
4196
  * block completion state via `markBlockCompleted()`.
3998
4197
  */
3999
- feedRepairSymbol(packetId, ssStart, ssbLength, rsId, repairData, catalogTrackName) {
4000
- this.#fecStats.repairPackets++;
4001
- this.#statsForPacket(packetId).repairPackets++;
4002
- if (!this.#hasBlockProfile(packetId)) return null;
4198
+ /**
4199
+ * Whether a repair symbol of `byteLength` bytes is a valid member of a
4200
+ * `packetId` block: every repair symbol is exactly the track's T. A symbol of
4201
+ * any other size is counted on `repairSymbolSizeMismatches`, warned (rate
4202
+ * limited) and refused. The router calls this before the symbol takes any
4203
+ * other part in block state (placement, first-arrival dedup, completed-block
4204
+ * accounting), so a malformed repair is counted whatever its arrival order:
4205
+ * judged after dedup, one landing on an already-complete block, or behind a
4206
+ * valid copy from the other transport, was swallowed as a duplicate and never
4207
+ * counted (BLO-48306). A packetId with no configured block profile admits
4208
+ * nothing here; its repair is dropped upstream as unreadable.
4209
+ */
4210
+ /**
4211
+ * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
4212
+ * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
4213
+ * block state unchanged. The router calls this before the repair places a
4214
+ * block or takes any other part in block bookkeeping. A RaptorQ track admits
4215
+ * every header that parsed (its RS_ID < RSB_length check is in the parser).
4216
+ */
4217
+ admitRepairBlockLength(packetId, ssbLength, rsbLength, rsId) {
4218
+ if (rsId >= rsbLength) return false;
4219
+ if (this.#trackConfigs.get(packetId)?.algorithm !== "reed-solomon") return true;
4220
+ return ssbLength + rsbLength <= RS_MAX_BLOCK_SYMBOLS;
4221
+ }
4222
+ admitRepairSymbolSize(packetId, ssStart, ssbLength, rsId, byteLength) {
4223
+ if (!this.#hasBlockProfile(packetId)) return false;
4003
4224
  const symbolSize = this.#trackConfig(packetId).symbolSize;
4004
- if (symbolSize > 0 && repairData.byteLength !== symbolSize) {
4225
+ if (symbolSize > 0 && byteLength !== symbolSize) {
4005
4226
  this.#repairSymbolSizeMismatchCount++;
4006
4227
  if (this.#repairSymbolSizeMismatchCount <= 5 || this.#repairSymbolSizeMismatchCount % 100 === 0) {
4007
4228
  console.warn(
4008
- `[FECManager] Dropping repair symbol with invalid size: got ${repairData.byteLength}B, expected ${symbolSize}B (packetId=${packetId}, ssStart=${ssStart}, ssbLength=${ssbLength}, rsId=${rsId})`
4229
+ `[FECManager] Dropping repair symbol with invalid size: got ${byteLength}B, expected ${symbolSize}B (packetId=${packetId}, ssStart=${ssStart}, ssbLength=${ssbLength}, rsId=${rsId})`
4009
4230
  );
4010
4231
  }
4011
- return null;
4232
+ return false;
4012
4233
  }
4234
+ return true;
4235
+ }
4236
+ feedRepairSymbol(packetId, ssStart, ssbLength, rsId, repairData, catalogTrackName) {
4237
+ this.#fecStats.repairPackets++;
4238
+ this.#statsForPacket(packetId).repairPackets++;
4239
+ if (!this.#hasBlockProfile(packetId)) return null;
4240
+ if (!this.admitRepairSymbolSize(packetId, ssStart, ssbLength, rsId, repairData.byteLength)) return null;
4013
4241
  const fecData = repairData;
4014
4242
  const k = this.#trackConfig(packetId).k;
4015
4243
  const block = this.#isoLocatorFor(packetId, catalogTrackName).blockAt(ssStart);
@@ -4162,7 +4390,14 @@ var FECManager = class _FECManager {
4162
4390
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
4163
4391
  const k = trackConfig.k;
4164
4392
  if (this.#completedBlocks.has(key)) return;
4165
- this.#noteSbnSeen(sbn, packetId, catalogTrackName, "source", evidence.packetSequenceNumber);
4393
+ this.#noteSbnSeen(
4394
+ sbn,
4395
+ packetId,
4396
+ catalogTrackName,
4397
+ "source",
4398
+ evidence.packetSequenceNumber,
4399
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
4400
+ );
4166
4401
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
4167
4402
  if (Number.isInteger(esi) && esi >= authoredLength) {
4168
4403
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -4413,6 +4648,7 @@ var FECManager = class _FECManager {
4413
4648
  this.#repairedBlocks.clear();
4414
4649
  this.#materializedBlocks.clear();
4415
4650
  this.#highestSbn.clear();
4651
+ this.#sourceFrontiers.clear();
4416
4652
  this.#isoLocators.clear();
4417
4653
  this.#sourceAnchors.clear();
4418
4654
  this.#trackConfigs.clear();
@@ -9312,8 +9548,14 @@ var SampleCombiner = class {
9312
9548
  /**
9313
9549
  * Add one reassembled data unit. Returns the combined sample once every
9314
9550
  * constituent data unit has arrived and totals the authored size.
9551
+ *
9552
+ * `sampleSize` is the authored size the host resolves for the sample as the
9553
+ * data unit completes. It stands in only when no size was registered, which
9554
+ * happens when the data unit's FI=0/FI=1 reached the reassembler without the
9555
+ * host's own FT=2 parse: an FEC-recovered first fragment completed by source
9556
+ * fragments, or one decoded before its source copy arrived.
9315
9557
  */
9316
- addMfu(mfu) {
9558
+ addMfu(mfu, sampleSize) {
9317
9559
  if (mfu.movieFragmentSequenceNumber === void 0 || mfu.sampleNumber === void 0) {
9318
9560
  this.#stats.passthroughSamples++;
9319
9561
  return fromPassthrough(mfu);
@@ -9329,7 +9571,7 @@ var SampleCombiner = class {
9329
9571
  return null;
9330
9572
  }
9331
9573
  const dataLen = mfu.data.byteLength;
9332
- const authoredSize = this.#authoredSizes.get(key);
9574
+ const authoredSize = this.#authoredSizes.get(key) ?? sampleSize;
9333
9575
  if (offset === 0 && !this.#pending.has(key)) {
9334
9576
  const passesThrough = authoredSize === void 0 ? !this.#requireAuthoredSize : dataLen === authoredSize;
9335
9577
  if (passesThrough) {
@@ -9623,6 +9865,12 @@ if (void 0) {
9623
9865
  const out = c.addMfu(mfu(1, 9, 17, 5, [6, 7, 8, 9, 10], 1001n, false));
9624
9866
  expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
9625
9867
  });
9868
+ test("a size handed with the data unit completes a sample no head registered", () => {
9869
+ const c = combiner({ requireAuthoredSize: true });
9870
+ const out = c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5);
9871
+ expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5]));
9872
+ expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5)).toBeNull();
9873
+ });
9626
9874
  test("duplicate offset is rejected", () => {
9627
9875
  const c = combiner();
9628
9876
  c.registerAuthoredSize(void 0, 1, 9, 17, 10);
@@ -10867,6 +11115,7 @@ function isFmp4Box(data) {
10867
11115
  const type = String.fromCharCode(data[4], data[5], data[6], data[7]);
10868
11116
  return FMPU_BOX_TYPES.has(type);
10869
11117
  }
11118
+ var MAX_AWAITING_TIMING_HEADS = 8;
10870
11119
  var MmtpContainerParser = class _MmtpContainerParser {
10871
11120
  constructor(config) {
10872
11121
  this.#tracks = /* @__PURE__ */ new Map();
@@ -10925,6 +11174,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
10925
11174
  * reordering into the parser. */
10926
11175
  this.#reliableMoqStartupGate = /* @__PURE__ */ new Map();
10927
11176
  this.#disposed = false;
11177
+ this.#replayingAwaitingTiming = false;
10928
11178
  this.#fedObjects = 0;
10929
11179
  this.#reassemblerFragmentsFed = 0;
10930
11180
  this.#reassemblerDataUnitsReturned = 0;
@@ -11017,6 +11267,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
11017
11267
  #reorderStats;
11018
11268
  #reliableMoqStartupGate;
11019
11269
  #disposed;
11270
+ #replayingAwaitingTiming;
11020
11271
  #fedObjects;
11021
11272
  #reassemblerFragmentsFed;
11022
11273
  #reassemblerDataUnitsReturned;
@@ -11266,7 +11517,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
11266
11517
  * a single failure bucket. Returns null so call sites stay `return this.#drop(...)`.
11267
11518
  */
11268
11519
  #drop(reason) {
11269
- this.#countOutcome(`drop:${reason}`);
11520
+ if (this.#replayingAwaitingTiming) this.#countDeferredOutcome(reason);
11521
+ else this.#countOutcome(`drop:${reason}`);
11270
11522
  return null;
11271
11523
  }
11272
11524
  get reorderDiagnostics() {
@@ -11289,6 +11541,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
11289
11541
  for (const combiner of this.#sampleCombiners.values()) {
11290
11542
  combiner.cleanupTimeouts(timeoutMs);
11291
11543
  }
11544
+ const now = Date.now();
11545
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
11546
+ while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
11547
+ awaitingTiming.shift();
11548
+ }
11549
+ }
11292
11550
  }
11293
11551
  /**
11294
11552
  * Phase 1 of two-phase parsing. Returns structured header info for FEC feeding.
@@ -11369,7 +11627,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
11369
11627
  byteLength: packet.byteLength
11370
11628
  };
11371
11629
  }
11372
- if (info.fecPayloadId !== null && this.#sourceSymbolCb) {
11630
+ if (info.fecPayloadId !== null && this.#sourceSymbolCb && !this.#replayingAwaitingTiming) {
11373
11631
  const rawSymbol = packet.subarray(0, packet.length - 4);
11374
11632
  try {
11375
11633
  this.#sourceSymbolCb(info.packetId, info.fecPayloadId.ssId, rawSymbol);
@@ -11417,6 +11675,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
11417
11675
  }
11418
11676
  return this.#drop("fragment-timing-refused");
11419
11677
  }
11678
+ this.#replayAwaitingTiming(streamKey, resolver2);
11420
11679
  return {
11421
11680
  kind: "fragment",
11422
11681
  packet: info,
@@ -11440,7 +11699,18 @@ var MmtpContainerParser = class _MmtpContainerParser {
11440
11699
  mfuDuHeader.movieFragmentSequenceNumber,
11441
11700
  mfuDuHeader.sampleNumber
11442
11701
  );
11443
- if (!headTiming) return this.#drop("mfu-sample-timing-missing");
11702
+ if (!headTiming) {
11703
+ this.#awaitTiming(streamKey, {
11704
+ packet,
11705
+ options,
11706
+ parsed,
11707
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
11708
+ movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
11709
+ sampleNumber: mfuDuHeader.sampleNumber,
11710
+ arrivedAt: Date.now()
11711
+ });
11712
+ return this.#drop("mfu-sample-timing-missing");
11713
+ }
11444
11714
  const offset = mfuDuHeader.offset;
11445
11715
  if (!Number.isSafeInteger(offset) || offset < 0 || offset >= headTiming.size)
11446
11716
  return this.#drop("mfu-offset-out-of-range");
@@ -11516,16 +11786,17 @@ var MmtpContainerParser = class _MmtpContainerParser {
11516
11786
  const sampleNumber = assembled.sampleNumber;
11517
11787
  if (movieFragmentSequenceNumber === void 0 || sampleNumber === void 0)
11518
11788
  return this.#drop("assembled-identity-missing");
11519
- if (!resolver.sampleTiming(
11789
+ const assembledTiming = resolver.sampleTiming(
11520
11790
  assembled.mpuSequenceNumber,
11521
11791
  movieFragmentSequenceNumber,
11522
11792
  sampleNumber
11523
- )) return this.#drop("assembled-timing-missing");
11793
+ );
11794
+ if (!assembledTiming) return this.#drop("assembled-timing-missing");
11524
11795
  if (assembled.mpuSequenceNumber !== mpu.mpuSequenceNumber)
11525
11796
  return this.#drop("assembled-mpu-mismatch");
11526
11797
  let combined;
11527
11798
  try {
11528
- combined = this.#sampleCombinerFor(streamKey).addMfu(assembled);
11799
+ combined = this.#sampleCombinerFor(streamKey).addMfu(assembled, assembledTiming.size);
11529
11800
  } catch (error) {
11530
11801
  if (!(error instanceof SampleCombineError)) throw error;
11531
11802
  console.warn(
@@ -11834,9 +12105,37 @@ var MmtpContainerParser = class _MmtpContainerParser {
11834
12105
  if (existing) return existing.resolver;
11835
12106
  if (!create) return null;
11836
12107
  const resolver = new IsoBmffTimingResolver(this.#maxPendingTimingSamples);
11837
- this.#timingStreams.set(streamKey, { packetId, resolver });
12108
+ this.#timingStreams.set(streamKey, { packetId, resolver, awaitingTiming: [] });
11838
12109
  return resolver;
11839
12110
  }
12111
+ #awaitTiming(streamKey, head) {
12112
+ const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
12113
+ if (!awaitingTiming) return;
12114
+ awaitingTiming.push(head);
12115
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
12116
+ }
12117
+ /**
12118
+ * Feed again the heads whose timing the FT=1 just admitted declares. That
12119
+ * FT=1 can be an FEC recovery landing after its sample's FI=1, and neither
12120
+ * FEC path routes a source symbol that already arrived a second time.
12121
+ */
12122
+ #replayAwaitingTiming(streamKey, resolver) {
12123
+ const state = this.#timingStreams.get(streamKey);
12124
+ if (!state || state.awaitingTiming.length === 0) return;
12125
+ const ready = state.awaitingTiming.filter((head) => resolver.sampleTiming(
12126
+ head.mpuSequenceNumber,
12127
+ head.movieFragmentSequenceNumber,
12128
+ head.sampleNumber
12129
+ ));
12130
+ if (ready.length === 0) return;
12131
+ state.awaitingTiming = state.awaitingTiming.filter((head) => !ready.includes(head));
12132
+ this.#replayingAwaitingTiming = true;
12133
+ try {
12134
+ for (const head of ready) this.#feed(head.packet, head.options, head.parsed);
12135
+ } finally {
12136
+ this.#replayingAwaitingTiming = false;
12137
+ }
12138
+ }
11840
12139
  #dropTimingStream(streamKey) {
11841
12140
  const state = this.#timingStreams.get(streamKey);
11842
12141
  if (!state) return;
@@ -12440,6 +12739,18 @@ var MmtpRouter = class {
12440
12739
  // MSE recovery routes through CmafBlockAssembler and can reorder by block; the
12441
12740
  // direct callback path has to preserve decode order before frames leave libmmt.
12442
12741
  #latestVideoSeqByStream = /* @__PURE__ */ new Map();
12742
+ /**
12743
+ * Per stream, SS_ID - packet_sequence_number (mod 2^32) of its latest
12744
+ * first-arrival FEC source packet. A recovered source symbol's wire
12745
+ * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
12746
+ */
12747
+ #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
12748
+ /**
12749
+ * Streams whose multicast leg delivered a RAP-flagged source packet that was
12750
+ * not parsed, typically because its overlap copy was parsed first
12751
+ * (BLO-49179). The next video keyframe emitted on the stream consumes it.
12752
+ */
12753
+ #multicastRapTwinByStream = /* @__PURE__ */ new Set();
12443
12754
  #lastDirectSourceVideoTsByStream = /* @__PURE__ */ new Map();
12444
12755
  #lastDirectEmittedVideoTsByStream = /* @__PURE__ */ new Map();
12445
12756
  #pendingDirectRecoveredVideoByStream = /* @__PURE__ */ new Map();
@@ -12514,6 +12825,7 @@ var MmtpRouter = class {
12514
12825
  */
12515
12826
  #onPublisherRestart;
12516
12827
  #publisherRestarts = 0;
12828
+ #restampedRecoveredSeqs = 0;
12517
12829
  /** Inits delivered with no onTrackInit handler for their packetId (MOQT-01). */
12518
12830
  #unmappedInitDeliveries = 0;
12519
12831
  // FEC Payload IDs left unread because their (owner) packetId had no
@@ -12572,6 +12884,12 @@ var MmtpRouter = class {
12572
12884
  ...meta.catalogTrackName === void 0 ? {} : { catalogTrackName: meta.catalogTrackName }
12573
12885
  };
12574
12886
  if (meta.source) frameMeta.source = meta.source;
12887
+ if (isVideo && frameMeta.keyframe) {
12888
+ const twinSeen = this.#multicastRapTwinByStream.delete(
12889
+ this.#mediaStreamKey(packetId, frameMeta.catalogTrackName)
12890
+ );
12891
+ if (twinSeen && frameMeta.source === "moq") frameMeta.source = "multicast";
12892
+ }
12575
12893
  if (meta.deliveryProvenance !== void 0)
12576
12894
  frameMeta.deliveryProvenance = meta.deliveryProvenance;
12577
12895
  if (meta.recovered) frameMeta.recovered = true;
@@ -12734,6 +13052,14 @@ var MmtpRouter = class {
12734
13052
  get publisherRestartCount() {
12735
13053
  return this.#publisherRestarts;
12736
13054
  }
13055
+ /**
13056
+ * FEC-recovered source symbols whose reconstructed header named a
13057
+ * packet_sequence_number other than the wire sequence their SS_ID maps to:
13058
+ * a hop re-stamped the sequence after the sender protected the packet.
13059
+ */
13060
+ get restampedRecoveredSequenceCount() {
13061
+ return this.#restampedRecoveredSeqs;
13062
+ }
12737
13063
  /**
12738
13064
  * Packets whose Source or Repair FEC Payload ID was left unread because
12739
13065
  * their (owner) packetId had no configured `fec.blockProfile`: FEC not
@@ -13249,6 +13575,14 @@ var MmtpRouter = class {
13249
13575
  `[MmtpRouter] packetId=${ownerPacketId} is iso-ssbg1-v1 but its FEC manager cannot place ISO blocks`
13250
13576
  );
13251
13577
  }
13578
+ if (fec.admitRepairBlockLength && !fec.admitRepairBlockLength(ownerPacketId, repair.ssbLength, repair.rsbLength, repair.rsId)) return;
13579
+ if (fec.admitRepairSymbolSize && !fec.admitRepairSymbolSize(
13580
+ ownerPacketId,
13581
+ repair.ssStart,
13582
+ repair.ssbLength,
13583
+ repair.rsId,
13584
+ repair.symbolData.byteLength
13585
+ )) return;
13252
13586
  const placement = fec.placeIsoRepair(ownerPacketId, catalogTrackName, repair.ssStart, repair.ssbLength);
13253
13587
  if (placement.status !== "placed") return;
13254
13588
  const blockStart = placement.block.start;
@@ -13283,6 +13617,17 @@ var MmtpRouter = class {
13283
13617
  this.#routeRecoveredBlock(blockStart, recovered, ownerPacketId, catalogTrackName);
13284
13618
  }
13285
13619
  }
13620
+ /**
13621
+ * The range repair FETCH for an undelimited hole ended (draft-ramadan-moq-fec
13622
+ * §7.5): what no repair stated becomes repair-less spans, whose held sources
13623
+ * are fed exactly as a span a repair closed.
13624
+ */
13625
+ closeIsoHoles(ownerPacketId, catalogTrackName, start, length) {
13626
+ const spans = this.#fecManager?.closeIsoHoles?.(ownerPacketId, catalogTrackName, start, length) ?? [];
13627
+ for (const span of spans) {
13628
+ this.#replayIsoSources(ownerPacketId, catalogTrackName, span.block.start, span.placed);
13629
+ }
13630
+ }
13286
13631
  /**
13287
13632
  * Feed iso-ssbg1-v1 sources a repair just placed, in SS_ID order, exactly as
13288
13633
  * a first-arrival source is fed once its block is known: transport
@@ -13378,6 +13723,8 @@ var MmtpRouter = class {
13378
13723
  this.#trackSynced.delete(streamKey);
13379
13724
  this.#droppedPreSyncVideo.delete(streamKey);
13380
13725
  this.#latestVideoSeqByStream.delete(streamKey);
13726
+ this.#ssIdSeqOffsetByStream.delete(streamKey);
13727
+ this.#multicastRapTwinByStream.delete(streamKey);
13381
13728
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
13382
13729
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
13383
13730
  this.#pendingDirectRecoveredVideoByStream.delete(streamKey);
@@ -14148,6 +14495,12 @@ var MmtpRouter = class {
14148
14495
  } else if (fecUnreadable && info.fecPayloadId) {
14149
14496
  parseSourceSymbol = !duplicates.parsedSymbols.has(info.fecPayloadId.ssId);
14150
14497
  }
14498
+ if (fecPayloadId && !overlapCopy) {
14499
+ this.#ssIdSeqOffsetByStream.set(
14500
+ this.#mediaStreamKey(info.packetId, catalogTrackName),
14501
+ fecPayloadId.ssId - info.sequenceNumber >>> 0
14502
+ );
14503
+ }
14151
14504
  if (!this.#fecManager || !info.fecPayloadId || parseSourceSymbol) {
14152
14505
  if (this.#fecManager && info.fecPayloadId) {
14153
14506
  duplicates.parsedSymbols.add(info.fecPayloadId.ssId);
@@ -14170,6 +14523,10 @@ var MmtpRouter = class {
14170
14523
  // An FEC source frame is anchored by its own SS_ID (C.5.2).
14171
14524
  ...fecSource && fecPayloadId ? { fecSbn: fecPayloadId.ssId } : {}
14172
14525
  }, parsed);
14526
+ } else if (source === "multicast" && info.rapFlag) {
14527
+ this.#multicastRapTwinByStream.add(
14528
+ this.#mediaStreamKey(info.packetId, catalogTrackName)
14529
+ );
14173
14530
  }
14174
14531
  if (this.#classifyPacketId(info.packetId) === null) return;
14175
14532
  if (this.#fecManager && fecPayloadId && coords && sourceSymbolAccepted && sourceSymbolTrackable) {
@@ -14724,6 +15081,20 @@ var MmtpRouter = class {
14724
15081
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName) {
14725
15082
  if (ownerPacketId == null) return;
14726
15083
  if (this.#classifyPacketId(ownerPacketId) === null) return;
15084
+ const ssIdSeqOffset = this.#ssIdSeqOffsetByStream.get(
15085
+ this.#mediaStreamKey(ownerPacketId, catalogTrackName)
15086
+ );
15087
+ if (ssIdSeqOffset !== void 0) {
15088
+ result = {
15089
+ ...result,
15090
+ symbols: result.symbols.map((sym) => {
15091
+ const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
15092
+ if (wire === sym.packetSequenceNumber) return sym;
15093
+ this.#restampedRecoveredSeqs++;
15094
+ return { ...sym, packetSequenceNumber: wire };
15095
+ })
15096
+ };
15097
+ }
14727
15098
  this.#stream(ownerPacketId, catalogTrackName).duplicates.advance(blockId);
14728
15099
  const deliveryProvenance = this.#fecManager?.blockDeliveryProvenance?.(
14729
15100
  blockId,
@@ -15209,186 +15580,6 @@ var MmtpRouter = class {
15209
15580
  }
15210
15581
  };
15211
15582
 
15212
- // node_modules/@blockcast/mmt-transport/dist/types.js
15213
- var MoqFecAlgorithm;
15214
- (function(MoqFecAlgorithm2) {
15215
- MoqFecAlgorithm2[MoqFecAlgorithm2["None"] = 0] = "None";
15216
- MoqFecAlgorithm2[MoqFecAlgorithm2["Xor"] = 1] = "Xor";
15217
- MoqFecAlgorithm2[MoqFecAlgorithm2["RaptorQ"] = 2] = "RaptorQ";
15218
- })(MoqFecAlgorithm || (MoqFecAlgorithm = {}));
15219
-
15220
- // node_modules/@blockcast/mmt-base/dist/mmtp.js
15221
- var MPU_HEADER_SIZE2 = 8;
15222
- var MPU_LENGTH_FIELD_SIZE2 = 2;
15223
- var MPU_HEADER_REMAINDER_SIZE2 = MPU_HEADER_SIZE2 - MPU_LENGTH_FIELD_SIZE2;
15224
- var MMTP_SIGNALING_PACKET_ID2 = 0;
15225
- var MMTP_PACKET_ID_MAX2 = 65535;
15226
-
15227
- // node_modules/@blockcast/mmt-base/dist/net-constants.js
15228
- var DEFAULT_AMT_RELAY_PORT2 = 2268;
15229
-
15230
- // node_modules/@blockcast/mmt-base/dist/ntp-short.js
15231
- var NTP_SHORT_BITS2 = 32;
15232
- var NTP_SHORT_MODULUS2 = 2 ** NTP_SHORT_BITS2;
15233
- var NTP_SHORT_HALF_RANGE2 = 2 ** (NTP_SHORT_BITS2 - 1);
15234
- function isNtpShort(value) {
15235
- return Number.isInteger(value) && value >= 0 && value < NTP_SHORT_MODULUS2;
15236
- }
15237
- function compareNtpShort(a, b) {
15238
- if (!isNtpShort(a) || !isNtpShort(b)) {
15239
- throw new RangeError(`NTP-short values must be integers in [0, 2^${NTP_SHORT_BITS2}), got ${String(a)} and ${String(b)}`);
15240
- }
15241
- if (a === b)
15242
- return "equal";
15243
- const forward = (a - b + NTP_SHORT_MODULUS2) % NTP_SHORT_MODULUS2;
15244
- if (forward < NTP_SHORT_HALF_RANGE2)
15245
- return "after";
15246
- if (forward > NTP_SHORT_HALF_RANGE2)
15247
- return "before";
15248
- return "unordered";
15249
- }
15250
-
15251
- // node_modules/@blockcast/mmt-base/dist/fec-block-profile.js
15252
- var FEC_BLOCK_PROFILES2 = Object.freeze([
15253
- "iso-ssbg1-v1"
15254
- ]);
15255
-
15256
- // node_modules/@blockcast/mmt-transport/dist/driad-discovery.js
15257
- var DRIADDiscovery = class {
15258
- cache = /* @__PURE__ */ new Map();
15259
- cacheExpiry = 3e5;
15260
- // 5 minutes
15261
- /**
15262
- * Discover AMT relays for a multicast source address (RFC 8777)
15263
- *
15264
- * @param source - The multicast source IP address (NOT the group!)
15265
- * @returns Array of discovered AMT relays that can tunnel traffic from this source
15266
- */
15267
- async discoverRelays(source) {
15268
- const cached = this.cache.get(source);
15269
- if (cached) {
15270
- return cached;
15271
- }
15272
- try {
15273
- const reversedSource = source.split(".").reverse().join(".");
15274
- const queryDomain = `${reversedSource}.amt.in-addr.arpa`;
15275
- console.log(`[DRIAD] Discovering relays for source ${source} via ${queryDomain}`);
15276
- const relays = await this.queryDRIADProxy(source);
15277
- if (relays.length > 0) {
15278
- this.cache.set(source, relays);
15279
- setTimeout(() => this.cache.delete(source), this.cacheExpiry);
15280
- }
15281
- return relays;
15282
- } catch (error) {
15283
- console.warn(`[DRIAD] Discovery failed for source ${source}:`, error);
15284
- return [];
15285
- }
15286
- }
15287
- /**
15288
- * Query DRIAD proxy service (browser-compatible)
15289
- */
15290
- async queryDRIADProxy(source) {
15291
- const proxyEndpoints = [
15292
- "https://driad.amt.net/api/v1/relays",
15293
- "https://multicast-gateway.cloudflare.com/driad"
15294
- ];
15295
- for (const endpoint of proxyEndpoints) {
15296
- try {
15297
- const response = await fetch(`${endpoint}?source=${encodeURIComponent(source)}`, {
15298
- method: "GET",
15299
- headers: { Accept: "application/json" },
15300
- signal: AbortSignal.timeout(5e3)
15301
- });
15302
- if (response.ok) {
15303
- const data = await response.json();
15304
- return data.relays || [];
15305
- }
15306
- } catch {
15307
- }
15308
- }
15309
- const dohRelay = await this.queryDNSOverHTTPS(source);
15310
- if (dohRelay) {
15311
- return [dohRelay];
15312
- }
15313
- return [];
15314
- }
15315
- /**
15316
- * Query DNS-over-HTTPS for DRIAD relay based on source address (RFC 8777)
15317
- */
15318
- async queryDNSOverHTTPS(source) {
15319
- try {
15320
- const reversedSource = source.split(".").reverse().join(".");
15321
- const queryName = `${reversedSource}.amt.in-addr.arpa`;
15322
- const dohUrl = `https://cloudflare-dns.com/dns-query?name=${queryName}&type=A`;
15323
- const response = await fetch(dohUrl, {
15324
- headers: { Accept: "application/dns-json" },
15325
- signal: AbortSignal.timeout(3e3)
15326
- });
15327
- if (!response.ok) {
15328
- return null;
15329
- }
15330
- const result = await response.json();
15331
- if (result.Answer && result.Answer.length > 0) {
15332
- return {
15333
- host: result.Answer[0].data,
15334
- port: DEFAULT_AMT_RELAY_PORT2,
15335
- priority: 10,
15336
- weight: 100,
15337
- asn: 0
15338
- };
15339
- }
15340
- return null;
15341
- } catch (error) {
15342
- console.warn("[DRIAD] DNS-over-HTTPS query failed:", error);
15343
- return null;
15344
- }
15345
- }
15346
- /**
15347
- * Select best relay based on RTT measurements
15348
- */
15349
- async selectBestRelay(relays) {
15350
- if (relays.length === 0)
15351
- return null;
15352
- const measured = await Promise.all(relays.map(async (relay) => {
15353
- const rtt = await this.measureRTT(relay.host, relay.port);
15354
- return { ...relay, rtt };
15355
- }));
15356
- measured.sort((a, b) => {
15357
- if (a.priority !== b.priority)
15358
- return a.priority - b.priority;
15359
- return (a.rtt || Infinity) - (b.rtt || Infinity);
15360
- });
15361
- console.log(`[DRIAD] Selected relay: ${measured[0].host} (RTT: ${measured[0].rtt}ms)`);
15362
- return measured[0];
15363
- }
15364
- async measureRTT(host, _port) {
15365
- const start = performance.now();
15366
- try {
15367
- await fetch(`https://${host}/health`, {
15368
- method: "HEAD",
15369
- signal: AbortSignal.timeout(2e3),
15370
- mode: "no-cors"
15371
- });
15372
- return performance.now() - start;
15373
- } catch {
15374
- return Infinity;
15375
- }
15376
- }
15377
- /**
15378
- * Clear the relay cache
15379
- */
15380
- clearCache() {
15381
- this.cache.clear();
15382
- }
15383
- /**
15384
- * Get cached relays for a source address
15385
- */
15386
- getCached(source) {
15387
- return this.cache.get(source);
15388
- }
15389
- };
15390
- var driadDiscovery = new DRIADDiscovery();
15391
-
15392
15583
  // node_modules/@blockcast/mmt-transport/dist/multicast-tier.js
15393
15584
  function endpointKey(endpoint) {
15394
15585
  return `${endpoint.sourceAddress ?? ""}|${endpoint.groupAddress}|${endpoint.port}`;
@@ -15519,8 +15710,8 @@ var AdaptiveBitrateController = class {
15519
15710
  /**
15520
15711
  * Update FEC statistics for ABR decisions
15521
15712
  *
15522
- * Per draft-ramadan-moq-fec-00, ABR should use the effective loss rate
15523
- * (after FEC recovery) rather than raw transport loss rate.
15713
+ * ABR uses the effective loss rate (after FEC recovery) rather than the
15714
+ * raw transport loss rate.
15524
15715
  *
15525
15716
  * @param stats - FEC statistics from the FEC decoder
15526
15717
  */
@@ -15596,6 +15787,45 @@ var AdaptiveBitrateController = class {
15596
15787
  }
15597
15788
  };
15598
15789
 
15790
+ // node_modules/@blockcast/mmt-base/dist/mmtp.js
15791
+ var MPU_HEADER_SIZE2 = 8;
15792
+ var MPU_LENGTH_FIELD_SIZE2 = 2;
15793
+ var MPU_HEADER_REMAINDER_SIZE2 = MPU_HEADER_SIZE2 - MPU_LENGTH_FIELD_SIZE2;
15794
+ var MMTP_SIGNALING_PACKET_ID2 = 0;
15795
+ var MMTP_PACKET_ID_MAX2 = 65535;
15796
+
15797
+ // node_modules/@blockcast/mmt-base/dist/net-constants.js
15798
+ var DEFAULT_AMT_RELAY_PORT2 = 2268;
15799
+
15800
+ // node_modules/@blockcast/mmt-base/dist/ntp-short.js
15801
+ var NTP_SHORT_BITS2 = 32;
15802
+ var NTP_SHORT_MODULUS2 = 2 ** NTP_SHORT_BITS2;
15803
+ var NTP_SHORT_HALF_RANGE2 = 2 ** (NTP_SHORT_BITS2 - 1);
15804
+ function isNtpShort(value) {
15805
+ return Number.isInteger(value) && value >= 0 && value < NTP_SHORT_MODULUS2;
15806
+ }
15807
+ function compareNtpShort(a, b) {
15808
+ if (!isNtpShort(a) || !isNtpShort(b)) {
15809
+ throw new RangeError(`NTP-short values must be integers in [0, 2^${NTP_SHORT_BITS2}), got ${String(a)} and ${String(b)}`);
15810
+ }
15811
+ if (a === b)
15812
+ return "equal";
15813
+ const forward = (a - b + NTP_SHORT_MODULUS2) % NTP_SHORT_MODULUS2;
15814
+ if (forward < NTP_SHORT_HALF_RANGE2)
15815
+ return "after";
15816
+ if (forward > NTP_SHORT_HALF_RANGE2)
15817
+ return "before";
15818
+ return "unordered";
15819
+ }
15820
+
15821
+ // node_modules/@blockcast/mmt-base/dist/fec-block-profile.js
15822
+ var FEC_BLOCK_PROFILES2 = Object.freeze([
15823
+ "iso-ssbg1-v1"
15824
+ ]);
15825
+
15826
+ // node_modules/@blockcast/mmt-base/dist/catalog-fec-source.js
15827
+ var ALL_ROLES2 = Object.freeze(["video", "audio"]);
15828
+
15599
15829
  // node_modules/@blockcast/mmt-transport/dist/multicast-orchestrator.js
15600
15830
  var DEFAULT_DWELL_MS = 3e3;
15601
15831
  var DEFAULT_JOIN_DEADLINE_MS = 5e3;
@@ -15833,8 +16063,23 @@ function toWindowMulticastSubscribeConfig(input) {
15833
16063
  consume: "bytes",
15834
16064
  ...input.packetIds?.length ? { packetIds: [...input.packetIds] } : {}
15835
16065
  };
16066
+ if (input.atsc3) {
16067
+ const { frequency, plpId, serviceId } = input.atsc3;
16068
+ if (!Number.isInteger(frequency) || frequency < 1) {
16069
+ throw new TypeError(`ATSC3 tuning requires a positive integer frequency in kHz, got ${String(frequency)}`);
16070
+ }
16071
+ return {
16072
+ ...base,
16073
+ origin: "tuner",
16074
+ standard: "atsc3",
16075
+ frequency,
16076
+ ...plpId !== void 0 ? { plpId } : {},
16077
+ ...serviceId !== void 0 ? { serviceId } : {}
16078
+ };
16079
+ }
15836
16080
  const relay = input.amtRelay?.trim();
15837
- const wantsAmt = input.mode === "tunnel" || input.mode !== "native" && relay !== void 0 && relay !== "";
16081
+ const driad = !relay && input.amtDiscovery === "driad";
16082
+ const wantsAmt = input.mode === "tunnel" || input.mode !== "native" && (relay !== void 0 && relay !== "" || driad);
15838
16083
  if (!wantsAmt) {
15839
16084
  const native = {
15840
16085
  ...base,
@@ -15844,6 +16089,20 @@ function toWindowMulticastSubscribeConfig(input) {
15844
16089
  return native;
15845
16090
  }
15846
16091
  const relayPort = input.amtRelayPort;
16092
+ if (driad) {
16093
+ if (!base.source)
16094
+ throw new TypeError("AMT DRIAD discovery requires a source address");
16095
+ if (relayPort !== void 0 && !isPositivePort(relayPort)) {
16096
+ throw new TypeError("AMT DRIAD discovery requires a valid relay port when one is given");
16097
+ }
16098
+ return {
16099
+ ...base,
16100
+ source: base.source,
16101
+ origin: "amt",
16102
+ discovery: "driad",
16103
+ ...relayPort !== void 0 ? { relayPort } : {}
16104
+ };
16105
+ }
15847
16106
  if (!relay || relayPort === void 0 || !isPositivePort(relayPort)) {
15848
16107
  throw new TypeError("AMT requires a resolved relay and a valid relay port");
15849
16108
  }
@@ -15887,7 +16146,8 @@ function normalizeMulticastEndpoint(endpoint) {
15887
16146
  port: endpoint.port,
15888
16147
  ...endpoint.mode ? { mode: endpoint.mode } : {},
15889
16148
  ...amtRelay ? { amtRelay } : {},
15890
- ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
16149
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {},
16150
+ ...endpoint.amtDiscovery === "driad" ? { amtDiscovery: "driad" } : {}
15891
16151
  };
15892
16152
  }
15893
16153
  function multicastEndpointKey(endpoint) {
@@ -15900,7 +16160,9 @@ function multicastEndpointKey(endpoint) {
15900
16160
  normalized.port,
15901
16161
  normalized.mode ?? "auto",
15902
16162
  normalized.amtRelay ?? "",
15903
- normalized.amtRelayPort ?? ""
16163
+ normalized.amtRelayPort ?? "",
16164
+ // A DRIAD join is a different gateway subscription from a native one.
16165
+ ...normalized.amtDiscovery ? [normalized.amtDiscovery] : []
15904
16166
  ]);
15905
16167
  }
15906
16168
  function isMulticastTrackPacketId(value) {
@@ -15940,7 +16202,8 @@ var MulticastSubscriptionPool = class {
15940
16202
  port: config.port,
15941
16203
  mode: config.mode,
15942
16204
  amtRelay: config.amtRelay,
15943
- amtRelayPort: config.amtRelayPort
16205
+ amtRelayPort: config.amtRelayPort,
16206
+ amtDiscovery: config.amtDiscovery
15944
16207
  });
15945
16208
  if (!endpoint)
15946
16209
  throw new Error("Invalid multicast endpoint");
@@ -16006,7 +16269,8 @@ var MulticastSubscriptionPool = class {
16006
16269
  port: endpoint.port,
16007
16270
  ...endpoint.mode ? { mode: endpoint.mode } : {},
16008
16271
  ...endpoint.amtRelay ? { amtRelay: endpoint.amtRelay } : {},
16009
- ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
16272
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {},
16273
+ ...endpoint.amtDiscovery ? { amtDiscovery: endpoint.amtDiscovery } : {}
16010
16274
  }));
16011
16275
  const consumers = /* @__PURE__ */ new Map();
16012
16276
  let entry;
@@ -16086,7 +16350,6 @@ var TransportManager = class {
16086
16350
  };
16087
16351
  capabilities = null;
16088
16352
  subscription = null;
16089
- driad = new DRIADDiscovery();
16090
16353
  /** Built by `connect()` from the caller's ladder; there is no built-in one. */
16091
16354
  abr = null;
16092
16355
  multicastOrchestrator = null;
@@ -16136,8 +16399,8 @@ var TransportManager = class {
16136
16399
  nativeIGMP: hasGatewayBytes,
16137
16400
  directSockets: typeof win?.UDPSocket !== "undefined",
16138
16401
  amt: false,
16139
- driad: true,
16140
- // DRIAD uses HTTP proxy, always available
16402
+ driad: hasGatewayBytes,
16403
+ // the gateway runs RFC 8777 discovery
16141
16404
  fecDecode: false
16142
16405
  };
16143
16406
  console.log("[Transport] Capabilities:", this.capabilities);
@@ -16148,7 +16411,7 @@ var TransportManager = class {
16148
16411
  *
16149
16412
  * Promotion hierarchy:
16150
16413
  * 1. window.multicast gateway bytes
16151
- * 2. AMT proxy (specified or discovered via DRIAD)
16414
+ * 2. AMT: a configured relay via the AMT proxy, else gateway DRIAD discovery
16152
16415
  * 3. MOQ WebTransport (final fallback)
16153
16416
  *
16154
16417
  * The ABR ladder (`abrLadder`) and initial rendition (`initialQuality`)
@@ -16242,7 +16505,7 @@ var TransportManager = class {
16242
16505
  /**
16243
16506
  * Connect via the lowercase window.multicast bytes gateway.
16244
16507
  */
16245
- async connectWindowMulticast(config, generation) {
16508
+ async connectWindowMulticast(config, generation, mode = "multicast") {
16246
16509
  try {
16247
16510
  const gateway = this.getWindowMulticastGateway();
16248
16511
  if (typeof gateway?.subscribe !== "function")
@@ -16277,7 +16540,7 @@ var TransportManager = class {
16277
16540
  }
16278
16541
  };
16279
16542
  this.state = {
16280
- mode: "multicast",
16543
+ mode,
16281
16544
  connected: true,
16282
16545
  group: config.group,
16283
16546
  source: config.source,
@@ -16295,29 +16558,19 @@ var TransportManager = class {
16295
16558
  }
16296
16559
  }
16297
16560
  /**
16298
- * Connect via AMT proxy (with optional DRIAD discovery)
16561
+ * Connect via AMT: a configured relay goes through the AMT proxy; with no
16562
+ * relay, the window.multicast gateway discovers one per RFC 8777 (DRIAD).
16299
16563
  */
16300
16564
  async connectAmt(config, generation) {
16301
16565
  try {
16302
- let amtRelay = config.amtRelay;
16303
- if (!amtRelay && config.driadEnabled !== false && config.source) {
16304
- console.log(`[Transport] Discovering AMT relay via DRIAD for source ${config.source}...`);
16305
- const relays = await this.driad.discoverRelays(config.source);
16306
- if (generation !== this.connectionGeneration)
16307
- return false;
16308
- const bestRelay = await this.driad.selectBestRelay(relays);
16309
- if (generation !== this.connectionGeneration)
16310
- return false;
16311
- if (bestRelay) {
16312
- amtRelay = bestRelay.host;
16313
- this.state.amtRelay = amtRelay;
16314
- }
16315
- }
16316
- if (!amtRelay) {
16566
+ if (config.amtRelay)
16567
+ return await this.connectAmtProxy(config, config.amtRelay, generation);
16568
+ if (config.driadEnabled === false || !config.source || config.mode === "native") {
16317
16569
  console.warn("[Transport] No AMT relay available (DRIAD requires source address for SSM)");
16318
16570
  return false;
16319
16571
  }
16320
- return await this.connectAmtProxy(config, amtRelay, generation);
16572
+ console.log(`[Transport] Asking the gateway for a DRIAD relay for source ${config.source}...`);
16573
+ return await this.connectWindowMulticast({ ...config, amtDiscovery: "driad" }, generation, "amt");
16321
16574
  } catch (error) {
16322
16575
  console.warn("[Transport] AMT connection failed:", error);
16323
16576
  return false;
@@ -16548,7 +16801,6 @@ var AMTGatewayManager = class {
16548
16801
  subscriptions = /* @__PURE__ */ new Map();
16549
16802
  messageHandler;
16550
16803
  pendingPackets = /* @__PURE__ */ new Map();
16551
- driad = new DRIADDiscovery();
16552
16804
  constructor() {
16553
16805
  this.messageHandler = (event) => {
16554
16806
  const data = event.data;
@@ -16579,26 +16831,12 @@ var AMTGatewayManager = class {
16579
16831
  return keyStr;
16580
16832
  }
16581
16833
  try {
16582
- let relayAddress;
16583
- let discoveryMethod;
16834
+ const relayAddress = config.relayAddress;
16584
16835
  const relayPort = config.relayPort || DEFAULT_AMT_RELAY_PORT2;
16585
- if (config.relayAddress) {
16586
- relayAddress = config.relayAddress;
16587
- discoveryMethod = "manual";
16588
- console.log(`[AMT] Using configured relay ${relayAddress}:${relayPort}`);
16589
- } else if (key.source) {
16590
- console.log(`[AMT] No relay configured, discovering via DRIAD for source ${key.source}...`);
16591
- const relays = await this.driad.discoverRelays(key.source);
16592
- const bestRelay = await this.driad.selectBestRelay(relays);
16593
- if (!bestRelay) {
16594
- throw new Error(`AMT relay discovery failed for source ${key.source}. Please specify a relay address in the subscription configuration.`);
16595
- }
16596
- relayAddress = bestRelay.host;
16597
- discoveryMethod = "driad";
16598
- console.log(`[AMT] Discovered relay via DRIAD: ${relayAddress}:${relayPort}`);
16599
- } else {
16600
- throw new Error(`AMT relay discovery requires a source address for SSM (RFC 8777). Please specify either a relay address or source address.`);
16836
+ if (!relayAddress) {
16837
+ 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".`);
16601
16838
  }
16839
+ console.log(`[AMT] Using configured relay ${relayAddress}:${relayPort}`);
16602
16840
  const subscriptionId = keyStr;
16603
16841
  this.pendingPackets.set(subscriptionId, []);
16604
16842
  const subscription = {
@@ -16609,7 +16847,7 @@ var AMTGatewayManager = class {
16609
16847
  relay: {
16610
16848
  address: relayAddress,
16611
16849
  port: relayPort,
16612
- discoveryMethod,
16850
+ discoveryMethod: "manual",
16613
16851
  discoveredAt: Date.now()
16614
16852
  }
16615
16853
  };
@@ -16765,7 +17003,7 @@ function sameIds(a, b) {
16765
17003
  for (const id of a) if (!b.has(id)) return false;
16766
17004
  return true;
16767
17005
  }
16768
- var MulticastTransport = class _MulticastTransport {
17006
+ var MulticastTransport = class {
16769
17007
  #onPacket;
16770
17008
  #subscription = null;
16771
17009
  #packetListener = null;
@@ -16837,8 +17075,11 @@ var MulticastTransport = class _MulticastTransport {
16837
17075
  // droppedPacketIds.
16838
17076
  #unadvertisedPacketIds = /* @__PURE__ */ new Set();
16839
17077
  #joinGeneration = 0;
16840
- constructor(onPacket) {
17078
+ // The provider to subscribe through; window.multicast when unset.
17079
+ #gateway;
17080
+ constructor(onPacket, options = {}) {
16841
17081
  this.#onPacket = onPacket;
17082
+ this.#gateway = options.gateway;
16842
17083
  }
16843
17084
  static isAvailable() {
16844
17085
  return hasMulticastGateway();
@@ -16848,7 +17089,8 @@ var MulticastTransport = class _MulticastTransport {
16848
17089
  this.#releaseSubscription();
16849
17090
  this.#dataPlaneLive = false;
16850
17091
  if (this.#disposed) return this.#declined(generation, "disposed");
16851
- if (!_MulticastTransport.isAvailable()) {
17092
+ const gateway = this.#gateway ?? getMulticastGlobals().multicast;
17093
+ if (typeof gateway?.subscribe !== "function") {
16852
17094
  console.warn("[MulticastTransport] Multicast API not available");
16853
17095
  return this.#declined(generation, "unavailable");
16854
17096
  }
@@ -16865,11 +17107,13 @@ var MulticastTransport = class _MulticastTransport {
16865
17107
  mode: config.mode,
16866
17108
  amtRelay: config.amtRelay,
16867
17109
  amtRelayPort: config.amtRelayPort,
17110
+ amtDiscovery: config.amtDiscovery,
16868
17111
  packetIds: config.packetIds,
16869
- tracks: config.tracks
17112
+ tracks: config.tracks,
17113
+ atsc3: config.atsc3
16870
17114
  });
16871
17115
  failure = "provider-rejected";
16872
- const subscription = await getMulticastGlobals().multicast.subscribe(subscribeConfig);
17116
+ const subscription = await gateway.subscribe(subscribeConfig);
16873
17117
  failure = "invalid-subscription";
16874
17118
  console.log(`[MulticastTransport] window.multicast.subscribe returned:`, !!subscription);
16875
17119
  if (this.#disposed || generation !== this.#joinGeneration) {
@@ -17456,16 +17700,6 @@ var MulticastTransport = class _MulticastTransport {
17456
17700
  // src/multicast-manager.ts
17457
17701
  import { deriveFecInterleaveDepth as deriveFecInterleaveDepth3, FecBlockMapper as FecBlockMapper2 } from "@blockcast/mmt-fec";
17458
17702
 
17459
- // src/multicast-auth-catalog.ts
17460
- var BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
17461
- var BASE64URL_DECODE_TABLE = (() => {
17462
- const table = new Int8Array(128).fill(-1);
17463
- for (let i = 0; i < BASE64URL_ALPHABET.length; i++) {
17464
- table[BASE64URL_ALPHABET.charCodeAt(i)] = i;
17465
- }
17466
- return table;
17467
- })();
17468
-
17469
17703
  // src/repair-layers.ts
17470
17704
  var RepairContractError = class extends Error {
17471
17705
  constructor(code, path, message) {
@@ -17539,7 +17773,7 @@ function isFecCatalogGeometry(obj) {
17539
17773
  const o = obj;
17540
17774
  const algorithm = o["algorithm"];
17541
17775
  const symbolSize = o["symbolSize"];
17542
- 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;
17776
+ 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;
17543
17777
  }
17544
17778
  function isFecCatalogConfig(obj) {
17545
17779
  if (!isFecCatalogGeometry(obj)) return false;
@@ -17573,10 +17807,21 @@ function isoSpanUnavailable(fec, path, declaresFecInstance) {
17573
17807
  });
17574
17808
  }
17575
17809
  function catalogFecUnavailable(fec, fecPath) {
17810
+ if (catalogFecAvailable(fec)) return void 0;
17576
17811
  const block = recordOf2(fec);
17577
- if (block === void 0) return void 0;
17812
+ if (fecAlgorithmUnimplemented(block["algorithm"])) {
17813
+ return Object.freeze({
17814
+ code: "track_fec_algorithm_unimplemented",
17815
+ path: `${fecPath}.algorithm`,
17816
+ message: `algorithm ${JSON.stringify(block["algorithm"])} is not implemented: the track plays without FEC`
17817
+ });
17818
+ }
17578
17819
  const declaresFecInstance = block["algorithm"] !== "none";
17579
- return blockProfileUnavailable(block["blockProfile"], `${fecPath}.blockProfile`, declaresFecInstance) ?? isoSpanUnavailable(block, `${fecPath}.interleaveDepthMs`, declaresFecInstance);
17820
+ const reason = blockProfileUnavailable(block["blockProfile"], `${fecPath}.blockProfile`, declaresFecInstance) ?? isoSpanUnavailable(block, `${fecPath}.interleaveDepthMs`, declaresFecInstance);
17821
+ if (reason === void 0) {
17822
+ throw new Error(`catalogFecUnavailable: ${fecPath} is unavailable but no reason applies (rule drift)`);
17823
+ }
17824
+ return reason;
17580
17825
  }
17581
17826
 
17582
17827
  // src/multicast-manager.ts
@@ -17613,8 +17858,10 @@ function newBlockPolicyStats(packetId, catalogTrackName, epoch) {
17613
17858
  repairsSkippedRttUnmeasured: 0,
17614
17859
  repairsSkippedRttExceedsBudget: 0,
17615
17860
  repairsSkippedPresentationDelayUnavailable: 0,
17861
+ repairsSkippedRangeNoAnchor: 0,
17616
17862
  lastRepairSkip: null,
17617
17863
  keyframeRepairFetchesSent: 0,
17864
+ rangeRepairFetchesSent: 0,
17618
17865
  keyframeBudgetHolds: 0,
17619
17866
  keyframeBudgetHoldMs: 0,
17620
17867
  deltaBlocksFailed: 0,
@@ -17693,6 +17940,12 @@ var REPAIR_PRIORITY_REASONS = /* @__PURE__ */ new Set([
17693
17940
  "repair-priority-absent",
17694
17941
  "repair-priority-invalid"
17695
17942
  ]);
17943
+ var REPAIR_SKIP_REASONS = /* @__PURE__ */ new Set([
17944
+ "rtt-unmeasured",
17945
+ "rtt-exceeds-budget",
17946
+ "presentation-delay-unavailable"
17947
+ ]);
17948
+ var REPAIR_DEADLINE_BOUNDS = /* @__PURE__ */ new Set(["wait", "presentation", "keyframe", "retention"]);
17696
17949
  var GAP_REASONS = {
17697
17950
  "rap-lost": "stall",
17698
17951
  "rap-unknown": "stall",
@@ -17715,6 +17968,9 @@ function isSymbolCounts(value) {
17715
17968
  function isNullableNonNegative(value) {
17716
17969
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
17717
17970
  }
17971
+ function isFiniteNumber(value) {
17972
+ return typeof value === "number" && Number.isFinite(value);
17973
+ }
17718
17974
  function isRepairLifecycleEvent(value) {
17719
17975
  if (!isRecord(value) || value["version"] !== 2) return false;
17720
17976
  const block = value["block"];
@@ -17732,6 +17988,20 @@ function isRepairLifecycleEvent(value) {
17732
17988
  case "repair-preempted":
17733
17989
  case "repair-deferred":
17734
17990
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
17991
+ case "repair-sent":
17992
+ return hasExactKeys(value, [
17993
+ "version",
17994
+ "type",
17995
+ "block",
17996
+ "priority",
17997
+ "rttMs",
17998
+ "budgetMs",
17999
+ "delayMs",
18000
+ "blockAgeMs",
18001
+ "bound"
18002
+ ]) && 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"]);
18003
+ case "repair-skipped":
18004
+ return hasExactKeys(value, ["version", "type", "block", "reason", "rttMs", "budgetMs"]) && isRepairBlockIdentity(block) && REPAIR_SKIP_REASONS.has(value["reason"]) && isNullableNonNegative(value["rttMs"]) && isFiniteNumber(value["budgetMs"]);
17735
18005
  case "repair-priority": {
17736
18006
  const blockClass = value["blockClass"];
17737
18007
  const action = value["action"];
@@ -17911,6 +18181,9 @@ var MulticastManager = class {
17911
18181
  #router;
17912
18182
  #hostMfuTimeoutMs;
17913
18183
  #transport;
18184
+ /** Live joinRepairEndpoints() releases → the repair owners they registered,
18185
+ * re-applied after configureMultiTrack() clears catalog-derived owners. */
18186
+ #repairReleases = /* @__PURE__ */ new Map();
17914
18187
  #reportedFecDiagnosticsFailure = false;
17915
18188
  // ── Stream-global FEC timing reduction ──
17916
18189
  //
@@ -18174,7 +18447,9 @@ var MulticastManager = class {
18174
18447
  catalogTrackName
18175
18448
  );
18176
18449
  this.#configureTrackMapper(packetId, config);
18177
- this.#router.setPacketIdType(packetId, trackType);
18450
+ if (this.#router.trackKindFor(packetId) !== trackType) {
18451
+ this.#router.setPacketIdType(packetId, trackType);
18452
+ }
18178
18453
  }
18179
18454
  /**
18180
18455
  * Stop routing a stream's symbols to its Worker decoder. Returns false when
@@ -18255,6 +18530,14 @@ var MulticastManager = class {
18255
18530
  );
18256
18531
  }
18257
18532
  }
18533
+ for (const [packetId, c] of this.#trackFecTiming) {
18534
+ if (c.deliveryWindowMs === void 0) continue;
18535
+ mfuTimeoutMs = Math.max(
18536
+ mfuTimeoutMs ?? 0,
18537
+ this.#fec.terminalRetentionMsForPacket(packetId) ?? 0,
18538
+ this.#hostMfuTimeoutMs ?? 0
18539
+ );
18540
+ }
18258
18541
  const failbackWindowMs = deliveryWindowMs === void 0 ? minimumFailbackWindowMs : Math.max(deliveryWindowMs, minimumFailbackWindowMs ?? 0);
18259
18542
  this.#transport.setFailbackWindowMs(failbackWindowMs ?? null);
18260
18543
  this.#router.setMfuTimeoutMs(mfuTimeoutMs ?? this.#hostMfuTimeoutMs);
@@ -18438,6 +18721,7 @@ var MulticastManager = class {
18438
18721
  setMfuTimeoutMs(ms) {
18439
18722
  this.#router.setMfuTimeoutMs(ms);
18440
18723
  this.#hostMfuTimeoutMs = this.#router.reassembler.timeoutMs;
18724
+ if (this.#trackFecTiming.size > 0) this.#applyStreamGlobalFecTiming();
18441
18725
  }
18442
18726
  setTrackCodec(packetId, codec) {
18443
18727
  this.#router.setTrackCodec(packetId, codec);
@@ -18558,11 +18842,80 @@ var MulticastManager = class {
18558
18842
  // through whatever the relay looks like, since dropping it would be the
18559
18843
  // worse behaviour.
18560
18844
  amtRelayPort: config.amtRelayPort ?? config.relayPort ?? (amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : void 0),
18845
+ amtDiscovery: config.amtDiscovery,
18561
18846
  packetIds: config.packetIds,
18562
18847
  tracks: catalogTracks?.map(({ name, packetId }) => ({ name, packetId }))
18563
18848
  };
18564
18849
  return ingress === void 0 ? this.#transport.join(transportConfig) : this.#transport.join(transportConfig, ingress);
18565
18850
  }
18851
+ /**
18852
+ * Join the selected rung's dedicated repair groups beside the media join
18853
+ * (pim #3898): one subscription per endpoint, through `provider` when given
18854
+ * (a `window.multicast`-shaped gateway or a subscribe callback), otherwise a
18855
+ * new MulticastTransport on `window.multicast`. Returns the call that
18856
+ * releases every one of them; dispose() releases them too.
18857
+ *
18858
+ * Packets go straight to the router with the endpoint's ingress, never
18859
+ * through feedPacket(): repair arriving on its own group is not media
18860
+ * liveness, so it must not hold off the media leg's failback watchdog. The
18861
+ * repair roles and owners are registered here; in-band owners stay the
18862
+ * caller's. Joining is best effort: a group that fails to join is logged
18863
+ * and leaves the media join as it was.
18864
+ */
18865
+ joinRepairEndpoints(endpoints, provider) {
18866
+ const releases = [];
18867
+ let released = false;
18868
+ const safely = (each) => {
18869
+ try {
18870
+ each();
18871
+ } catch (error) {
18872
+ console.warn("[MulticastManager] repair group release failed", error);
18873
+ }
18874
+ };
18875
+ const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners);
18876
+ this.#applyRepairOwners(repairOwners);
18877
+ for (const endpoint of endpoints) {
18878
+ const ingress = {
18879
+ tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId })))
18880
+ };
18881
+ const onPacket = (packet) => {
18882
+ if (!released) this.#router.feedPacket(packet, "multicast", void 0, ingress);
18883
+ };
18884
+ const fail = (error) => console.warn(`[MulticastManager] repair group ${endpoint.group}:${endpoint.port} not joined`, error);
18885
+ if (typeof provider === "function") {
18886
+ Promise.resolve().then(() => provider(endpoint, onPacket)).then((release2) => released ? safely(release2) : releases.push(release2), fail);
18887
+ continue;
18888
+ }
18889
+ const transport = new MulticastTransport((packet) => onPacket(packet), { gateway: provider });
18890
+ releases.push(() => transport.dispose());
18891
+ void transport.join({
18892
+ sourceAddress: endpoint.source,
18893
+ groupAddress: endpoint.group,
18894
+ port: endpoint.port,
18895
+ mode: endpoint.mode,
18896
+ amtRelay: endpoint.amtRelay,
18897
+ amtRelayPort: endpoint.amtRelayPort ?? (endpoint.amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : void 0),
18898
+ packetIds: endpoint.packetIds,
18899
+ tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId }))
18900
+ }).then((joined) => {
18901
+ if (!joined && !released) fail(transport.lastJoinOutcome);
18902
+ });
18903
+ }
18904
+ const release = () => {
18905
+ if (released) return;
18906
+ released = true;
18907
+ this.#repairReleases.delete(release);
18908
+ for (const each of releases.splice(0)) safely(each);
18909
+ };
18910
+ this.#repairReleases.set(release, repairOwners);
18911
+ return release;
18912
+ }
18913
+ #applyRepairOwners(owners) {
18914
+ for (const { packetId, ownerPacketId } of owners) {
18915
+ this.#router.setPacketIdRole(packetId, "repair");
18916
+ this.#router.setRepairPacketIdOwner(packetId, ownerPacketId);
18917
+ }
18918
+ }
18566
18919
  // ---------------------------------------------------------------------------
18567
18920
  // In-place rendition switch
18568
18921
  // ---------------------------------------------------------------------------
@@ -18838,7 +19191,7 @@ var MulticastManager = class {
18838
19191
  *
18839
19192
  * D-04: Validates completeness via validateSwitchingSet — throws if incomplete.
18840
19193
  * D-07: Applies per-track FEC configs (base+delta get decoders; repair does not).
18841
- * D-17: Builds altGroup → track-name index for getSwitchingSet().
19194
+ * D-17: Builds altGroup → track-name index for getSwitchingSet() (repair legs excluded).
18842
19195
  * D-26: Registers packetId → TrackRole on MmtpRouter for block-complete fanout.
18843
19196
  *
18844
19197
  * FEC availability is per track (draft-ramadan-moq-fec §5.1). A media track
@@ -18889,11 +19242,9 @@ var MulticastManager = class {
18889
19242
  }
18890
19243
  }
18891
19244
  const repairOwnerGroup = /* @__PURE__ */ new Map();
18892
- const repairOwnerAltGroup = /* @__PURE__ */ new Map();
18893
19245
  for (const track of catalog.tracks) {
18894
19246
  for (const repairName of repairNamesBySource.get(track.name) ?? []) {
18895
19247
  repairOwnerGroup.set(repairName, altGroupKey(track));
18896
- repairOwnerAltGroup.set(repairName, track.altGroup);
18897
19248
  }
18898
19249
  }
18899
19250
  const groupKeyFor = (track) => repairOwnerGroup.get(track.name) ?? altGroupKey(track);
@@ -18924,11 +19275,7 @@ var MulticastManager = class {
18924
19275
  for (const [groupKey, roles] of resolvedRolesByGroup) {
18925
19276
  if (!(hasSwitchingSetByGroup.get(groupKey) ?? false)) continue;
18926
19277
  const presentRoles = new Set(roles.filter((r) => r !== "single"));
18927
- const required = [
18928
- "base",
18929
- "delta",
18930
- "repair"
18931
- ];
19278
+ const required = ["base", "repair"];
18932
19279
  const missing = required.filter((r) => !presentRoles.has(r));
18933
19280
  if (missing.length > 0) {
18934
19281
  throw new Error(
@@ -18975,6 +19322,7 @@ var MulticastManager = class {
18975
19322
  this.#switchingSets.clear();
18976
19323
  this.#repairPacketIds.clear();
18977
19324
  this.#router.clearRepairPacketIdOwners();
19325
+ for (const owners of this.#repairReleases.values()) this.#applyRepairOwners(owners);
18978
19326
  const fecPacketIds = new Set([...fecDecoders.keys()].map((i) => catalog.tracks[i].packetId));
18979
19327
  for (const [packetId, catalogTrackName] of this.#multiTrackFecTracks) {
18980
19328
  if (fecPacketIds.has(packetId)) continue;
@@ -18995,11 +19343,10 @@ var MulticastManager = class {
18995
19343
  for (let i = 0; i < catalog.tracks.length; i++) {
18996
19344
  const track = catalog.tracks[i];
18997
19345
  const role = resolvedRoles[i];
18998
- const altGroup = repairOwnerAltGroup.has(track.name) ? repairOwnerAltGroup.get(track.name) : track.altGroup;
18999
- if (altGroup !== void 0) {
19000
- const existing = this.#switchingSets.get(altGroup) ?? [];
19346
+ if (role !== "repair" && track.altGroup !== void 0) {
19347
+ const existing = this.#switchingSets.get(track.altGroup) ?? [];
19001
19348
  existing.push(track.name);
19002
- this.#switchingSets.set(altGroup, existing);
19349
+ this.#switchingSets.set(track.altGroup, existing);
19003
19350
  }
19004
19351
  if (track.packetId !== void 0) {
19005
19352
  this.#router.setPacketIdRole(track.packetId, role);
@@ -19074,7 +19421,7 @@ var MulticastManager = class {
19074
19421
  #multiTrackFecTracks = /* @__PURE__ */ new Map();
19075
19422
  /**
19076
19423
  * Return the track names belonging to the given altGroup switching set.
19077
- * D-17: altGroup groups base+delta+repair into one switching set.
19424
+ * D-17: tracks with equal altGroup form one switching set; repair legs are in none.
19078
19425
  *
19079
19426
  * @param altGroup - The altGroup number to look up.
19080
19427
  * @returns Array of track names in that switching set (empty if none).
@@ -19102,6 +19449,19 @@ var MulticastManager = class {
19102
19449
  this.requestRepairForBlock(sbn, packetId, catalogTrackName, blockClass);
19103
19450
  };
19104
19451
  }
19452
+ /**
19453
+ * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
19454
+ * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
19455
+ * pending hole and reported here, and `closeIsoHoles` must be called for it
19456
+ * once its range FETCH ends (or none is sent).
19457
+ */
19458
+ onUndelimitedLoss(cb) {
19459
+ this.#fec.setUndelimitedLossHandler(cb);
19460
+ }
19461
+ /** End a pending hole's range repair: feed what no repair stated as spans. */
19462
+ closeIsoHoles(packetId, catalogTrackName, start, length) {
19463
+ this.#router.closeIsoHoles(packetId, catalogTrackName, start, length);
19464
+ }
19105
19465
  /**
19106
19466
  * Record a repair request whose SUBSCRIBER_PRIORITY the catalog could not
19107
19467
  * supply (draft-ramadan-moq-fec §11.4.5): sent without the parameter, or
@@ -19123,6 +19483,7 @@ var MulticastManager = class {
19123
19483
  stats.repairsSkipped++;
19124
19484
  if (reason === "rtt-unmeasured") stats.repairsSkippedRttUnmeasured++;
19125
19485
  else if (reason === "rtt-exceeds-budget") stats.repairsSkippedRttExceedsBudget++;
19486
+ else if (reason === "range-no-anchor") stats.repairsSkippedRangeNoAnchor++;
19126
19487
  else stats.repairsSkippedPresentationDelayUnavailable++;
19127
19488
  stats.lastRepairSkip = {
19128
19489
  reason,
@@ -19154,8 +19515,20 @@ var MulticastManager = class {
19154
19515
  stats.keyframeBudgetHoldMs += extensionMs;
19155
19516
  }
19156
19517
  /** Record a repair FETCH the scheduler admitted and sent. */
19157
- noteRepairFetchSent(priority, _sbn, packetId, catalogTrackName) {
19518
+ noteRepairFetchSent(priority, sbn, packetId, catalogTrackName, measurement) {
19158
19519
  if (priority === 0) this.#statsFor(packetId, catalogTrackName).keyframeRepairFetchesSent++;
19520
+ if (measurement.range) this.#statsFor(packetId, catalogTrackName).rangeRepairFetchesSent++;
19521
+ this.#emitRepairLifecycle({
19522
+ version: 2,
19523
+ type: "repair-sent",
19524
+ block: repairBlockIdentity(packetId, sbn, catalogTrackName),
19525
+ priority,
19526
+ rttMs: measurement.rttMs,
19527
+ budgetMs: measurement.budgetMs,
19528
+ delayMs: measurement.delayMs,
19529
+ blockAgeMs: measurement.blockAgeMs,
19530
+ bound: measurement.bound
19531
+ });
19159
19532
  }
19160
19533
  /**
19161
19534
  * Record a repair-scheduler decision about a delta block: preempted for
@@ -19306,6 +19679,7 @@ var MulticastManager = class {
19306
19679
  this.#trackResetObservers.clear();
19307
19680
  this.#repairLifecycleObservers.clear();
19308
19681
  this.#transport.dispose();
19682
+ for (const release of [...this.#repairReleases.keys()]) release();
19309
19683
  this.#router.dispose();
19310
19684
  this.#fec.dispose();
19311
19685
  }