@blockcast/mmt-container 2.2.0-main.3cc3ad1f4323 → 2.2.0-main.4298ac9d803a

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 (85) hide show
  1. package/dist/browser-runtime.js +1022 -162
  2. package/dist/browser-runtime.js.map +3 -3
  3. package/dist/carp-catalog.js.map +2 -2
  4. package/dist/catalog-fec-params.d.ts +1 -1
  5. package/dist/catalog-fec-params.d.ts.map +1 -1
  6. package/dist/catalog-fec-params.js +14 -1
  7. package/dist/catalog-fec-params.js.map +2 -2
  8. package/dist/catalog-network-source.js.map +2 -2
  9. package/dist/cmaf-block-assembler.js +92 -1
  10. package/dist/cmaf-block-assembler.js.map +2 -2
  11. package/dist/codec-utils.d.ts.map +1 -1
  12. package/dist/codec-utils.js +92 -1
  13. package/dist/codec-utils.js.map +2 -2
  14. package/dist/delivery-catalog.js.map +2 -2
  15. package/dist/delta-fallback-config.js +5 -1
  16. package/dist/delta-fallback-config.js.map +3 -3
  17. package/dist/fec-manager.d.ts +81 -14
  18. package/dist/fec-manager.d.ts.map +1 -1
  19. package/dist/fec-manager.js +329 -64
  20. package/dist/fec-manager.js.map +2 -2
  21. package/dist/fec-state.js +5 -1
  22. package/dist/fec-state.js.map +2 -2
  23. package/dist/fec-worker-setup.js.map +2 -2
  24. package/dist/held-layer-admission.js.map +2 -2
  25. package/dist/index.d.ts +2 -2
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +3 -1
  28. package/dist/index.js.map +2 -2
  29. package/dist/iso-block-locator.d.ts +39 -13
  30. package/dist/iso-block-locator.d.ts.map +1 -1
  31. package/dist/iso-block-locator.js +80 -25
  32. package/dist/iso-block-locator.js.map +2 -2
  33. package/dist/media-router.js.map +1 -1
  34. package/dist/mfu-reassembler.js.map +2 -2
  35. package/dist/mmtp-container-parser.d.ts +69 -10
  36. package/dist/mmtp-container-parser.d.ts.map +1 -1
  37. package/dist/mmtp-container-parser.js +226 -18
  38. package/dist/mmtp-container-parser.js.map +2 -2
  39. package/dist/mmtp-container-parser.no-modules.js +244 -21
  40. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  41. package/dist/mmtp-decode-pipeline.js +226 -18
  42. package/dist/mmtp-decode-pipeline.js.map +2 -2
  43. package/dist/mmtp-fec-session.js.map +2 -2
  44. package/dist/mmtp-router.d.ts +20 -9
  45. package/dist/mmtp-router.d.ts.map +1 -1
  46. package/dist/mmtp-router.js +409 -51
  47. package/dist/mmtp-router.js.map +3 -3
  48. package/dist/multicast-auth-catalog.js.map +2 -2
  49. package/dist/multicast-input.js.map +2 -2
  50. package/dist/multicast-manager.d.ts +26 -3
  51. package/dist/multicast-manager.d.ts.map +1 -1
  52. package/dist/multicast-manager.js +833 -135
  53. package/dist/multicast-manager.js.map +3 -3
  54. package/dist/multicast-transport.js +2 -2
  55. package/dist/multicast-transport.js.map +2 -2
  56. package/dist/multicast-unwrap.js.map +2 -2
  57. package/dist/no-modules.d.ts +1 -0
  58. package/dist/no-modules.d.ts.map +1 -1
  59. package/dist/no-modules.js +248 -22
  60. package/dist/no-modules.js.map +4 -4
  61. package/dist/repair-fetch.d.ts +38 -8
  62. package/dist/repair-fetch.d.ts.map +1 -1
  63. package/dist/repair-fetch.js +286 -27
  64. package/dist/repair-fetch.js.map +3 -3
  65. package/dist/repair-layer-subscriptions.js.map +2 -2
  66. package/dist/signaling.js.map +2 -2
  67. package/dist/timestamp-codec.js.map +2 -2
  68. package/dist/track-session.d.ts.map +1 -1
  69. package/dist/track-session.js +1 -0
  70. package/dist/track-session.js.map +2 -2
  71. package/dist/wasm-mfu-reassembler.js.map +2 -2
  72. package/dist/wasm-mmtp-container-parser.js +226 -18
  73. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  74. package/package.json +5 -5
  75. package/src/catalog-fec-params.ts +1 -0
  76. package/src/codec-utils.ts +121 -1
  77. package/src/fec-manager.ts +371 -39
  78. package/src/index.ts +4 -0
  79. package/src/iso-block-locator.ts +114 -31
  80. package/src/mmtp-container-parser.ts +257 -24
  81. package/src/mmtp-router.ts +287 -58
  82. package/src/multicast-manager.ts +136 -16
  83. package/src/no-modules.ts +3 -0
  84. package/src/repair-fetch.ts +366 -50
  85. package/src/track-session.ts +3 -0
@@ -851,6 +851,17 @@ function readRepairFecPayloadIdFields(mmtpPacket, parsedHeader) {
851
851
  dataOffset: off + REPAIR_FEC_PID_SIZE
852
852
  };
853
853
  }
854
+ function extractRepairFecPayloadId(mmtpPacket) {
855
+ const fields = readRepairFecPayloadIdFields(mmtpPacket);
856
+ if (!fields)
857
+ return null;
858
+ return {
859
+ ssStart: fields.ssStart,
860
+ rsbLength: fields.rsbLength,
861
+ rsId: fields.rsId,
862
+ ssbLength: fields.ssbLength
863
+ };
864
+ }
854
865
  function parseMoqRepairFrame(frame) {
855
866
  return moqRepairFrameFrom(frame, readRepairFecPayloadIdFields(frame));
856
867
  }
@@ -1786,13 +1797,25 @@ function fecCatalogTracks(catalog) {
1786
1797
  });
1787
1798
  return { tracks, pointers };
1788
1799
  }
1789
- function resolveFecBindings(catalog, receiver = RUNTIME_FEC_RECEIVER) {
1800
+ function runtimeView(catalog, receiver) {
1790
1801
  const { tracks, pointers } = fecCatalogTracks(catalog);
1791
1802
  const report = validateFecCatalog({ tracks }, receiver);
1792
1803
  const at2 = (path) => {
1793
1804
  const m = /^\/tracks\/(\d+)(.*)$/.exec(path);
1794
1805
  return m ? pointers[Number(m[1])] + m[2] : path;
1795
1806
  };
1807
+ return { tracks, pointers, report, at: at2 };
1808
+ }
1809
+ function runtimeFecCatalogReport(catalog, receiver = RUNTIME_FEC_RECEIVER) {
1810
+ const { report, at: at2 } = runtimeView(catalog, receiver);
1811
+ const issue = (i) => Object.freeze({ code: i.code, path: at2(i.path) });
1812
+ return Object.freeze({
1813
+ instances: Object.freeze(report.instances.map((i) => Object.freeze({ ...i, path: at2(i.path), issues: Object.freeze(i.issues.map(issue)) }))),
1814
+ issues: Object.freeze(report.issues.map(issue))
1815
+ });
1816
+ }
1817
+ function resolveFecBindings(catalog, receiver = RUNTIME_FEC_RECEIVER) {
1818
+ const { tracks, pointers, report, at: at2 } = runtimeView(catalog, receiver);
1796
1819
  const trackAt = (i) => recordOf(tracks[i]) ?? {};
1797
1820
  const nameAt = (i) => i === null ? void 0 : trackAt(i)["name"];
1798
1821
  const why = (i) => Object.freeze({
@@ -6088,9 +6111,10 @@ function isH264IntraSlice(nal) {
6088
6111
  const sliceType = readH264SliceType(nal);
6089
6112
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
6090
6113
  }
6114
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
6091
6115
  function readH264SliceType(nal) {
6092
6116
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
6093
- const rbsp = removeEmulationPrevention(nal.subarray(1));
6117
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
6094
6118
  const state = { bitOffset: 0 };
6095
6119
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
6096
6120
  return readUnsignedExpGolomb(rbsp, state);
@@ -6459,6 +6483,96 @@ if (void 0) {
6459
6483
  ]))).toBe(false);
6460
6484
  });
6461
6485
  });
