@blockcast/mmt-container 2.2.0-main.da2e7cd1dd5d → 2.2.0-main.ef09fa701ea8

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 (67) hide show
  1. package/dist/browser-runtime.js +1447 -179
  2. package/dist/browser-runtime.js.map +3 -3
  3. package/dist/cmaf-block-assembler.js +92 -1
  4. package/dist/cmaf-block-assembler.js.map +2 -2
  5. package/dist/codec-utils.d.ts.map +1 -1
  6. package/dist/codec-utils.js +92 -1
  7. package/dist/codec-utils.js.map +2 -2
  8. package/dist/delivery-catalog.js +2 -1
  9. package/dist/delivery-catalog.js.map +2 -2
  10. package/dist/delta-fallback-config.js.map +1 -1
  11. package/dist/fec-manager.d.ts +105 -14
  12. package/dist/fec-manager.d.ts.map +1 -1
  13. package/dist/fec-manager.js +502 -58
  14. package/dist/fec-manager.js.map +2 -2
  15. package/dist/fec-worker-setup.js.map +1 -1
  16. package/dist/index.d.ts +2 -2
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js.map +2 -2
  19. package/dist/iso-block-locator.d.ts +48 -13
  20. package/dist/iso-block-locator.d.ts.map +1 -1
  21. package/dist/iso-block-locator.js +97 -25
  22. package/dist/iso-block-locator.js.map +2 -2
  23. package/dist/iso-bmff-timing.d.ts +10 -1
  24. package/dist/iso-bmff-timing.d.ts.map +1 -1
  25. package/dist/iso-bmff-timing.js +36 -2
  26. package/dist/iso-bmff-timing.js.map +2 -2
  27. package/dist/media-router.js.map +1 -1
  28. package/dist/mmtp-container-parser.d.ts +104 -12
  29. package/dist/mmtp-container-parser.d.ts.map +1 -1
  30. package/dist/mmtp-container-parser.js +308 -27
  31. package/dist/mmtp-container-parser.js.map +2 -2
  32. package/dist/mmtp-container-parser.no-modules.js +310 -30
  33. package/dist/mmtp-container-parser.no-modules.js.map +3 -3
  34. package/dist/mmtp-decode-pipeline.js +307 -27
  35. package/dist/mmtp-decode-pipeline.js.map +2 -2
  36. package/dist/mmtp-router.d.ts +36 -8
  37. package/dist/mmtp-router.d.ts.map +1 -1
  38. package/dist/mmtp-router.js +675 -75
  39. package/dist/mmtp-router.js.map +3 -3
  40. package/dist/multicast-manager.d.ts +26 -3
  41. package/dist/multicast-manager.d.ts.map +1 -1
  42. package/dist/multicast-manager.js +1267 -152
  43. package/dist/multicast-manager.js.map +3 -3
  44. package/dist/multicast-transport.js +4 -3
  45. package/dist/multicast-transport.js.map +2 -2
  46. package/dist/no-modules.js +307 -27
  47. package/dist/no-modules.js.map +3 -3
  48. package/dist/repair-fetch.d.ts +38 -8
  49. package/dist/repair-fetch.d.ts.map +1 -1
  50. package/dist/repair-fetch.js +286 -27
  51. package/dist/repair-fetch.js.map +3 -3
  52. package/dist/track-session.d.ts.map +1 -1
  53. package/dist/track-session.js +1 -0
  54. package/dist/track-session.js.map +2 -2
  55. package/dist/wasm-mmtp-container-parser.js +307 -27
  56. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  57. package/package.json +5 -5
  58. package/src/codec-utils.ts +121 -1
  59. package/src/fec-manager.ts +571 -32
  60. package/src/index.ts +3 -0
  61. package/src/iso-block-locator.ts +133 -31
  62. package/src/iso-bmff-timing.ts +40 -1
  63. package/src/mmtp-container-parser.ts +341 -32
  64. package/src/mmtp-router.ts +600 -55
  65. package/src/multicast-manager.ts +136 -16
  66. package/src/repair-fetch.ts +366 -50
  67. 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
  }
@@ -6088,9 +6099,10 @@ function isH264IntraSlice(nal) {
6088
6099
  const sliceType = readH264SliceType(nal);
6089
6100
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
6090
6101
  }
6102
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
6091
6103
  function readH264SliceType(nal) {
6092
6104
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
6093
- const rbsp = removeEmulationPrevention(nal.subarray(1));
6105
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
6094
6106
  const state = { bitOffset: 0 };
6095
6107
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
6096
6108
  return readUnsignedExpGolomb(rbsp, state);
@@ -6459,6 +6471,96 @@ if (void 0) {
6459
6471
  ]))).toBe(false);
6460
6472
  });
6461
6473
  });