6486
+ describe("readH264SliceType", () => {
6487
+ const wholeNalSliceType = (nal) => {
6488
+ if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
6489
+ const rbsp = removeEmulationPrevention(nal.subarray(1));
6490
+ const state = { bitOffset: 0 };
6491
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null;
6492
+ return readUnsignedExpGolomb(rbsp, state);
6493
+ };
6494
+ const hex3 = (text2) => Uint8Array.from(text2.match(/../g), (byte) => parseInt(byte, 16));
6495
+ const ue = (value) => {
6496
+ const code = (value + 1).toString(2);
6497
+ return "0".repeat(code.length - 1) + code;
6498
+ };
6499
+ const sliceNal = (bits) => {
6500
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, "0").match(/.{8}/g);
6501
+ const nal = [1];
6502
+ let zeros = 0;
6503
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
6504
+ if (zeros >= 2 && byte <= 3) {
6505
+ nal.push(3);
6506
+ zeros = 0;
6507
+ }
6508
+ nal.push(byte);
6509
+ zeros = byte === 0 ? zeros + 1 : 0;
6510
+ }
6511
+ return Uint8Array.from(nal);
6512
+ };
6513
+ const x264Slices = [
6514
+ ["64x48 P", hex3("419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176"), 5, false],
6515
+ ["64x48 B", hex3("419e414212fffeeade283707cb70f7"), 6, false],
6516
+ ["64x48 non-IDR I", hex3(
6517
+ "4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39a527e23eb34c8167fd"
6518
+ ), 7, true],
6519
+ ["1280x720 B, escape at byte 10", hex3(
6520
+ "01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e19b75d92170917306190f262fd58268702db2eff86a9651e48"
6521
+ ), 6, false],
6522
+ ["1280x720 P, escape at byte 15", hex3(
6523
+ "41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f02c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e85302da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3"
6524
+ ), 5, false],
6525
+ ["1280x720 B, escape at byte 22", hex3("01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352"), 6, false],
6526
+ ["7680x4320 IDR, first_mb_in_slice 97440", hex3(
6527
+ "650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9"
6528
+ ), null, true],
6529
+ ["7680x4320 P, first_mb_in_slice 32640", hex3(
6530
+ "410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020"
6531
+ ), 5, false],
6532
+ ["7680x4320 P, first_mb_in_slice 97440", hex3(
6533
+ "410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806"
6534
+ ), 5, false]
6535
+ ];
6536
+ const syntheticSlices = [
6537
+ ["an escape inside first_mb_in_slice", sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
6538
+ ["an escape between the fields", sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
6539
+ ["an escape inside slice_type", sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
6540
+ ["the longest fields, five escapes", sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
6541
+ ["the largest values", sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
6542
+ ["31 leading zeros in first_mb_in_slice", sliceNal(`${"0".repeat(31)}1`), null],
6543
+ ["31 leading zeros in slice_type", sliceNal(`1${"0".repeat(31)}1`), null],
6544
+ ["escapes running past the slice header", sliceNal(ue(0) + ue(5) + "0".repeat(400)), 5]
6545
+ ];
6546
+ test("reads the slice_type of real and synthetic slices", () => {
6547
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
6548
+ expect(readH264SliceType(nal), name).toBe(sliceType);
6549
+ }
6550
+ });
6551
+ test("matches the whole-NAL unescape at every truncation", () => {
6552
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
6553
+ for (let end = 0; end <= nal.length; end++) {
6554
+ const cut = nal.subarray(0, end);
6555
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut));
6556
+ }
6557
+ }
6558
+ });
6559
+ test("matches the whole-NAL unescape on zero-heavy NAL units", () => {
6560
+ const bytes = [0, 0, 0, 3, 1, 2, 128, 255];
6561
+ let seed = 1;
6562
+ const next = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) >>> 16;
6563
+ for (let i = 0; i < 5e3; i++) {
6564
+ const nal = new Uint8Array(2 + next() % 63);
6565
+ nal[0] = 65;
6566
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length];
6567
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal));
6568
+ }
6569
+ });
6570
+ test("classifies the x264 slices as keyframes or not", () => {
6571
+ for (const [name, nal, , keyframe] of x264Slices) {
6572
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe);
6573
+ }
6574
+ });
6575
+ });
6462
6576
  describe("avccToAnnexB", () => {
6463
6577
  test("converts with SPS/PPS on keyframe", () => {
6464
6578
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -8625,9 +8739,9 @@ async function openSubscription(rx, openedPromise, options, packetIds) {
8625
8739
  } catch (error) {
8626
8740
  throw new MulticastError("subscription-failed", "MulticastReceiver did not open", error);
8627
8741
  }
8628
- if (rx.integrityScheme !== INTEGRITY_SCHEME) {
8742
+ if (opened.integrityScheme !== INTEGRITY_SCHEME) {
8629
8743
  await rx.close();
8630
- throw unsupported(`integrity scheme ${String(rx.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
8744
+ throw unsupported(`integrity scheme ${String(opened.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
8631
8745
  }
8632
8746
  const events = new EventTarget();
8633
8747
  let state = "connected";
@@ -12435,6 +12549,7 @@ var TrackSession = class {
12435
12549
  this.#state = "idle";
12436
12550
  this.#subscription = null;
12437
12551
  this.#disarmFec();
12552
+ this.#unsuppress();
12438
12553
  }
12439
12554
  // -----------------------------------------------------------------------
12440
12555
  // Internal
@@ -12928,6 +13043,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
12928
13043
  this.#heldEvicted = 0;
12929
13044
  /** Pending holes (see `deferIncompleteGaps`): unstated, sources still held. */
12930
13045
  this.#holes = [];
13046
+ /** Holes the horizon passed while pending: sources held until closed. */
13047
+ this.#expired = [];
13048
+ /** Of `#expired`, those `takeExpiredHoles` has not handed out yet. */
13049
+ this.#newlyExpired = [];
13050
+ /**
13051
+ * Spans closed from expired holes: behind the horizon, so kept only for
13052
+ * `locate` while their sources are fed, until the next retirement.
13053
+ */
13054
+ this.#closedBehind = [];
12931
13055
  /**
12932
13056
  * Keep a gap that is missing a source as a pending hole rather than a span,
12933
13057
  * so a repair FETCHed for it (draft-ramadan-moq-fec §7.5) can still state
@@ -12951,6 +13075,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
12951
13075
  #newest;
12952
13076
  #newestSource;
12953
13077
  #holes;
13078
+ #expired;
13079
+ #newlyExpired;
13080
+ #closedBehind;
12954
13081
  static #checkedRetention(retentionBlocks) {
12955
13082
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
12956
13083
  throw new Error(
@@ -13020,17 +13147,29 @@ var IsoBlockLocator = class _IsoBlockLocator {
13020
13147
  }
13021
13148
  /** The known block or span containing `ssId`, with its ESI. */
13022
13149
  locate(ssId) {
13023
- for (let i = this.#blocks.length - 1; i >= 0; i--) {
13024
- const block = this.#blocks[i];
13025
- if (isoBlockContains(block.start, block.length, ssId)) {
13026
- return { block, esi: serial32Distance(block.start, ssId) };
13150
+ for (const blocks of [this.#blocks, this.#closedBehind]) {
13151
+ for (let i = blocks.length - 1; i >= 0; i--) {
13152
+ const block = blocks[i];
13153
+ if (isoBlockContains(block.start, block.length, ssId)) {
13154
+ return { block, esi: serial32Distance(block.start, ssId) };
13155
+ }
13027
13156
  }
13028
13157
  }
13029
13158
  return null;
13030
13159
  }
13031
- /** Number of pending holes. */
13160
+ /** Number of holes not closed yet, pending or past the horizon. */
13032
13161
  get holeCount() {
13033
- return this.#holes.length;
13162
+ return this.#holes.length + this.#expired.length;
13163
+ }
13164
+ /**
13165
+ * The pending holes the horizon has passed since the last call, in the
13166
+ * order it passed them. Each is no longer pending: no repair states a block
13167
+ * in it (that repair is `stale`, as for a span the horizon retired) and the
13168
+ * release gate does not wait for it. Its owner must close it
13169
+ * (`closeHolesWithin`), which turns it into a span that is not kept here.
13170
+ */
13171
+ takeExpiredHoles() {
13172
+ return this.#newlyExpired.splice(0);
13034
13173
  }
13035
13174
  /** The stated block (never a span) ending exactly at `end`. */
13036
13175
  blockEndingAt(end) {
@@ -13086,9 +13225,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
13086
13225
  /**
13087
13226
  * Apply one repair symbol's `(SS_Start, SSB_length)`. The first repair of a
13088
13227
  * block states its range and places every held source in it; later repair
13089
- * symbols of the same block change nothing. A range that contradicts a
13090
- * known block (a different length, or an overlap with another block or a
13091
- * span) fails closed: the repair symbol is dropped and no block changes.
13228
+ * symbols of the same block change nothing. A repair whose range is exactly
13229
+ * a repair-less span states that span's one block. A range that contradicts
13230
+ * a known block (a different length, or an overlap with another block or
13231
+ * with part of a span) fails closed: the repair symbol is dropped and no
13232
+ * block changes.
13092
13233
  * A newly stated block retires behind its SS_Start (see the class note).
13093
13234
  * A block so far past `newest` that stating it would retire the position
13094
13235
  * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
@@ -13107,7 +13248,16 @@ var IsoBlockLocator = class _IsoBlockLocator {
13107
13248
  const known = this.blockAt(start);
13108
13249
  if (known !== void 0) {
13109
13250
  if (known.span) {
13110
- return { status: "overlap", reason: `repair block ${start}+${length} falls inside a repair-less span` };
13251
+ if (known.length === length) {
13252
+ const block2 = { start, length, span: false };
13253
+ this.#blocks[this.#blocks.indexOf(known)] = block2;
13254
+ return { status: "placed", block: block2, placed: [] };
13255
+ }
13256
+ return length < known.length ? {
13257
+ status: "overlap",
13258
+ reason: `repair block ${start}+${length} is only the first block of repair-less span ${known.start}+${known.length}`,
13259
+ ofSpan: known
13260
+ } : { status: "overlap", reason: `repair block ${start}+${length} runs past repair-less span ${known.start}+${known.length}` };
13111
13261
  }
13112
13262
  if (known.length !== length) {
13113
13263
  return {
@@ -13175,18 +13325,28 @@ var IsoBlockLocator = class _IsoBlockLocator {
13175
13325
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
13176
13326
  }
13177
13327
  /**
13178
- * Turn every pending hole inside `[start, start + length)` into a
13179
- * repair-less span, claiming its held sources: its range FETCH ended, so
13180
- * nothing more will state its blocks. Returns the spans, in SS_ID order.
13328
+ * Turn every hole inside `[start, start + length)` into a repair-less span,
13329
+ * claiming its held sources: its range FETCH ended, so nothing more will
13330
+ * state its blocks. A hole the horizon passed (`takeExpiredHoles`) leaves a
13331
+ * span that is not kept among the blocks, as the horizon would retire it at
13332
+ * once; only `locate` finds it, until the next retirement, so its sources
13333
+ * can be fed. Returns the spans, in SS_ID order.
13181
13334
  */
13182
13335
  closeHolesWithin(start, length) {
13183
13336
  const closed = [];
13184
- for (const hole of [...this.#holes]) {
13185
- if (!isoBlockContains(start, length, hole.start)) continue;
13186
- this.#holes.splice(this.#holes.indexOf(hole), 1);
13187
- const spanBlock = { start: hole.start, length: hole.length, span: true };
13188
- closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
13189
- this.#blocks.push(spanBlock);
13337
+ for (const holes of [this.#holes, this.#expired]) {
13338
+ for (const hole of [...holes]) {
13339
+ if (!isoBlockContains(start, length, hole.start)) continue;
13340
+ holes.splice(holes.indexOf(hole), 1);
13341
+ const spanBlock = { start: hole.start, length: hole.length, span: true };
13342
+ closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
13343
+ if (holes === this.#holes) {
13344
+ this.#blocks.push(spanBlock);
13345
+ } else {
13346
+ this.#closedBehind.push(spanBlock);
13347
+ if (this.#newlyExpired.includes(hole)) this.#newlyExpired.splice(this.#newlyExpired.indexOf(hole), 1);
13348
+ }
13349
+ }
13190
13350
  }
13191
13351
  return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
13192
13352
  }
@@ -13200,15 +13360,17 @@ var IsoBlockLocator = class _IsoBlockLocator {
13200
13360
  return void 0;
13201
13361
  }
13202
13362
  /**
13203
- * Retire every block and span whose last SS_ID, and every held source,
13204
- * lies more than `retentionBlocks` blocks behind `position`, with the shared
13205
- * lower-bound metric (`isoBlocksBehindLowerBound`) every ISO interleave
13206
- * horizon uses. Returns the retired block starts.
13363
+ * Retire every block and span whose last SS_ID, and every held source
13364
+ * outside a hole, lies more than `retentionBlocks` blocks behind
13365
+ * `position`, with the shared lower-bound metric (`isoBlocksBehindLowerBound`)
13366
+ * every ISO interleave horizon uses; a pending hole so far behind expires
13367
+ * (`takeExpiredHoles`). Returns the retired block starts.
13207
13368
  */
13208
13369
  retireBehind(position) {
13209
13370
  this.observe(position);
13210
13371
  const horizon = this.#retentionBlocks;
13211
13372
  const retired = [];
13373
+ this.#closedBehind.length = 0;
13212
13374
  for (let i = this.#blocks.length - 1; i >= 0; i--) {
13213
13375
  const block = this.#blocks[i];
13214
13376
  const last = serial32Add(block.start, block.length - 1);
@@ -13220,10 +13382,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
13220
13382
  for (let i = this.#holes.length - 1; i >= 0; i--) {
13221
13383
  const hole = this.#holes[i];
13222
13384
  const last = serial32Add(hole.start, hole.length - 1);
13223
- if (isoBlocksBehindLowerBound(last, position, this.#kMax) > horizon) this.#holes.splice(i, 1);
13385
+ if (isoBlocksBehindLowerBound(last, position, this.#kMax) <= horizon) continue;
13386
+ this.#holes.splice(i, 1);
13387
+ this.#expired.push(hole);
13388
+ this.#newlyExpired.push(hole);
13224
13389
  }
13225
13390
  for (const ssId of [...this.#held.keys()]) {
13226
- if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon) this.#held.delete(ssId);
13391
+ if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon && !this.#holes.some((hole) => isoBlockContains(hole.start, hole.length, ssId)) && !this.#expired.some((hole) => isoBlockContains(hole.start, hole.length, ssId))) {
13392
+ this.#held.delete(ssId);
13393
+ }
13227
13394
  }
13228
13395
  return retired;
13229
13396
  }
@@ -13231,6 +13398,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
13231
13398
  reset() {
13232
13399
  this.#blocks.length = 0;
13233
13400
  this.#holes.length = 0;
13401
+ this.#expired.length = 0;
13402
+ this.#newlyExpired.length = 0;
13403
+ this.#closedBehind.length = 0;
13234
13404
  this.#held.clear();
13235
13405
  this.#coverageEnd = void 0;
13236
13406
  this.#newest = void 0;
@@ -13948,6 +14118,10 @@ var FECManager = class _FECManager {
13948
14118
  // 'pending' forever, which would park every later frame of its stream in
13949
14119
  // the in-order release gate. Each entry owns its handle; the callback
13950
14120
  // checks it still owns the key, so a settled or reset key is never touched.
14121
+ /**
14122
+ * Per owed Worker cleanup: the bound on its acknowledgement, when its block
14123
+ * was due, and when its cleanup was asked for (see `onCleanupComplete`).
14124
+ */
13951
14125
  this.#pendingWorkerCleanupBounds = /* @__PURE__ */ new Map();
13952
14126
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
13953
14127
  this.#blockSourceCounts = /* @__PURE__ */ new Map();
@@ -13964,10 +14138,14 @@ var FECManager = class _FECManager {
13964
14138
  // SSB_length source arrivals and recoverable from SSB_length received
13965
14139
  // symbols; waiting for K fails every one of them.
13966
14140
  this.#blockAuthoredLengths = /* @__PURE__ */ new Map();
14141
+ // Keys whose authored length is a repair-less span's (#openIsoSpan), until
14142
+ // a repair states the block there or the span resolves.
14143
+ this.#isoSpanKeys = /* @__PURE__ */ new Set();
13967
14144
  this.#ssbLengthConflictCount = 0;
13968
14145
  this.#blockRepairRsIds = /* @__PURE__ */ new Map();
13969
14146
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
13970
- // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
14147
+ // symbols its repair group carries; 0 for a repair-less span no repair can
14148
+ // state (#openIsoSpan). Same lifecycle as #blockRepairRsIds.
13971
14149
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
13972
14150
  /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
13973
14151
  this.#heldLayerStates = /* @__PURE__ */ new Map();
@@ -14155,13 +14333,17 @@ var FECManager = class _FECManager {
14155
14333
  this.#workerErrorCounts = /* @__PURE__ */ new Map();
14156
14334
  this.#decoderUnavailableEvents = 0;
14157
14335
  this.#repairSymbolSizeMismatchCount = 0;
14336
+ this.#unlistedRepairTrackRefusals = 0;
14158
14337
  // Event callbacks — block lifecycle notifications for MmtpRouter wiring.
14159
14338
  // NOTE: For sync WASM path, recovery routing is handled by MmtpRouter from
14160
14339
  // feedSourceSymbol/feedRepairSymbol return values. For Worker path, recovery
14161
14340
  // arrives via onBlockRecovered callback.
14162
14341
  this.onBlockStarted = null;
14163
14342
  this.onBlockComplete = null;
14164
- /** A block reached its fail bound. `blockClass` is its class at failure. */
14343
+ /**
14344
+ * A block reached its fail bound. `blockClass` is its class at failure.
14345
+ * `span` is set when what failed is a repair-less span starting at `sbn`.
14346
+ */
14165
14347
  this.onBlockFailed = null;
14166
14348
  /**
14167
14349
  * Fired once per stream when its Worker decoder stops being routable.
@@ -14203,12 +14385,24 @@ var FECManager = class _FECManager {
14203
14385
  * for it, which it must be.
14204
14386
  */
14205
14387
  this.#onUndelimitedLoss = null;
14388
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
14389
+ this.#onIsoHoleExpired = null;
14206
14390
  /** A block every symbol of which vanished was created by SBN evidence. */
14207
14391
  this.onBlockVanished = null;
14208
14392
  /** A block reached a terminal state (completed, recovered, or failed). */
14209
14393
  this.onBlockResolved = null;
14210
14394
  /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
14211
14395
  this.onSourceDiscontinuity = null;
14396
+ /**
14397
+ * The span and tolerance the catalog states for a keyframe overlay
14398
+ * installed over a source track (draft-ramadan-moq-mmt-02 7.4.1: the
14399
+ * overlay instance's own interleaveDepthMs and reorderToleranceMs), or
14400
+ * undefined while none is installed. A stated block only a late source
14401
+ * can complete, and a frame whose gap may hide a RAP behind a span only a
14402
+ * late source can fill, also wait for that overlay's repair
14403
+ * (#overlayLateWaitMs).
14404
+ */
14405
+ this.keyframeOverlayTiming = null;
14212
14406
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
14213
14407
  /**
14214
14408
  * A recovered source symbol. Return false when admission refused the
@@ -14247,6 +14441,7 @@ var FECManager = class _FECManager {
14247
14441
  #blockSourceEsis;
14248
14442
  #blockRebuiltEsis;
14249
14443
  #blockAuthoredLengths;
14444
+ #isoSpanKeys;
14250
14445
  #ssbLengthConflictCount;
14251
14446
  #blockRepairRsIds;
14252
14447
  #blockRsbLengths;
@@ -14312,7 +14507,9 @@ var FECManager = class _FECManager {
14312
14507
  #workerErrorCounts;
14313
14508
  #decoderUnavailableEvents;
14314
14509
  #repairSymbolSizeMismatchCount;
14510
+ #unlistedRepairTrackRefusals;
14315
14511
  #onUndelimitedLoss;
14512
+ #onIsoHoleExpired;
14316
14513
  #encodeTrackName(catalogTrackName) {
14317
14514
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
14318
14515
  if (encoded === void 0) {
@@ -14784,7 +14981,10 @@ var FECManager = class _FECManager {
14784
14981
  timer.handle = null;
14785
14982
  this.#requestRepair(sbn, packetId, catalogTrackName);
14786
14983
  };
14787
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
14984
+ timer.handle = setTimeout(
14985
+ onFire,
14986
+ this.#receiptAtMs === void 0 ? Math.max(0, deadlineMs - performance.now()) : this.#receiptTimerDelayMs(deadlineMs, 0)
14987
+ );
14788
14988
  this.#repairDeadlines.set(key, timer);
14789
14989
  }
14790
14990
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -14928,8 +15128,14 @@ var FECManager = class _FECManager {
14928
15128
  * Vanished blocks are not enumerated here: their starts are unknown until a
14929
15129
  * repair states them. The SS_IDs between two stated blocks become one
14930
15130
  * repair-less span when the later block's repair arrives (placeIsoRepair).
15131
+ *
15132
+ * A `held` source arrived before its block was known and is fed only now
15133
+ * that a repair, a span or a closed hole placed it: how far its block start
15134
+ * then lies behind the frontier measures how long the receiver held it, not
15135
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
15136
+ * it (BLO-52085).
14931
15137
  */
14932
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
15138
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn, held = false) {
14933
15139
  const streamKey = this.#streamKey(packetId, catalogTrackName);
14934
15140
  const now = performance.now();
14935
15141
  const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
@@ -14968,7 +15174,7 @@ var FECManager = class _FECManager {
14968
15174
  return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
14969
15175
  };
14970
15176
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
14971
- 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))) {
15177
+ if (symbol === "source" && window2 !== null && this.#blockPrecedes(sbn, previous.sbn) && (!held && 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))) {
14972
15178
  discontinuity();
14973
15179
  return;
14974
15180
  }
@@ -15230,17 +15436,21 @@ var FECManager = class _FECManager {
15230
15436
  this.#blockWaitDeadlinesMs.delete(key);
15231
15437
  this.#repairHoldUntilMs.delete(key);
15232
15438
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
15233
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName);
15439
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs);
15234
15440
  };
15235
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)));
15441
+ timer.handle = setTimeout(
15442
+ onFire,
15443
+ this.#receiptAtMs === void 0 ? Math.max(1, Math.ceil(deadlineMs - nowMs)) : this.#receiptTimerDelayMs(deadlineMs, 1)
15444
+ );
15236
15445
  this.#activeBlocks.set(key, timer);
15237
15446
  this.#indexBlockKey(key, sbn, packetId);
15238
15447
  }
15239
15448
  /**
15240
15449
  * Hand a block whose delivery is over to its decoder for finalization: the
15241
- * datagram deadline fired, or the ordered relay moved past it.
15450
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
15451
+ * is when it was due: its deadline, or now.
15242
15452
  */
15243
- #finalizeExpiredBlock(sbn, packetId, catalogTrackName) {
15453
+ #finalizeExpiredBlock(sbn, packetId, catalogTrackName, dueAtMs = performance.now()) {
15244
15454
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
15245
15455
  if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
15246
15456
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -15256,7 +15466,7 @@ var FECManager = class _FECManager {
15256
15466
  if (workerClient) {
15257
15467
  this.#pendingWorkerCleanups.add(key);
15258
15468
  this.#pendingWorkerCleanupClients.set(key, workerClient);
15259
- this.#boundOwedCleanup(key, packetId, workerClient);
15469
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs);
15260
15470
  workerClient.cleanup(sbn);
15261
15471
  } else {
15262
15472
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
@@ -15466,6 +15676,7 @@ var FECManager = class _FECManager {
15466
15676
  packetId
15467
15677
  })),
15468
15678
  repairSymbolSizeMismatches: this.#repairSymbolSizeMismatchCount,
15679
+ unlistedRepairTrackRefusals: this.#unlistedRepairTrackRefusals,
15469
15680
  repairObjectRejects: [...this.#repairObjectRejects.values()].map((r) => ({ ...r })),
15470
15681
  workerErrors: Object.fromEntries(this.#workerErrorCounts)
15471
15682
  };
@@ -15570,6 +15781,7 @@ var FECManager = class _FECManager {
15570
15781
  resetMap(this.#blockSourceEsis);
15571
15782
  resetMap(this.#blockRebuiltEsis);
15572
15783
  resetMap(this.#blockAuthoredLengths);
15784
+ resetSet(this.#isoSpanKeys);
15573
15785
  resetMap(this.#blockRepairRsIds);
15574
15786
  resetMap(this.#blockRsbLengths);
15575
15787
  resetMap(this.#heldLayerStates);
@@ -15695,6 +15907,7 @@ var FECManager = class _FECManager {
15695
15907
  dropMap(this.#blockSourceEsis);
15696
15908
  dropMap(this.#blockRebuiltEsis);
15697
15909
  dropMap(this.#blockAuthoredLengths);
15910
+ dropSet(this.#isoSpanKeys);
15698
15911
  dropMap(this.#blockRepairRsIds);
15699
15912
  dropMap(this.#blockRsbLengths);
15700
15913
  dropMap(this.#blockPathCounts);
@@ -15968,8 +16181,10 @@ var FECManager = class _FECManager {
15968
16181
  }
15969
16182
  /**
15970
16183
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
15971
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
15972
- * Undefined for a block that is not open.
16184
+ * (SSB_length) and RSB_length (each undefined until a repair stated it; a
16185
+ * repair-less span states its length, and RSB_length 0 when it is longer
16186
+ * than K, since no repair can reach it). Undefined for a block that is not
16187
+ * open.
15973
16188
  */
15974
16189
  blockSymbolCounts(sbn, packetId, catalogTrackName) {
15975
16190
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -16037,8 +16252,9 @@ var FECManager = class _FECManager {
16037
16252
  return true;
16038
16253
  }
16039
16254
  /**
16040
- * Drop a block's repair hold: its FETCH ended without delivering. The block
16041
- * falls back to its multicast wait, which may already have passed.
16255
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
16256
+ * back only a repair that cannot complete it. The block falls back to its
16257
+ * multicast wait, which may already have passed.
16042
16258
  */
16043
16259
  releaseRepairHold(sbn, packetId, catalogTrackName) {
16044
16260
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -16084,7 +16300,7 @@ var FECManager = class _FECManager {
16084
16300
  }
16085
16301
  const trackConfig = this.#trackConfigs.get(packetId);
16086
16302
  if (trackConfig === void 0) return void 0;
16087
- return Math.max(1, trackConfig.timeoutMs - this.#repairDeadlineMs(trackConfig));
16303
+ return Math.max(1, this.#repairGraceMs(trackConfig, this.#multicastWaitMs(trackConfig)));
16088
16304
  }
16089
16305
  /** True once configureTrack/setFecDecoder/setFecWorker configured this packetId. */
16090
16306
  // -----------------------------------------------------------------------
@@ -16176,6 +16392,7 @@ var FECManager = class _FECManager {
16176
16392
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
16177
16393
  const evictedBefore = locator.heldEvicted;
16178
16394
  const held = locator.hold(ssId, source);
16395
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
16179
16396
  if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
16180
16397
  const evicted = locator.heldEvicted - evictedBefore;
16181
16398
  if (evicted > 0) {
@@ -16197,17 +16414,20 @@ var FECManager = class _FECManager {
16197
16414
  * contradicts a known block is refused (counted) and must be dropped.
16198
16415
  */
16199
16416
  placeIsoRepair(packetId, catalogTrackName, ssStart, ssbLength) {
16200
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength);
16417
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
16418
+ const placement = locator.placeRepair(ssStart, ssbLength);
16419
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
16201
16420
  if (placement.status !== "placed") {
16202
16421
  this.#isoRepairRefusedCount++;
16203
16422
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
16204
16423
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`);
16205
16424
  }
16425
+ if (placement.ofSpan !== void 0) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName);
16206
16426
  return placement;
16207
16427
  }
16428
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName));
16208
16429
  if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
16209
16430
  if (placement.hole !== void 0) {
16210
- const locator = this.#isoLocatorFor(packetId, catalogTrackName);
16211
16431
  const hole = placement.hole.block;
16212
16432
  const previous = locator.blockEndingAt(hole.start);
16213
16433
  const loss = {
@@ -16228,17 +16448,29 @@ var FECManager = class _FECManager {
16228
16448
  * `handler`, instead of a repair-less span; null restores spans. Set by the
16229
16449
  * range repair scheduler; applies to every stream from its next gap. The
16230
16450
  * handler and the deferral are one setting, so no hole is ever created with
16231
- * nobody to close it.
16451
+ * nobody to close it. `onExpired` is told of each pending hole the stream
16452
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
16453
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
16454
+ * reported; otherwise the hole is discarded with its sources.
16232
16455
  */
16233
- setUndelimitedLossHandler(handler) {
16456
+ setUndelimitedLossHandler(handler, onExpired = null) {
16234
16457
  this.#onUndelimitedLoss = handler;
16458
+ this.#onIsoHoleExpired = handler === null ? null : onExpired;
16235
16459
  this.#deferIsoGaps = handler !== null;
16236
16460
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
16237
16461
  }
16462
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
16463
+ #settleExpiredIsoHoles(locator, packetId, catalogTrackName) {
16464
+ for (const hole of locator.takeExpiredHoles()) {
16465
+ const expired = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length };
16466
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length);
16467
+ }
16468
+ }
16238
16469
  /**
16239
- * The range repair for a hole ended: every hole still pending inside
16240
- * `[start, start + length)` becomes a repair-less span. Returns those spans
16241
- * with the held sources they placed, for the caller to feed (MmtpRouter).
16470
+ * The range repair for a hole ended: every hole inside `[start, start +
16471
+ * length)`, pending or expired, becomes a repair-less span. Returns those
16472
+ * spans with the held sources they placed, for the caller to feed
16473
+ * (MmtpRouter).
16242
16474
  */
16243
16475
  closeIsoHoles(packetId, catalogTrackName, start, length) {
16244
16476
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
@@ -16254,10 +16486,25 @@ var FECManager = class _FECManager {
16254
16486
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
16255
16487
  * SS_ID of which vanished resolves through its deadline like any vanished
16256
16488
  * block.
16489
+ *
16490
+ * A span longer than K holds more than one block (SSB_length <= K), and the
16491
+ * locator states no block inside a span, only one exactly its range
16492
+ * (IsoBlockLocator.placeRepair): no repair, multicast or FETCHed, can ever
16493
+ * reach it. Its repair group is empty, so the repair scheduler FETCHes no
16494
+ * Group of it (group-cannot-complete). Every span still keeps its whole
16495
+ * wait (#lateSourceWaitMs): failing it early released the frames behind it
16496
+ * past a keyframe the overlay was still rebuilding (BLO-52085). The release
16497
+ * gate lets those frames go once only a late source can fill the gap
16498
+ * before them, as long after they arrived as the gap's decision allows
16499
+ * (isoRepairlessWaitMs).
16257
16500
  */
16258
16501
  #openIsoSpan(span, packetId, catalogTrackName) {
16259
16502
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
16260
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
16503
+ if (!this.#blockAuthoredLengths.has(key)) {
16504
+ this.#blockAuthoredLengths.set(key, span.block.length);
16505
+ this.#isoSpanKeys.add(key);
16506
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0);
16507
+ }
16261
16508
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
16262
16509
  }
16263
16510
  /**
@@ -16295,6 +16542,62 @@ var FECManager = class _FECManager {
16295
16542
  }
16296
16543
  return lost;
16297
16544
  }
16545
+ /**
16546
+ * The release gate's wait, from a frame's arrival, for the SS_IDs strictly
16547
+ * between two released frames' SS_IDs once only a late source can still
16548
+ * fill them, else undefined. That is when every one missing (neither
16549
+ * arrived nor held) lies in a repair-less span longer than K, which no
16550
+ * repair can state a block of (#openIsoSpan), or in a stated block its
16551
+ * own repair group cannot complete every SS_ID of which it misses lies
16552
+ * between them (so the gap's decision covers all it lost), and a multicast
16553
+ * source at or past `toSsId` arrived, so each is lost or reordered behind
16554
+ * it (a MoQ source shows nothing: MoQ streams overtake one another). The
16555
+ * span or block itself keeps its own wait.
16556
+ *
16557
+ * The wait is the late-symbol allowance, unless `rapMayHide`: the gap may
16558
+ * hold a RAP packet an installed keyframe overlay can still rebuild (its
16559
+ * decision stalls, or it ends at a RAP that may lie past a whole MPU).
16560
+ * Then the frame waits as a stated block its group cannot complete does
16561
+ * (#overlayLateWaitMs): the allowance alone with no overlay installed, the
16562
+ * overlay's span plus the larger of the allowance and its tolerance, or,
16563
+ * for an overlay that states no span, the span's whole wait (undefined).
16564
+ * So does `rapNext` (the gap ends at the RAP that opens the next MPU) when
16565
+ * the gap holds a stated block's loss.
16566
+ */
16567
+ isoRepairlessWaitMs(packetId, catalogTrackName, fromSsId, toSsId, rapMayHide = false, rapNext = false) {
16568
+ const config = this.#trackConfigs.get(packetId);
16569
+ if (config === void 0 || !_FECManager.#hasCatalogTiming(config)) return void 0;
16570
+ const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
16571
+ if (locator === void 0 || !locator.coversBetween(fromSsId, toSsId)) return void 0;
16572
+ const newestSource = locator.newestSource;
16573
+ if (newestSource === void 0 || serial32Precedes(newestSource, toSsId)) return void 0;
16574
+ let repairless = false;
16575
+ let stated = false;
16576
+ for (const block of locator.blocksBetween(fromSsId, toSsId)) {
16577
+ const key = this.#blockKey(block.start, packetId, catalogTrackName);
16578
+ if (this.#completedBlocks.has(key)) continue;
16579
+ if (block.span && block.length > locator.kMax) {
16580
+ repairless = true;
16581
+ continue;
16582
+ }
16583
+ const received = this.#blockSourceEsis.get(key);
16584
+ const rebuilt = this.#blockRebuiltEsis.get(key);
16585
+ let missesInGap = false;
16586
+ let missesOutside = false;
16587
+ for (let esi = 0; esi < block.length; esi++) {
16588
+ const ssId = serial32Add(block.start, esi);
16589
+ if (received?.has(esi) || locator.isHeld(ssId)) continue;
16590
+ if (serial32Precedes(fromSsId, ssId) && serial32Precedes(ssId, toSsId)) missesInGap = true;
16591
+ else if (!rebuilt?.has(esi)) missesOutside = true;
16592
+ }
16593
+ if (!missesInGap) continue;
16594
+ if (missesOutside || block.span || !this.#groupCannotComplete(key)) return void 0;
16595
+ repairless = stated = true;
16596
+ }
16597
+ if (!repairless) return void 0;
16598
+ const waitMs = rapMayHide || stated && rapNext ? this.#overlayLateWaitMs(packetId, catalogTrackName, config) : this.#multicastWaitMs(config) - config.interleaveDepthMs;
16599
+ return waitMs === void 0 ? void 0 : Math.max(0, waitMs);
16600
+ }
16298
16601
  /**
16299
16602
  * iso-ssbg1-v1 block location: repair symbols it refused, oversize sources,
16300
16603
  * the sources held now for a block no repair has stated yet, and the held
@@ -16598,11 +16901,14 @@ var FECManager = class _FECManager {
16598
16901
  });
16599
16902
  client.onCleanupComplete((sbn) => {
16600
16903
  if (this.#releasedWorkerClients.has(client)) return;
16601
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
16904
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
16905
+ const cleanupKeys = owed.filter((key) => {
16602
16906
  const block = this.#parseBlockKey(key);
16603
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
16907
+ return block.packetId === packetId && block.sbn === sbn;
16604
16908
  });
16605
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
16909
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
16910
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
16911
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
16606
16912
  });
16607
16913
  client.onError((msg, code) => {
16608
16914
  const requestedKind = code ?? msg;
@@ -16672,9 +16978,11 @@ var FECManager = class _FECManager {
16672
16978
  * fail deadline already passed, so failing it is the decision that deadline
16673
16979
  * made. A late ack then finds nothing owed and is a no-op.
16674
16980
  */
16675
- #boundOwedCleanup(key, packetId, client) {
16981
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
16676
16982
  this.#clearOwedCleanupBound(key);
16677
16983
  const bound = {
16984
+ dueAtMs,
16985
+ askedAtMs: performance.now(),
16678
16986
  handle: setTimeout(() => {
16679
16987
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
16680
16988
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -16844,9 +17152,15 @@ var FECManager = class _FECManager {
16844
17152
  rebuilt = /* @__PURE__ */ new Set();
16845
17153
  this.#blockRebuiltEsis.set(key, rebuilt);
16846
17154
  }
17155
+ const config = this.#trackConfigs.get(packetId);
17156
+ const wasShort = config !== void 0 && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) !== void 0;
16847
17157
  rebuilt.add(located.esi);
16848
17158
  const recovered = this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn);
16849
- if (recovered === null) this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName);
17159
+ if (recovered === null && !this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName)) {
17160
+ if (wasShort && this.#activeBlocks.has(key) && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) === void 0) {
17161
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, this.#multicastWaitMs(config));
17162
+ }
17163
+ }
16850
17164
  return { taken: true, recovered };
16851
17165
  }
16852
17166
  /**
@@ -16932,7 +17246,10 @@ var FECManager = class _FECManager {
16932
17246
  this.#layerAnchorHorizon(packetId),
16933
17247
  this.#sourceFrontiers.get(streamKey)?.sbn
16934
17248
  );
16935
- if (verdict === "discard") return false;
17249
+ if (verdict === "discard") {
17250
+ this.#unlistedRepairTrackRefusals++;
17251
+ return false;
17252
+ }
16936
17253
  if (verdict !== void 0) {
16937
17254
  this.#failClosed(streamKey, verdict, packetId, catalogTrackName);
16938
17255
  return false;
@@ -17089,7 +17406,7 @@ var FECManager = class _FECManager {
17089
17406
  const previous = locator.newestSource;
17090
17407
  if (!locator.noteSource(ssId) || previous === void 0) return;
17091
17408
  for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
17092
- if (block.span || !serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
17409
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
17093
17410
  this.#shortenUnrecoverableWait(
17094
17411
  this.#blockKey(block.start, packetId, catalogTrackName),
17095
17412
  block.start,
@@ -17107,18 +17424,61 @@ var FECManager = class _FECManager {
17107
17424
  * covers repair symbols paced after its sources, buys it nothing: it waits
17108
17425
  * the late-symbol allowance alone, the multicast wait less the span (the
17109
17426
  * catalog tolerance or the measured delivery gap). Undefined for any other
17110
- * block.
17427
+ * block. While a keyframe overlay is installed, the block waits for its
17428
+ * repair too (#overlayLateWaitMs). A repair-less span keeps its whole
17429
+ * wait, even one longer than K whose group is empty (#openIsoSpan): its
17430
+ * resolution is what releases the frames behind it, and failing it early
17431
+ * released them past a keyframe the overlay was still rebuilding, which
17432
+ * then arrived stale. The release gate lets them go instead
17433
+ * (isoRepairlessWaitMs).
17111
17434
  */
17112
17435
  #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
17436
+ if (this.#isoSpanKeys.has(key) || !this.#groupCannotComplete(key)) return void 0;
17113
17437
  const authoredLength = this.#blockAuthoredLengths.get(key);
17114
- const rsbLength = this.#blockRsbLengths.get(key);
17115
- if (authoredLength === void 0 || rsbLength === void 0) return void 0;
17116
- if ((this.#blockSourceCounts.get(key) ?? 0) + rsbLength >= authoredLength) return void 0;
17117
17438
  const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
17118
17439
  if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
17119
17440
  return void 0;
17120
17441
  }
17121
- return this.#multicastWaitMs(config) - config.interleaveDepthMs;
17442
+ return this.#overlayLateWaitMs(packetId, catalogTrackName, config);
17443
+ }
17444
+ /**
17445
+ * A repair stated the block, and its sources plus every symbol its repair
17446
+ * group carries (RSB_length) are short of its SSB_length.
17447
+ */
17448
+ #groupCannotComplete(key) {
17449
+ const authoredLength = this.#blockAuthoredLengths.get(key);
17450
+ const rsbLength = this.#blockRsbLengths.get(key);
17451
+ if (authoredLength === void 0 || rsbLength === void 0) return false;
17452
+ let present = this.#blockSourceCounts.get(key) ?? 0;
17453
+ const received = this.#blockSourceEsis.get(key);
17454
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
17455
+ return present + rsbLength < authoredLength;
17456
+ }
17457
+ /**
17458
+ * How long a loss only a late source or an installed keyframe overlay can
17459
+ * still fill waits once a later source passed it: the late-symbol
17460
+ * allowance alone (the multicast wait less the span) while no overlay is
17461
+ * installed. An installed one (keyframeOverlayTiming) may still rebuild a
17462
+ * RAP packet the loss took: a second FEC instance over the same packets
17463
+ * (draft-ramadan-moq-mmt-02 7.4), whose repair is paced across its own
17464
+ * span, unrelated to the base's. That packet can complete a stated block
17465
+ * (feedRebuiltSourceSymbol), or play behind a span; giving the loss up
17466
+ * first lets the release gate pass the keyframe, whose rebuild then lands
17467
+ * stale. The overlay repair of a packet the loss took goes out within the
17468
+ * overlay's span of that packet (fec-core-00 9.3), and the later source was
17469
+ * sent after it, so the loss waits that span plus the larger of the
17470
+ * allowance and the overlay's own tolerance. An overlay that states no
17471
+ * span (its block may then span keyframes), or one whose wait is not
17472
+ * shorter than the whole multicast wait, leaves the whole wait: undefined.
17473
+ */
17474
+ #overlayLateWaitMs(packetId, catalogTrackName, config) {
17475
+ const waitMs = this.#multicastWaitMs(config);
17476
+ const allowanceMs = waitMs - config.interleaveDepthMs;
17477
+ const overlay = this.keyframeOverlayTiming?.(packetId, catalogTrackName);
17478
+ if (overlay === void 0) return allowanceMs;
17479
+ const overlaySpanMs = overlay.interleaveDepthMs ?? 0;
17480
+ const overlayWaitMs = overlaySpanMs + Math.max(allowanceMs, overlay.reorderToleranceMs ?? 0);
17481
+ return overlaySpanMs > 0 && overlayWaitMs < waitMs ? overlayWaitMs : void 0;
17122
17482
  }
17123
17483
  /**
17124
17484
  * Bring an open block's wait in to its late-source wait, when it has one.
@@ -17236,12 +17596,13 @@ var FECManager = class _FECManager {
17236
17596
  * the inactivity deadline on each symbol, records the symbol's in-band
17237
17597
  * classification evidence, and marks the block clean when all of its
17238
17598
  * authored source symbols arrived: the SSB_length a repair symbol declared,
17239
- * otherwise K.
17599
+ * otherwise K. `held` marks a source held unplaced since it arrived and
17600
+ * placed only now (see #noteSbnSeen).
17240
17601
  *
17241
17602
  * Throws for a packetId that was never configured, so a classified block
17242
17603
  * never reads the manager-global K or timeout.
17243
17604
  */
17244
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
17605
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
17245
17606
  const trackConfig = this.#trackConfigs.get(packetId);
17246
17607
  if (trackConfig === void 0) {
17247
17608
  throw new Error(
@@ -17257,7 +17618,8 @@ var FECManager = class _FECManager {
17257
17618
  catalogTrackName,
17258
17619
  "source",
17259
17620
  evidence.packetSequenceNumber,
17260
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
17621
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
17622
+ held
17261
17623
  );
17262
17624
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
17263
17625
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -17312,6 +17674,7 @@ var FECManager = class _FECManager {
17312
17674
  this.#blockSourceEsis.delete(key);
17313
17675
  this.#blockRebuiltEsis.delete(key);
17314
17676
  this.#blockAuthoredLengths.delete(key);
17677
+ this.#isoSpanKeys.delete(key);
17315
17678
  this.#blockRepairRsIds.delete(key);
17316
17679
  this.#blockRsbLengths.delete(key);
17317
17680
  this.#markTerminal(key, sbn, packetId, true);
@@ -17342,6 +17705,19 @@ var FECManager = class _FECManager {
17342
17705
  #receiptNow() {
17343
17706
  return this.#receiptAtMs ?? performance.now();
17344
17707
  }
17708
+ /**
17709
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
17710
+ * scope: counted from the receipt time, as the timer of a symbol fed when
17711
+ * it was received was, less the whole ms since. So it fires on the tick
17712
+ * that timer would have, never later than a delay counted from now, and
17713
+ * its handler still re-arms a timer that fires before its deadline.
17714
+ * Counted from now, a deadline set from the receipt time is rounded up
17715
+ * from another fraction of a ms (BLO-52085).
17716
+ */
17717
+ #receiptTimerDelayMs(deadlineMs, minMs) {
17718
+ const receivedAtMs = this.#receiptAtMs;
17719
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
17720
+ }
17345
17721
  /**
17346
17722
  * A held packet admitted late arms from its (earlier) receipt time; that
17347
17723
  * never pulls in a deadline later activity already armed. Outside a
@@ -17390,6 +17766,7 @@ var FECManager = class _FECManager {
17390
17766
  }
17391
17767
  #failBlock(sbn, packetId, catalogTrackName) {
17392
17768
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
17769
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
17393
17770
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
17394
17771
  this.#clearRepairDeadline(key);
17395
17772
  this.#clearBlockTimer(key);
@@ -17409,7 +17786,8 @@ var FECManager = class _FECManager {
17409
17786
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
17410
17787
  this.#fecStats.blocksFailed++;
17411
17788
  this.#statsForPacket(packetId).blocksFailed++;
17412
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
17789
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
17790
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
17413
17791
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
17414
17792
  }
17415
17793
  /**
@@ -17440,6 +17818,7 @@ var FECManager = class _FECManager {
17440
17818
  this.#blockSourceEsis.delete(key);
17441
17819
  this.#blockRebuiltEsis.delete(key);
17442
17820
  this.#blockAuthoredLengths.delete(key);
17821
+ this.#isoSpanKeys.delete(key);
17443
17822
  this.#blockRepairRsIds.delete(key);
17444
17823
  this.#blockRsbLengths.delete(key);
17445
17824
  this.#clearBlockTimer(key);
@@ -17532,6 +17911,7 @@ var FECManager = class _FECManager {
17532
17911
  this.#blockSourceEsis.clear();
17533
17912
  this.#blockRebuiltEsis.clear();
17534
17913
  this.#blockAuthoredLengths.clear();
17914
+ this.#isoSpanKeys.clear();
17535
17915
  this.#blockRepairRsIds.clear();
17536
17916
  this.#blockRsbLengths.clear();
17537
17917
  this.#heldLayerStates.clear();
@@ -18433,6 +18813,9 @@ function authoredGap(before, after) {
18433
18813
  function ssIdAfter(a, b) {
18434
18814
  return (a - b | 0) > 0;
18435
18815
  }
18816
+ function holdsRebuilt(stream) {
18817
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
18818
+ }
18436
18819
  var FecReleaseSequencer = class {
18437
18820
  #streams = /* @__PURE__ */ new Map();
18438
18821
  #gate;
@@ -18495,6 +18878,7 @@ var FecReleaseSequencer = class {
18495
18878
  stream.lastSbn = void 0;
18496
18879
  stream.discontinuity = false;
18497
18880
  stream.rapSsId = void 0;
18881
+ stream.sourced = false;
18498
18882
  }
18499
18883
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
18500
18884
  this.#recordStat("droppedStale");
@@ -18521,6 +18905,7 @@ var FecReleaseSequencer = class {
18521
18905
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
18522
18906
  else hi = mid;
18523
18907
  }
18908
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
18524
18909
  stream.buf.splice(lo, 0, frame);
18525
18910
  this.#drainUnlessDeferred(stream);
18526
18911
  }
@@ -18556,6 +18941,41 @@ var FecReleaseSequencer = class {
18556
18941
  }
18557
18942
  return false;
18558
18943
  }
18944
+ /**
18945
+ * These streams' sink is being replaced by one that has seen no source
18946
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
18947
+ * release to the sink being replaced the frames the unanchored path had
18948
+ * already released to it (#cursorPassed): there they waited in its queue,
18949
+ * which its replacement flushes. A stream that holds none is not drained:
18950
+ * it holds nothing the anchor kept back, and a drain would still force out
18951
+ * a frame held past the hold limit, which before the anchor waited for the
18952
+ * next push. Then treat the streams as unsourced until a source frame is
18953
+ * released.
18954
+ */
18955
+ unsource(packetId, catalogTrackName) {
18956
+ for (const stream of this.#streams.values()) {
18957
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
18958
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
18959
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
18960
+ else this.#drain(stream, true);
18961
+ }
18962
+ stream.sourced = false;
18963
+ }
18964
+ }
18965
+ }
18966
+ /**
18967
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
18968
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
18969
+ * packetId.
18970
+ */
18971
+ holdsRebuilt(packetId, catalogTrackName) {
18972
+ for (const stream of this.#streams.values()) {
18973
+ if (stream.packetId !== packetId) continue;
18974
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
18975
+ if (holdsRebuilt(stream)) return true;
18976
+ }
18977
+ return false;
18978
+ }
18559
18979
  /** Re-evaluate held gaps after FEC state changed. */
18560
18980
  poke(streamKey) {
18561
18981
  if (streamKey !== void 0) {
@@ -18647,16 +19067,32 @@ var FecReleaseSequencer = class {
18647
19067
  last: null,
18648
19068
  lastSbn: void 0,
18649
19069
  discontinuity: false,
18650
- rapSsId: void 0
19070
+ rapSsId: void 0,
19071
+ sourced: false,
19072
+ draining: 0
18651
19073
  };
18652
19074
  this.#streams.set(streamKey, stream);
18653
19075
  }
18654
19076
  return stream;
18655
19077
  }
18656
- #drain(stream) {
19078
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
19079
+ #drain(stream, asUnanchored = false) {
19080
+ stream.draining++;
19081
+ try {
19082
+ this.#drainLoop(stream, asUnanchored);
19083
+ } finally {
19084
+ stream.draining--;
19085
+ }
19086
+ }
19087
+ #drainLoop(stream, asUnanchored) {
18657
19088
  while (stream.buf.length > 0 && stream.last !== null) {
18658
19089
  const head = stream.buf[0];
18659
19090
  const last = stream.last;
19091
+ if (compareFrameOrder(head, last) <= 0) {
19092
+ stream.buf.shift();
19093
+ this.#release(stream, head, void 0);
19094
+ continue;
19095
+ }
18660
19096
  if (stream.discontinuity) {
18661
19097
  stream.discontinuity = false;
18662
19098
  stream.buf.shift();
@@ -18670,9 +19106,10 @@ var FecReleaseSequencer = class {
18670
19106
  }
18671
19107
  const headSbn = head.meta.fecSbn;
18672
19108
  const from = stream.lastSbn ?? headSbn;
18673
- const to = headSbn ?? stream.lastSbn;
19109
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
18674
19110
  let lost = [];
18675
19111
  const unanchored = from === void 0 && to === void 0;
19112
+ let unresolved = false;
18676
19113
  if (from !== void 0 && to !== void 0) {
18677
19114
  const resolved = this.#gate.resolvedLoss(
18678
19115
  stream.packetId,
@@ -18681,7 +19118,8 @@ var FecReleaseSequencer = class {
18681
19118
  Math.max(from, to),
18682
19119
  from
18683
19120
  );
18684
- if (resolved === null) {
19121
+ unresolved = resolved === null;
19122
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored) && !this.#unrepairableWaitOver(stream, last, head, from, to)) {
18685
19123
  const heldMs = performance.now() - head.arrivedAtMs;
18686
19124
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
18687
19125
  this.#recordStat("forcedWindowFlushes");
@@ -18689,22 +19127,69 @@ var FecReleaseSequencer = class {
18689
19127
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
18690
19128
  continue;
18691
19129
  }
18692
- lost = resolved;
19130
+ lost = resolved ?? [];
18693
19131
  }
18694
19132
  stream.buf.shift();
18695
19133
  this.#release(
18696
19134
  stream,
18697
19135
  head,
18698
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
19136
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
18699
19137
  );
18700
19138
  }
18701
19139
  }
19140
+ /**
19141
+ * The head has waited out a gap only a late source can still fill
19142
+ * (FecReleaseGate.unrepairableWaitMs). Not yet: the gate is asked to poke
19143
+ * the stream when it has (`wakeAt`), since no packet may come by then.
19144
+ */
19145
+ #unrepairableWaitOver(stream, last, head, from, to) {
19146
+ const waitMs = this.#gate.unrepairableWaitMs?.(last, head, from, to);
19147
+ if (waitMs === void 0) return false;
19148
+ const atMs = head.arrivedAtMs + waitMs;
19149
+ if (performance.now() >= atMs) return true;
19150
+ this.#gate.wakeAt?.(stream.packetId, stream.catalogTrackName, atMs);
19151
+ return false;
19152
+ }
19153
+ /**
19154
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
19155
+ * source cursor holds it unanchored, and neither does a later frame behind
19156
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
19157
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
19158
+ * like each frame that arrived in front of it since (stale there). The head
19159
+ * then goes, decided as it would be unanchored, once a frame the base path
19160
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
19161
+ * marked one: the base path has passed that one, so a frame still missing
19162
+ * before it can only come from a repair. It also goes while no source frame
19163
+ * has been released, when the direct path shows a recovered frame at once.
19164
+ * And it goes at once while a staged switch decides on when frames arrive
19165
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
19166
+ * sink being replaced: unanchored, it had already reached the sink.
19167
+ * The scan also writes: the `passed` marks it sets stay on the frames,
19168
+ * and push marks a frame it inserts in front of a marked one from them.
19169
+ */
19170
+ #cursorPassed(stream, asUnanchored) {
19171
+ let at2 = -1;
19172
+ for (let i = 0; i < stream.buf.length; i++) {
19173
+ const frame = stream.buf[i];
19174
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
19175
+ frame.passed = true;
19176
+ if (at2 < 0) at2 = i;
19177
+ } else if (frame.passed !== true) break;
19178
+ }
19179
+ if (at2 < 0) return false;
19180
+ return asUnanchored || !stream.sourced || this.#gate.releaseUnanchored?.(stream.packetId, stream.catalogTrackName) === true || stream.buf.some(({ meta }, i) => i > at2 && meta.fecSbnFirst === void 0 && (meta.recovered !== true || meta.fecSbn !== void 0));
19181
+ }
18702
19182
  #release(stream, frame, decision) {
19183
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
19184
+ if (stale) this.#recordStat("droppedStale");
18703
19185
  if (decision) frame.meta.gapBefore = decision;
18704
19186
  stream.last = frame;
18705
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
19187
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
19188
+ stream.lastSbn = frame.meta.fecSbn;
19189
+ }
19190
+ if (frame.meta.recovered !== true) stream.sourced = true;
18706
19191
  this.#gate.onReleased?.(frame.data, frame.meta);
18707
- this.#emit(frame.data, frame.meta);
19192
+ if (!stale) this.#emit(frame.data, frame.meta);
18708
19193
  }
18709
19194
  };
18710
19195
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -18965,11 +19450,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
18965
19450
  /**
18966
19451
  * Typed view of the ISO-BMFF timing-sample budget.
18967
19452
  *
18968
- * This is the acceptance signal for the budget ratchet: `pending` walking
18969
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
18970
- * and it is observable here rather than only as media silently stopping.
18971
- * Per repo policy this is a producer-owned counter -- never infer budget
18972
- * state by parsing logs.
19453
+ * Each stream admits timing against its own window of `capacity` slots
19454
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
19455
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
19456
+ * timing a stream declared and never delivered shows up there. `pending`
19457
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
19458
+ * a producer-owned counter -- never infer budget state by parsing logs.
18973
19459
  */
18974
19460
  get timingBudgetStats() {
18975
19461
  return {
@@ -19029,6 +19515,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
19029
19515
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
19030
19516
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
19031
19517
  }
19518
+ /** See FecReleaseSequencer.unsource. */
19519
+ unsourceFecRelease(packetId, catalogTrackName) {
19520
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
19521
+ }
19522
+ /** See FecReleaseSequencer.holdsRebuilt. */
19523
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
19524
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
19525
+ }
19032
19526
  /** Re-evaluate held gaps after FEC block state changed. */
19033
19527
  pokeFecRelease(packetId, catalogTrackName) {
19034
19528
  if (!this.#fecSequencer) return;
@@ -19282,7 +19776,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19282
19776
  if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
19283
19777
  const pendingBefore = resolver2.pendingSampleCount;
19284
19778
  const evictedBefore = resolver2.evictedSampleCount;
19285
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
19779
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
19286
19780
  const admitted = resolver2.addMovieFragment(
19287
19781
  mpu.mpuSequenceNumber,
19288
19782
  data,
@@ -19355,7 +19849,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
19355
19849
  info,
19356
19850
  resolver,
19357
19851
  options?.recovered === true,
19358
- options?.fecSbn
19852
+ options?.fecSbn,
19853
+ options?.fecSbnFirst
19359
19854
  );
19360
19855
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
19361
19856
  }
@@ -19448,7 +19943,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
19448
19943
  info,
19449
19944
  resolver,
19450
19945
  options?.recovered === true,
19451
- options?.fecSbn
19946
+ options?.fecSbn,
19947
+ options?.fecSbnFirst
19452
19948
  );
19453
19949
  if (outcome.record !== void 0) return outcome.record;
19454
19950
  return this.#drop(outcome.reason);
@@ -19468,7 +19964,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19468
19964
  * attribution exists to keep readable. Leaving the choice at the call site
19469
19965
  * is what keeps both true.
19470
19966
  */
19471
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
19967
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
19472
19968
  const timing = resolver.sampleTiming(
19473
19969
  combined.mpuSequenceNumber,
19474
19970
  combined.movieFragmentSequenceNumber,
@@ -19485,6 +19981,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19485
19981
  );
19486
19982
  if (!meta) return { reason: "combined-meta-build-failed" };
19487
19983
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
19984
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
19488
19985
  if (!resolver.consumeSample(
19489
19986
  combined.mpuSequenceNumber,
19490
19987
  combined.movieFragmentSequenceNumber,
@@ -23001,6 +23498,7 @@ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
23001
23498
  var OVERLAY_ROUTED_LIMIT = 1024;
23002
23499
  var OVERLAY_PENDING_LIMIT = 256;
23003
23500
  var OVERLAY_OFFSET_MPUS = 16;
23501
+ var OVERLAY_REBUILT_LIMIT = 256;
23004
23502
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
23005
23503
  function assertStreamIdentity(role, stream) {
23006
23504
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -23177,6 +23675,17 @@ var MmtpRouter = class {
23177
23675
  * an MPU no member of which arrived).
23178
23676
  */
23179
23677
  #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
23678
+ /**
23679
+ * The same, shown by the overlay alone, before any base recovery did: a
23680
+ * packet it rebuilt whose base copy carries its protected psn
23681
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
23682
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
23683
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
23684
+ * make the base drop a late base copy of a keyframe the overlay never
23685
+ * finished, and lift a block's late-source cut, which nothing before
23686
+ * this offset did.
23687
+ */
23688
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
23180
23689
  /**
23181
23690
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
23182
23691
  * not parsed, typically because its overlap copy was parsed first
@@ -23222,6 +23731,8 @@ var MmtpRouter = class {
23222
23731
  // end: a synchronous recovery completes its block BEFORE routing the
23223
23732
  // recovered frames, and releasing a held gap in between would strand them.
23224
23733
  #fecPokeDepth = 0;
23734
+ /** FecReleaseGate.wakeAt timers, by media stream key. */
23735
+ #fecWakes = /* @__PURE__ */ new Map();
23225
23736
  #pendingFecPokes = /* @__PURE__ */ new Map();
23226
23737
  // ── Phase 14: per-role packetId dispatch (D-26, D-27, D-28) ───────
23227
23738
  /** Maps packetId → TrackRole. Default: 'single' when absent (legacy path). */
@@ -23454,13 +23965,18 @@ var MmtpRouter = class {
23454
23965
  this.#onDeltaBlockCompleteCb?.(packetId, false);
23455
23966
  }
23456
23967
  };
23457
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
23968
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
23458
23969
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
23459
23970
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
23460
23971
  this.#onDeltaBlockCompleteCb?.(packetId, true);
23461
23972
  }
23462
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23463
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23973
+ if (span === void 0) {
23974
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23975
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23976
+ } else {
23977
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
23978
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
23979
+ }
23464
23980
  };
23465
23981
  }
23466
23982
  }
@@ -23505,8 +24021,9 @@ var MmtpRouter = class {
23505
24021
  }
23506
24022
  /**
23507
24023
  * FEC-recovered source symbols whose reconstructed header named a
23508
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
23509
- * a hop re-stamped the sequence after the sender protected the packet.
24024
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
24025
+ * or, rebuilt by the overlay, than their base copy carries: a hop
24026
+ * re-stamped the sequence after the sender protected the packet.
23510
24027
  */
23511
24028
  get restampedRecoveredSequenceCount() {
23512
24029
  return this.#restampedRecoveredSeqs;
@@ -23685,6 +24202,7 @@ var MmtpRouter = class {
23685
24202
  enableMseAssembler(packetId, config, catalogTrackName) {
23686
24203
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
23687
24204
  const previous = this.#mseAssemblers.get(assemblerKey);
24205
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
23688
24206
  if (previous) {
23689
24207
  previous.flush();
23690
24208
  previous.dispose();
@@ -23835,7 +24353,8 @@ var MmtpRouter = class {
23835
24353
  fec,
23836
24354
  k,
23837
24355
  offsets: /* @__PURE__ */ new Map(),
23838
- moqBlocks: /* @__PURE__ */ new Set()
24356
+ moqBlocks: /* @__PURE__ */ new Set(),
24357
+ rebuilt: /* @__PURE__ */ new Map()
23839
24358
  };
23840
24359
  this.#overlays.set(repairPacketId, inst);
23841
24360
  return () => {
@@ -23876,6 +24395,7 @@ var MmtpRouter = class {
23876
24395
  inst.last = void 0;
23877
24396
  inst.offsets.clear();
23878
24397
  inst.moqBlocks.clear();
24398
+ inst.rebuilt.clear();
23879
24399
  }
23880
24400
  #overlaysForSource(sourcePacketId, catalogTrackName) {
23881
24401
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -23928,13 +24448,23 @@ var MmtpRouter = class {
23928
24448
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
23929
24449
  * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
23930
24450
  * FEC reads it.
24451
+ *
24452
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
24453
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
24454
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
24455
+ * the stream unstamped at the SS_ID offset it states, for the release gate
24456
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
24457
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
23931
24458
  */
23932
24459
  #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
23933
24460
  if (this.#overlays.size === 0) return;
23934
24461
  const ssId = keyframeOverlaySsId(header);
23935
24462
  if (ssId === void 0) return;
24463
+ let rebuiltPsn;
23936
24464
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
23937
24465
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
24466
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
24467
+ inst.rebuilt.delete(ssId);
23938
24468
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
23939
24469
  if (identity !== null) {
23940
24470
  inst.offsets.delete(identity.mpuSequenceNumber);
@@ -23964,6 +24494,14 @@ var MmtpRouter = class {
23964
24494
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
23965
24495
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
23966
24496
  }
24497
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
24498
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
24499
+ if (rebuiltPsn !== sequenceNumber) {
24500
+ this.#restampedRecoveredSeqs++;
24501
+ } else if (baseSsId !== void 0) {
24502
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24503
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
24504
+ }
23967
24505
  }
23968
24506
  #noteOverlayMoqBlock(inst, blockStart) {
23969
24507
  inst.moqBlocks.add(blockStart);
@@ -23997,11 +24535,16 @@ var MmtpRouter = class {
23997
24535
  }
23998
24536
  /**
23999
24537
  * Route an overlay-recovered block's packets as source media of the
24000
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
24001
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
24002
- * base re-stamp, no block advance. Each packet's wire sequence is restored
24003
- * from its keyframe's own offset; without one, a stream the base never
24004
- * re-stamped keeps the header's sequence and any other drops the packet.
24538
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
24539
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
24540
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
24541
+ * base FEC recovered does, so it waits behind base frames still in flight,
24542
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
24543
+ * longer than unanchored; one whose base SS_ID is undetermined has no
24544
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
24545
+ * advance. Each packet's wire sequence is restored from its keyframe's own
24546
+ * offset; without one, a stream the base never re-stamped keeps the
24547
+ * header's sequence and any other drops the packet.
24005
24548
  */
24006
24549
  #routeOverlayRecovered(inst, blockStart, recovered) {
24007
24550
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -24022,40 +24565,65 @@ var MmtpRouter = class {
24022
24565
  const restamped = this.#restampedStreams.has(streamKey);
24023
24566
  const restored = /* @__PURE__ */ new Set();
24024
24567
  const baseSsIds = /* @__PURE__ */ new Map();
24568
+ const gateOnly = /* @__PURE__ */ new Set();
24025
24569
  const symbols = result.symbols.flatMap((sym) => {
24570
+ const overlaySsId = serial32Add(blockStart, sym.index);
24026
24571
  const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
24027
24572
  if (anchor !== void 0) {
24028
- const overlaySsId = serial32Add(blockStart, sym.index);
24029
24573
  const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
24030
24574
  restored.add(packetSequenceNumber);
24031
24575
  const out = { ...sym, packetSequenceNumber };
24032
24576
  const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
24033
- if (baseSsId !== void 0) baseSsIds.set(out, baseSsId);
24577
+ if (baseSsId !== void 0) {
24578
+ baseSsIds.set(sym.index, baseSsId);
24579
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24580
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
24581
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
24582
+ }
24583
+ }
24034
24584
  return [out];
24035
24585
  }
24036
24586
  if (!restamped) {
24037
- const baseSsId = unstampedBaseSsId(
24038
- this.#ssIdSeqOffsetByStream.get(streamKey),
24039
- this.#unstampedSsIdSeqOffsetByStream.get(streamKey),
24040
- sym.packetSequenceNumber
24041
- );
24042
- if (baseSsId !== void 0) baseSsIds.set(sym, baseSsId);
24587
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24588
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
24589
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
24590
+ if (baseSsId !== void 0) {
24591
+ baseSsIds.set(sym.index, baseSsId);
24592
+ if (fedSsId === void 0) gateOnly.add(sym.index);
24593
+ } else {
24594
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
24595
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
24596
+ }
24043
24597
  return [sym];
24044
24598
  }
24045
24599
  this.#overlayStats.unsequencedDropped++;
24046
24600
  return [];
24047
24601
  });
24048
24602
  this.#overlayStats.recovered++;
24603
+ const mpuFirst = /* @__PURE__ */ new Map();
24604
+ for (const sym of symbols) {
24605
+ const ssId = baseSsIds.get(sym.index);
24606
+ const mpu = sym.fragment.mpuSequenceNumber;
24607
+ const first = mpuFirst.get(mpu);
24608
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
24609
+ }
24610
+ const firstSsIds = /* @__PURE__ */ new Map();
24611
+ for (const sym of symbols) {
24612
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
24613
+ }
24049
24614
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
24050
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
24615
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
24616
+ baseSsIds,
24617
+ firstSsIds
24051
24618
  });
24052
24619
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
24053
- this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds);
24620
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
24054
24621
  }
24055
24622
  /**
24056
24623
  * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
24057
24624
  * its base block too, once its base SS_ID is determined (overlayBaseSsId,
24058
- * from a received member of its MPU, else unstampedBaseSsId),
24625
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
24626
+ * base recovery showed; `baseSsIds` holds no other),
24059
24627
  * so it is fed to the base decoder as a rebuilt source
24060
24628
  * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
24061
24629
  * fewer to solve, and its repair can recover the block's other packets.
@@ -24081,7 +24649,7 @@ var MmtpRouter = class {
24081
24649
  const feeds = [];
24082
24650
  for (const sym of symbols) {
24083
24651
  if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
24084
- const ssId = baseSsIds.get(sym);
24652
+ const ssId = baseSsIds.get(sym.index);
24085
24653
  if (ssId === void 0) {
24086
24654
  this.#overlayStats.baseUndetermined++;
24087
24655
  continue;
@@ -24810,7 +25378,7 @@ var MmtpRouter = class {
24810
25378
  catalogTrackName
24811
25379
  )) continue;
24812
25380
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
24813
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
25381
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
24814
25382
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
24815
25383
  }
24816
25384
  if (payload.oversized) continue;
@@ -24898,6 +25466,7 @@ var MmtpRouter = class {
24898
25466
  this.#latestVideoSeqByStream.delete(streamKey);
24899
25467
  this.#ssIdSeqOffsetByStream.delete(streamKey);
24900
25468
  this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
25469
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
24901
25470
  this.#multicastRapTwinByStream.delete(streamKey);
24902
25471
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
24903
25472
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -25024,6 +25593,12 @@ var MmtpRouter = class {
25024
25593
  * the outgoing stream stops. The hold is bounded by the incoming stream's
25025
25594
  * own RAP cadence, so no timer is involved.
25026
25595
  *
25596
+ * While the switch is staged, the FEC release gate lets a keyframe the
25597
+ * overlay rebuilt reach it, on either side, when the keyframe did before
25598
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
25599
+ * decides on what each side delivered, and the commit discards the gate's
25600
+ * frames of the outgoing stream.
25601
+ *
25027
25602
  * The commit is one synchronous transition inside the frame path: the
25028
25603
  * outgoing stream's already-admitted frames are released (its queued FEC
25029
25604
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -25074,6 +25649,9 @@ var MmtpRouter = class {
25074
25649
  droppedIncomingFrames: 0
25075
25650
  };
25076
25651
  this.#staged = state;
25652
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
25653
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
25654
+ }
25077
25655
  return {
25078
25656
  cancel: () => {
25079
25657
  if (this.#staged !== state) return false;
@@ -25156,7 +25734,17 @@ var MmtpRouter = class {
25156
25734
  */
25157
25735
  #routeParsedFrame(data, meta) {
25158
25736
  if (this.#classifyPacketId(meta.packetId) === null) return;
25159
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
25737
+ if (this.#staged !== null) {
25738
+ let consumed = false;
25739
+ this.#fecPokeDepth++;
25740
+ try {
25741
+ consumed = this.#interceptSwitchFrame(data, meta);
25742
+ } finally {
25743
+ this.#fecPokeDepth--;
25744
+ this.#flushPendingFecPokes();
25745
+ }
25746
+ if (consumed) return;
25747
+ }
25160
25748
  this.#deliverParsedFrame(data, meta);
25161
25749
  }
25162
25750
  #commitStreamSwitch(state, rap, reason) {
@@ -25205,6 +25793,8 @@ var MmtpRouter = class {
25205
25793
  this.#disposed = true;
25206
25794
  this.#staged = null;
25207
25795
  this.cancelKeyframeLostTimer();
25796
+ for (const { timer } of this.#fecWakes.values()) clearTimeout(timer);
25797
+ this.#fecWakes.clear();
25208
25798
  this.#parser.dispose();
25209
25799
  this.#streams.clear();
25210
25800
  this.#trackPacketCallbacks.clear();
@@ -25308,12 +25898,16 @@ var MmtpRouter = class {
25308
25898
  this.#parser.deferFecRelease(work);
25309
25899
  } finally {
25310
25900
  this.#fecPokeDepth--;
25311
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
25312
- const pokes = [...this.#pendingFecPokes.values()];
25313
- this.#pendingFecPokes.clear();
25314
- for (const poke of pokes) {
25315
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
25316
- }
25901
+ this.#flushPendingFecPokes();
25902
+ }
25903
+ }
25904
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
25905
+ #flushPendingFecPokes() {
25906
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
25907
+ const pokes = [...this.#pendingFecPokes.values()];
25908
+ this.#pendingFecPokes.clear();
25909
+ for (const poke of pokes) {
25910
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
25317
25911
  }
25318
25912
  }
25319
25913
  }
@@ -25382,6 +25976,31 @@ var MmtpRouter = class {
25382
25976
  if (!fec?.terminalRetentionMsForPacket) return Infinity;
25383
25977
  return fec.terminalRetentionMsForPacket(packetId) ?? 0;
25384
25978
  },
25979
+ // Once no repair can fill a gap (FECManager.isoRepairlessWaitMs: only a
25980
+ // late source can), its frame waits the late-symbol allowance when the
25981
+ // gap holds no RAP an installed keyframe overlay could still rebuild:
25982
+ // lost deltas of one MPU (delta-lost), the tail of the MPU before a RAP
25983
+ // that opens the next one while MPU boundaries bound RAPs (rap-next,
25984
+ // unless the gap holds a stated block's loss: the overlay may rebuild
25985
+ // that MPU's FT=0, and the block's group then complete it), or
25986
+ // an audio gap. A gap that may hold one (rap-lost, rap-unknown, or any
25987
+ // other rap-next, whose gap may hold a whole MPU and the keyframe the
25988
+ // overlay protects) waits for that overlay's repair too (BLO-52085
25989
+ // D4). The FEC check comes first: most held gaps are not behind such a
25990
+ // span, and deciding one scans both frames' bitstreams.
25991
+ unrepairableWaitMs: (before, after, fromSbn, toSbn) => {
25992
+ const fec = this.#fecManager;
25993
+ const { packetId, catalogTrackName } = after.meta;
25994
+ const allowanceMs = fec?.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn);
25995
+ if (!fec || allowanceMs === void 0) return void 0;
25996
+ const decision = this.#decideGap(before, after, [], false);
25997
+ const mpu = before.meta.mpuSequenceNumber;
25998
+ const intoNextMpu = decision.reason === "rap-next" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu + 1 >>> 0 && fec.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
25999
+ if (decision.action === "stall" || decision.reason === "rap-next" && !intoNextMpu) {
26000
+ return fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, true);
26001
+ }
26002
+ return decision.reason === "rap-next" ? fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, true) : allowanceMs;
26003
+ },
25385
26004
  decide: (before, after, lostBlocks, discontinuity) => {
25386
26005
  const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
25387
26006
  this.#onFrameGap?.(decision);
@@ -25391,6 +26010,28 @@ var MmtpRouter = class {
25391
26010
  onRap: (packetId, catalogTrackName, ssId) => {
25392
26011
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
25393
26012
  },
26013
+ // One timer per stream, at the earliest wake asked: its drain re-arms
26014
+ // for the next frame still waiting.
26015
+ wakeAt: (packetId, catalogTrackName, atMs) => {
26016
+ if (this.#disposed) return;
26017
+ const key = this.#mediaStreamKey(packetId, catalogTrackName);
26018
+ const armed = this.#fecWakes.get(key);
26019
+ if (armed !== void 0 && armed.atMs <= atMs) return;
26020
+ if (armed !== void 0) clearTimeout(armed.timer);
26021
+ const timer = setTimeout(() => {
26022
+ this.#fecWakes.delete(key);
26023
+ this.#requestFecPoke(packetId, catalogTrackName);
26024
+ }, Math.max(0, Math.ceil(atMs - performance.now())));
26025
+ this.#fecWakes.set(key, { atMs, timer });
26026
+ },
26027
+ // A staged switch commits on when each side's frames reach it
26028
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
26029
+ // they did unanchored.
26030
+ releaseUnanchored: (packetId, catalogTrackName) => {
26031
+ const staged = this.#staged;
26032
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
26033
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
26034
+ },
25394
26035
  onReleased: (data, meta) => {
25395
26036
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
25396
26037
  const timing = meta.authoredTiming;
@@ -25841,7 +26482,8 @@ var MmtpRouter = class {
25841
26482
  source: parserOptions?.source,
25842
26483
  deliveryProvenance: parserOptions?.deliveryProvenance,
25843
26484
  catalogTrackName: parserOptions?.catalogTrackName,
25844
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
26485
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
26486
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
25845
26487
  };
25846
26488
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
25847
26489
  else this.#parser.feed(packet, feedOptions);
@@ -26307,7 +26949,12 @@ var MmtpRouter = class {
26307
26949
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
26308
26950
  if (ownerPacketId == null) return;
26309
26951
  if (this.#classifyPacketId(ownerPacketId) === null) return;
26310
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
26952
+ const fecSbnOf = (index) => {
26953
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
26954
+ const fecSbn = overlay.baseSsIds.get(index);
26955
+ const fecSbnFirst = overlay.firstSsIds.get(index);
26956
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
26957
+ };
26311
26958
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
26312
26959
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
26313
26960
  if (ssIdSeqOffset !== void 0) {
@@ -28103,6 +28750,12 @@ function isNonNegativeSafeInteger(value) {
28103
28750
  function isSymbolCounts(value) {
28104
28751
  return isRecord(value) && hasExactKeys(value, ["multicast", "moq"]) && isNonNegativeSafeInteger(value["multicast"]) && isNonNegativeSafeInteger(value["moq"]);
28105
28752
  }
28753
+ function isSpanFailure(value) {
28754
+ if (!isRecord(value) || !hasExactKeys(value, ["length", "sources"])) return false;
28755
+ const length = value["length"];
28756
+ const sources = value["sources"];
28757
+ return Number.isSafeInteger(length) && length > 0 && isNonNegativeSafeInteger(sources) && sources < length;
28758
+ }
28106
28759
  function isNullableNonNegative(value) {
28107
28760
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
28108
28761
  }
@@ -28122,7 +28775,10 @@ function isRepairLifecycleEvent(value) {
28122
28775
  case "recovered":
28123
28776
  return hasExactKeys(value, ["version", "type", "block", "blockClass", "via", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && (value["via"] === "inband" || value["via"] === "quic") && isSymbolCounts(value["symbols"]);
28124
28777
  case "failed":
28125
- return hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]);
28778
+ return hasExactKeys(
28779
+ value,
28780
+ "span" in value ? ["version", "type", "block", "blockClass", "symbols", "span"] : ["version", "type", "block", "blockClass", "symbols"]
28781
+ ) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]) && (!("span" in value) || isSpanFailure(value["span"]));
28126
28782
  case "repair-preempted":
28127
28783
  case "repair-deferred":
28128
28784
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
@@ -28331,6 +28987,8 @@ var MulticastManager = class {
28331
28987
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
28332
28988
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
28333
28989
  #repairReleases = /* @__PURE__ */ new Map();
28990
+ /** Protected repair flows owned by each live repair-endpoint release. */
28991
+ #repairProvenanceFlows = /* @__PURE__ */ new Map();
28334
28992
  /** Each source's catalog keyframe overlay, from its `ok` binding. */
28335
28993
  #overlayBindings = /* @__PURE__ */ new Map();
28336
28994
  /** Installed overlay decoders (`setKeyframeOverlayDecoder`), by source. */
@@ -28388,7 +29046,7 @@ var MulticastManager = class {
28388
29046
  onPublisherRestart: (packetId, catalogTrackName) => {
28389
29047
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
28390
29048
  },
28391
- onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
29049
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass, span) => {
28392
29050
  const pathCount = this.#fec.blockPathCount(
28393
29051
  sbn,
28394
29052
  packetId,
@@ -28406,7 +29064,8 @@ var MulticastManager = class {
28406
29064
  symbols: {
28407
29065
  multicast: pathCount?.multicastSymbols ?? 0,
28408
29066
  moq: pathCount?.moqSymbols ?? 0
28409
- }
29067
+ },
29068
+ ...span === void 0 ? {} : { span }
28410
29069
  });
28411
29070
  },
28412
29071
  onFrameGap: (decision) => {
@@ -28494,6 +29153,11 @@ var MulticastManager = class {
28494
29153
  this.#fec.onBlockVanished = (_sbn, packetId, catalogTrackName) => {
28495
29154
  this.#statsFor(packetId, catalogTrackName).vanishedBlocks++;
28496
29155
  };
29156
+ this.#fec.keyframeOverlayTiming = (packetId, catalogTrackName) => {
29157
+ const binding = this.#overlayInstalls.has(packetId) ? this.#overlayBindings.get(packetId) : void 0;
29158
+ if (binding === void 0) return void 0;
29159
+ return catalogTrackName === void 0 || catalogTrackName === binding.sourceCatalogTrackName ? binding.geometry : void 0;
29160
+ };
28497
29161
  this.#fec.onDecoderUnavailable = (event) => {
28498
29162
  this.#emitRepairLifecycle({
28499
29163
  version: 2,
@@ -28996,6 +29660,9 @@ var MulticastManager = class {
28996
29660
  this.#transport.onFailback((reason) => {
28997
29661
  const joined = this.#provenanceJoin;
28998
29662
  if (joined !== null) this.#router.unprotectProvenanceFlow(joined.flow);
29663
+ for (const flows of this.#repairProvenanceFlows.values()) {
29664
+ for (const flow of flows) this.#router.unprotectProvenanceFlow(flow);
29665
+ }
28999
29666
  this.#onFailback?.(reason);
29000
29667
  });
29001
29668
  }
@@ -29030,6 +29697,12 @@ var MulticastManager = class {
29030
29697
  "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
29031
29698
  );
29032
29699
  }
29700
+ if (provenanceFlow !== void 0) {
29701
+ const flow = multicastProvenanceFlowKey(provenanceFlow);
29702
+ if ([...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
29703
+ throw new TypeError(`[MulticastManager] join: provenance flow already registered by a repair endpoint: ${flow}`);
29704
+ }
29705
+ }
29033
29706
  const staged = this.#renditionSwitch;
29034
29707
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
29035
29708
  this.configureFec(config);
@@ -29037,8 +29710,8 @@ var MulticastManager = class {
29037
29710
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
29038
29711
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
29039
29712
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
29040
- this.#releaseProvenanceJoin();
29041
29713
  const provenance = config.provenance;
29714
+ this.#releaseProvenanceJoin();
29042
29715
  const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
29043
29716
  const ingress = protectedTracks === void 0 ? void 0 : {
29044
29717
  tracks: Object.freeze(
@@ -29091,8 +29764,13 @@ var MulticastManager = class {
29091
29764
  * feeds the flow's receiver; media datagrams are held until one admits them.
29092
29765
  */
29093
29766
  #joinProvenance(provenance, ingress) {
29767
+ this.#router.registerProvenanceFlow(ingress, this.#provenanceReceiver(provenance));
29768
+ this.#hookFailback();
29769
+ this.#provenanceJoin = { flow: ingress.flow };
29770
+ }
29771
+ #provenanceReceiver(provenance) {
29094
29772
  const { flow, auth } = provenance;
29095
- const receiver = new BcProvenanceV2Receiver({
29773
+ return new BcProvenanceV2Receiver({
29096
29774
  ...provenance.receiver,
29097
29775
  // The caller's ctx when it passes one, else the catalog's: an explicit
29098
29776
  // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
@@ -29109,9 +29787,6 @@ var MulticastManager = class {
29109
29787
  maxAuthDelayMs: flow.maxAuthDelayMs,
29110
29788
  manifestTimerMs: flow.manifestTimerMs
29111
29789
  });
29112
- this.#router.registerProvenanceFlow(ingress, receiver);
29113
- this.#hookFailback();
29114
- this.#provenanceJoin = { flow: ingress.flow };
29115
29790
  }
29116
29791
  /** Un-protect: drop the flow's hold queues (no expiry counted). */
29117
29792
  #releaseProvenanceJoin() {
@@ -29142,8 +29817,25 @@ var MulticastManager = class {
29142
29817
  * callback delivers must come from a subscription opened on
29143
29818
  * `options.gateway`. A callback that also merges another source (a MoQ or
29144
29819
  * WebSocket repair feed) must not name a native provider here.
29820
+ *
29821
+ * An endpoint's `provenance` makes its group a protected flow of its own
29822
+ * (multicast-02 7.2.7), registered here and released with the group; its
29823
+ * records ride in band on the group's port. On the user-agent path a
29824
+ * flow-less repair group of a protected track is set aside, never read, so
29825
+ * a player joining a protected catalog's repair groups passes it.
29145
29826
  */
29146
29827
  joinRepairEndpoints(endpoints, provider, options) {
29828
+ for (const { provenance, flow, source, group, port: port2 } of endpoints) {
29829
+ if (provenance === void 0) continue;
29830
+ if (flow !== void 0) {
29831
+ throw new TypeError("[MulticastManager] joinRepairEndpoints: an endpoint names provenance or flow, never both");
29832
+ }
29833
+ if (!sameIpAddress(source, provenance.flow.source) || !sameIpAddress(group, provenance.flow.groupAddress) || port2 !== provenance.flow.port) {
29834
+ throw new RangeError(
29835
+ "[MulticastManager] joinRepairEndpoints: provenance flow (S, G, port) must match the endpoint's source, group and port"
29836
+ );
29837
+ }
29838
+ }
29147
29839
  const releases = [];
29148
29840
  let released = false;
29149
29841
  const safely = (each) => {
@@ -29153,17 +29845,36 @@ var MulticastManager = class {
29153
29845
  console.warn("[MulticastManager] repair group release failed", error);
29154
29846
  }
29155
29847
  };
29848
+ const usedFlows = new Set(endpoints.flatMap(({ flow }) => flow === void 0 ? [] : [flow]));
29849
+ const preparedProvenance = endpoints.map((endpoint) => {
29850
+ if (endpoint.provenance === void 0) return void 0;
29851
+ const flow = multicastProvenanceFlowKey(endpoint.provenance.flow);
29852
+ if (usedFlows.has(flow) || this.#provenanceJoin?.flow === flow || [...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
29853
+ throw new TypeError(`[MulticastManager] joinRepairEndpoints: provenance flow already registered: ${flow}`);
29854
+ }
29855
+ usedFlows.add(flow);
29856
+ return { flow, receiver: this.#provenanceReceiver(endpoint.provenance) };
29857
+ });
29858
+ const provenanceFlows = [];
29156
29859
  const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners.map((owner) => owner.instance !== "keyframe" ? owner : {
29157
29860
  ...owner,
29158
29861
  ownerTrackName: endpoint.tracks.find((t) => t.packetId === owner.ownerPacketId)?.name,
29159
29862
  repairTrackName: endpoint.tracks.find((t) => t.packetId === owner.packetId)?.name
29160
29863
  }));
29161
29864
  this.#applyRepairOwners(repairOwners);
29162
- for (const endpoint of endpoints) {
29865
+ for (const [index, endpoint] of endpoints.entries()) {
29866
+ const flow = endpoint.provenance === void 0 ? endpoint.flow : multicastProvenanceFlowKey(endpoint.provenance.flow);
29163
29867
  const ingress = {
29164
29868
  tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
29165
- ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
29869
+ ...flow === void 0 ? {} : { flow }
29166
29870
  };
29871
+ if (endpoint.provenance !== void 0) {
29872
+ const prepared = preparedProvenance[index];
29873
+ if (prepared === void 0) throw new Error("[MulticastManager] repair provenance preparation missing");
29874
+ this.#router.registerProvenanceFlow(ingress, prepared.receiver);
29875
+ provenanceFlows.push(prepared.flow);
29876
+ releases.push(() => this.#router.releaseProvenanceFlow(flow));
29877
+ }
29167
29878
  let sender;
29168
29879
  const feed = (packet, sourceAddress, ingressToFeed) => {
29169
29880
  if (released) return;
@@ -29193,7 +29904,7 @@ var MulticastManager = class {
29193
29904
  packetIds: endpoint.packetIds,
29194
29905
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
29195
29906
  // A protected repair group's records ride in band on its port (7.2.3).
29196
- ...endpoint.flow === void 0 ? {} : { protected: true }
29907
+ ...flow === void 0 ? {} : { protected: true }
29197
29908
  }, ingress).then((joined) => {
29198
29909
  if (!joined && !released) fail(transport.lastJoinOutcome);
29199
29910
  });
@@ -29202,9 +29913,12 @@ var MulticastManager = class {
29202
29913
  if (released) return;
29203
29914
  released = true;
29204
29915
  this.#repairReleases.delete(release);
29916
+ this.#repairProvenanceFlows.delete(release);
29205
29917
  for (const each of releases.splice(0)) safely(each);
29206
29918
  };
29207
29919
  this.#repairReleases.set(release, repairOwners);
29920
+ this.#repairProvenanceFlows.set(release, provenanceFlows);
29921
+ if (provenanceFlows.length) this.#hookFailback();
29208
29922
  return release;
29209
29923
  }
29210
29924
  #applyRepairOwners(owners) {
@@ -29690,7 +30404,8 @@ var MulticastManager = class {
29690
30404
  blockProfile: parseFecBlockProfile(
29691
30405
  geometry2.blockProfile,
29692
30406
  `tracks[${JSON.stringify(track.name)}].fec keyframe overlay blockProfile`
29693
- )
30407
+ ),
30408
+ geometry: geometry2
29694
30409
  });
29695
30410
  }
29696
30411
  }
@@ -29729,7 +30444,7 @@ var MulticastManager = class {
29729
30444
  for (const [sourcePacketId, install] of [...this.#overlayInstalls]) {
29730
30445
  const before = this.#overlayBindings.get(sourcePacketId);
29731
30446
  const after = overlayBindings.get(sourcePacketId);
29732
- const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => after[key] === before[key]);
30447
+ const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => key === "geometry" || after[key] === before[key]);
29733
30448
  if (!same) install.dispose();
29734
30449
  else if (this.#router.hasKeyframeOverlay(after.repairPacketId)) this.#router.resetKeyframeOverlays(sourcePacketId);
29735
30450
  else install.reattach();
@@ -29786,10 +30501,12 @@ var MulticastManager = class {
29786
30501
  * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
29787
30502
  * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
29788
30503
  * pending hole and reported here, and `closeIsoHoles` must be called for it
29789
- * once its range FETCH ends (or none is sent).
30504
+ * once its range FETCH ends (or none is sent). `onExpired` is told of a
30505
+ * pending hole the stream runs past the locator's horizon: returning true,
30506
+ * the caller closes it (`closeIsoHoles`); otherwise it is discarded.
29790
30507
  */
29791
- onUndelimitedLoss(cb) {
29792
- this.#fec.setUndelimitedLossHandler(cb);
30508
+ onUndelimitedLoss(cb, onExpired) {
30509
+ this.#fec.setUndelimitedLossHandler(cb, onExpired ?? null);
29793
30510
  }
29794
30511
  /**
29795
30512
  * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
@@ -30025,7 +30742,8 @@ var MulticastManager = class {
30025
30742
  "stream" in event ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
30026
30743
  ...event,
30027
30744
  block: Object.freeze({ ...event.block }),
30028
- ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {}
30745
+ ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {},
30746
+ ..."span" in event && event.span !== void 0 ? { span: Object.freeze({ ...event.span }) } : {}
30029
30747
  }
30030
30748
  );
30031
30749
  if (this.#logRepairLifecycle) {
@@ -32697,6 +33415,7 @@ var RepairLayerSubscriptions = class {
32697
33415
 
32698
33416
  // src/repair-fetch.ts
32699
33417
  var MOQT_PRIORITY_MAX = 255;
33418
+ var WALK_LEAD_MS = 3;
32700
33419
  var SOURCE_MEDIA_PRIORITY_MAX = REPAIR_PRIORITY_MIN - 1;
32701
33420
  function isMoqtPriority(value) {
32702
33421
  return Number.isSafeInteger(value) && value >= 0 && value <= MOQT_PRIORITY_MAX;
@@ -32747,8 +33466,17 @@ function wireRepairFetch(mc, opts) {
32747
33466
  mc.noteRepairScheduling(type, entry.sbn, entry.packetId, entry.catalogTrackName);
32748
33467
  };
32749
33468
  const clearEntry = (entry) => {
32750
- if (entry.range) mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, entry.range.holeLength);
32751
- else clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
33469
+ const { range } = entry;
33470
+ if (range) {
33471
+ atReport(range, () => mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, range.holeLength));
33472
+ } else {
33473
+ clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
33474
+ }
33475
+ };
33476
+ const atReport = (range, work) => {
33477
+ const fec = mc.fecManager;
33478
+ if (range.groups !== null || fec.withReceiptTime === void 0) work();
33479
+ else fec.withReceiptTime(range.reportedAt, work);
32752
33480
  };
32753
33481
  const releaseHold = (entry) => {
32754
33482
  if (entry.range) return;
@@ -32760,7 +33488,7 @@ function wireRepairFetch(mc, opts) {
32760
33488
  if (!run) return;
32761
33489
  entry.running = null;
32762
33490
  run.stopped = reason;
32763
- run.controller.abort();
33491
+ run.controller.abort(reason);
32764
33492
  if (reason === "preempted") releaseHold(entry);
32765
33493
  mc.noteRepairStopped?.(reason, entry.sbn, entry.packetId, entry.catalogTrackName);
32766
33494
  };
@@ -32815,21 +33543,42 @@ function wireRepairFetch(mc, opts) {
32815
33543
  const admit = (entry, now) => {
32816
33544
  const budgetMs = entry.deadlineAt - now;
32817
33545
  const rttMs = readRtt();
32818
- const reason = !entry.range && !groupCanComplete(entry.sbn, entry.packetId, entry.catalogTrackName) ? "group-cannot-complete" : rttMs === null ? "rtt-unmeasured" : rttMs < budgetMs ? null : "rtt-exceeds-budget";
33546
+ const reason = refusal(entry, now, rttMs);
32819
33547
  if (reason === null) return rttMs;
32820
33548
  skip(entry, reason, rttMs, budgetMs);
32821
33549
  return null;
32822
33550
  };
33551
+ const refusal = (entry, now, rttMs) => !entry.range && !groupCanComplete(entry.sbn, entry.packetId, entry.catalogTrackName) ? "group-cannot-complete" : rttMs === null ? "rtt-unmeasured" : rttMs < entry.deadlineAt - now ? null : "rtt-exceeds-budget";
32823
33552
  const retire = (entry) => {
32824
33553
  if (entries.get(entry.key) === entry) entries.delete(entry.key);
32825
33554
  if (entry.expiry !== void 0) clearTimeout(entry.expiry);
32826
33555
  };
32827
- const outstandingBelow = (priority) => {
33556
+ const holdsBack = (entry, priority, videoWalks = true) => {
33557
+ if (entry.priority >= priority) return false;
33558
+ const { walk } = entry;
33559
+ if (walk === void 0) return true;
33560
+ if (entry.priority !== 0 || !videoWalks) return false;
33561
+ return entry.running === null || walk.group !== null && !walk.group.controller.signal.aborted;
33562
+ };
33563
+ const outstandingBelow = (priority, videoWalks = true) => {
32828
33564
  for (const entry of entries.values()) {
32829
- if (entry.priority < priority) return true;
33565
+ if (holdsBack(entry, priority, videoWalks)) return true;
32830
33566
  }
32831
33567
  return false;
32832
33568
  };
33569
+ const yieldVideoWalks = (queued) => {
33570
+ const now = performance.now();
33571
+ const rttMs = readRtt();
33572
+ const due = queued.some((entry) => entry.priority !== 0 && entry.walk === void 0 && !outstandingBelow(entry.priority, false) && refusal(entry, now, rttMs) === null);
33573
+ if (!due) return;
33574
+ for (const entry of entries.values()) {
33575
+ const walk = entry.walk;
33576
+ if (entry.priority !== 0 || walk === void 0 || walk.group === null) continue;
33577
+ if (walk.group.controller.signal.aborted) continue;
33578
+ walk.yielded = true;
33579
+ walk.group.controller.abort();
33580
+ }
33581
+ };
32833
33582
  const preemptBestEffort = () => {
32834
33583
  for (const entry of entries.values()) {
32835
33584
  if (entry.priority === 0 || !entry.running) continue;
@@ -32858,7 +33607,8 @@ function wireRepairFetch(mc, opts) {
32858
33607
  }
32859
33608
  const rttMs = admit(entry, now);
32860
33609
  if (rttMs === null) return;
32861
- if (entry.priority === 0) preemptBestEffort();
33610
+ if (entry.priority === 0 && entry.walk === void 0) preemptBestEffort();
33611
+ if (entry.range === void 0) leaveWalkedGroup(entry);
32862
33612
  if (counted) entry.attempts++;
32863
33613
  mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName, {
32864
33614
  rttMs,
@@ -32880,6 +33630,14 @@ function wireRepairFetch(mc, opts) {
32880
33630
  }
32881
33631
  void execute(entry, run);
32882
33632
  };
33633
+ const leaveWalkedGroup = (block) => {
33634
+ for (const entry of entries.values()) {
33635
+ const group = entry.walk?.group;
33636
+ if (group?.sbn === block.sbn && entry.packetId === block.packetId && entry.catalogTrackName === block.catalogTrackName) {
33637
+ group.controller.abort();
33638
+ }
33639
+ }
33640
+ };
32883
33641
  const dispatch = () => {
32884
33642
  if (disposed) return;
32885
33643
  const now = performance.now();
@@ -32904,6 +33662,7 @@ function wireRepairFetch(mc, opts) {
32904
33662
  for (const entry of queued) {
32905
33663
  if (entry.priority === 0) start(entry);
32906
33664
  }
33665
+ yieldVideoWalks(queued);
32907
33666
  if (outstandingBelow(1)) return;
32908
33667
  for (const entry of queued) {
32909
33668
  if (entry.priority === 1) start(entry);
@@ -32930,6 +33689,16 @@ function wireRepairFetch(mc, opts) {
32930
33689
  }
32931
33690
  return counts.sources + counts.repairGroupLength >= counts.authoredLength;
32932
33691
  };
33692
+ const groupServed = (sbn, packetId, catalogTrackName) => {
33693
+ if (mc.fecManager.blockSymbolCounts === void 0) return false;
33694
+ const counts = symbolCounts(sbn, packetId, catalogTrackName);
33695
+ if (counts === void 0 || counts.authoredLength === void 0) return true;
33696
+ return counts.sources + counts.repairs >= counts.authoredLength || !groupCanComplete(sbn, packetId, catalogTrackName);
33697
+ };
33698
+ const statedEnd = (sbn, packetId, catalogTrackName) => {
33699
+ const length = symbolCounts(sbn, packetId, catalogTrackName)?.authoredLength;
33700
+ return length === void 0 ? void 0 : serial32Add(sbn, length);
33701
+ };
32933
33702
  const finish = (entry, run, fed, error) => {
32934
33703
  if (run.stopped !== null || entry.running !== run || entries.get(entry.key) !== entry) {
32935
33704
  return;
@@ -32974,27 +33743,81 @@ function wireRepairFetch(mc, opts) {
32974
33743
  signal: run.controller.signal,
32975
33744
  subscriberPriority: entry.subscriberPriority
32976
33745
  };
33746
+ const { range } = entry;
33747
+ const feed = (packet) => {
33748
+ if (entry.catalogTrackName === void 0) {
33749
+ mc.processRepairFromMoQ(packet, entry.packetId);
33750
+ } else {
33751
+ mc.processRepairFromMoQ(packet, entry.packetId, entry.catalogTrackName);
33752
+ }
33753
+ };
32977
33754
  try {
32978
- const packets = entry.range ? opts.rangeTransport({
33755
+ const packets = range === void 0 ? opts.transport({ ...common, sbn: entry.sbn }) : entry.walk !== void 0 ? walkHole(entry, entry.walk, range, common) : opts.rangeTransport({
32979
33756
  ...common,
32980
- startGroup: entry.range.startGroup,
32981
- endGroup: entry.range.endGroup,
32982
- lostSsId: entry.range.lostSsId
32983
- }) : opts.transport({ ...common, sbn: entry.sbn });
33757
+ startGroup: range.groups.startGroup,
33758
+ endGroup: range.groups.endGroup,
33759
+ lostSsId: range.lostSsId
33760
+ });
32984
33761
  for await (const packet of packets) {
32985
33762
  if (run.stopped !== null || entry.running !== run) break;
32986
33763
  fed++;
32987
- if (entry.catalogTrackName === void 0) {
32988
- mc.processRepairFromMoQ(packet, entry.packetId);
32989
- } else {
32990
- mc.processRepairFromMoQ(packet, entry.packetId, entry.catalogTrackName);
32991
- }
33764
+ if (range === void 0) feed(packet);
33765
+ else atReport(range, () => feed(packet));
32992
33766
  }
32993
33767
  finish(entry, run, fed, void 0);
32994
33768
  } catch (error) {
32995
33769
  finish(entry, run, fed, error ?? new Error("repair transport rejected"));
32996
33770
  }
32997
33771
  };
33772
+ async function* walkHole(entry, walk, hole, common) {
33773
+ const lostAt = serial32Distance(entry.sbn, hole.lostSsId);
33774
+ for (let first = true; !common.signal.aborted; first = false) {
33775
+ if (!first && entry.priority !== 0 && outstandingBelow(1)) {
33776
+ stop(entry, "preempted");
33777
+ note("repair-preempted", entry);
33778
+ return;
33779
+ }
33780
+ if (!first && entry.priority === 0) {
33781
+ dispatch();
33782
+ if (common.signal.aborted) return;
33783
+ }
33784
+ const sbn = walk.next;
33785
+ let next;
33786
+ if (entries.get(requestKey(sbn, entry.packetId, entry.catalogTrackName))?.running == null) {
33787
+ const rsIds = /* @__PURE__ */ new Set();
33788
+ const group = new AbortController();
33789
+ const cancel = () => group.abort(common.signal.reason);
33790
+ common.signal.addEventListener("abort", cancel, { once: true });
33791
+ walk.group = { sbn, controller: group };
33792
+ try {
33793
+ for await (const packet of opts.transport({ ...common, sbn, signal: group.signal })) {
33794
+ yield packet;
33795
+ const id = extractRepairFecPayloadId(packet);
33796
+ if (id === null || id.ssStart !== sbn || id.ssbLength === 0) continue;
33797
+ next ??= serial32Add(sbn, id.ssbLength);
33798
+ rsIds.add(id.rsId);
33799
+ if (rsIds.size >= id.rsbLength || groupServed(sbn, entry.packetId, entry.catalogTrackName)) {
33800
+ group.abort();
33801
+ break;
33802
+ }
33803
+ }
33804
+ } catch (error) {
33805
+ if (!group.signal.aborted || common.signal.aborted) throw error;
33806
+ } finally {
33807
+ common.signal.removeEventListener("abort", cancel);
33808
+ walk.group = null;
33809
+ }
33810
+ if (walk.yielded) {
33811
+ walk.yielded = false;
33812
+ continue;
33813
+ }
33814
+ }
33815
+ next ??= statedEnd(sbn, entry.packetId, entry.catalogTrackName);
33816
+ if (next === void 0) return;
33817
+ if (serial32Distance(entry.sbn, next) > lostAt) return;
33818
+ walk.next = next;
33819
+ }
33820
+ }
32998
33821
  const removeResetObserver = mc.addTrackResetObserver((packetId, catalogTrackName) => {
32999
33822
  for (const entry of [...entries.values()]) {
33000
33823
  if (entry.packetId !== packetId || entry.catalogTrackName !== catalogTrackName) continue;
@@ -33190,7 +34013,37 @@ function wireRepairFetch(mc, opts) {
33190
34013
  throw error;
33191
34014
  }
33192
34015
  };
33193
- if (opts.rangeTransport !== void 0) {
34016
+ const trackKind = (packetId) => {
34017
+ try {
34018
+ return mc.fecManager.trackKindFor?.(packetId);
34019
+ } catch {
34020
+ return void 0;
34021
+ }
34022
+ };
34023
+ const walkDeadlineAt = (packetId, now, deadlineAt) => {
34024
+ let repairDeadlineMs;
34025
+ try {
34026
+ repairDeadlineMs = mc.fecManager.repairDeadlineMsForPacket?.(packetId);
34027
+ } catch {
34028
+ repairDeadlineMs = void 0;
34029
+ }
34030
+ if (repairDeadlineMs === void 0 || !Number.isFinite(repairDeadlineMs)) return deadlineAt;
34031
+ return Math.min(deadlineAt, now + repairDeadlineMs - WALK_LEAD_MS);
34032
+ };
34033
+ const onHoleExpired = (hole) => {
34034
+ if (disposed) return false;
34035
+ const entry = [...entries.values()].find((candidate) => candidate.walk !== void 0 && candidate.packetId === hole.packetId && candidate.catalogTrackName === hole.catalogTrackName && serial32Distance(candidate.sbn, hole.holeStart) < candidate.range.holeLength);
34036
+ if (entry === void 0) return false;
34037
+ queueMicrotask(() => {
34038
+ if (entries.get(entry.key) !== entry) return;
34039
+ retire(entry);
34040
+ stop(entry, "expired");
34041
+ clearEntry(entry);
34042
+ dispatch();
34043
+ });
34044
+ return true;
34045
+ };
34046
+ if (mc.onUndelimitedLoss !== void 0 && mc.closeIsoHoles !== void 0) {
33194
34047
  mc.onUndelimitedLoss((loss) => {
33195
34048
  const { packetId, catalogTrackName, holeStart, holeLength } = loss;
33196
34049
  const close = () => mc.closeIsoHoles(packetId, catalogTrackName, holeStart, holeLength);
@@ -33198,9 +34051,11 @@ function wireRepairFetch(mc, opts) {
33198
34051
  const blockProfile = blockProfileOf(packetId);
33199
34052
  const target = opts.resolveTarget(packetId, catalogTrackName);
33200
34053
  if (!target) return close();
33201
- const priority = repairPriorityForClass("unknown");
33202
- const range = rangeFor(loss, target.repairTrack);
33203
- if (range === null) {
34054
+ const walked = opts.rangeTransport === void 0;
34055
+ const holeClass = walked && trackKind(packetId) === "audio" ? "audio" : "unknown";
34056
+ const priority = repairPriorityForClass(holeClass);
34057
+ const groups = walked ? null : rangeFor(loss, target.repairTrack);
34058
+ if (!walked && groups === null) {
33204
34059
  close();
33205
34060
  mc.noteRepairSkipped("range-no-anchor", { rttMs: readRtt(), budgetMs: 0, priority }, holeStart, packetId, catalogTrackName);
33206
34061
  return;
@@ -33211,8 +34066,10 @@ function wireRepairFetch(mc, opts) {
33211
34066
  packetId,
33212
34067
  ...catalogTrackName === void 0 ? {} : { catalogTrackName }
33213
34068
  };
33214
- const wire = wirePriority(identity, "unknown");
33215
- const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, performance.now(), "unknown");
34069
+ const wire = wirePriority(identity, holeClass);
34070
+ if (wire === null) return close();
34071
+ const now = performance.now();
34072
+ const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, now, holeClass);
33216
34073
  if (deadline === null) {
33217
34074
  close();
33218
34075
  mc.noteRepairSkipped(
@@ -33224,6 +34081,7 @@ function wireRepairFetch(mc, opts) {
33224
34081
  );
33225
34082
  return;
33226
34083
  }
34084
+ const deadlineAt = walked ? walkDeadlineAt(packetId, now, deadline.deadlineAt) : deadline.deadlineAt;
33227
34085
  const entry = {
33228
34086
  key: JSON.stringify(["range", packetId, catalogTrackName ?? null, holeStart]),
33229
34087
  ...identity,
@@ -33231,15 +34089,16 @@ function wireRepairFetch(mc, opts) {
33231
34089
  blockProfile,
33232
34090
  priority,
33233
34091
  subscriberPriority: wire.subscriberPriority,
33234
- deadlineAt: deadline.deadlineAt,
33235
- playoutDeadlineAt: deadline.deadlineAt - deadline.extensionMs,
34092
+ deadlineAt,
34093
+ playoutDeadlineAt: deadlineAt - deadline.extensionMs,
33236
34094
  anchorAt: deadline.anchorAt,
33237
34095
  delayMs: deadline.delayMs,
33238
34096
  bound: deadline.bound,
33239
34097
  order: enqueueOrder++,
33240
34098
  attempts: 0,
33241
34099
  running: null,
33242
- range: { ...range, lostSsId: loss.lostSsId, holeLength }
34100
+ range: { lostSsId: loss.lostSsId, holeLength, groups, reportedAt: now },
34101
+ ...walked ? { walk: { next: holeStart, group: null, yielded: false } } : {}
33243
34102
  };
33244
34103
  const previous = entries.get(entry.key);
33245
34104
  if (previous) {
@@ -33249,7 +34108,7 @@ function wireRepairFetch(mc, opts) {
33249
34108
  entries.set(entry.key, entry);
33250
34109
  entry.expiry = setTimeout(dispatch, Math.max(0, entry.deadlineAt - performance.now()) + 1);
33251
34110
  dispatch();
33252
- });
34111
+ }, onHoleExpired);
33253
34112
  }
33254
34113
  const removeRapObserver = mc.addRapCompleteObserver?.((packetId) => {
33255
34114
  queueMicrotask(() => {
@@ -33463,6 +34322,7 @@ export {
33463
34322
  resolveGroupDurationMs,
33464
34323
  resolveGroupDurationTicks,
33465
34324
  resolveRepairLayers,
34325
+ runtimeFecCatalogReport,
33466
34326
  secondsFromTicks,
33467
34327
  setupFecWorkerForTrack,
33468
34328
  setupTrackPipeline,