6474
+ describe("readH264SliceType", () => {
6475
+ const wholeNalSliceType = (nal) => {
6476
+ if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
6477
+ const rbsp = removeEmulationPrevention(nal.subarray(1));
6478
+ const state = { bitOffset: 0 };
6479
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null;
6480
+ return readUnsignedExpGolomb(rbsp, state);
6481
+ };
6482
+ const hex3 = (text2) => Uint8Array.from(text2.match(/../g), (byte) => parseInt(byte, 16));
6483
+ const ue = (value) => {
6484
+ const code = (value + 1).toString(2);
6485
+ return "0".repeat(code.length - 1) + code;
6486
+ };
6487
+ const sliceNal = (bits) => {
6488
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, "0").match(/.{8}/g);
6489
+ const nal = [1];
6490
+ let zeros = 0;
6491
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
6492
+ if (zeros >= 2 && byte <= 3) {
6493
+ nal.push(3);
6494
+ zeros = 0;
6495
+ }
6496
+ nal.push(byte);
6497
+ zeros = byte === 0 ? zeros + 1 : 0;
6498
+ }
6499
+ return Uint8Array.from(nal);
6500
+ };
6501
+ const x264Slices = [
6502
+ ["64x48 P", hex3("419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176"), 5, false],
6503
+ ["64x48 B", hex3("419e414212fffeeade283707cb70f7"), 6, false],
6504
+ ["64x48 non-IDR I", hex3(
6505
+ "4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39a527e23eb34c8167fd"
6506
+ ), 7, true],
6507
+ ["1280x720 B, escape at byte 10", hex3(
6508
+ "01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e19b75d92170917306190f262fd58268702db2eff86a9651e48"
6509
+ ), 6, false],
6510
+ ["1280x720 P, escape at byte 15", hex3(
6511
+ "41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f02c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e85302da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3"
6512
+ ), 5, false],
6513
+ ["1280x720 B, escape at byte 22", hex3("01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352"), 6, false],
6514
+ ["7680x4320 IDR, first_mb_in_slice 97440", hex3(
6515
+ "650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9"
6516
+ ), null, true],
6517
+ ["7680x4320 P, first_mb_in_slice 32640", hex3(
6518
+ "410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020"
6519
+ ), 5, false],
6520
+ ["7680x4320 P, first_mb_in_slice 97440", hex3(
6521
+ "410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806"
6522
+ ), 5, false]
6523
+ ];
6524
+ const syntheticSlices = [
6525
+ ["an escape inside first_mb_in_slice", sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
6526
+ ["an escape between the fields", sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
6527
+ ["an escape inside slice_type", sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
6528
+ ["the longest fields, five escapes", sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
6529
+ ["the largest values", sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
6530
+ ["31 leading zeros in first_mb_in_slice", sliceNal(`${"0".repeat(31)}1`), null],
6531
+ ["31 leading zeros in slice_type", sliceNal(`1${"0".repeat(31)}1`), null],
6532
+ ["escapes running past the slice header", sliceNal(ue(0) + ue(5) + "0".repeat(400)), 5]
6533
+ ];
6534
+ test("reads the slice_type of real and synthetic slices", () => {
6535
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
6536
+ expect(readH264SliceType(nal), name).toBe(sliceType);
6537
+ }
6538
+ });
6539
+ test("matches the whole-NAL unescape at every truncation", () => {
6540
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
6541
+ for (let end = 0; end <= nal.length; end++) {
6542
+ const cut = nal.subarray(0, end);
6543
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut));
6544
+ }
6545
+ }
6546
+ });
6547
+ test("matches the whole-NAL unescape on zero-heavy NAL units", () => {
6548
+ const bytes = [0, 0, 0, 3, 1, 2, 128, 255];
6549
+ let seed = 1;
6550
+ const next = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) >>> 16;
6551
+ for (let i = 0; i < 5e3; i++) {
6552
+ const nal = new Uint8Array(2 + next() % 63);
6553
+ nal[0] = 65;
6554
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length];
6555
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal));
6556
+ }
6557
+ });
6558
+ test("classifies the x264 slices as keyframes or not", () => {
6559
+ for (const [name, nal, , keyframe] of x264Slices) {
6560
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe);
6561
+ }
6562
+ });
6563
+ });
6462
6564
  describe("avccToAnnexB", () => {
6463
6565
  test("converts with SPS/PPS on keyframe", () => {
6464
6566
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -8625,9 +8727,9 @@ async function openSubscription(rx, openedPromise, options, packetIds) {
8625
8727
  } catch (error) {
8626
8728
  throw new MulticastError("subscription-failed", "MulticastReceiver did not open", error);
8627
8729
  }
8628
- if (rx.integrityScheme !== INTEGRITY_SCHEME) {
8730
+ if (opened.integrityScheme !== INTEGRITY_SCHEME) {
8629
8731
  await rx.close();
8630
- throw unsupported(`integrity scheme ${String(rx.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
8732
+ throw unsupported(`integrity scheme ${String(opened.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
8631
8733
  }
8632
8734
  const events = new EventTarget();
8633
8735
  let state = "connected";
@@ -8746,6 +8848,7 @@ var MOQT_PUBLISHER_PRIORITY = Object.freeze({
8746
8848
  });
8747
8849
 
8748
8850
  // node_modules/@blockcast/mmt-transport/dist/amt-gateway.js
8851
+ var MAX_PENDING_PACKETS = 256;
8749
8852
  var AMTGatewayManager = class {
8750
8853
  subscriptions = /* @__PURE__ */ new Map();
8751
8854
  messageHandler;
@@ -8869,7 +8972,7 @@ var AMTGatewayManager = class {
8869
8972
  if (!subscription.handshakeComplete) {
8870
8973
  const queue = this.pendingPackets.get(subscriptionId);
8871
8974
  const packetData2 = data;
8872
- if (queue) {
8975
+ if (queue && queue.length < MAX_PENDING_PACKETS) {
8873
8976
  queue.push({
8874
8977
  data: packetData2.data,
8875
8978
  remoteAddress: packetData2.remoteAddress,
@@ -12434,6 +12537,7 @@ var TrackSession = class {
12434
12537
  this.#state = "idle";
12435
12538
  this.#subscription = null;
12436
12539
  this.#disarmFec();
12540
+ this.#unsuppress();
12437
12541
  }
12438
12542
  // -----------------------------------------------------------------------
12439
12543
  // Internal
@@ -12927,6 +13031,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
12927
13031
  this.#heldEvicted = 0;
12928
13032
  /** Pending holes (see `deferIncompleteGaps`): unstated, sources still held. */
12929
13033
  this.#holes = [];
13034
+ /** Holes the horizon passed while pending: sources held until closed. */
13035
+ this.#expired = [];
13036
+ /** Of `#expired`, those `takeExpiredHoles` has not handed out yet. */
13037
+ this.#newlyExpired = [];
13038
+ /**
13039
+ * Spans closed from expired holes: behind the horizon, so kept only for
13040
+ * `locate` while their sources are fed, until the next retirement.
13041
+ */
13042
+ this.#closedBehind = [];
12930
13043
  /**
12931
13044
  * Keep a gap that is missing a source as a pending hole rather than a span,
12932
13045
  * so a repair FETCHed for it (draft-ramadan-moq-fec §7.5) can still state
@@ -12948,7 +13061,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
12948
13061
  #retentionBlocks;
12949
13062
  #heldEvicted;
12950
13063
  #newest;
13064
+ #newestSource;
12951
13065
  #holes;
13066
+ #expired;
13067
+ #newlyExpired;
13068
+ #closedBehind;
12952
13069
  static #checkedRetention(retentionBlocks) {
12953
13070
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
12954
13071
  throw new Error(
@@ -12985,6 +13102,21 @@ var IsoBlockLocator = class _IsoBlockLocator {
12985
13102
  observe(position) {
12986
13103
  if (this.#newest === void 0 || serial32Precedes(this.#newest, position)) this.#newest = position;
12987
13104
  }
13105
+ /**
13106
+ * The newest source SS_ID noted with `noteSource` (RFC 1982 order). Unlike
13107
+ * `newest`, a repair never moves it: a repair can run ahead of its sources,
13108
+ * a source cannot run ahead of the sources sent before it except by
13109
+ * reordering.
13110
+ */
13111
+ get newestSource() {
13112
+ return this.#newestSource;
13113
+ }
13114
+ /** Note a received source's SS_ID; true when it is the newest one yet. */
13115
+ noteSource(ssId) {
13116
+ if (this.#newestSource !== void 0 && !serial32Precedes(this.#newestSource, ssId)) return false;
13117
+ this.#newestSource = ssId;
13118
+ return true;
13119
+ }
12988
13120
  /** Held sources evicted by `heldCapacity` (never by the horizon itself). */
12989
13121
  get heldEvicted() {
12990
13122
  return this.#heldEvicted;
@@ -13003,17 +13135,29 @@ var IsoBlockLocator = class _IsoBlockLocator {
13003
13135
  }
13004
13136
  /** The known block or span containing `ssId`, with its ESI. */
13005
13137
  locate(ssId) {
13006
- for (let i = this.#blocks.length - 1; i >= 0; i--) {
13007
- const block = this.#blocks[i];
13008
- if (isoBlockContains(block.start, block.length, ssId)) {
13009
- return { block, esi: serial32Distance(block.start, ssId) };
13138
+ for (const blocks of [this.#blocks, this.#closedBehind]) {
13139
+ for (let i = blocks.length - 1; i >= 0; i--) {
13140
+ const block = blocks[i];
13141
+ if (isoBlockContains(block.start, block.length, ssId)) {
13142
+ return { block, esi: serial32Distance(block.start, ssId) };
13143
+ }
13010
13144
  }
13011
13145
  }
13012
13146
  return null;
13013
13147
  }
13014
- /** Number of pending holes. */
13148
+ /** Number of holes not closed yet, pending or past the horizon. */
13015
13149
  get holeCount() {
13016
- return this.#holes.length;
13150
+ return this.#holes.length + this.#expired.length;
13151
+ }
13152
+ /**
13153
+ * The pending holes the horizon has passed since the last call, in the
13154
+ * order it passed them. Each is no longer pending: no repair states a block
13155
+ * in it (that repair is `stale`, as for a span the horizon retired) and the
13156
+ * release gate does not wait for it. Its owner must close it
13157
+ * (`closeHolesWithin`), which turns it into a span that is not kept here.
13158
+ */
13159
+ takeExpiredHoles() {
13160
+ return this.#newlyExpired.splice(0);
13017
13161
  }
13018
13162
  /** The stated block (never a span) ending exactly at `end`. */
13019
13163
  blockEndingAt(end) {
@@ -13069,9 +13213,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
13069
13213
  /**
13070
13214
  * Apply one repair symbol's `(SS_Start, SSB_length)`. The first repair of a
13071
13215
  * block states its range and places every held source in it; later repair
13072
- * symbols of the same block change nothing. A range that contradicts a
13073
- * known block (a different length, or an overlap with another block or a
13074
- * span) fails closed: the repair symbol is dropped and no block changes.
13216
+ * symbols of the same block change nothing. A repair whose range is exactly
13217
+ * a repair-less span states that span's one block. A range that contradicts
13218
+ * a known block (a different length, or an overlap with another block or
13219
+ * with part of a span) fails closed: the repair symbol is dropped and no
13220
+ * block changes.
13075
13221
  * A newly stated block retires behind its SS_Start (see the class note).
13076
13222
  * A block so far past `newest` that stating it would retire the position
13077
13223
  * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
@@ -13090,7 +13236,16 @@ var IsoBlockLocator = class _IsoBlockLocator {
13090
13236
  const known = this.blockAt(start);
13091
13237
  if (known !== void 0) {
13092
13238
  if (known.span) {
13093
- return { status: "overlap", reason: `repair block ${start}+${length} falls inside a repair-less span` };
13239
+ if (known.length === length) {
13240
+ const block2 = { start, length, span: false };
13241
+ this.#blocks[this.#blocks.indexOf(known)] = block2;
13242
+ return { status: "placed", block: block2, placed: [] };
13243
+ }
13244
+ return length < known.length ? {
13245
+ status: "overlap",
13246
+ reason: `repair block ${start}+${length} is only the first block of repair-less span ${known.start}+${known.length}`,
13247
+ ofSpan: known
13248
+ } : { status: "overlap", reason: `repair block ${start}+${length} runs past repair-less span ${known.start}+${known.length}` };
13094
13249
  }
13095
13250
  if (known.length !== length) {
13096
13251
  return {
@@ -13158,18 +13313,28 @@ var IsoBlockLocator = class _IsoBlockLocator {
13158
13313
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
13159
13314
  }
13160
13315
  /**
13161
- * Turn every pending hole inside `[start, start + length)` into a
13162
- * repair-less span, claiming its held sources: its range FETCH ended, so
13163
- * nothing more will state its blocks. Returns the spans, in SS_ID order.
13316
+ * Turn every hole inside `[start, start + length)` into a repair-less span,
13317
+ * claiming its held sources: its range FETCH ended, so nothing more will
13318
+ * state its blocks. A hole the horizon passed (`takeExpiredHoles`) leaves a
13319
+ * span that is not kept among the blocks, as the horizon would retire it at
13320
+ * once; only `locate` finds it, until the next retirement, so its sources
13321
+ * can be fed. Returns the spans, in SS_ID order.
13164
13322
  */
13165
13323
  closeHolesWithin(start, length) {
13166
13324
  const closed = [];
13167
- for (const hole of [...this.#holes]) {
13168
- if (!isoBlockContains(start, length, hole.start)) continue;
13169
- this.#holes.splice(this.#holes.indexOf(hole), 1);
13170
- const spanBlock = { start: hole.start, length: hole.length, span: true };
13171
- closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
13172
- this.#blocks.push(spanBlock);
13325
+ for (const holes of [this.#holes, this.#expired]) {
13326
+ for (const hole of [...holes]) {
13327
+ if (!isoBlockContains(start, length, hole.start)) continue;
13328
+ holes.splice(holes.indexOf(hole), 1);
13329
+ const spanBlock = { start: hole.start, length: hole.length, span: true };
13330
+ closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
13331
+ if (holes === this.#holes) {
13332
+ this.#blocks.push(spanBlock);
13333
+ } else {
13334
+ this.#closedBehind.push(spanBlock);
13335
+ if (this.#newlyExpired.includes(hole)) this.#newlyExpired.splice(this.#newlyExpired.indexOf(hole), 1);
13336
+ }
13337
+ }
13173
13338
  }
13174
13339
  return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
13175
13340
  }
@@ -13183,15 +13348,17 @@ var IsoBlockLocator = class _IsoBlockLocator {
13183
13348
  return void 0;
13184
13349
  }
13185
13350
  /**
13186
- * Retire every block and span whose last SS_ID, and every held source,
13187
- * lies more than `retentionBlocks` blocks behind `position`, with the shared
13188
- * lower-bound metric (`isoBlocksBehindLowerBound`) every ISO interleave
13189
- * horizon uses. Returns the retired block starts.
13351
+ * Retire every block and span whose last SS_ID, and every held source
13352
+ * outside a hole, lies more than `retentionBlocks` blocks behind
13353
+ * `position`, with the shared lower-bound metric (`isoBlocksBehindLowerBound`)
13354
+ * every ISO interleave horizon uses; a pending hole so far behind expires
13355
+ * (`takeExpiredHoles`). Returns the retired block starts.
13190
13356
  */
13191
13357
  retireBehind(position) {
13192
13358
  this.observe(position);
13193
13359
  const horizon = this.#retentionBlocks;
13194
13360
  const retired = [];
13361
+ this.#closedBehind.length = 0;
13195
13362
  for (let i = this.#blocks.length - 1; i >= 0; i--) {
13196
13363
  const block = this.#blocks[i];
13197
13364
  const last = serial32Add(block.start, block.length - 1);
@@ -13203,10 +13370,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
13203
13370
  for (let i = this.#holes.length - 1; i >= 0; i--) {
13204
13371
  const hole = this.#holes[i];
13205
13372
  const last = serial32Add(hole.start, hole.length - 1);
13206
- if (isoBlocksBehindLowerBound(last, position, this.#kMax) > horizon) this.#holes.splice(i, 1);
13373
+ if (isoBlocksBehindLowerBound(last, position, this.#kMax) <= horizon) continue;
13374
+ this.#holes.splice(i, 1);
13375
+ this.#expired.push(hole);
13376
+ this.#newlyExpired.push(hole);
13207
13377
  }
13208
13378
  for (const ssId of [...this.#held.keys()]) {
13209
- if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon) this.#held.delete(ssId);
13379
+ 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))) {
13380
+ this.#held.delete(ssId);
13381
+ }
13210
13382
  }
13211
13383
  return retired;
13212
13384
  }
@@ -13214,9 +13386,13 @@ var IsoBlockLocator = class _IsoBlockLocator {
13214
13386
  reset() {
13215
13387
  this.#blocks.length = 0;
13216
13388
  this.#holes.length = 0;
13389
+ this.#expired.length = 0;
13390
+ this.#newlyExpired.length = 0;
13391
+ this.#closedBehind.length = 0;
13217
13392
  this.#held.clear();
13218
13393
  this.#coverageEnd = void 0;
13219
13394
  this.#newest = void 0;
13395
+ this.#newestSource = void 0;
13220
13396
  }
13221
13397
  #claim(block) {
13222
13398
  const placed = [];
@@ -13836,6 +14012,7 @@ var WORKER_ERROR_LOG_CAP = 5;
13836
14012
  var WORKER_ERROR_KIND_CAP = 32;
13837
14013
  var WORKER_ERROR_OVERFLOW_KIND = "other";
13838
14014
  var STARTUP_REPAIR_WAIT_SOURCE_BOUNDARIES = 2;
14015
+ var NOT_TAKEN = Object.freeze({ taken: false, recovered: null });
13839
14016
  function isMulticastSymbolDelivery(value) {
13840
14017
  return value === "datagram" || value === "ordered-relay";
13841
14018
  }
@@ -13929,10 +14106,18 @@ var FECManager = class _FECManager {
13929
14106
  // 'pending' forever, which would park every later frame of its stream in
13930
14107
  // the in-order release gate. Each entry owns its handle; the callback
13931
14108
  // checks it still owns the key, so a settled or reset key is never touched.
14109
+ /**
14110
+ * Per owed Worker cleanup: the bound on its acknowledgement, when its block
14111
+ * was due, and when its cleanup was asked for (see `onCleanupComplete`).
14112
+ */
13932
14113
  this.#pendingWorkerCleanupBounds = /* @__PURE__ */ new Map();
13933
14114
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
13934
14115
  this.#blockSourceCounts = /* @__PURE__ */ new Map();
13935
14116
  this.#blockSourceEsis = /* @__PURE__ */ new Map();
14117
+ // Source ESIs per block that another FEC instance rebuilt and fed in
14118
+ // (feedRebuiltSourceSymbol). Kept apart from #blockSourceEsis: they are
14119
+ // not network arrivals and never make a block clean.
14120
+ this.#blockRebuiltEsis = /* @__PURE__ */ new Map();
13936
14121
  // Authored SSB_length per block (ISO/IEC 23008-1 §C.5.3), learned from the
13937
14122
  // first repair symbol. The FFmpeg moq_mmt publisher closes a block every D
13938
14123
  // media units, usually before it holds K symbols; under iso-ssbg1-v1
@@ -13941,10 +14126,14 @@ var FECManager = class _FECManager {
13941
14126
  // SSB_length source arrivals and recoverable from SSB_length received
13942
14127
  // symbols; waiting for K fails every one of them.
13943
14128
  this.#blockAuthoredLengths = /* @__PURE__ */ new Map();
14129
+ // Keys whose authored length is a repair-less span's (#openIsoSpan), until
14130
+ // a repair states the block there or the span resolves.
14131
+ this.#isoSpanKeys = /* @__PURE__ */ new Set();
13944
14132
  this.#ssbLengthConflictCount = 0;
13945
14133
  this.#blockRepairRsIds = /* @__PURE__ */ new Map();
13946
14134
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
13947
- // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
14135
+ // symbols its repair group carries; 0 for a repair-less span no repair can
14136
+ // state (#openIsoSpan). Same lifecycle as #blockRepairRsIds.
13948
14137
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
13949
14138
  /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
13950
14139
  this.#heldLayerStates = /* @__PURE__ */ new Map();
@@ -14138,7 +14327,10 @@ var FECManager = class _FECManager {
14138
14327
  // arrives via onBlockRecovered callback.
14139
14328
  this.onBlockStarted = null;
14140
14329
  this.onBlockComplete = null;
14141
- /** A block reached its fail bound. `blockClass` is its class at failure. */
14330
+ /**
14331
+ * A block reached its fail bound. `blockClass` is its class at failure.
14332
+ * `span` is set when what failed is a repair-less span starting at `sbn`.
14333
+ */
14142
14334
  this.onBlockFailed = null;
14143
14335
  /**
14144
14336
  * Fired once per stream when its Worker decoder stops being routable.
@@ -14180,12 +14372,24 @@ var FECManager = class _FECManager {
14180
14372
  * for it, which it must be.
14181
14373
  */
14182
14374
  this.#onUndelimitedLoss = null;
14375
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
14376
+ this.#onIsoHoleExpired = null;
14183
14377
  /** A block every symbol of which vanished was created by SBN evidence. */
14184
14378
  this.onBlockVanished = null;
14185
14379
  /** A block reached a terminal state (completed, recovered, or failed). */
14186
14380
  this.onBlockResolved = null;
14187
14381
  /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
14188
14382
  this.onSourceDiscontinuity = null;
14383
+ /**
14384
+ * The span and tolerance the catalog states for a keyframe overlay
14385
+ * installed over a source track (draft-ramadan-moq-mmt-02 7.4.1: the
14386
+ * overlay instance's own interleaveDepthMs and reorderToleranceMs), or
14387
+ * undefined while none is installed. A stated block only a late source
14388
+ * can complete, and a frame whose gap may hide a RAP behind a span only a
14389
+ * late source can fill, also wait for that overlay's repair
14390
+ * (#overlayLateWaitMs).
14391
+ */
14392
+ this.keyframeOverlayTiming = null;
14189
14393
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
14190
14394
  /**
14191
14395
  * A recovered source symbol. Return false when admission refused the
@@ -14222,7 +14426,9 @@ var FECManager = class _FECManager {
14222
14426
  #pendingWorkerCleanupBounds;
14223
14427
  #blockSourceCounts;
14224
14428
  #blockSourceEsis;
14429
+ #blockRebuiltEsis;
14225
14430
  #blockAuthoredLengths;
14431
+ #isoSpanKeys;
14226
14432
  #ssbLengthConflictCount;
14227
14433
  #blockRepairRsIds;
14228
14434
  #blockRsbLengths;
@@ -14289,6 +14495,7 @@ var FECManager = class _FECManager {
14289
14495
  #decoderUnavailableEvents;
14290
14496
  #repairSymbolSizeMismatchCount;
14291
14497
  #onUndelimitedLoss;
14498
+ #onIsoHoleExpired;
14292
14499
  #encodeTrackName(catalogTrackName) {
14293
14500
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
14294
14501
  if (encoded === void 0) {
@@ -14760,7 +14967,10 @@ var FECManager = class _FECManager {
14760
14967
  timer.handle = null;
14761
14968
  this.#requestRepair(sbn, packetId, catalogTrackName);
14762
14969
  };
14763
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
14970
+ timer.handle = setTimeout(
14971
+ onFire,
14972
+ this.#receiptAtMs === void 0 ? Math.max(0, deadlineMs - performance.now()) : this.#receiptTimerDelayMs(deadlineMs, 0)
14973
+ );
14764
14974
  this.#repairDeadlines.set(key, timer);
14765
14975
  }
14766
14976
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -14904,8 +15114,14 @@ var FECManager = class _FECManager {
14904
15114
  * Vanished blocks are not enumerated here: their starts are unknown until a
14905
15115
  * repair states them. The SS_IDs between two stated blocks become one
14906
15116
  * repair-less span when the later block's repair arrives (placeIsoRepair).
15117
+ *
15118
+ * A `held` source arrived before its block was known and is fed only now
15119
+ * that a repair, a span or a closed hole placed it: how far its block start
15120
+ * then lies behind the frontier measures how long the receiver held it, not
15121
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
15122
+ * it (BLO-52085).
14907
15123
  */
14908
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
15124
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn, held = false) {
14909
15125
  const streamKey = this.#streamKey(packetId, catalogTrackName);
14910
15126
  const now = performance.now();
14911
15127
  const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
@@ -14944,7 +15160,7 @@ var FECManager = class _FECManager {
14944
15160
  return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
14945
15161
  };
14946
15162
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
14947
- 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))) {
15163
+ 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))) {
14948
15164
  discontinuity();
14949
15165
  return;
14950
15166
  }
@@ -15206,17 +15422,21 @@ var FECManager = class _FECManager {
15206
15422
  this.#blockWaitDeadlinesMs.delete(key);
15207
15423
  this.#repairHoldUntilMs.delete(key);
15208
15424
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
15209
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName);
15425
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs);
15210
15426
  };
15211
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)));
15427
+ timer.handle = setTimeout(
15428
+ onFire,
15429
+ this.#receiptAtMs === void 0 ? Math.max(1, Math.ceil(deadlineMs - nowMs)) : this.#receiptTimerDelayMs(deadlineMs, 1)
15430
+ );
15212
15431
  this.#activeBlocks.set(key, timer);
15213
15432
  this.#indexBlockKey(key, sbn, packetId);
15214
15433
  }
15215
15434
  /**
15216
15435
  * Hand a block whose delivery is over to its decoder for finalization: the
15217
- * datagram deadline fired, or the ordered relay moved past it.
15436
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
15437
+ * is when it was due: its deadline, or now.
15218
15438
  */
15219
- #finalizeExpiredBlock(sbn, packetId, catalogTrackName) {
15439
+ #finalizeExpiredBlock(sbn, packetId, catalogTrackName, dueAtMs = performance.now()) {
15220
15440
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
15221
15441
  if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
15222
15442
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -15232,7 +15452,7 @@ var FECManager = class _FECManager {
15232
15452
  if (workerClient) {
15233
15453
  this.#pendingWorkerCleanups.add(key);
15234
15454
  this.#pendingWorkerCleanupClients.set(key, workerClient);
15235
- this.#boundOwedCleanup(key, packetId, workerClient);
15455
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs);
15236
15456
  workerClient.cleanup(sbn);
15237
15457
  } else {
15238
15458
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
@@ -15544,7 +15764,9 @@ var FECManager = class _FECManager {
15544
15764
  }
15545
15765
  resetMap(this.#blockSourceCounts);
15546
15766
  resetMap(this.#blockSourceEsis);
15767
+ resetMap(this.#blockRebuiltEsis);
15547
15768
  resetMap(this.#blockAuthoredLengths);
15769
+ resetSet(this.#isoSpanKeys);
15548
15770
  resetMap(this.#blockRepairRsIds);
15549
15771
  resetMap(this.#blockRsbLengths);
15550
15772
  resetMap(this.#heldLayerStates);
@@ -15668,7 +15890,9 @@ var FECManager = class _FECManager {
15668
15890
  dropMap(this.#pendingWorkerCleanupClients);
15669
15891
  dropMap(this.#blockSourceCounts);
15670
15892
  dropMap(this.#blockSourceEsis);
15893
+ dropMap(this.#blockRebuiltEsis);
15671
15894
  dropMap(this.#blockAuthoredLengths);
15895
+ dropSet(this.#isoSpanKeys);
15672
15896
  dropMap(this.#blockRepairRsIds);
15673
15897
  dropMap(this.#blockRsbLengths);
15674
15898
  dropMap(this.#blockPathCounts);
@@ -15830,6 +16054,9 @@ var FECManager = class _FECManager {
15830
16054
  this.#unindexBlockKey(key);
15831
16055
  }
15832
16056
  }
16057
+ if (isSourceSymbol && source === "multicast") {
16058
+ this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), sbn + esi >>> 0, packetId, catalogTrackName);
16059
+ }
15833
16060
  return true;
15834
16061
  }
15835
16062
  #observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName) {
@@ -15939,8 +16166,10 @@ var FECManager = class _FECManager {
15939
16166
  }
15940
16167
  /**
15941
16168
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
15942
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
15943
- * Undefined for a block that is not open.
16169
+ * (SSB_length) and RSB_length (each undefined until a repair stated it; a
16170
+ * repair-less span states its length, and RSB_length 0 when it is longer
16171
+ * than K, since no repair can reach it). Undefined for a block that is not
16172
+ * open.
15944
16173
  */
15945
16174
  blockSymbolCounts(sbn, packetId, catalogTrackName) {
15946
16175
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -16008,8 +16237,9 @@ var FECManager = class _FECManager {
16008
16237
  return true;
16009
16238
  }
16010
16239
  /**
16011
- * Drop a block's repair hold: its FETCH ended without delivering. The block
16012
- * falls back to its multicast wait, which may already have passed.
16240
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
16241
+ * back only a repair that cannot complete it. The block falls back to its
16242
+ * multicast wait, which may already have passed.
16013
16243
  */
16014
16244
  releaseRepairHold(sbn, packetId, catalogTrackName) {
16015
16245
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -16055,7 +16285,7 @@ var FECManager = class _FECManager {
16055
16285
  }
16056
16286
  const trackConfig = this.#trackConfigs.get(packetId);
16057
16287
  if (trackConfig === void 0) return void 0;
16058
- return Math.max(1, trackConfig.timeoutMs - this.#repairDeadlineMs(trackConfig));
16288
+ return Math.max(1, this.#repairGraceMs(trackConfig, this.#multicastWaitMs(trackConfig)));
16059
16289
  }
16060
16290
  /** True once configureTrack/setFecDecoder/setFecWorker configured this packetId. */
16061
16291
  // -----------------------------------------------------------------------
@@ -16147,6 +16377,8 @@ var FECManager = class _FECManager {
16147
16377
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
16148
16378
  const evictedBefore = locator.heldEvicted;
16149
16379
  const held = locator.hold(ssId, source);
16380
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
16381
+ if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
16150
16382
  const evicted = locator.heldEvicted - evictedBefore;
16151
16383
  if (evicted > 0) {
16152
16384
  const before = this.#isoHeldEvictedCount;
@@ -16167,17 +16399,20 @@ var FECManager = class _FECManager {
16167
16399
  * contradicts a known block is refused (counted) and must be dropped.
16168
16400
  */
16169
16401
  placeIsoRepair(packetId, catalogTrackName, ssStart, ssbLength) {
16170
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength);
16402
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
16403
+ const placement = locator.placeRepair(ssStart, ssbLength);
16404
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
16171
16405
  if (placement.status !== "placed") {
16172
16406
  this.#isoRepairRefusedCount++;
16173
16407
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
16174
16408
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`);
16175
16409
  }
16410
+ if (placement.ofSpan !== void 0) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName);
16176
16411
  return placement;
16177
16412
  }
16413
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName));
16178
16414
  if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
16179
16415
  if (placement.hole !== void 0) {
16180
- const locator = this.#isoLocatorFor(packetId, catalogTrackName);
16181
16416
  const hole = placement.hole.block;
16182
16417
  const previous = locator.blockEndingAt(hole.start);
16183
16418
  const loss = {
@@ -16198,17 +16433,29 @@ var FECManager = class _FECManager {
16198
16433
  * `handler`, instead of a repair-less span; null restores spans. Set by the
16199
16434
  * range repair scheduler; applies to every stream from its next gap. The
16200
16435
  * handler and the deferral are one setting, so no hole is ever created with
16201
- * nobody to close it.
16436
+ * nobody to close it. `onExpired` is told of each pending hole the stream
16437
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
16438
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
16439
+ * reported; otherwise the hole is discarded with its sources.
16202
16440
  */
16203
- setUndelimitedLossHandler(handler) {
16441
+ setUndelimitedLossHandler(handler, onExpired = null) {
16204
16442
  this.#onUndelimitedLoss = handler;
16443
+ this.#onIsoHoleExpired = handler === null ? null : onExpired;
16205
16444
  this.#deferIsoGaps = handler !== null;
16206
16445
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
16207
16446
  }
16447
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
16448
+ #settleExpiredIsoHoles(locator, packetId, catalogTrackName) {
16449
+ for (const hole of locator.takeExpiredHoles()) {
16450
+ const expired = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length };
16451
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length);
16452
+ }
16453
+ }
16208
16454
  /**
16209
- * The range repair for a hole ended: every hole still pending inside
16210
- * `[start, start + length)` becomes a repair-less span. Returns those spans
16211
- * with the held sources they placed, for the caller to feed (MmtpRouter).
16455
+ * The range repair for a hole ended: every hole inside `[start, start +
16456
+ * length)`, pending or expired, becomes a repair-less span. Returns those
16457
+ * spans with the held sources they placed, for the caller to feed
16458
+ * (MmtpRouter).
16212
16459
  */
16213
16460
  closeIsoHoles(packetId, catalogTrackName, start, length) {
16214
16461
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
@@ -16224,10 +16471,25 @@ var FECManager = class _FECManager {
16224
16471
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
16225
16472
  * SS_ID of which vanished resolves through its deadline like any vanished
16226
16473
  * block.
16474
+ *
16475
+ * A span longer than K holds more than one block (SSB_length <= K), and the
16476
+ * locator states no block inside a span, only one exactly its range
16477
+ * (IsoBlockLocator.placeRepair): no repair, multicast or FETCHed, can ever
16478
+ * reach it. Its repair group is empty, so the repair scheduler FETCHes no
16479
+ * Group of it (group-cannot-complete). Every span still keeps its whole
16480
+ * wait (#lateSourceWaitMs): failing it early released the frames behind it
16481
+ * past a keyframe the overlay was still rebuilding (BLO-52085). The release
16482
+ * gate lets those frames go once only a late source can fill the gap
16483
+ * before them, as long after they arrived as the gap's decision allows
16484
+ * (isoRepairlessWaitMs).
16227
16485
  */
16228
16486
  #openIsoSpan(span, packetId, catalogTrackName) {
16229
16487
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
16230
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
16488
+ if (!this.#blockAuthoredLengths.has(key)) {
16489
+ this.#blockAuthoredLengths.set(key, span.block.length);
16490
+ this.#isoSpanKeys.add(key);
16491
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0);
16492
+ }
16231
16493
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
16232
16494
  }
16233
16495
  /**
@@ -16265,6 +16527,62 @@ var FECManager = class _FECManager {
16265
16527
  }
16266
16528
  return lost;
16267
16529
  }
16530
+ /**
16531
+ * The release gate's wait, from a frame's arrival, for the SS_IDs strictly
16532
+ * between two released frames' SS_IDs once only a late source can still
16533
+ * fill them, else undefined. That is when every one missing (neither
16534
+ * arrived nor held) lies in a repair-less span longer than K, which no
16535
+ * repair can state a block of (#openIsoSpan), or in a stated block its
16536
+ * own repair group cannot complete every SS_ID of which it misses lies
16537
+ * between them (so the gap's decision covers all it lost), and a multicast
16538
+ * source at or past `toSsId` arrived, so each is lost or reordered behind
16539
+ * it (a MoQ source shows nothing: MoQ streams overtake one another). The
16540
+ * span or block itself keeps its own wait.
16541
+ *
16542
+ * The wait is the late-symbol allowance, unless `rapMayHide`: the gap may
16543
+ * hold a RAP packet an installed keyframe overlay can still rebuild (its
16544
+ * decision stalls, or it ends at a RAP that may lie past a whole MPU).
16545
+ * Then the frame waits as a stated block its group cannot complete does
16546
+ * (#overlayLateWaitMs): the allowance alone with no overlay installed, the
16547
+ * overlay's span plus the larger of the allowance and its tolerance, or,
16548
+ * for an overlay that states no span, the span's whole wait (undefined).
16549
+ * So does `rapNext` (the gap ends at the RAP that opens the next MPU) when
16550
+ * the gap holds a stated block's loss.
16551
+ */
16552
+ isoRepairlessWaitMs(packetId, catalogTrackName, fromSsId, toSsId, rapMayHide = false, rapNext = false) {
16553
+ const config = this.#trackConfigs.get(packetId);
16554
+ if (config === void 0 || !_FECManager.#hasCatalogTiming(config)) return void 0;
16555
+ const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
16556
+ if (locator === void 0 || !locator.coversBetween(fromSsId, toSsId)) return void 0;
16557
+ const newestSource = locator.newestSource;
16558
+ if (newestSource === void 0 || serial32Precedes(newestSource, toSsId)) return void 0;
16559
+ let repairless = false;
16560
+ let stated = false;
16561
+ for (const block of locator.blocksBetween(fromSsId, toSsId)) {
16562
+ const key = this.#blockKey(block.start, packetId, catalogTrackName);
16563
+ if (this.#completedBlocks.has(key)) continue;
16564
+ if (block.span && block.length > locator.kMax) {
16565
+ repairless = true;
16566
+ continue;
16567
+ }
16568
+ const received = this.#blockSourceEsis.get(key);
16569
+ const rebuilt = this.#blockRebuiltEsis.get(key);
16570
+ let missesInGap = false;
16571
+ let missesOutside = false;
16572
+ for (let esi = 0; esi < block.length; esi++) {
16573
+ const ssId = serial32Add(block.start, esi);
16574
+ if (received?.has(esi) || locator.isHeld(ssId)) continue;
16575
+ if (serial32Precedes(fromSsId, ssId) && serial32Precedes(ssId, toSsId)) missesInGap = true;
16576
+ else if (!rebuilt?.has(esi)) missesOutside = true;
16577
+ }
16578
+ if (!missesInGap) continue;
16579
+ if (missesOutside || block.span || !this.#groupCannotComplete(key)) return void 0;
16580
+ repairless = stated = true;
16581
+ }
16582
+ if (!repairless) return void 0;
16583
+ const waitMs = rapMayHide || stated && rapNext ? this.#overlayLateWaitMs(packetId, catalogTrackName, config) : this.#multicastWaitMs(config) - config.interleaveDepthMs;
16584
+ return waitMs === void 0 ? void 0 : Math.max(0, waitMs);
16585
+ }
16268
16586
  /**
16269
16587
  * iso-ssbg1-v1 block location: repair symbols it refused, oversize sources,
16270
16588
  * the sources held now for a block no repair has stated yet, and the held
@@ -16568,11 +16886,14 @@ var FECManager = class _FECManager {
16568
16886
  });
16569
16887
  client.onCleanupComplete((sbn) => {
16570
16888
  if (this.#releasedWorkerClients.has(client)) return;
16571
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
16889
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
16890
+ const cleanupKeys = owed.filter((key) => {
16572
16891
  const block = this.#parseBlockKey(key);
16573
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
16892
+ return block.packetId === packetId && block.sbn === sbn;
16574
16893
  });
16575
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
16894
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
16895
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
16896
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
16576
16897
  });
16577
16898
  client.onError((msg, code) => {
16578
16899
  const requestedKind = code ?? msg;
@@ -16642,9 +16963,11 @@ var FECManager = class _FECManager {
16642
16963
  * fail deadline already passed, so failing it is the decision that deadline
16643
16964
  * made. A late ack then finds nothing owed and is a no-op.
16644
16965
  */
16645
- #boundOwedCleanup(key, packetId, client) {
16966
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
16646
16967
  this.#clearOwedCleanupBound(key);
16647
16968
  const bound = {
16969
+ dueAtMs,
16970
+ askedAtMs: performance.now(),
16648
16971
  handle: setTimeout(() => {
16649
16972
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
16650
16973
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -16742,7 +17065,15 @@ var FECManager = class _FECManager {
16742
17065
  this.#isoSourceOversizeCount++;
16743
17066
  return null;
16744
17067
  }
16745
- const sbn = located.block.start;
17068
+ return this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, located.block.start);
17069
+ }
17070
+ /**
17071
+ * Hand one placed source symbol to the stream's decoder: its Worker, which
17072
+ * answers through onFrame (null here), or its synchronous decoder, whose
17073
+ * recovered block is returned. `sbn` is the SS_Start of the block a repair
17074
+ * stated for `ssId`.
17075
+ */
17076
+ #feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn) {
16746
17077
  const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
16747
17078
  const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey);
16748
17079
  const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
@@ -16771,6 +17102,74 @@ var FECManager = class _FECManager {
16771
17102
  }
16772
17103
  return recovered;
16773
17104
  }
17105
+ /**
17106
+ * Feed a source symbol of this stream that another FEC instance over the
17107
+ * same packets rebuilt: a keyframe overlay recovery whose base SS_ID the
17108
+ * caller determined (draft-ramadan-moq-mmt-02 7.1, 7.4.4; joint decoding,
17109
+ * BLO-52085). It joins its block's decoder as a received source would, so
17110
+ * it reduces the erasures the block still has to solve, but it is not a
17111
+ * network arrival: no transport accounting, no classification evidence,
17112
+ * no deadline refresh, and it never makes a block clean.
17113
+ *
17114
+ * Only a block a repair stated takes one (a repair-less span has no
17115
+ * decoder block). A block that is terminal, or already holds that source,
17116
+ * does not. The symbol is the exact protected packet, unpadded, as
17117
+ * feedSourceSymbol takes it.
17118
+ *
17119
+ * `recovered` is the block the synchronous decoder completed with it; the
17120
+ * caller routes it and completes the block, as for any recovery. When
17121
+ * every source of the block is then present, received or rebuilt, and no
17122
+ * decoder returned it (a Worker answers asynchronously, and reports such a
17123
+ * block as clean on its own side), the block is completed here as
17124
+ * recovered, with nothing left to route.
17125
+ */
17126
+ feedRebuiltSourceSymbol(packetId, ssId, symbolData, catalogTrackName) {
17127
+ if (!this.#hasBlockProfile(packetId)) return NOT_TAKEN;
17128
+ const located = this.#isoLocatorFor(packetId, catalogTrackName).locate(ssId);
17129
+ if (located === null || located.block.span) return NOT_TAKEN;
17130
+ if (!ssbg1FitsSymbol(symbolData.byteLength, this.#trackConfig(packetId).symbolSize)) return NOT_TAKEN;
17131
+ const sbn = located.block.start;
17132
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
17133
+ if (this.#completedBlocks.has(key) || this.#blockSourceEsis.get(key)?.has(located.esi)) return NOT_TAKEN;
17134
+ let rebuilt = this.#blockRebuiltEsis.get(key);
17135
+ if (rebuilt?.has(located.esi)) return NOT_TAKEN;
17136
+ if (rebuilt === void 0) {
17137
+ rebuilt = /* @__PURE__ */ new Set();
17138
+ this.#blockRebuiltEsis.set(key, rebuilt);
17139
+ }
17140
+ const config = this.#trackConfigs.get(packetId);
17141
+ const wasShort = config !== void 0 && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) !== void 0;
17142
+ rebuilt.add(located.esi);
17143
+ const recovered = this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn);
17144
+ if (recovered === null && !this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName)) {
17145
+ if (wasShort && this.#activeBlocks.has(key) && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) === void 0) {
17146
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, this.#multicastWaitMs(config));
17147
+ }
17148
+ }
17149
+ return { taken: true, recovered };
17150
+ }
17151
+ /**
17152
+ * A block that holds every one of its `length` sources, received or
17153
+ * rebuilt by another instance, with at least one rebuilt, is recovered:
17154
+ * every packet of it was delivered, by its own arrival or by the instance
17155
+ * that rebuilt it, so nothing is routed. Returns whether it completed it.
17156
+ */
17157
+ #completeWhenSourcesPresent(key, sbn, length, packetId, catalogTrackName) {
17158
+ const rebuilt = this.#blockRebuiltEsis.get(key);
17159
+ if (rebuilt === void 0 || this.#completedBlocks.has(key)) return false;
17160
+ let present = rebuilt.size;
17161
+ for (const esi of this.#blockSourceEsis.get(key) ?? []) if (!rebuilt.has(esi)) present++;
17162
+ if (present < length) return false;
17163
+ this.#traceLifecycle("recovered", sbn, packetId, catalogTrackName);
17164
+ this.countRecovery(packetId, sbn, catalogTrackName);
17165
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
17166
+ if (catalogTrackName === void 0) {
17167
+ this.onBlockComplete?.(sbn, packetId);
17168
+ } else {
17169
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName);
17170
+ }
17171
+ return true;
17172
+ }
16774
17173
  /**
16775
17174
  * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
16776
17175
  * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
@@ -16973,8 +17372,115 @@ var FECManager = class _FECManager {
16973
17372
  this.#completeCleanBlock(blockKey, sbn, packetId, catalogTrackName);
16974
17373
  return null;
16975
17374
  }
17375
+ if (recovered === null) this.#shortenUnrecoverableWait(blockKey, sbn, packetId, catalogTrackName);
16976
17376
  return recovered;
16977
17377
  }
17378
+ /**
17379
+ * A first-arrival multicast source, held or placed. A datagram flow keeps
17380
+ * its sources in send order, so one that moves the stream's newest source
17381
+ * position past a block leaves the sources that block still misses
17382
+ * reordered behind it at best: it shortens the wait of every block it
17383
+ * passed that only a late source can complete. MoQ is left out: its streams
17384
+ * can overtake one another, so a MoQ source shows nothing about the sources
17385
+ * sent before it.
17386
+ */
17387
+ #noteMulticastSource(locator, ssId, packetId, catalogTrackName) {
17388
+ const previous = locator.newestSource;
17389
+ if (!locator.noteSource(ssId) || previous === void 0) return;
17390
+ for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
17391
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
17392
+ this.#shortenUnrecoverableWait(
17393
+ this.#blockKey(block.start, packetId, catalogTrackName),
17394
+ block.start,
17395
+ packetId,
17396
+ catalogTrackName
17397
+ );
17398
+ }
17399
+ }
17400
+ /**
17401
+ * The wait of a block that only a late source can complete (BLO-52085): a
17402
+ * repair stated it, its received sources plus every symbol its repair group
17403
+ * carries (RSB_length) are short of K' (the repair scheduler's
17404
+ * group-cannot-complete), and a later source of the stream has arrived, so
17405
+ * a source it misses is lost or reordered behind that one. The span, which
17406
+ * covers repair symbols paced after its sources, buys it nothing: it waits
17407
+ * the late-symbol allowance alone, the multicast wait less the span (the
17408
+ * catalog tolerance or the measured delivery gap). Undefined for any other
17409
+ * block. While a keyframe overlay is installed, the block waits for its
17410
+ * repair too (#overlayLateWaitMs). A repair-less span keeps its whole
17411
+ * wait, even one longer than K whose group is empty (#openIsoSpan): its
17412
+ * resolution is what releases the frames behind it, and failing it early
17413
+ * released them past a keyframe the overlay was still rebuilding, which
17414
+ * then arrived stale. The release gate lets them go instead
17415
+ * (isoRepairlessWaitMs).
17416
+ */
17417
+ #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
17418
+ if (this.#isoSpanKeys.has(key) || !this.#groupCannotComplete(key)) return void 0;
17419
+ const authoredLength = this.#blockAuthoredLengths.get(key);
17420
+ const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
17421
+ if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
17422
+ return void 0;
17423
+ }
17424
+ return this.#overlayLateWaitMs(packetId, catalogTrackName, config);
17425
+ }
17426
+ /**
17427
+ * A repair stated the block, and its sources plus every symbol its repair
17428
+ * group carries (RSB_length) are short of its SSB_length.
17429
+ */
17430
+ #groupCannotComplete(key) {
17431
+ const authoredLength = this.#blockAuthoredLengths.get(key);
17432
+ const rsbLength = this.#blockRsbLengths.get(key);
17433
+ if (authoredLength === void 0 || rsbLength === void 0) return false;
17434
+ let present = this.#blockSourceCounts.get(key) ?? 0;
17435
+ const received = this.#blockSourceEsis.get(key);
17436
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
17437
+ return present + rsbLength < authoredLength;
17438
+ }
17439
+ /**
17440
+ * How long a loss only a late source or an installed keyframe overlay can
17441
+ * still fill waits once a later source passed it: the late-symbol
17442
+ * allowance alone (the multicast wait less the span) while no overlay is
17443
+ * installed. An installed one (keyframeOverlayTiming) may still rebuild a
17444
+ * RAP packet the loss took: a second FEC instance over the same packets
17445
+ * (draft-ramadan-moq-mmt-02 7.4), whose repair is paced across its own
17446
+ * span, unrelated to the base's. That packet can complete a stated block
17447
+ * (feedRebuiltSourceSymbol), or play behind a span; giving the loss up
17448
+ * first lets the release gate pass the keyframe, whose rebuild then lands
17449
+ * stale. The overlay repair of a packet the loss took goes out within the
17450
+ * overlay's span of that packet (fec-core-00 9.3), and the later source was
17451
+ * sent after it, so the loss waits that span plus the larger of the
17452
+ * allowance and the overlay's own tolerance. An overlay that states no
17453
+ * span (its block may then span keyframes), or one whose wait is not
17454
+ * shorter than the whole multicast wait, leaves the whole wait: undefined.
17455
+ */
17456
+ #overlayLateWaitMs(packetId, catalogTrackName, config) {
17457
+ const waitMs = this.#multicastWaitMs(config);
17458
+ const allowanceMs = waitMs - config.interleaveDepthMs;
17459
+ const overlay = this.keyframeOverlayTiming?.(packetId, catalogTrackName);
17460
+ if (overlay === void 0) return allowanceMs;
17461
+ const overlaySpanMs = overlay.interleaveDepthMs ?? 0;
17462
+ const overlayWaitMs = overlaySpanMs + Math.max(allowanceMs, overlay.reorderToleranceMs ?? 0);
17463
+ return overlaySpanMs > 0 && overlayWaitMs < waitMs ? overlayWaitMs : void 0;
17464
+ }
17465
+ /**
17466
+ * Bring an open block's wait in to its late-source wait, when it has one.
17467
+ * Never later than it is armed: only a source can complete such a block,
17468
+ * so a repair of its group (paced across the span) must not keep it open.
17469
+ */
17470
+ #shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName) {
17471
+ if (!this.#activeBlocks.has(key)) return;
17472
+ const config = this.#trackConfigs.get(packetId);
17473
+ if (config === void 0) return;
17474
+ const waitMs = this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config);
17475
+ if (waitMs === void 0) return;
17476
+ const armedAtMs = this.#blockWaitDeadlinesMs.get(key);
17477
+ this.#armBlockTimeout(
17478
+ sbn,
17479
+ packetId,
17480
+ catalogTrackName,
17481
+ armedAtMs === void 0 ? waitMs : Math.min(waitMs, armedAtMs - this.#receiptNow())
17482
+ );
17483
+ }
16978
17484
  /**
16979
17485
  * Record a block's authored SSB_length from a repair symbol. Returns false,
16980
17486
  * leaving the block unchanged, when the symbol contradicts the block: a
@@ -17072,12 +17578,13 @@ var FECManager = class _FECManager {
17072
17578
  * the inactivity deadline on each symbol, records the symbol's in-band
17073
17579
  * classification evidence, and marks the block clean when all of its
17074
17580
  * authored source symbols arrived: the SSB_length a repair symbol declared,
17075
- * otherwise K.
17581
+ * otherwise K. `held` marks a source held unplaced since it arrived and
17582
+ * placed only now (see #noteSbnSeen).
17076
17583
  *
17077
17584
  * Throws for a packetId that was never configured, so a classified block
17078
17585
  * never reads the manager-global K or timeout.
17079
17586
  */
17080
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
17587
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
17081
17588
  const trackConfig = this.#trackConfigs.get(packetId);
17082
17589
  if (trackConfig === void 0) {
17083
17590
  throw new Error(
@@ -17093,7 +17600,8 @@ var FECManager = class _FECManager {
17093
17600
  catalogTrackName,
17094
17601
  "source",
17095
17602
  evidence.packetSequenceNumber,
17096
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
17603
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
17604
+ held
17097
17605
  );
17098
17606
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
17099
17607
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -17129,6 +17637,15 @@ var FECManager = class _FECManager {
17129
17637
  this.#completeCleanBlock(key, sbn, packetId, catalogTrackName);
17130
17638
  return;
17131
17639
  }
17640
+ if (this.#blockRebuiltEsis.has(key) && this.#completeWhenSourcesPresent(
17641
+ key,
17642
+ sbn,
17643
+ this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? authoredLength,
17644
+ packetId,
17645
+ catalogTrackName
17646
+ )) {
17647
+ return;
17648
+ }
17132
17649
  this.noteBlockActivity(sbn, packetId, catalogTrackName, true);
17133
17650
  }
17134
17651
  #completeCleanBlock(key, sbn, packetId, catalogTrackName) {
@@ -17137,7 +17654,9 @@ var FECManager = class _FECManager {
17137
17654
  this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
17138
17655
  this.#blockSourceCounts.delete(key);
17139
17656
  this.#blockSourceEsis.delete(key);
17657
+ this.#blockRebuiltEsis.delete(key);
17140
17658
  this.#blockAuthoredLengths.delete(key);
17659
+ this.#isoSpanKeys.delete(key);
17141
17660
  this.#blockRepairRsIds.delete(key);
17142
17661
  this.#blockRsbLengths.delete(key);
17143
17662
  this.#markTerminal(key, sbn, packetId, true);
@@ -17168,6 +17687,19 @@ var FECManager = class _FECManager {
17168
17687
  #receiptNow() {
17169
17688
  return this.#receiptAtMs ?? performance.now();
17170
17689
  }
17690
+ /**
17691
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
17692
+ * scope: counted from the receipt time, as the timer of a symbol fed when
17693
+ * it was received was, less the whole ms since. So it fires on the tick
17694
+ * that timer would have, never later than a delay counted from now, and
17695
+ * its handler still re-arms a timer that fires before its deadline.
17696
+ * Counted from now, a deadline set from the receipt time is rounded up
17697
+ * from another fraction of a ms (BLO-52085).
17698
+ */
17699
+ #receiptTimerDelayMs(deadlineMs, minMs) {
17700
+ const receivedAtMs = this.#receiptAtMs;
17701
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
17702
+ }
17171
17703
  /**
17172
17704
  * A held packet admitted late arms from its (earlier) receipt time; that
17173
17705
  * never pulls in a deadline later activity already armed. Outside a
@@ -17203,10 +17735,20 @@ var FECManager = class _FECManager {
17203
17735
  this.#repairDeadlineMs(trackConfig)
17204
17736
  );
17205
17737
  }
17206
- this.#armBlockTimeout(sbn, packetId, catalogTrackName, timeoutMs);
17738
+ if (!sourceProgress && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) !== void 0) {
17739
+ this.#shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName);
17740
+ return;
17741
+ }
17742
+ this.#armBlockTimeout(
17743
+ sbn,
17744
+ packetId,
17745
+ catalogTrackName,
17746
+ this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) ?? timeoutMs
17747
+ );
17207
17748
  }
17208
17749
  #failBlock(sbn, packetId, catalogTrackName) {
17209
17750
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
17751
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
17210
17752
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
17211
17753
  this.#clearRepairDeadline(key);
17212
17754
  this.#clearBlockTimer(key);
@@ -17216,6 +17758,7 @@ var FECManager = class _FECManager {
17216
17758
  }
17217
17759
  this.#blockSourceCounts.delete(key);
17218
17760
  this.#blockSourceEsis.delete(key);
17761
+ this.#blockRebuiltEsis.delete(key);
17219
17762
  this.#blockAuthoredLengths.delete(key);
17220
17763
  this.#blockRepairRsIds.delete(key);
17221
17764
  this.#blockRsbLengths.delete(key);
@@ -17225,7 +17768,8 @@ var FECManager = class _FECManager {
17225
17768
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
17226
17769
  this.#fecStats.blocksFailed++;
17227
17770
  this.#statsForPacket(packetId).blocksFailed++;
17228
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
17771
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
17772
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
17229
17773
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
17230
17774
  }
17231
17775
  /**
@@ -17254,7 +17798,9 @@ var FECManager = class _FECManager {
17254
17798
  this.#retireBlockClass(key, block.sbn, block.packetId, block.catalogTrackName);
17255
17799
  this.#blockSourceCounts.delete(key);
17256
17800
  this.#blockSourceEsis.delete(key);
17801
+ this.#blockRebuiltEsis.delete(key);
17257
17802
  this.#blockAuthoredLengths.delete(key);
17803
+ this.#isoSpanKeys.delete(key);
17258
17804
  this.#blockRepairRsIds.delete(key);
17259
17805
  this.#blockRsbLengths.delete(key);
17260
17806
  this.#clearBlockTimer(key);
@@ -17345,7 +17891,9 @@ var FECManager = class _FECManager {
17345
17891
  this.#blockKeysBySbn.clear();
17346
17892
  this.#blockSourceCounts.clear();
17347
17893
  this.#blockSourceEsis.clear();
17894
+ this.#blockRebuiltEsis.clear();
17348
17895
  this.#blockAuthoredLengths.clear();
17896
+ this.#isoSpanKeys.clear();
17349
17897
  this.#blockRepairRsIds.clear();
17350
17898
  this.#blockRsbLengths.clear();
17351
17899
  this.#heldLayerStates.clear();
@@ -17901,9 +18449,21 @@ var IsoBmffTimingResolver = class {
17901
18449
  }
17902
18450
  #track = null;
17903
18451
  #fragments = /* @__PURE__ */ new Map();
18452
+ /** First sample of each pending fragment, kept in `#delivered` with its sample count. */
18453
+ #firstSamples = /* @__PURE__ */ new Map();
18454
+ /**
18455
+ * First sample and sample count of the newest fragments whose every slot was
18456
+ * cleared. Abandonment counts: `releaseSample` clears a slot too, which
18457
+ * matches the combiner, since it retires an abandoned sample as well.
18458
+ */
18459
+ #delivered = /* @__PURE__ */ new Map();
17904
18460
  #pendingSamples = 0;
17905
18461
  #evictedSamples = 0;
17906
18462
  #lastMovieFragmentRejection = null;
18463
+ /** True once an FT=0 has bound the track that FT=1 timing is read against. */
18464
+ get initialized() {
18465
+ return this.#track !== null;
18466
+ }
17907
18467
  get pendingSampleCount() {
17908
18468
  return this.#pendingSamples;
17909
18469
  }
@@ -17927,7 +18487,14 @@ var IsoBmffTimingResolver = class {
17927
18487
  this.#track = timing;
17928
18488
  return true;
17929
18489
  }
17930
- addMovieFragment(mpuSequenceNumber2, data, additionalSampleLimit = this.maxPendingSamples) {
18490
+ /**
18491
+ * `recovered` marks an FEC-recovered copy. A recovered block hands back
18492
+ * every FT=1 it holds, the received ones included, so a recovered copy of a
18493
+ * fragment whose samples are all done is a duplicate: admitting it again
18494
+ * would charge stale timing and could displace the live MPU's. A source
18495
+ * copy is still admitted again (a rendition switch re-arms timing that way).
18496
+ */
18497
+ addMovieFragment(mpuSequenceNumber2, data, additionalSampleLimit = this.maxPendingSamples, recovered = false) {
17931
18498
  this.#lastMovieFragmentRejection = null;
17932
18499
  if (!Number.isInteger(additionalSampleLimit) || additionalSampleLimit < 0) {
17933
18500
  this.#lastMovieFragmentRejection = "invalid";
@@ -17953,6 +18520,8 @@ var IsoBmffTimingResolver = class {
17953
18520
  (sample, index) => sample !== null && sameSample(sample, parsed.samples[index])
17954
18521
  );
17955
18522
  }
18523
+ const delivered = recovered ? this.#delivered.get(key) : void 0;
18524
+ if (delivered && delivered.sampleCount === parsed.samples.length && sameSample(delivered.first, parsed.samples[0])) return true;
17956
18525
  let freed = 0;
17957
18526
  while (this.#fragments.size > 0 && (this.#pendingSamples + parsed.samples.length > this.maxPendingSamples || parsed.samples.length - freed > additionalSampleLimit)) {
17958
18527
  freed += this.#evictOldestFragment();
@@ -17966,6 +18535,7 @@ var IsoBmffTimingResolver = class {
17966
18535
  return false;
17967
18536
  }
17968
18537
  this.#fragments.set(key, [...parsed.samples]);
18538
+ this.#firstSamples.set(key, parsed.samples[0]);
17969
18539
  this.#pendingSamples += parsed.samples.length;
17970
18540
  return true;
17971
18541
  }
@@ -18023,6 +18593,7 @@ var IsoBmffTimingResolver = class {
18023
18593
  let live = 0;
18024
18594
  for (const sample of samples) if (sample !== null) live++;
18025
18595
  this.#fragments.delete(oldest);
18596
+ this.#firstSamples.delete(oldest);
18026
18597
  this.#pendingSamples -= live;
18027
18598
  this.#evictedSamples += live;
18028
18599
  return live;
@@ -18038,12 +18609,23 @@ var IsoBmffTimingResolver = class {
18038
18609
  if (!samples || !samples[index]) return false;
18039
18610
  samples[index] = null;
18040
18611
  this.#pendingSamples--;
18041
- if (samples.every((value) => value === null)) this.#fragments.delete(key);
18612
+ if (samples.every((value) => value === null)) {
18613
+ this.#fragments.delete(key);
18614
+ const first = this.#firstSamples.get(key);
18615
+ this.#firstSamples.delete(key);
18616
+ this.#delivered.delete(key);
18617
+ this.#delivered.set(key, { first, sampleCount: samples.length });
18618
+ if (this.#delivered.size > this.maxPendingSamples) {
18619
+ this.#delivered.delete(this.#delivered.keys().next().value);
18620
+ }
18621
+ }
18042
18622
  return true;
18043
18623
  }
18044
18624
  reset() {
18045
18625
  this.#track = null;
18046
18626
  this.#fragments.clear();
18627
+ this.#firstSamples.clear();
18628
+ this.#delivered.clear();
18047
18629
  this.#pendingSamples = 0;
18048
18630
  }
18049
18631
  };
@@ -18213,6 +18795,9 @@ function authoredGap(before, after) {
18213
18795
  function ssIdAfter(a, b) {
18214
18796
  return (a - b | 0) > 0;
18215
18797
  }
18798
+ function holdsRebuilt(stream) {
18799
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
18800
+ }
18216
18801
  var FecReleaseSequencer = class {
18217
18802
  #streams = /* @__PURE__ */ new Map();
18218
18803
  #gate;
@@ -18275,6 +18860,7 @@ var FecReleaseSequencer = class {
18275
18860
  stream.lastSbn = void 0;
18276
18861
  stream.discontinuity = false;
18277
18862
  stream.rapSsId = void 0;
18863
+ stream.sourced = false;
18278
18864
  }
18279
18865
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
18280
18866
  this.#recordStat("droppedStale");
@@ -18301,6 +18887,7 @@ var FecReleaseSequencer = class {
18301
18887
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
18302
18888
  else hi = mid;
18303
18889
  }
18890
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
18304
18891
  stream.buf.splice(lo, 0, frame);
18305
18892
  this.#drainUnlessDeferred(stream);
18306
18893
  }
@@ -18336,6 +18923,41 @@ var FecReleaseSequencer = class {
18336
18923
  }
18337
18924
  return false;
18338
18925
  }
18926
+ /**
18927
+ * These streams' sink is being replaced by one that has seen no source
18928
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
18929
+ * release to the sink being replaced the frames the unanchored path had
18930
+ * already released to it (#cursorPassed): there they waited in its queue,
18931
+ * which its replacement flushes. A stream that holds none is not drained:
18932
+ * it holds nothing the anchor kept back, and a drain would still force out
18933
+ * a frame held past the hold limit, which before the anchor waited for the
18934
+ * next push. Then treat the streams as unsourced until a source frame is
18935
+ * released.
18936
+ */
18937
+ unsource(packetId, catalogTrackName) {
18938
+ for (const stream of this.#streams.values()) {
18939
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
18940
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
18941
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
18942
+ else this.#drain(stream, true);
18943
+ }
18944
+ stream.sourced = false;
18945
+ }
18946
+ }
18947
+ }
18948
+ /**
18949
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
18950
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
18951
+ * packetId.
18952
+ */
18953
+ holdsRebuilt(packetId, catalogTrackName) {
18954
+ for (const stream of this.#streams.values()) {
18955
+ if (stream.packetId !== packetId) continue;
18956
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
18957
+ if (holdsRebuilt(stream)) return true;
18958
+ }
18959
+ return false;
18960
+ }
18339
18961
  /** Re-evaluate held gaps after FEC state changed. */
18340
18962
  poke(streamKey) {
18341
18963
  if (streamKey !== void 0) {
@@ -18427,16 +19049,32 @@ var FecReleaseSequencer = class {
18427
19049
  last: null,
18428
19050
  lastSbn: void 0,
18429
19051
  discontinuity: false,
18430
- rapSsId: void 0
19052
+ rapSsId: void 0,
19053
+ sourced: false,
19054
+ draining: 0
18431
19055
  };
18432
19056
  this.#streams.set(streamKey, stream);
18433
19057
  }
18434
19058
  return stream;
18435
19059
  }
18436
- #drain(stream) {
19060
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
19061
+ #drain(stream, asUnanchored = false) {
19062
+ stream.draining++;
19063
+ try {
19064
+ this.#drainLoop(stream, asUnanchored);
19065
+ } finally {
19066
+ stream.draining--;
19067
+ }
19068
+ }
19069
+ #drainLoop(stream, asUnanchored) {
18437
19070
  while (stream.buf.length > 0 && stream.last !== null) {
18438
19071
  const head = stream.buf[0];
18439
19072
  const last = stream.last;
19073
+ if (compareFrameOrder(head, last) <= 0) {
19074
+ stream.buf.shift();
19075
+ this.#release(stream, head, void 0);
19076
+ continue;
19077
+ }
18440
19078
  if (stream.discontinuity) {
18441
19079
  stream.discontinuity = false;
18442
19080
  stream.buf.shift();
@@ -18450,9 +19088,10 @@ var FecReleaseSequencer = class {
18450
19088
  }
18451
19089
  const headSbn = head.meta.fecSbn;
18452
19090
  const from = stream.lastSbn ?? headSbn;
18453
- const to = headSbn ?? stream.lastSbn;
19091
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
18454
19092
  let lost = [];
18455
19093
  const unanchored = from === void 0 && to === void 0;
19094
+ let unresolved = false;
18456
19095
  if (from !== void 0 && to !== void 0) {
18457
19096
  const resolved = this.#gate.resolvedLoss(
18458
19097
  stream.packetId,
@@ -18461,7 +19100,8 @@ var FecReleaseSequencer = class {
18461
19100
  Math.max(from, to),
18462
19101
  from
18463
19102
  );
18464
- if (resolved === null) {
19103
+ unresolved = resolved === null;
19104
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored) && !this.#unrepairableWaitOver(stream, last, head, from, to)) {
18465
19105
  const heldMs = performance.now() - head.arrivedAtMs;
18466
19106
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
18467
19107
  this.#recordStat("forcedWindowFlushes");
@@ -18469,22 +19109,69 @@ var FecReleaseSequencer = class {
18469
19109
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
18470
19110
  continue;
18471
19111
  }
18472
- lost = resolved;
19112
+ lost = resolved ?? [];
18473
19113
  }
18474
19114
  stream.buf.shift();
18475
19115
  this.#release(
18476
19116
  stream,
18477
19117
  head,
18478
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
19118
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
18479
19119
  );
18480
19120
  }
18481
19121
  }
19122
+ /**
19123
+ * The head has waited out a gap only a late source can still fill
19124
+ * (FecReleaseGate.unrepairableWaitMs). Not yet: the gate is asked to poke
19125
+ * the stream when it has (`wakeAt`), since no packet may come by then.
19126
+ */
19127
+ #unrepairableWaitOver(stream, last, head, from, to) {
19128
+ const waitMs = this.#gate.unrepairableWaitMs?.(last, head, from, to);
19129
+ if (waitMs === void 0) return false;
19130
+ const atMs = head.arrivedAtMs + waitMs;
19131
+ if (performance.now() >= atMs) return true;
19132
+ this.#gate.wakeAt?.(stream.packetId, stream.catalogTrackName, atMs);
19133
+ return false;
19134
+ }
19135
+ /**
19136
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
19137
+ * source cursor holds it unanchored, and neither does a later frame behind
19138
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
19139
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
19140
+ * like each frame that arrived in front of it since (stale there). The head
19141
+ * then goes, decided as it would be unanchored, once a frame the base path
19142
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
19143
+ * marked one: the base path has passed that one, so a frame still missing
19144
+ * before it can only come from a repair. It also goes while no source frame
19145
+ * has been released, when the direct path shows a recovered frame at once.
19146
+ * And it goes at once while a staged switch decides on when frames arrive
19147
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
19148
+ * sink being replaced: unanchored, it had already reached the sink.
19149
+ * The scan also writes: the `passed` marks it sets stay on the frames,
19150
+ * and push marks a frame it inserts in front of a marked one from them.
19151
+ */
19152
+ #cursorPassed(stream, asUnanchored) {
19153
+ let at2 = -1;
19154
+ for (let i = 0; i < stream.buf.length; i++) {
19155
+ const frame = stream.buf[i];
19156
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
19157
+ frame.passed = true;
19158
+ if (at2 < 0) at2 = i;
19159
+ } else if (frame.passed !== true) break;
19160
+ }
19161
+ if (at2 < 0) return false;
19162
+ 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));
19163
+ }
18482
19164
  #release(stream, frame, decision) {
19165
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
19166
+ if (stale) this.#recordStat("droppedStale");
18483
19167
  if (decision) frame.meta.gapBefore = decision;
18484
19168
  stream.last = frame;
18485
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
19169
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
19170
+ stream.lastSbn = frame.meta.fecSbn;
19171
+ }
19172
+ if (frame.meta.recovered !== true) stream.sourced = true;
18486
19173
  this.#gate.onReleased?.(frame.data, frame.meta);
18487
- this.#emit(frame.data, frame.meta);
19174
+ if (!stale) this.#emit(frame.data, frame.meta);
18488
19175
  }
18489
19176
  };
18490
19177
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -18525,6 +19212,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
18525
19212
  this.#reclaimedTimingSamples = 0;
18526
19213
  this.#evictedTimingSamples = 0;
18527
19214
  this.#rejectedMovieFragments = 0;
19215
+ this.#recoveredHeadsAwaitingTiming = {
19216
+ held: 0,
19217
+ expired: 0,
19218
+ discarded: 0,
19219
+ superseded: 0
19220
+ };
18528
19221
  this.#sequencers = /* @__PURE__ */ new Map();
18529
19222
  this.#fecGate = null;
18530
19223
  this.#fecSequencer = null;
@@ -18633,6 +19326,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
18633
19326
  #reclaimedTimingSamples;
18634
19327
  #evictedTimingSamples;
18635
19328
  #rejectedMovieFragments;
19329
+ #recoveredHeadsAwaitingTiming;
18636
19330
  #sequencers;
18637
19331
  #fecGate;
18638
19332
  #fecSequencer;
@@ -18738,11 +19432,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
18738
19432
  /**
18739
19433
  * Typed view of the ISO-BMFF timing-sample budget.
18740
19434
  *
18741
- * This is the acceptance signal for the budget ratchet: `pending` walking
18742
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
18743
- * and it is observable here rather than only as media silently stopping.
18744
- * Per repo policy this is a producer-owned counter -- never infer budget
18745
- * state by parsing logs.
19435
+ * Each stream admits timing against its own window of `capacity` slots
19436
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
19437
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
19438
+ * timing a stream declared and never delivered shows up there. `pending`
19439
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
19440
+ * a producer-owned counter -- never infer budget state by parsing logs.
18746
19441
  */
18747
19442
  get timingBudgetStats() {
18748
19443
  return {
@@ -18753,6 +19448,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
18753
19448
  rejectedMovieFragments: this.#rejectedMovieFragments
18754
19449
  };
18755
19450
  }
19451
+ /** Recovered heads parked for FT=1 timing (BLO-53369). Survives dispose(). */
19452
+ get recoveredHeadsAwaitingTiming() {
19453
+ let pending = 0;
19454
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
19455
+ for (const head of awaitingTiming) if (head.options?.recovered) pending++;
19456
+ }
19457
+ return { ...this.#recoveredHeadsAwaitingTiming, pending };
19458
+ }
18756
19459
  get reorderStats() {
18757
19460
  let bufferedFrames = this.#fecSequencer?.buffered ?? 0;
18758
19461
  for (const { sequencer } of this.#sequencers.values()) bufferedFrames += sequencer.buffered;
@@ -18794,6 +19497,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
18794
19497
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
18795
19498
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
18796
19499
  }
19500
+ /** See FecReleaseSequencer.unsource. */
19501
+ unsourceFecRelease(packetId, catalogTrackName) {
19502
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
19503
+ }
19504
+ /** See FecReleaseSequencer.holdsRebuilt. */
19505
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
19506
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
19507
+ }
18797
19508
  /** Re-evaluate held gaps after FEC block state changed. */
18798
19509
  pokeFecRelease(packetId, catalogTrackName) {
18799
19510
  if (!this.#fecSequencer) return;
@@ -18926,7 +19637,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
18926
19637
  const now = Date.now();
18927
19638
  for (const { awaitingTiming } of this.#timingStreams.values()) {
18928
19639
  while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
18929
- awaitingTiming.shift();
19640
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
18930
19641
  }
18931
19642
  }
18932
19643
  }
@@ -19044,11 +19755,16 @@ var MmtpContainerParser = class _MmtpContainerParser {
19044
19755
  if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
19045
19756
  return this.#drop("fragment-unexpected-fragmentation");
19046
19757
  const resolver2 = this.#timingResolver(streamKey, info.packetId, false);
19047
- if (!resolver2) return this.#drop("fragment-no-resolver");
19758
+ if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
19048
19759
  const pendingBefore = resolver2.pendingSampleCount;
19049
19760
  const evictedBefore = resolver2.evictedSampleCount;
19050
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
19051
- const admitted = resolver2.addMovieFragment(mpu.mpuSequenceNumber, data, remaining);
19761
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
19762
+ const admitted = resolver2.addMovieFragment(
19763
+ mpu.mpuSequenceNumber,
19764
+ data,
19765
+ remaining,
19766
+ options?.recovered === true
19767
+ );
19052
19768
  this.#pendingTimingSamples += resolver2.pendingSampleCount - pendingBefore;
19053
19769
  this.#evictedTimingSamples += resolver2.evictedSampleCount - evictedBefore;
19054
19770
  if (!admitted) {
@@ -19068,7 +19784,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19068
19784
  };
19069
19785
  }
19070
19786
  if (fragmentType !== 2) return this.#drop("unknown-fragment-type");
19071
- const resolver = this.#timingResolver(streamKey, info.packetId, false);
19787
+ const resolver = this.#timingResolver(streamKey, info.packetId, true);
19072
19788
  if (!resolver) return this.#drop("mfu-no-resolver");
19073
19789
  if (!Number.isSafeInteger(data.byteLength) || data.byteLength <= 0)
19074
19790
  return this.#drop("mfu-empty-payload");
@@ -19089,6 +19805,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19089
19805
  mpuSequenceNumber: mpu.mpuSequenceNumber,
19090
19806
  movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
19091
19807
  sampleNumber: mfuDuHeader.sampleNumber,
19808
+ sequenceNumber: info.sequenceNumber,
19092
19809
  arrivedAt: Date.now()
19093
19810
  });
19094
19811
  return this.#drop("mfu-sample-timing-missing");
@@ -19114,7 +19831,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
19114
19831
  info,
19115
19832
  resolver,
19116
19833
  options?.recovered === true,
19117
- options?.fecSbn
19834
+ options?.fecSbn,
19835
+ options?.fecSbnFirst
19118
19836
  );
19119
19837
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
19120
19838
  }
@@ -19207,7 +19925,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
19207
19925
  info,
19208
19926
  resolver,
19209
19927
  options?.recovered === true,
19210
- options?.fecSbn
19928
+ options?.fecSbn,
19929
+ options?.fecSbnFirst
19211
19930
  );
19212
19931
  if (outcome.record !== void 0) return outcome.record;
19213
19932
  return this.#drop(outcome.reason);
@@ -19227,7 +19946,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19227
19946
  * attribution exists to keep readable. Leaving the choice at the call site
19228
19947
  * is what keeps both true.
19229
19948
  */
19230
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
19949
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
19231
19950
  const timing = resolver.sampleTiming(
19232
19951
  combined.mpuSequenceNumber,
19233
19952
  combined.movieFragmentSequenceNumber,
@@ -19244,6 +19963,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19244
19963
  );
19245
19964
  if (!meta) return { reason: "combined-meta-build-failed" };
19246
19965
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
19966
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
19247
19967
  if (!resolver.consumeSample(
19248
19968
  combined.mpuSequenceNumber,
19249
19969
  combined.movieFragmentSequenceNumber,
@@ -19477,6 +20197,9 @@ var MmtpContainerParser = class _MmtpContainerParser {
19477
20197
  for (const { sequencer } of this.#sequencers.values()) sequencer.discard();
19478
20198
  this.#sequencers.clear();
19479
20199
  this.#fecSequencer?.discard();
20200
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
20201
+ for (const head of awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
20202
+ }
19480
20203
  this.#timingStreams.clear();
19481
20204
  this.#pendingTimingSamples = 0;
19482
20205
  this.#reliableMoqStartupGate.clear();
@@ -19495,10 +20218,23 @@ var MmtpContainerParser = class _MmtpContainerParser {
19495
20218
  return resolver;
19496
20219
  }
19497
20220
  #awaitTiming(streamKey, head) {
19498
- const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
19499
- if (!awaitingTiming) return;
20221
+ const state = this.#timingStreams.get(streamKey);
20222
+ if (!state) return;
20223
+ if (!head.options?.recovered) {
20224
+ const kept = state.awaitingTiming.filter((queued) => !queued.options?.recovered || queued.sequenceNumber !== head.sequenceNumber);
20225
+ this.#recoveredHeadsAwaitingTiming.superseded += state.awaitingTiming.length - kept.length;
20226
+ state.awaitingTiming = kept;
20227
+ }
20228
+ const awaitingTiming = state.awaitingTiming;
19500
20229
  awaitingTiming.push(head);
19501
- if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
20230
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming.held++;
20231
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) {
20232
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
20233
+ }
20234
+ }
20235
+ /** Count a recovered head leaving the queue other than by replay or its source copy. */
20236
+ #leaveAwaitingTiming(head, outcome) {
20237
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming[outcome]++;
19502
20238
  }
19503
20239
  /**
19504
20240
  * Feed again the heads whose timing the FT=1 just admitted declares. That
@@ -19526,6 +20262,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19526
20262
  const state = this.#timingStreams.get(streamKey);
19527
20263
  if (!state) return;
19528
20264
  this.#timingStreams.delete(streamKey);
20265
+ for (const head of state.awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
19529
20266
  this.#pendingTimingSamples -= state.resolver.pendingSampleCount;
19530
20267
  if (this.#pendingTimingSamples < 0) {
19531
20268
  throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");
@@ -22732,7 +23469,18 @@ function keyframeOverlaySsId(header) {
22732
23469
  if (ext?.type !== KEYFRAME_OVERLAY_EXTENSION_TYPE || ext.data.length !== 4) return void 0;
22733
23470
  return new DataView(ext.data.buffer, ext.data.byteOffset, 4).getUint32(0);
22734
23471
  }
23472
+ function overlayBaseSsId(anchor, overlaySsId, restoredPsn, headerPsn) {
23473
+ if (anchor.baseSsId === void 0 || headerPsn !== restoredPsn) return void 0;
23474
+ return serial32Add(anchor.baseSsId, overlaySsId - anchor.overlaySsId | 0);
23475
+ }
23476
+ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
23477
+ if (offset === void 0 || offset !== unstampedOffset) return void 0;
23478
+ return headerPsn + offset >>> 0;
23479
+ }
23480
+ var OVERLAY_ROUTED_LIMIT = 1024;
23481
+ var OVERLAY_PENDING_LIMIT = 256;
22735
23482
  var OVERLAY_OFFSET_MPUS = 16;
23483
+ var OVERLAY_REBUILT_LIMIT = 256;
22736
23484
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
22737
23485
  function assertStreamIdentity(role, stream) {
22738
23486
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -22843,6 +23591,7 @@ var MmtpRouter = class {
22843
23591
  #provenance = /* @__PURE__ */ new Map();
22844
23592
  #onFlowProtected = null;
22845
23593
  #unadmittedListedDrops = 0;
23594
+ #admittedSourceDatagrams = 0;
22846
23595
  #unlistedRepairSetAside = 0;
22847
23596
  #assistBlocks = /* @__PURE__ */ new Map();
22848
23597
  #assistFailures = /* @__PURE__ */ new Map();
@@ -22899,6 +23648,26 @@ var MmtpRouter = class {
22899
23648
  * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
22900
23649
  */
22901
23650
  #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
23651
+ /**
23652
+ * Per stream, the SS_ID offset at which a base recovery last showed the
23653
+ * sender's own packet_sequence_number: a recovered packet's header psn
23654
+ * equal to its SS_ID minus that offset. While it equals the stream's
23655
+ * current offset, no hop re-stamps the stream, and a packet's protected psn
23656
+ * names its base SS_ID within unstampedBaseSsId's limits (joint decoding of
23657
+ * an MPU no member of which arrived).
23658
+ */
23659
+ #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
23660
+ /**
23661
+ * The same, shown by the overlay alone, before any base recovery did: a
23662
+ * packet it rebuilt whose base copy carries its protected psn
23663
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
23664
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
23665
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
23666
+ * make the base drop a late base copy of a keyframe the overlay never
23667
+ * finished, and lift a block's late-source cut, which nothing before
23668
+ * this offset did.
23669
+ */
23670
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
22902
23671
  /**
22903
23672
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
22904
23673
  * not parsed, typically because its overlap copy was parsed first
@@ -22944,6 +23713,8 @@ var MmtpRouter = class {
22944
23713
  // end: a synchronous recovery completes its block BEFORE routing the
22945
23714
  // recovered frames, and releasing a held gap in between would strand them.
22946
23715
  #fecPokeDepth = 0;
23716
+ /** FecReleaseGate.wakeAt timers, by media stream key. */
23717
+ #fecWakes = /* @__PURE__ */ new Map();
22947
23718
  #pendingFecPokes = /* @__PURE__ */ new Map();
22948
23719
  // ── Phase 14: per-role packetId dispatch (D-26, D-27, D-28) ───────
22949
23720
  /** Maps packetId → TrackRole. Default: 'single' when absent (legacy path). */
@@ -22968,7 +23739,9 @@ var MmtpRouter = class {
22968
23739
  recovered: 0,
22969
23740
  restarts: 0,
22970
23741
  unsequencedDropped: 0,
22971
- protectedDropped: 0
23742
+ protectedDropped: 0,
23743
+ baseFed: 0,
23744
+ baseUndetermined: 0
22972
23745
  };
22973
23746
  /** Callback fired when a delta-track FEC block completes or fails. */
22974
23747
  #onDeltaBlockCompleteCb = null;
@@ -23141,7 +23914,7 @@ var MmtpRouter = class {
23141
23914
  const cb = this.#getFrameCallback(packetId);
23142
23915
  if (isVideo && !assembler) {
23143
23916
  if (frameMeta.recovered) {
23144
- this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb);
23917
+ this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb, meta.fecSbn);
23145
23918
  } else {
23146
23919
  this.#routeDirectSourceVideo(packetId, data, frameMeta, cb);
23147
23920
  }
@@ -23174,13 +23947,18 @@ var MmtpRouter = class {
23174
23947
  this.#onDeltaBlockCompleteCb?.(packetId, false);
23175
23948
  }
23176
23949
  };
23177
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
23950
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
23178
23951
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
23179
23952
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
23180
23953
  this.#onDeltaBlockCompleteCb?.(packetId, true);
23181
23954
  }
23182
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23183
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23955
+ if (span === void 0) {
23956
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23957
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23958
+ } else {
23959
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
23960
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
23961
+ }
23184
23962
  };
23185
23963
  }
23186
23964
  }
@@ -23225,8 +24003,9 @@ var MmtpRouter = class {
23225
24003
  }
23226
24004
  /**
23227
24005
  * FEC-recovered source symbols whose reconstructed header named a
23228
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
23229
- * a hop re-stamped the sequence after the sender protected the packet.
24006
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
24007
+ * or, rebuilt by the overlay, than their base copy carries: a hop
24008
+ * re-stamped the sequence after the sender protected the packet.
23230
24009
  */
23231
24010
  get restampedRecoveredSequenceCount() {
23232
24011
  return this.#restampedRecoveredSeqs;
@@ -23405,6 +24184,7 @@ var MmtpRouter = class {
23405
24184
  enableMseAssembler(packetId, config, catalogTrackName) {
23406
24185
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
23407
24186
  const previous = this.#mseAssemblers.get(assemblerKey);
24187
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
23408
24188
  if (previous) {
23409
24189
  previous.flush();
23410
24190
  previous.dispose();
@@ -23531,6 +24311,10 @@ var MmtpRouter = class {
23531
24311
  get keyframeOverlayStats() {
23532
24312
  return { ...this.#overlayStats };
23533
24313
  }
24314
+ /** Recovered FT=2 heads held for their FT=1, and how each left the wait (BLO-53369). */
24315
+ get recoveredHeadsAwaitingTiming() {
24316
+ return this.#parser.recoveredHeadsAwaitingTiming;
24317
+ }
23534
24318
  #isOverlayRepair(repairPacketId, repairTrackName) {
23535
24319
  return this.#overlayLegs.has(repairPacketId) || repairTrackName !== void 0 && this.#overlayRepairNames.has(repairTrackName);
23536
24320
  }
@@ -23551,7 +24335,8 @@ var MmtpRouter = class {
23551
24335
  fec,
23552
24336
  k,
23553
24337
  offsets: /* @__PURE__ */ new Map(),
23554
- moqBlocks: /* @__PURE__ */ new Set()
24338
+ moqBlocks: /* @__PURE__ */ new Set(),
24339
+ rebuilt: /* @__PURE__ */ new Map()
23555
24340
  };
23556
24341
  this.#overlays.set(repairPacketId, inst);
23557
24342
  return () => {
@@ -23581,12 +24366,18 @@ var MmtpRouter = class {
23581
24366
  */
23582
24367
  resetKeyframeOverlays(sourcePacketId, catalogTrackName) {
23583
24368
  for (const inst of this.#overlaysForSource(sourcePacketId, catalogTrackName)) this.#resetOverlay(inst);
24369
+ for (const [name, stream] of this.#streams.get(sourcePacketId) ?? []) {
24370
+ if (catalogTrackName !== void 0 && name !== catalogTrackName) continue;
24371
+ stream.overlayToBase.routed.clear();
24372
+ stream.overlayToBase.pending.clear();
24373
+ }
23584
24374
  }
23585
24375
  #resetOverlay(inst) {
23586
24376
  inst.fec.resetTrack(inst.repairPacketId, inst.streamName);
23587
24377
  inst.last = void 0;
23588
24378
  inst.offsets.clear();
23589
24379
  inst.moqBlocks.clear();
24380
+ inst.rebuilt.clear();
23590
24381
  }
23591
24382
  #overlaysForSource(sourcePacketId, catalogTrackName) {
23592
24383
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -23637,18 +24428,33 @@ var MmtpRouter = class {
23637
24428
  * A source packet that carries a 0x8B01 overlay SS_ID is also a symbol of
23638
24429
  * every overlay installed for its source, at that SS_ID, with the bytes the
23639
24430
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
23640
- * included (7.1, 7.4.3).
23641
- */
23642
- #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source) {
24431
+ * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
24432
+ * FEC reads it.
24433
+ *
24434
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
24435
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
24436
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
24437
+ * the stream unstamped at the SS_ID offset it states, for the release gate
24438
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
24439
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
24440
+ */
24441
+ #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
23643
24442
  if (this.#overlays.size === 0) return;
23644
24443
  const ssId = keyframeOverlaySsId(header);
23645
24444
  if (ssId === void 0) return;
24445
+ let rebuiltPsn;
23646
24446
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
23647
24447
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
24448
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
24449
+ inst.rebuilt.delete(ssId);
23648
24450
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
23649
24451
  if (identity !== null) {
23650
24452
  inst.offsets.delete(identity.mpuSequenceNumber);
23651
- inst.offsets.set(identity.mpuSequenceNumber, ssId - sequenceNumber >>> 0);
24453
+ inst.offsets.set(identity.mpuSequenceNumber, {
24454
+ psnOffset: ssId - sequenceNumber >>> 0,
24455
+ overlaySsId: ssId,
24456
+ ...baseSsId === void 0 ? {} : { baseSsId }
24457
+ });
23652
24458
  if (inst.offsets.size > OVERLAY_OFFSET_MPUS) inst.offsets.delete(inst.offsets.keys().next().value);
23653
24459
  }
23654
24460
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -23670,6 +24476,14 @@ var MmtpRouter = class {
23670
24476
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
23671
24477
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
23672
24478
  }
24479
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
24480
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
24481
+ if (rebuiltPsn !== sequenceNumber) {
24482
+ this.#restampedRecoveredSeqs++;
24483
+ } else if (baseSsId !== void 0) {
24484
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24485
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
24486
+ }
23673
24487
  }
23674
24488
  #noteOverlayMoqBlock(inst, blockStart) {
23675
24489
  inst.moqBlocks.add(blockStart);
@@ -23703,11 +24517,16 @@ var MmtpRouter = class {
23703
24517
  }
23704
24518
  /**
23705
24519
  * Route an overlay-recovered block's packets as source media of the
23706
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
23707
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
23708
- * base re-stamp, no block advance. Each packet's wire sequence is restored
23709
- * from its keyframe's own offset; without one, a stream the base never
23710
- * re-stamped keeps the header's sequence and any other drops the packet.
24520
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
24521
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
24522
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
24523
+ * base FEC recovered does, so it waits behind base frames still in flight,
24524
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
24525
+ * longer than unanchored; one whose base SS_ID is undetermined has no
24526
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
24527
+ * advance. Each packet's wire sequence is restored from its keyframe's own
24528
+ * offset; without one, a stream the base never re-stamped keeps the
24529
+ * header's sequence and any other drops the packet.
23711
24530
  */
23712
24531
  #routeOverlayRecovered(inst, blockStart, recovered) {
23713
24532
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -23727,22 +24546,139 @@ var MmtpRouter = class {
23727
24546
  const streamKey = this.#mediaStreamKey(sourcePacketId, sourceName);
23728
24547
  const restamped = this.#restampedStreams.has(streamKey);
23729
24548
  const restored = /* @__PURE__ */ new Set();
24549
+ const baseSsIds = /* @__PURE__ */ new Map();
24550
+ const gateOnly = /* @__PURE__ */ new Set();
23730
24551
  const symbols = result.symbols.flatMap((sym) => {
23731
- const offset = inst.offsets.get(sym.fragment.mpuSequenceNumber);
23732
- if (offset !== void 0) {
23733
- const packetSequenceNumber = serial32Add(blockStart, sym.index) - offset >>> 0;
24552
+ const overlaySsId = serial32Add(blockStart, sym.index);
24553
+ const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
24554
+ if (anchor !== void 0) {
24555
+ const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
23734
24556
  restored.add(packetSequenceNumber);
23735
- return [{ ...sym, packetSequenceNumber }];
24557
+ const out = { ...sym, packetSequenceNumber };
24558
+ const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
24559
+ if (baseSsId !== void 0) {
24560
+ baseSsIds.set(sym.index, baseSsId);
24561
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24562
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
24563
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
24564
+ }
24565
+ }
24566
+ return [out];
24567
+ }
24568
+ if (!restamped) {
24569
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24570
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
24571
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
24572
+ if (baseSsId !== void 0) {
24573
+ baseSsIds.set(sym.index, baseSsId);
24574
+ if (fedSsId === void 0) gateOnly.add(sym.index);
24575
+ } else {
24576
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
24577
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
24578
+ }
24579
+ return [sym];
23736
24580
  }
23737
- if (!restamped) return [sym];
23738
24581
  this.#overlayStats.unsequencedDropped++;
23739
24582
  return [];
23740
24583
  });
23741
24584
  this.#overlayStats.recovered++;
24585
+ const mpuFirst = /* @__PURE__ */ new Map();
24586
+ for (const sym of symbols) {
24587
+ const ssId = baseSsIds.get(sym.index);
24588
+ const mpu = sym.fragment.mpuSequenceNumber;
24589
+ const first = mpuFirst.get(mpu);
24590
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
24591
+ }
24592
+ const firstSsIds = /* @__PURE__ */ new Map();
24593
+ for (const sym of symbols) {
24594
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
24595
+ }
23742
24596
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
23743
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
24597
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
24598
+ baseSsIds,
24599
+ firstSsIds
23744
24600
  });
23745
24601
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
24602
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
24603
+ }
24604
+ /**
24605
+ * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
24606
+ * its base block too, once its base SS_ID is determined (overlayBaseSsId,
24607
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
24608
+ * base recovery showed; `baseSsIds` holds no other),
24609
+ * so it is fed to the base decoder as a rebuilt source
24610
+ * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
24611
+ * fewer to solve, and its repair can recover the block's other packets.
24612
+ * A base block no repair has stated yet takes it when one does
24613
+ * (#feedPendingRebuilt).
24614
+ *
24615
+ * The overlay route already handled each packet fed (delivered it, or
24616
+ * held an untimed head for its FT=1), so a base recovery routes none of
24617
+ * them again (#routeVerifiedFecSymbols): a second recovered copy of a
24618
+ * held head would wait in the parser for timing its first copy consumed.
24619
+ * Only an overlay block decoded from multicast symbols alone is fed: with
24620
+ * a MoQ symbol in it, the base block's recovery would depend on bytes
24621
+ * that crossed no multicast socket, which the provenance counted from the
24622
+ * block's own arrivals cannot show.
24623
+ */
24624
+ #feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds) {
24625
+ const fec = this.#fecManager;
24626
+ const owner = inst.leg.sourcePacketId;
24627
+ const name = inst.leg.sourceCatalogTrackName;
24628
+ if (!fec?.feedRebuiltSourceSymbol || inst.moqBlocks.has(blockStart)) return;
24629
+ if (this.#classifyPacketId(owner) === null || fec.isTrackConfigured?.(owner) === false) return;
24630
+ const { duplicates, overlayToBase: { routed } } = this.#stream(owner, name);
24631
+ const feeds = [];
24632
+ for (const sym of symbols) {
24633
+ if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
24634
+ const ssId = baseSsIds.get(sym.index);
24635
+ if (ssId === void 0) {
24636
+ this.#overlayStats.baseUndetermined++;
24637
+ continue;
24638
+ }
24639
+ routed.delete(ssId);
24640
+ routed.add(ssId);
24641
+ if (routed.size > OVERLAY_ROUTED_LIMIT) routed.delete(routed.values().next().value);
24642
+ feeds.push([ssId, sym.rawSymbol]);
24643
+ }
24644
+ for (const [ssId, symbolData] of feeds) {
24645
+ if (this.#classifyPacketId(owner) === null) return;
24646
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
24647
+ }
24648
+ }
24649
+ /** Feed one rebuilt source to its base block, or keep it until a repair states that block. */
24650
+ #feedRebuiltToBase(owner, name, ssId, symbolData) {
24651
+ const fec = this.#fecManager;
24652
+ if (!fec?.feedRebuiltSourceSymbol) return;
24653
+ const coords = fec.locateIsoSource?.(owner, name, ssId);
24654
+ if (coords == null) {
24655
+ const pending = this.#stream(owner, name).overlayToBase.pending;
24656
+ pending.delete(ssId);
24657
+ pending.set(ssId, symbolData.slice());
24658
+ if (pending.size > OVERLAY_PENDING_LIMIT) pending.delete(pending.keys().next().value);
24659
+ return;
24660
+ }
24661
+ const fed = fec.feedRebuiltSourceSymbol(owner, ssId, symbolData, name);
24662
+ if (!fed.taken) return;
24663
+ this.#overlayStats.baseFed++;
24664
+ if (fed.recovered === null) return;
24665
+ const sbn = coords.sbn;
24666
+ this.#routeRecoveredBlock(sbn, fed.recovered, owner, name, () => {
24667
+ fec.cancelBlockTimeout(sbn, owner, name);
24668
+ fec.countRecovery(owner, sbn, name);
24669
+ fec.markBlockCompleted(sbn, owner, name);
24670
+ });
24671
+ }
24672
+ /** A repair stated `block`: the rebuilt sources that waited for it join it now. */
24673
+ #feedPendingRebuilt(owner, name, block) {
24674
+ const pending = this.#streams.get(owner)?.get(name)?.overlayToBase.pending;
24675
+ if (pending === void 0 || pending.size === 0) return;
24676
+ for (const [ssId, symbolData] of [...pending]) {
24677
+ if (this.#classifyPacketId(owner) === null) return;
24678
+ if (serial32Distance(block.start, ssId) >= block.length) continue;
24679
+ pending.delete(ssId);
24680
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
24681
+ }
23746
24682
  }
23747
24683
  /** fec-multicast-00 §6.6: report each base block whose RAP MFU fragments
23748
24684
  * the overlay restored, when the keyframe's FT=0 and FT=1 are held too. A
@@ -23882,6 +24818,10 @@ var MmtpRouter = class {
23882
24818
  get unadmittedListedDropCount() {
23883
24819
  return this.#unadmittedListedDrops;
23884
24820
  }
24821
+ /** Source datagrams (multicast or MoQ) a protected flow's bc-provenance v2 receiver released: admitted at once or held, then admitted by a record. Repair symbols and user-agent-admitted datagrams are not counted. Counted at release, before this router's own track checks: a released datagram those drop, which only a track change between hold and release can cause, still counts, so this is not a count of routed media. */
24822
+ get admittedSourceDatagramCount() {
24823
+ return this.#admittedSourceDatagrams;
24824
+ }
23885
24825
  /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
23886
24826
  get unlistedRepairSetAsideCount() {
23887
24827
  return this.#unlistedRepairSetAside;
@@ -24368,6 +25308,8 @@ var MmtpRouter = class {
24368
25308
  )) return;
24369
25309
  fec.noteBlockActivity?.(blockStart, ownerPacketId, catalogTrackName);
24370
25310
  fec.noteRepairGroupLength?.(blockStart, ownerPacketId, repair.rsbLength, catalogTrackName);
25311
+ this.#feedPendingRebuilt(ownerPacketId, catalogTrackName, placement.block);
25312
+ if (this.#classifyPacketId(ownerPacketId) === null) return;
24371
25313
  const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
24372
25314
  const recovered = fec.feedRepairSymbol(
24373
25315
  ownerPacketId,
@@ -24418,7 +25360,7 @@ var MmtpRouter = class {
24418
25360
  catalogTrackName
24419
25361
  )) continue;
24420
25362
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
24421
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
25363
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
24422
25364
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
24423
25365
  }
24424
25366
  if (payload.oversized) continue;
@@ -24505,6 +25447,8 @@ var MmtpRouter = class {
24505
25447
  this.#droppedPreSyncVideo.delete(streamKey);
24506
25448
  this.#latestVideoSeqByStream.delete(streamKey);
24507
25449
  this.#ssIdSeqOffsetByStream.delete(streamKey);
25450
+ this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
25451
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
24508
25452
  this.#multicastRapTwinByStream.delete(streamKey);
24509
25453
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
24510
25454
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -24631,6 +25575,12 @@ var MmtpRouter = class {
24631
25575
  * the outgoing stream stops. The hold is bounded by the incoming stream's
24632
25576
  * own RAP cadence, so no timer is involved.
24633
25577
  *
25578
+ * While the switch is staged, the FEC release gate lets a keyframe the
25579
+ * overlay rebuilt reach it, on either side, when the keyframe did before
25580
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
25581
+ * decides on what each side delivered, and the commit discards the gate's
25582
+ * frames of the outgoing stream.
25583
+ *
24634
25584
  * The commit is one synchronous transition inside the frame path: the
24635
25585
  * outgoing stream's already-admitted frames are released (its queued FEC
24636
25586
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -24681,6 +25631,9 @@ var MmtpRouter = class {
24681
25631
  droppedIncomingFrames: 0
24682
25632
  };
24683
25633
  this.#staged = state;
25634
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
25635
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
25636
+ }
24684
25637
  return {
24685
25638
  cancel: () => {
24686
25639
  if (this.#staged !== state) return false;
@@ -24763,7 +25716,17 @@ var MmtpRouter = class {
24763
25716
  */
24764
25717
  #routeParsedFrame(data, meta) {
24765
25718
  if (this.#classifyPacketId(meta.packetId) === null) return;
24766
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
25719
+ if (this.#staged !== null) {
25720
+ let consumed = false;
25721
+ this.#fecPokeDepth++;
25722
+ try {
25723
+ consumed = this.#interceptSwitchFrame(data, meta);
25724
+ } finally {
25725
+ this.#fecPokeDepth--;
25726
+ this.#flushPendingFecPokes();
25727
+ }
25728
+ if (consumed) return;
25729
+ }
24767
25730
  this.#deliverParsedFrame(data, meta);
24768
25731
  }
24769
25732
  #commitStreamSwitch(state, rap, reason) {
@@ -24812,6 +25775,8 @@ var MmtpRouter = class {
24812
25775
  this.#disposed = true;
24813
25776
  this.#staged = null;
24814
25777
  this.cancelKeyframeLostTimer();
25778
+ for (const { timer } of this.#fecWakes.values()) clearTimeout(timer);
25779
+ this.#fecWakes.clear();
24815
25780
  this.#parser.dispose();
24816
25781
  this.#streams.clear();
24817
25782
  this.#trackPacketCallbacks.clear();
@@ -24915,12 +25880,16 @@ var MmtpRouter = class {
24915
25880
  this.#parser.deferFecRelease(work);
24916
25881
  } finally {
24917
25882
  this.#fecPokeDepth--;
24918
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
24919
- const pokes = [...this.#pendingFecPokes.values()];
24920
- this.#pendingFecPokes.clear();
24921
- for (const poke of pokes) {
24922
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
24923
- }
25883
+ this.#flushPendingFecPokes();
25884
+ }
25885
+ }
25886
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
25887
+ #flushPendingFecPokes() {
25888
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
25889
+ const pokes = [...this.#pendingFecPokes.values()];
25890
+ this.#pendingFecPokes.clear();
25891
+ for (const poke of pokes) {
25892
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
24924
25893
  }
24925
25894
  }
24926
25895
  }
@@ -24989,6 +25958,31 @@ var MmtpRouter = class {
24989
25958
  if (!fec?.terminalRetentionMsForPacket) return Infinity;
24990
25959
  return fec.terminalRetentionMsForPacket(packetId) ?? 0;
24991
25960
  },
25961
+ // Once no repair can fill a gap (FECManager.isoRepairlessWaitMs: only a
25962
+ // late source can), its frame waits the late-symbol allowance when the
25963
+ // gap holds no RAP an installed keyframe overlay could still rebuild:
25964
+ // lost deltas of one MPU (delta-lost), the tail of the MPU before a RAP
25965
+ // that opens the next one while MPU boundaries bound RAPs (rap-next,
25966
+ // unless the gap holds a stated block's loss: the overlay may rebuild
25967
+ // that MPU's FT=0, and the block's group then complete it), or
25968
+ // an audio gap. A gap that may hold one (rap-lost, rap-unknown, or any
25969
+ // other rap-next, whose gap may hold a whole MPU and the keyframe the
25970
+ // overlay protects) waits for that overlay's repair too (BLO-52085
25971
+ // D4). The FEC check comes first: most held gaps are not behind such a
25972
+ // span, and deciding one scans both frames' bitstreams.
25973
+ unrepairableWaitMs: (before, after, fromSbn, toSbn) => {
25974
+ const fec = this.#fecManager;
25975
+ const { packetId, catalogTrackName } = after.meta;
25976
+ const allowanceMs = fec?.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn);
25977
+ if (!fec || allowanceMs === void 0) return void 0;
25978
+ const decision = this.#decideGap(before, after, [], false);
25979
+ const mpu = before.meta.mpuSequenceNumber;
25980
+ const intoNextMpu = decision.reason === "rap-next" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu + 1 >>> 0 && fec.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
25981
+ if (decision.action === "stall" || decision.reason === "rap-next" && !intoNextMpu) {
25982
+ return fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, true);
25983
+ }
25984
+ return decision.reason === "rap-next" ? fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, true) : allowanceMs;
25985
+ },
24992
25986
  decide: (before, after, lostBlocks, discontinuity) => {
24993
25987
  const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
24994
25988
  this.#onFrameGap?.(decision);
@@ -24998,6 +25992,28 @@ var MmtpRouter = class {
24998
25992
  onRap: (packetId, catalogTrackName, ssId) => {
24999
25993
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
25000
25994
  },
25995
+ // One timer per stream, at the earliest wake asked: its drain re-arms
25996
+ // for the next frame still waiting.
25997
+ wakeAt: (packetId, catalogTrackName, atMs) => {
25998
+ if (this.#disposed) return;
25999
+ const key = this.#mediaStreamKey(packetId, catalogTrackName);
26000
+ const armed = this.#fecWakes.get(key);
26001
+ if (armed !== void 0 && armed.atMs <= atMs) return;
26002
+ if (armed !== void 0) clearTimeout(armed.timer);
26003
+ const timer = setTimeout(() => {
26004
+ this.#fecWakes.delete(key);
26005
+ this.#requestFecPoke(packetId, catalogTrackName);
26006
+ }, Math.max(0, Math.ceil(atMs - performance.now())));
26007
+ this.#fecWakes.set(key, { atMs, timer });
26008
+ },
26009
+ // A staged switch commits on when each side's frames reach it
26010
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
26011
+ // they did unanchored.
26012
+ releaseUnanchored: (packetId, catalogTrackName) => {
26013
+ const staged = this.#staged;
26014
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
26015
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
26016
+ },
25001
26017
  onReleased: (data, meta) => {
25002
26018
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
25003
26019
  const timing = meta.authoredTiming;
@@ -25139,6 +26155,7 @@ var MmtpRouter = class {
25139
26155
  const parsed = this.#parser.parsePacket(packet);
25140
26156
  if (!parsed) return;
25141
26157
  const info = parsed.info;
26158
+ if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
25142
26159
  if (source === "multicast" && !manifestAdmitted) {
25143
26160
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
25144
26161
  }
@@ -25420,7 +26437,8 @@ var MmtpRouter = class {
25420
26437
  parsed.header,
25421
26438
  info.sequenceNumber,
25422
26439
  info.rapFlag,
25423
- source
26440
+ source,
26441
+ fecPayloadId?.ssId
25424
26442
  );
25425
26443
  }
25426
26444
  }
@@ -25446,7 +26464,8 @@ var MmtpRouter = class {
25446
26464
  source: parserOptions?.source,
25447
26465
  deliveryProvenance: parserOptions?.deliveryProvenance,
25448
26466
  catalogTrackName: parserOptions?.catalogTrackName,
25449
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
26467
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
26468
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
25450
26469
  };
25451
26470
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
25452
26471
  else this.#parser.feed(packet, feedOptions);
@@ -25570,7 +26589,8 @@ var MmtpRouter = class {
25570
26589
  if (stream === void 0) {
25571
26590
  stream = {
25572
26591
  key: JSON.stringify([packetId, catalogTrackName ?? null]),
25573
- duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId))
26592
+ duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId)),
26593
+ overlayToBase: { routed: /* @__PURE__ */ new Set(), pending: /* @__PURE__ */ new Map() }
25574
26594
  };
25575
26595
  byName.set(catalogTrackName, stream);
25576
26596
  }
@@ -25685,8 +26705,16 @@ var MmtpRouter = class {
25685
26705
  this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
25686
26706
  this.#emitDirectVideo(packetId, data, meta, cb);
25687
26707
  }
25688
- #routeDirectRecoveredVideo(packetId, data, meta, cb) {
26708
+ #routeDirectRecoveredVideo(packetId, data, meta, cb, fecSbn) {
25689
26709
  const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);
26710
+ if (this.#isFecTrack(packetId)) {
26711
+ const high = this.#deliveredVideoHighWaterByStream.get(streamKey);
26712
+ if (fecSbn !== void 0 || high !== void 0 && authoredAdjacent(high, meta)) {
26713
+ this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
26714
+ this.#emitDirectVideo(packetId, data, meta, cb);
26715
+ return;
26716
+ }
26717
+ }
25690
26718
  this.#enqueueDirectRecoveredVideo(packetId, data, meta);
25691
26719
  const lastSourceTs = this.#lastDirectSourceVideoTsByStream.get(streamKey);
25692
26720
  this.#drainDirectRecoveredVideo(
@@ -25840,6 +26868,13 @@ var MmtpRouter = class {
25840
26868
  * frames by epoch only if pre-protection input ever matters.
25841
26869
  */
25842
26870
  #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete, assisted = false) {
26871
+ const overlayRouted = ownerPacketId == null ? void 0 : this.#streams.get(ownerPacketId)?.get(catalogTrackName)?.overlayToBase.routed;
26872
+ if (overlayRouted !== void 0 && overlayRouted.size > 0) {
26873
+ result = {
26874
+ ...result,
26875
+ symbols: result.symbols.filter((sym) => !overlayRouted.has(this.#fecAnchorForRecovered(blockId, sym.index)))
26876
+ };
26877
+ }
25843
26878
  const entry = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
25844
26879
  const receiver = entry === void 0 || entry === "ambiguous" ? entry : entry.receiver;
25845
26880
  const userAgent = !assisted && entry !== void 0 && entry !== "ambiguous" && entry.protected === true && entry.userAgent === true;
@@ -25896,7 +26931,12 @@ var MmtpRouter = class {
25896
26931
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
25897
26932
  if (ownerPacketId == null) return;
25898
26933
  if (this.#classifyPacketId(ownerPacketId) === null) return;
25899
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
26934
+ const fecSbnOf = (index) => {
26935
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
26936
+ const fecSbn = overlay.baseSsIds.get(index);
26937
+ const fecSbnFirst = overlay.firstSsIds.get(index);
26938
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
26939
+ };
25900
26940
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
25901
26941
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
25902
26942
  if (ssIdSeqOffset !== void 0) {
@@ -25904,7 +26944,10 @@ var MmtpRouter = class {
25904
26944
  ...result,
25905
26945
  symbols: result.symbols.map((sym) => {
25906
26946
  const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
25907
- if (wire === sym.packetSequenceNumber) return sym;
26947
+ if (wire === sym.packetSequenceNumber) {
26948
+ this.#unstampedSsIdSeqOffsetByStream.set(streamKey, ssIdSeqOffset);
26949
+ return sym;
26950
+ }
25908
26951
  this.#restampedRecoveredSeqs++;
25909
26952
  this.#restampedStreams.add(streamKey);
25910
26953
  return { ...sym, packetSequenceNumber: wire };
@@ -25940,16 +26983,29 @@ var MmtpRouter = class {
25940
26983
  }
25941
26984
  );
25942
26985
  }
25943
- result = {
25944
- ...result,
25945
- symbols: result.symbols.filter((sym) => sym.fragmentType !== 2 || sym.fragment.fragmentationIndicator !== 1 || sym.fragment.movieFragmentSequenceNumber === void 0 || sym.fragment.sampleNumber === void 0 || this.#parser.hasAuthoredTimingFor(
25946
- ownerPacketId,
25947
- sym.fragment.mpuSequenceNumber,
25948
- sym.fragment.movieFragmentSequenceNumber,
25949
- sym.fragment.sampleNumber,
25950
- catalogTrackName
25951
- ))
25952
- };
26986
+ const untimedHead = (sym) => sym.fragmentType === 2 && sym.fragment.fragmentationIndicator === 1 && sym.fragment.movieFragmentSequenceNumber !== void 0 && sym.fragment.sampleNumber !== void 0 && !this.#parser.hasAuthoredTimingFor(
26987
+ ownerPacketId,
26988
+ sym.fragment.mpuSequenceNumber,
26989
+ sym.fragment.movieFragmentSequenceNumber,
26990
+ sym.fragment.sampleNumber,
26991
+ catalogTrackName
26992
+ );
26993
+ for (const sym of result.symbols) {
26994
+ if (!untimedHead(sym) || this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) continue;
26995
+ this.#feedViaParser(
26996
+ sym.rawSymbol,
26997
+ { packetId: ownerPacketId, sequenceNumber: sym.packetSequenceNumber },
26998
+ void 0,
26999
+ {
27000
+ skipFecPayloadId: true,
27001
+ recovered: true,
27002
+ deliveryProvenance,
27003
+ ...fecSbnOf(sym.index),
27004
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
27005
+ }
27006
+ );
27007
+ }
27008
+ result = { ...result, symbols: result.symbols.filter((sym) => !untimedHead(sym)) };
25953
27009
  const gated = this.#isFecTrack(ownerPacketId);
25954
27010
  const assembler = this.#mseAssemblerFor(ownerPacketId, catalogTrackName);
25955
27011
  if (assembler) {
@@ -27676,6 +28732,12 @@ function isNonNegativeSafeInteger(value) {
27676
28732
  function isSymbolCounts(value) {
27677
28733
  return isRecord(value) && hasExactKeys(value, ["multicast", "moq"]) && isNonNegativeSafeInteger(value["multicast"]) && isNonNegativeSafeInteger(value["moq"]);
27678
28734
  }
28735
+ function isSpanFailure(value) {
28736
+ if (!isRecord(value) || !hasExactKeys(value, ["length", "sources"])) return false;
28737
+ const length = value["length"];
28738
+ const sources = value["sources"];
28739
+ return Number.isSafeInteger(length) && length > 0 && isNonNegativeSafeInteger(sources) && sources < length;
28740
+ }
27679
28741
  function isNullableNonNegative(value) {
27680
28742
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
27681
28743
  }
@@ -27695,7 +28757,10 @@ function isRepairLifecycleEvent(value) {
27695
28757
  case "recovered":
27696
28758
  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"]);
27697
28759
  case "failed":
27698
- return hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]);
28760
+ return hasExactKeys(
28761
+ value,
28762
+ "span" in value ? ["version", "type", "block", "blockClass", "symbols", "span"] : ["version", "type", "block", "blockClass", "symbols"]
28763
+ ) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]) && (!("span" in value) || isSpanFailure(value["span"]));
27699
28764
  case "repair-preempted":
27700
28765
  case "repair-deferred":
27701
28766
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
@@ -27904,6 +28969,8 @@ var MulticastManager = class {
27904
28969
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
27905
28970
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
27906
28971
  #repairReleases = /* @__PURE__ */ new Map();
28972
+ /** Protected repair flows owned by each live repair-endpoint release. */
28973
+ #repairProvenanceFlows = /* @__PURE__ */ new Map();
27907
28974
  /** Each source's catalog keyframe overlay, from its `ok` binding. */
27908
28975
  #overlayBindings = /* @__PURE__ */ new Map();
27909
28976
  /** Installed overlay decoders (`setKeyframeOverlayDecoder`), by source. */
@@ -27961,7 +29028,7 @@ var MulticastManager = class {
27961
29028
  onPublisherRestart: (packetId, catalogTrackName) => {
27962
29029
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
27963
29030
  },
27964
- onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
29031
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass, span) => {
27965
29032
  const pathCount = this.#fec.blockPathCount(
27966
29033
  sbn,
27967
29034
  packetId,
@@ -27979,7 +29046,8 @@ var MulticastManager = class {
27979
29046
  symbols: {
27980
29047
  multicast: pathCount?.multicastSymbols ?? 0,
27981
29048
  moq: pathCount?.moqSymbols ?? 0
27982
- }
29049
+ },
29050
+ ...span === void 0 ? {} : { span }
27983
29051
  });
27984
29052
  },
27985
29053
  onFrameGap: (decision) => {
@@ -28067,6 +29135,11 @@ var MulticastManager = class {
28067
29135
  this.#fec.onBlockVanished = (_sbn, packetId, catalogTrackName) => {
28068
29136
  this.#statsFor(packetId, catalogTrackName).vanishedBlocks++;
28069
29137
  };
29138
+ this.#fec.keyframeOverlayTiming = (packetId, catalogTrackName) => {
29139
+ const binding = this.#overlayInstalls.has(packetId) ? this.#overlayBindings.get(packetId) : void 0;
29140
+ if (binding === void 0) return void 0;
29141
+ return catalogTrackName === void 0 || catalogTrackName === binding.sourceCatalogTrackName ? binding.geometry : void 0;
29142
+ };
28070
29143
  this.#fec.onDecoderUnavailable = (event) => {
28071
29144
  this.#emitRepairLifecycle({
28072
29145
  version: 2,
@@ -28569,6 +29642,9 @@ var MulticastManager = class {
28569
29642
  this.#transport.onFailback((reason) => {
28570
29643
  const joined = this.#provenanceJoin;
28571
29644
  if (joined !== null) this.#router.unprotectProvenanceFlow(joined.flow);
29645
+ for (const flows of this.#repairProvenanceFlows.values()) {
29646
+ for (const flow of flows) this.#router.unprotectProvenanceFlow(flow);
29647
+ }
28572
29648
  this.#onFailback?.(reason);
28573
29649
  });
28574
29650
  }
@@ -28603,6 +29679,12 @@ var MulticastManager = class {
28603
29679
  "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
28604
29680
  );
28605
29681
  }
29682
+ if (provenanceFlow !== void 0) {
29683
+ const flow = multicastProvenanceFlowKey(provenanceFlow);
29684
+ if ([...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
29685
+ throw new TypeError(`[MulticastManager] join: provenance flow already registered by a repair endpoint: ${flow}`);
29686
+ }
29687
+ }
28606
29688
  const staged = this.#renditionSwitch;
28607
29689
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
28608
29690
  this.configureFec(config);
@@ -28610,8 +29692,8 @@ var MulticastManager = class {
28610
29692
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
28611
29693
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
28612
29694
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
28613
- this.#releaseProvenanceJoin();
28614
29695
  const provenance = config.provenance;
29696
+ this.#releaseProvenanceJoin();
28615
29697
  const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
28616
29698
  const ingress = protectedTracks === void 0 ? void 0 : {
28617
29699
  tracks: Object.freeze(
@@ -28664,8 +29746,13 @@ var MulticastManager = class {
28664
29746
  * feeds the flow's receiver; media datagrams are held until one admits them.
28665
29747
  */
28666
29748
  #joinProvenance(provenance, ingress) {
29749
+ this.#router.registerProvenanceFlow(ingress, this.#provenanceReceiver(provenance));
29750
+ this.#hookFailback();
29751
+ this.#provenanceJoin = { flow: ingress.flow };
29752
+ }
29753
+ #provenanceReceiver(provenance) {
28667
29754
  const { flow, auth } = provenance;
28668
- const receiver = new BcProvenanceV2Receiver({
29755
+ return new BcProvenanceV2Receiver({
28669
29756
  ...provenance.receiver,
28670
29757
  // The caller's ctx when it passes one, else the catalog's: an explicit
28671
29758
  // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
@@ -28682,9 +29769,6 @@ var MulticastManager = class {
28682
29769
  maxAuthDelayMs: flow.maxAuthDelayMs,
28683
29770
  manifestTimerMs: flow.manifestTimerMs
28684
29771
  });
28685
- this.#router.registerProvenanceFlow(ingress, receiver);
28686
- this.#hookFailback();
28687
- this.#provenanceJoin = { flow: ingress.flow };
28688
29772
  }
28689
29773
  /** Un-protect: drop the flow's hold queues (no expiry counted). */
28690
29774
  #releaseProvenanceJoin() {
@@ -28715,8 +29799,25 @@ var MulticastManager = class {
28715
29799
  * callback delivers must come from a subscription opened on
28716
29800
  * `options.gateway`. A callback that also merges another source (a MoQ or
28717
29801
  * WebSocket repair feed) must not name a native provider here.
29802
+ *
29803
+ * An endpoint's `provenance` makes its group a protected flow of its own
29804
+ * (multicast-02 7.2.7), registered here and released with the group; its
29805
+ * records ride in band on the group's port. On the user-agent path a
29806
+ * flow-less repair group of a protected track is set aside, never read, so
29807
+ * a player joining a protected catalog's repair groups passes it.
28718
29808
  */
28719
29809
  joinRepairEndpoints(endpoints, provider, options) {
29810
+ for (const { provenance, flow, source, group, port: port2 } of endpoints) {
29811
+ if (provenance === void 0) continue;
29812
+ if (flow !== void 0) {
29813
+ throw new TypeError("[MulticastManager] joinRepairEndpoints: an endpoint names provenance or flow, never both");
29814
+ }
29815
+ if (!sameIpAddress(source, provenance.flow.source) || !sameIpAddress(group, provenance.flow.groupAddress) || port2 !== provenance.flow.port) {
29816
+ throw new RangeError(
29817
+ "[MulticastManager] joinRepairEndpoints: provenance flow (S, G, port) must match the endpoint's source, group and port"
29818
+ );
29819
+ }
29820
+ }
28720
29821
  const releases = [];
28721
29822
  let released = false;
28722
29823
  const safely = (each) => {
@@ -28726,17 +29827,36 @@ var MulticastManager = class {
28726
29827
  console.warn("[MulticastManager] repair group release failed", error);
28727
29828
  }
28728
29829
  };
29830
+ const usedFlows = new Set(endpoints.flatMap(({ flow }) => flow === void 0 ? [] : [flow]));
29831
+ const preparedProvenance = endpoints.map((endpoint) => {
29832
+ if (endpoint.provenance === void 0) return void 0;
29833
+ const flow = multicastProvenanceFlowKey(endpoint.provenance.flow);
29834
+ if (usedFlows.has(flow) || this.#provenanceJoin?.flow === flow || [...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
29835
+ throw new TypeError(`[MulticastManager] joinRepairEndpoints: provenance flow already registered: ${flow}`);
29836
+ }
29837
+ usedFlows.add(flow);
29838
+ return { flow, receiver: this.#provenanceReceiver(endpoint.provenance) };
29839
+ });
29840
+ const provenanceFlows = [];
28729
29841
  const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners.map((owner) => owner.instance !== "keyframe" ? owner : {
28730
29842
  ...owner,
28731
29843
  ownerTrackName: endpoint.tracks.find((t) => t.packetId === owner.ownerPacketId)?.name,
28732
29844
  repairTrackName: endpoint.tracks.find((t) => t.packetId === owner.packetId)?.name
28733
29845
  }));
28734
29846
  this.#applyRepairOwners(repairOwners);
28735
- for (const endpoint of endpoints) {
29847
+ for (const [index, endpoint] of endpoints.entries()) {
29848
+ const flow = endpoint.provenance === void 0 ? endpoint.flow : multicastProvenanceFlowKey(endpoint.provenance.flow);
28736
29849
  const ingress = {
28737
29850
  tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
28738
- ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
29851
+ ...flow === void 0 ? {} : { flow }
28739
29852
  };
29853
+ if (endpoint.provenance !== void 0) {
29854
+ const prepared = preparedProvenance[index];
29855
+ if (prepared === void 0) throw new Error("[MulticastManager] repair provenance preparation missing");
29856
+ this.#router.registerProvenanceFlow(ingress, prepared.receiver);
29857
+ provenanceFlows.push(prepared.flow);
29858
+ releases.push(() => this.#router.releaseProvenanceFlow(flow));
29859
+ }
28740
29860
  let sender;
28741
29861
  const feed = (packet, sourceAddress, ingressToFeed) => {
28742
29862
  if (released) return;
@@ -28766,7 +29886,7 @@ var MulticastManager = class {
28766
29886
  packetIds: endpoint.packetIds,
28767
29887
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
28768
29888
  // A protected repair group's records ride in band on its port (7.2.3).
28769
- ...endpoint.flow === void 0 ? {} : { protected: true }
29889
+ ...flow === void 0 ? {} : { protected: true }
28770
29890
  }, ingress).then((joined) => {
28771
29891
  if (!joined && !released) fail(transport.lastJoinOutcome);
28772
29892
  });
@@ -28775,9 +29895,12 @@ var MulticastManager = class {
28775
29895
  if (released) return;
28776
29896
  released = true;
28777
29897
  this.#repairReleases.delete(release);
29898
+ this.#repairProvenanceFlows.delete(release);
28778
29899
  for (const each of releases.splice(0)) safely(each);
28779
29900
  };
28780
29901
  this.#repairReleases.set(release, repairOwners);
29902
+ this.#repairProvenanceFlows.set(release, provenanceFlows);
29903
+ if (provenanceFlows.length) this.#hookFailback();
28781
29904
  return release;
28782
29905
  }
28783
29906
  #applyRepairOwners(owners) {
@@ -29263,7 +30386,8 @@ var MulticastManager = class {
29263
30386
  blockProfile: parseFecBlockProfile(
29264
30387
  geometry2.blockProfile,
29265
30388
  `tracks[${JSON.stringify(track.name)}].fec keyframe overlay blockProfile`
29266
- )
30389
+ ),
30390
+ geometry: geometry2
29267
30391
  });
29268
30392
  }
29269
30393
  }
@@ -29302,7 +30426,7 @@ var MulticastManager = class {
29302
30426
  for (const [sourcePacketId, install] of [...this.#overlayInstalls]) {
29303
30427
  const before = this.#overlayBindings.get(sourcePacketId);
29304
30428
  const after = overlayBindings.get(sourcePacketId);
29305
- const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => after[key] === before[key]);
30429
+ const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => key === "geometry" || after[key] === before[key]);
29306
30430
  if (!same) install.dispose();
29307
30431
  else if (this.#router.hasKeyframeOverlay(after.repairPacketId)) this.#router.resetKeyframeOverlays(sourcePacketId);
29308
30432
  else install.reattach();
@@ -29359,10 +30483,12 @@ var MulticastManager = class {
29359
30483
  * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
29360
30484
  * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
29361
30485
  * pending hole and reported here, and `closeIsoHoles` must be called for it
29362
- * once its range FETCH ends (or none is sent).
30486
+ * once its range FETCH ends (or none is sent). `onExpired` is told of a
30487
+ * pending hole the stream runs past the locator's horizon: returning true,
30488
+ * the caller closes it (`closeIsoHoles`); otherwise it is discarded.
29363
30489
  */
29364
- onUndelimitedLoss(cb) {
29365
- this.#fec.setUndelimitedLossHandler(cb);
30490
+ onUndelimitedLoss(cb, onExpired) {
30491
+ this.#fec.setUndelimitedLossHandler(cb, onExpired ?? null);
29366
30492
  }
29367
30493
  /**
29368
30494
  * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
@@ -29598,7 +30724,8 @@ var MulticastManager = class {
29598
30724
  "stream" in event ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
29599
30725
  ...event,
29600
30726
  block: Object.freeze({ ...event.block }),
29601
- ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {}
30727
+ ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {},
30728
+ ..."span" in event && event.span !== void 0 ? { span: Object.freeze({ ...event.span }) } : {}
29602
30729
  }
29603
30730
  );
29604
30731
  if (this.#logRepairLifecycle) {
@@ -32270,6 +33397,7 @@ var RepairLayerSubscriptions = class {
32270
33397
 
32271
33398
  // src/repair-fetch.ts
32272
33399
  var MOQT_PRIORITY_MAX = 255;
33400
+ var WALK_LEAD_MS = 3;
32273
33401
  var SOURCE_MEDIA_PRIORITY_MAX = REPAIR_PRIORITY_MIN - 1;
32274
33402
  function isMoqtPriority(value) {
32275
33403
  return Number.isSafeInteger(value) && value >= 0 && value <= MOQT_PRIORITY_MAX;
@@ -32320,8 +33448,17 @@ function wireRepairFetch(mc, opts) {
32320
33448
  mc.noteRepairScheduling(type, entry.sbn, entry.packetId, entry.catalogTrackName);
32321
33449
  };
32322
33450
  const clearEntry = (entry) => {
32323
- if (entry.range) mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, entry.range.holeLength);
32324
- else clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
33451
+ const { range } = entry;
33452
+ if (range) {
33453
+ atReport(range, () => mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, range.holeLength));
33454
+ } else {
33455
+ clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
33456
+ }
33457
+ };
33458
+ const atReport = (range, work) => {
33459
+ const fec = mc.fecManager;
33460
+ if (range.groups !== null || fec.withReceiptTime === void 0) work();
33461
+ else fec.withReceiptTime(range.reportedAt, work);
32325
33462
  };
32326
33463
  const releaseHold = (entry) => {
32327
33464
  if (entry.range) return;
@@ -32333,7 +33470,7 @@ function wireRepairFetch(mc, opts) {
32333
33470
  if (!run) return;
32334
33471
  entry.running = null;
32335
33472
  run.stopped = reason;
32336
- run.controller.abort();
33473
+ run.controller.abort(reason);
32337
33474
  if (reason === "preempted") releaseHold(entry);
32338
33475
  mc.noteRepairStopped?.(reason, entry.sbn, entry.packetId, entry.catalogTrackName);
32339
33476
  };
@@ -32388,21 +33525,42 @@ function wireRepairFetch(mc, opts) {
32388
33525
  const admit = (entry, now) => {
32389
33526
  const budgetMs = entry.deadlineAt - now;
32390
33527
  const rttMs = readRtt();
32391
- const reason = !entry.range && !groupCanComplete(entry.sbn, entry.packetId, entry.catalogTrackName) ? "group-cannot-complete" : rttMs === null ? "rtt-unmeasured" : rttMs < budgetMs ? null : "rtt-exceeds-budget";
33528
+ const reason = refusal(entry, now, rttMs);
32392
33529
  if (reason === null) return rttMs;
32393
33530
  skip(entry, reason, rttMs, budgetMs);
32394
33531
  return null;
32395
33532
  };
33533
+ 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";
32396
33534
  const retire = (entry) => {
32397
33535
  if (entries.get(entry.key) === entry) entries.delete(entry.key);
32398
33536
  if (entry.expiry !== void 0) clearTimeout(entry.expiry);
32399
33537
  };
32400
- const outstandingBelow = (priority) => {
33538
+ const holdsBack = (entry, priority, videoWalks = true) => {
33539
+ if (entry.priority >= priority) return false;
33540
+ const { walk } = entry;
33541
+ if (walk === void 0) return true;
33542
+ if (entry.priority !== 0 || !videoWalks) return false;
33543
+ return entry.running === null || walk.group !== null && !walk.group.controller.signal.aborted;
33544
+ };
33545
+ const outstandingBelow = (priority, videoWalks = true) => {
32401
33546
  for (const entry of entries.values()) {
32402
- if (entry.priority < priority) return true;
33547
+ if (holdsBack(entry, priority, videoWalks)) return true;
32403
33548
  }
32404
33549
  return false;
32405
33550
  };
33551
+ const yieldVideoWalks = (queued) => {
33552
+ const now = performance.now();
33553
+ const rttMs = readRtt();
33554
+ const due = queued.some((entry) => entry.priority !== 0 && entry.walk === void 0 && !outstandingBelow(entry.priority, false) && refusal(entry, now, rttMs) === null);
33555
+ if (!due) return;
33556
+ for (const entry of entries.values()) {
33557
+ const walk = entry.walk;
33558
+ if (entry.priority !== 0 || walk === void 0 || walk.group === null) continue;
33559
+ if (walk.group.controller.signal.aborted) continue;
33560
+ walk.yielded = true;
33561
+ walk.group.controller.abort();
33562
+ }
33563
+ };
32406
33564
  const preemptBestEffort = () => {
32407
33565
  for (const entry of entries.values()) {
32408
33566
  if (entry.priority === 0 || !entry.running) continue;
@@ -32431,7 +33589,8 @@ function wireRepairFetch(mc, opts) {
32431
33589
  }
32432
33590
  const rttMs = admit(entry, now);
32433
33591
  if (rttMs === null) return;
32434
- if (entry.priority === 0) preemptBestEffort();
33592
+ if (entry.priority === 0 && entry.walk === void 0) preemptBestEffort();
33593
+ if (entry.range === void 0) leaveWalkedGroup(entry);
32435
33594
  if (counted) entry.attempts++;
32436
33595
  mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName, {
32437
33596
  rttMs,
@@ -32453,6 +33612,14 @@ function wireRepairFetch(mc, opts) {
32453
33612
  }
32454
33613
  void execute(entry, run);
32455
33614
  };
33615
+ const leaveWalkedGroup = (block) => {
33616
+ for (const entry of entries.values()) {
33617
+ const group = entry.walk?.group;
33618
+ if (group?.sbn === block.sbn && entry.packetId === block.packetId && entry.catalogTrackName === block.catalogTrackName) {
33619
+ group.controller.abort();
33620
+ }
33621
+ }
33622
+ };
32456
33623
  const dispatch = () => {
32457
33624
  if (disposed) return;
32458
33625
  const now = performance.now();
@@ -32477,6 +33644,7 @@ function wireRepairFetch(mc, opts) {
32477
33644
  for (const entry of queued) {
32478
33645
  if (entry.priority === 0) start(entry);
32479
33646
  }
33647
+ yieldVideoWalks(queued);
32480
33648
  if (outstandingBelow(1)) return;
32481
33649
  for (const entry of queued) {
32482
33650
  if (entry.priority === 1) start(entry);
@@ -32503,6 +33671,16 @@ function wireRepairFetch(mc, opts) {
32503
33671
  }
32504
33672
  return counts.sources + counts.repairGroupLength >= counts.authoredLength;
32505
33673
  };
33674
+ const groupServed = (sbn, packetId, catalogTrackName) => {
33675
+ if (mc.fecManager.blockSymbolCounts === void 0) return false;
33676
+ const counts = symbolCounts(sbn, packetId, catalogTrackName);
33677
+ if (counts === void 0 || counts.authoredLength === void 0) return true;
33678
+ return counts.sources + counts.repairs >= counts.authoredLength || !groupCanComplete(sbn, packetId, catalogTrackName);
33679
+ };
33680
+ const statedEnd = (sbn, packetId, catalogTrackName) => {
33681
+ const length = symbolCounts(sbn, packetId, catalogTrackName)?.authoredLength;
33682
+ return length === void 0 ? void 0 : serial32Add(sbn, length);
33683
+ };
32506
33684
  const finish = (entry, run, fed, error) => {
32507
33685
  if (run.stopped !== null || entry.running !== run || entries.get(entry.key) !== entry) {
32508
33686
  return;
@@ -32547,27 +33725,81 @@ function wireRepairFetch(mc, opts) {
32547
33725
  signal: run.controller.signal,
32548
33726
  subscriberPriority: entry.subscriberPriority
32549
33727
  };
33728
+ const { range } = entry;
33729
+ const feed = (packet) => {
33730
+ if (entry.catalogTrackName === void 0) {
33731
+ mc.processRepairFromMoQ(packet, entry.packetId);
33732
+ } else {
33733
+ mc.processRepairFromMoQ(packet, entry.packetId, entry.catalogTrackName);
33734
+ }
33735
+ };
32550
33736
  try {
32551
- const packets = entry.range ? opts.rangeTransport({
33737
+ const packets = range === void 0 ? opts.transport({ ...common, sbn: entry.sbn }) : entry.walk !== void 0 ? walkHole(entry, entry.walk, range, common) : opts.rangeTransport({
32552
33738
  ...common,
32553
- startGroup: entry.range.startGroup,
32554
- endGroup: entry.range.endGroup,
32555
- lostSsId: entry.range.lostSsId
32556
- }) : opts.transport({ ...common, sbn: entry.sbn });
33739
+ startGroup: range.groups.startGroup,
33740
+ endGroup: range.groups.endGroup,
33741
+ lostSsId: range.lostSsId
33742
+ });
32557
33743
  for await (const packet of packets) {
32558
33744
  if (run.stopped !== null || entry.running !== run) break;
32559
33745
  fed++;
32560
- if (entry.catalogTrackName === void 0) {
32561
- mc.processRepairFromMoQ(packet, entry.packetId);
32562
- } else {
32563
- mc.processRepairFromMoQ(packet, entry.packetId, entry.catalogTrackName);
32564
- }
33746
+ if (range === void 0) feed(packet);
33747
+ else atReport(range, () => feed(packet));
32565
33748
  }
32566
33749
  finish(entry, run, fed, void 0);
32567
33750
  } catch (error) {
32568
33751
  finish(entry, run, fed, error ?? new Error("repair transport rejected"));
32569
33752
  }
32570
33753
  };
33754
+ async function* walkHole(entry, walk, hole, common) {
33755
+ const lostAt = serial32Distance(entry.sbn, hole.lostSsId);
33756
+ for (let first = true; !common.signal.aborted; first = false) {
33757
+ if (!first && entry.priority !== 0 && outstandingBelow(1)) {
33758
+ stop(entry, "preempted");
33759
+ note("repair-preempted", entry);
33760
+ return;
33761
+ }
33762
+ if (!first && entry.priority === 0) {
33763
+ dispatch();
33764
+ if (common.signal.aborted) return;
33765
+ }
33766
+ const sbn = walk.next;
33767
+ let next;
33768
+ if (entries.get(requestKey(sbn, entry.packetId, entry.catalogTrackName))?.running == null) {
33769
+ const rsIds = /* @__PURE__ */ new Set();
33770
+ const group = new AbortController();
33771
+ const cancel = () => group.abort(common.signal.reason);
33772
+ common.signal.addEventListener("abort", cancel, { once: true });
33773
+ walk.group = { sbn, controller: group };
33774
+ try {
33775
+ for await (const packet of opts.transport({ ...common, sbn, signal: group.signal })) {
33776
+ yield packet;
33777
+ const id = extractRepairFecPayloadId(packet);
33778
+ if (id === null || id.ssStart !== sbn || id.ssbLength === 0) continue;
33779
+ next ??= serial32Add(sbn, id.ssbLength);
33780
+ rsIds.add(id.rsId);
33781
+ if (rsIds.size >= id.rsbLength || groupServed(sbn, entry.packetId, entry.catalogTrackName)) {
33782
+ group.abort();
33783
+ break;
33784
+ }
33785
+ }
33786
+ } catch (error) {
33787
+ if (!group.signal.aborted || common.signal.aborted) throw error;
33788
+ } finally {
33789
+ common.signal.removeEventListener("abort", cancel);
33790
+ walk.group = null;
33791
+ }
33792
+ if (walk.yielded) {
33793
+ walk.yielded = false;
33794
+ continue;
33795
+ }
33796
+ }
33797
+ next ??= statedEnd(sbn, entry.packetId, entry.catalogTrackName);
33798
+ if (next === void 0) return;
33799
+ if (serial32Distance(entry.sbn, next) > lostAt) return;
33800
+ walk.next = next;
33801
+ }
33802
+ }
32571
33803
  const removeResetObserver = mc.addTrackResetObserver((packetId, catalogTrackName) => {
32572
33804
  for (const entry of [...entries.values()]) {
32573
33805
  if (entry.packetId !== packetId || entry.catalogTrackName !== catalogTrackName) continue;
@@ -32763,7 +33995,37 @@ function wireRepairFetch(mc, opts) {
32763
33995
  throw error;
32764
33996
  }
32765
33997
  };
32766
- if (opts.rangeTransport !== void 0) {
33998
+ const trackKind = (packetId) => {
33999
+ try {
34000
+ return mc.fecManager.trackKindFor?.(packetId);
34001
+ } catch {
34002
+ return void 0;
34003
+ }
34004
+ };
34005
+ const walkDeadlineAt = (packetId, now, deadlineAt) => {
34006
+ let repairDeadlineMs;
34007
+ try {
34008
+ repairDeadlineMs = mc.fecManager.repairDeadlineMsForPacket?.(packetId);
34009
+ } catch {
34010
+ repairDeadlineMs = void 0;
34011
+ }
34012
+ if (repairDeadlineMs === void 0 || !Number.isFinite(repairDeadlineMs)) return deadlineAt;
34013
+ return Math.min(deadlineAt, now + repairDeadlineMs - WALK_LEAD_MS);
34014
+ };
34015
+ const onHoleExpired = (hole) => {
34016
+ if (disposed) return false;
34017
+ 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);
34018
+ if (entry === void 0) return false;
34019
+ queueMicrotask(() => {
34020
+ if (entries.get(entry.key) !== entry) return;
34021
+ retire(entry);
34022
+ stop(entry, "expired");
34023
+ clearEntry(entry);
34024
+ dispatch();
34025
+ });
34026
+ return true;
34027
+ };
34028
+ if (mc.onUndelimitedLoss !== void 0 && mc.closeIsoHoles !== void 0) {
32767
34029
  mc.onUndelimitedLoss((loss) => {
32768
34030
  const { packetId, catalogTrackName, holeStart, holeLength } = loss;
32769
34031
  const close = () => mc.closeIsoHoles(packetId, catalogTrackName, holeStart, holeLength);
@@ -32771,9 +34033,11 @@ function wireRepairFetch(mc, opts) {
32771
34033
  const blockProfile = blockProfileOf(packetId);
32772
34034
  const target = opts.resolveTarget(packetId, catalogTrackName);
32773
34035
  if (!target) return close();
32774
- const priority = repairPriorityForClass("unknown");
32775
- const range = rangeFor(loss, target.repairTrack);
32776
- if (range === null) {
34036
+ const walked = opts.rangeTransport === void 0;
34037
+ const holeClass = walked && trackKind(packetId) === "audio" ? "audio" : "unknown";
34038
+ const priority = repairPriorityForClass(holeClass);
34039
+ const groups = walked ? null : rangeFor(loss, target.repairTrack);
34040
+ if (!walked && groups === null) {
32777
34041
  close();
32778
34042
  mc.noteRepairSkipped("range-no-anchor", { rttMs: readRtt(), budgetMs: 0, priority }, holeStart, packetId, catalogTrackName);
32779
34043
  return;
@@ -32784,8 +34048,10 @@ function wireRepairFetch(mc, opts) {
32784
34048
  packetId,
32785
34049
  ...catalogTrackName === void 0 ? {} : { catalogTrackName }
32786
34050
  };
32787
- const wire = wirePriority(identity, "unknown");
32788
- const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, performance.now(), "unknown");
34051
+ const wire = wirePriority(identity, holeClass);
34052
+ if (wire === null) return close();
34053
+ const now = performance.now();
34054
+ const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, now, holeClass);
32789
34055
  if (deadline === null) {
32790
34056
  close();
32791
34057
  mc.noteRepairSkipped(
@@ -32797,6 +34063,7 @@ function wireRepairFetch(mc, opts) {
32797
34063
  );
32798
34064
  return;
32799
34065
  }
34066
+ const deadlineAt = walked ? walkDeadlineAt(packetId, now, deadline.deadlineAt) : deadline.deadlineAt;
32800
34067
  const entry = {
32801
34068
  key: JSON.stringify(["range", packetId, catalogTrackName ?? null, holeStart]),
32802
34069
  ...identity,
@@ -32804,15 +34071,16 @@ function wireRepairFetch(mc, opts) {
32804
34071
  blockProfile,
32805
34072
  priority,
32806
34073
  subscriberPriority: wire.subscriberPriority,
32807
- deadlineAt: deadline.deadlineAt,
32808
- playoutDeadlineAt: deadline.deadlineAt - deadline.extensionMs,
34074
+ deadlineAt,
34075
+ playoutDeadlineAt: deadlineAt - deadline.extensionMs,
32809
34076
  anchorAt: deadline.anchorAt,
32810
34077
  delayMs: deadline.delayMs,
32811
34078
  bound: deadline.bound,
32812
34079
  order: enqueueOrder++,
32813
34080
  attempts: 0,
32814
34081
  running: null,
32815
- range: { ...range, lostSsId: loss.lostSsId, holeLength }
34082
+ range: { lostSsId: loss.lostSsId, holeLength, groups, reportedAt: now },
34083
+ ...walked ? { walk: { next: holeStart, group: null, yielded: false } } : {}
32816
34084
  };
32817
34085
  const previous = entries.get(entry.key);
32818
34086
  if (previous) {
@@ -32822,7 +34090,7 @@ function wireRepairFetch(mc, opts) {
32822
34090
  entries.set(entry.key, entry);
32823
34091
  entry.expiry = setTimeout(dispatch, Math.max(0, entry.deadlineAt - performance.now()) + 1);
32824
34092
  dispatch();
32825
- });
34093
+ }, onHoleExpired);
32826
34094
  }
32827
34095
  const removeRapObserver = mc.addRapCompleteObserver?.((packetId) => {
32828
34096
  queueMicrotask(() => {