@blockcast/mmt-container 2.2.0-main.4fb5899c44e6 → 2.2.0-main.60d918495132

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 (65) hide show
  1. package/dist/browser-runtime.js +1256 -172
  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/delta-fallback-config.js.map +1 -1
  9. package/dist/fec-manager.d.ts +67 -11
  10. package/dist/fec-manager.d.ts.map +1 -1
  11. package/dist/fec-manager.js +377 -54
  12. package/dist/fec-manager.js.map +2 -2
  13. package/dist/fec-worker-setup.js.map +1 -1
  14. package/dist/index.d.ts +2 -2
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js.map +2 -2
  17. package/dist/iso-block-locator.d.ts +48 -13
  18. package/dist/iso-block-locator.d.ts.map +1 -1
  19. package/dist/iso-block-locator.js +97 -25
  20. package/dist/iso-block-locator.js.map +2 -2
  21. package/dist/iso-bmff-timing.d.ts +10 -1
  22. package/dist/iso-bmff-timing.d.ts.map +1 -1
  23. package/dist/iso-bmff-timing.js +36 -2
  24. package/dist/iso-bmff-timing.js.map +2 -2
  25. package/dist/media-router.js.map +1 -1
  26. package/dist/mmtp-container-parser.d.ts +77 -10
  27. package/dist/mmtp-container-parser.d.ts.map +1 -1
  28. package/dist/mmtp-container-parser.js +295 -27
  29. package/dist/mmtp-container-parser.js.map +2 -2
  30. package/dist/mmtp-container-parser.no-modules.js +297 -30
  31. package/dist/mmtp-container-parser.no-modules.js.map +3 -3
  32. package/dist/mmtp-decode-pipeline.js +294 -27
  33. package/dist/mmtp-decode-pipeline.js.map +2 -2
  34. package/dist/mmtp-router.d.ts +34 -8
  35. package/dist/mmtp-router.d.ts.map +1 -1
  36. package/dist/mmtp-router.js +617 -74
  37. package/dist/mmtp-router.js.map +3 -3
  38. package/dist/multicast-manager.d.ts +26 -3
  39. package/dist/multicast-manager.d.ts.map +1 -1
  40. package/dist/multicast-manager.js +1076 -145
  41. package/dist/multicast-manager.js.map +3 -3
  42. package/dist/multicast-transport.js +2 -2
  43. package/dist/multicast-transport.js.map +2 -2
  44. package/dist/no-modules.js +294 -27
  45. package/dist/no-modules.js.map +3 -3
  46. package/dist/repair-fetch.d.ts +38 -8
  47. package/dist/repair-fetch.d.ts.map +1 -1
  48. package/dist/repair-fetch.js +286 -27
  49. package/dist/repair-fetch.js.map +3 -3
  50. package/dist/track-session.d.ts.map +1 -1
  51. package/dist/track-session.js +1 -0
  52. package/dist/track-session.js.map +2 -2
  53. package/dist/wasm-mmtp-container-parser.js +294 -27
  54. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  55. package/package.json +5 -5
  56. package/src/codec-utils.ts +121 -1
  57. package/src/fec-manager.ts +407 -28
  58. package/src/index.ts +3 -0
  59. package/src/iso-block-locator.ts +133 -31
  60. package/src/iso-bmff-timing.ts +40 -1
  61. package/src/mmtp-container-parser.ts +294 -29
  62. package/src/mmtp-router.ts +544 -55
  63. package/src/multicast-manager.ts +118 -14
  64. package/src/repair-fetch.ts +366 -50
  65. 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";
@@ -12435,6 +12537,7 @@ var TrackSession = class {
12435
12537
  this.#state = "idle";
12436
12538
  this.#subscription = null;
12437
12539
  this.#disarmFec();
12540
+ this.#unsuppress();
12438
12541
  }
12439
12542
  // -----------------------------------------------------------------------
12440
12543
  // Internal
@@ -12928,6 +13031,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
12928
13031
  this.#heldEvicted = 0;
12929
13032
  /** Pending holes (see `deferIncompleteGaps`): unstated, sources still held. */
12930
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 = [];
12931
13043
  /**
12932
13044
  * Keep a gap that is missing a source as a pending hole rather than a span,
12933
13045
  * so a repair FETCHed for it (draft-ramadan-moq-fec §7.5) can still state
@@ -12949,7 +13061,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
12949
13061
  #retentionBlocks;
12950
13062
  #heldEvicted;
12951
13063
  #newest;
13064
+ #newestSource;
12952
13065
  #holes;
13066
+ #expired;
13067
+ #newlyExpired;
13068
+ #closedBehind;
12953
13069
  static #checkedRetention(retentionBlocks) {
12954
13070
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
12955
13071
  throw new Error(
@@ -12986,6 +13102,21 @@ var IsoBlockLocator = class _IsoBlockLocator {
12986
13102
  observe(position) {
12987
13103
  if (this.#newest === void 0 || serial32Precedes(this.#newest, position)) this.#newest = position;
12988
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
+ }
12989
13120
  /** Held sources evicted by `heldCapacity` (never by the horizon itself). */
12990
13121
  get heldEvicted() {
12991
13122
  return this.#heldEvicted;
@@ -13004,17 +13135,29 @@ var IsoBlockLocator = class _IsoBlockLocator {
13004
13135
  }
13005
13136
  /** The known block or span containing `ssId`, with its ESI. */
13006
13137
  locate(ssId) {
13007
- for (let i = this.#blocks.length - 1; i >= 0; i--) {
13008
- const block = this.#blocks[i];
13009
- if (isoBlockContains(block.start, block.length, ssId)) {
13010
- 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
+ }
13011
13144
  }
13012
13145
  }
13013
13146
  return null;
13014
13147
  }
13015
- /** Number of pending holes. */
13148
+ /** Number of holes not closed yet, pending or past the horizon. */
13016
13149
  get holeCount() {
13017
- 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);
13018
13161
  }
13019
13162
  /** The stated block (never a span) ending exactly at `end`. */
13020
13163
  blockEndingAt(end) {
@@ -13070,9 +13213,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
13070
13213
  /**
13071
13214
  * Apply one repair symbol's `(SS_Start, SSB_length)`. The first repair of a
13072
13215
  * block states its range and places every held source in it; later repair
13073
- * symbols of the same block change nothing. A range that contradicts a
13074
- * known block (a different length, or an overlap with another block or a
13075
- * 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.
13076
13221
  * A newly stated block retires behind its SS_Start (see the class note).
13077
13222
  * A block so far past `newest` that stating it would retire the position
13078
13223
  * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
@@ -13091,7 +13236,16 @@ var IsoBlockLocator = class _IsoBlockLocator {
13091
13236
  const known = this.blockAt(start);
13092
13237
  if (known !== void 0) {
13093
13238
  if (known.span) {
13094
- 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}` };
13095
13249
  }
13096
13250
  if (known.length !== length) {
13097
13251
  return {
@@ -13159,18 +13313,28 @@ var IsoBlockLocator = class _IsoBlockLocator {
13159
13313
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
13160
13314
  }
13161
13315
  /**
13162
- * Turn every pending hole inside `[start, start + length)` into a
13163
- * repair-less span, claiming its held sources: its range FETCH ended, so
13164
- * 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.
13165
13322
  */
13166
13323
  closeHolesWithin(start, length) {
13167
13324
  const closed = [];
13168
- for (const hole of [...this.#holes]) {
13169
- if (!isoBlockContains(start, length, hole.start)) continue;
13170
- this.#holes.splice(this.#holes.indexOf(hole), 1);
13171
- const spanBlock = { start: hole.start, length: hole.length, span: true };
13172
- closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
13173
- 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
+ }
13174
13338
  }
13175
13339
  return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
13176
13340
  }
@@ -13184,15 +13348,17 @@ var IsoBlockLocator = class _IsoBlockLocator {
13184
13348
  return void 0;
13185
13349
  }
13186
13350
  /**
13187
- * Retire every block and span whose last SS_ID, and every held source,
13188
- * lies more than `retentionBlocks` blocks behind `position`, with the shared
13189
- * lower-bound metric (`isoBlocksBehindLowerBound`) every ISO interleave
13190
- * 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.
13191
13356
  */
13192
13357
  retireBehind(position) {
13193
13358
  this.observe(position);
13194
13359
  const horizon = this.#retentionBlocks;
13195
13360
  const retired = [];
13361
+ this.#closedBehind.length = 0;
13196
13362
  for (let i = this.#blocks.length - 1; i >= 0; i--) {
13197
13363
  const block = this.#blocks[i];
13198
13364
  const last = serial32Add(block.start, block.length - 1);
@@ -13204,10 +13370,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
13204
13370
  for (let i = this.#holes.length - 1; i >= 0; i--) {
13205
13371
  const hole = this.#holes[i];
13206
13372
  const last = serial32Add(hole.start, hole.length - 1);
13207
- 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);
13208
13377
  }
13209
13378
  for (const ssId of [...this.#held.keys()]) {
13210
- 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
+ }
13211
13382
  }
13212
13383
  return retired;
13213
13384
  }
@@ -13215,9 +13386,13 @@ var IsoBlockLocator = class _IsoBlockLocator {
13215
13386
  reset() {
13216
13387
  this.#blocks.length = 0;
13217
13388
  this.#holes.length = 0;
13389
+ this.#expired.length = 0;
13390
+ this.#newlyExpired.length = 0;
13391
+ this.#closedBehind.length = 0;
13218
13392
  this.#held.clear();
13219
13393
  this.#coverageEnd = void 0;
13220
13394
  this.#newest = void 0;
13395
+ this.#newestSource = void 0;
13221
13396
  }
13222
13397
  #claim(block) {
13223
13398
  const placed = [];
@@ -13837,6 +14012,7 @@ var WORKER_ERROR_LOG_CAP = 5;
13837
14012
  var WORKER_ERROR_KIND_CAP = 32;
13838
14013
  var WORKER_ERROR_OVERFLOW_KIND = "other";
13839
14014
  var STARTUP_REPAIR_WAIT_SOURCE_BOUNDARIES = 2;
14015
+ var NOT_TAKEN = Object.freeze({ taken: false, recovered: null });
13840
14016
  function isMulticastSymbolDelivery(value) {
13841
14017
  return value === "datagram" || value === "ordered-relay";
13842
14018
  }
@@ -13930,10 +14106,18 @@ var FECManager = class _FECManager {
13930
14106
  // 'pending' forever, which would park every later frame of its stream in
13931
14107
  // the in-order release gate. Each entry owns its handle; the callback
13932
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
+ */
13933
14113
  this.#pendingWorkerCleanupBounds = /* @__PURE__ */ new Map();
13934
14114
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
13935
14115
  this.#blockSourceCounts = /* @__PURE__ */ new Map();
13936
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();
13937
14121
  // Authored SSB_length per block (ISO/IEC 23008-1 §C.5.3), learned from the
13938
14122
  // first repair symbol. The FFmpeg moq_mmt publisher closes a block every D
13939
14123
  // media units, usually before it holds K symbols; under iso-ssbg1-v1
@@ -13942,6 +14126,9 @@ var FECManager = class _FECManager {
13942
14126
  // SSB_length source arrivals and recoverable from SSB_length received
13943
14127
  // symbols; waiting for K fails every one of them.
13944
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();
13945
14132
  this.#ssbLengthConflictCount = 0;
13946
14133
  this.#blockRepairRsIds = /* @__PURE__ */ new Map();
13947
14134
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
@@ -14139,7 +14326,10 @@ var FECManager = class _FECManager {
14139
14326
  // arrives via onBlockRecovered callback.
14140
14327
  this.onBlockStarted = null;
14141
14328
  this.onBlockComplete = null;
14142
- /** A block reached its fail bound. `blockClass` is its class at failure. */
14329
+ /**
14330
+ * A block reached its fail bound. `blockClass` is its class at failure.
14331
+ * `span` is set when what failed is a repair-less span starting at `sbn`.
14332
+ */
14143
14333
  this.onBlockFailed = null;
14144
14334
  /**
14145
14335
  * Fired once per stream when its Worker decoder stops being routable.
@@ -14181,6 +14371,8 @@ var FECManager = class _FECManager {
14181
14371
  * for it, which it must be.
14182
14372
  */
14183
14373
  this.#onUndelimitedLoss = null;
14374
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
14375
+ this.#onIsoHoleExpired = null;
14184
14376
  /** A block every symbol of which vanished was created by SBN evidence. */
14185
14377
  this.onBlockVanished = null;
14186
14378
  /** A block reached a terminal state (completed, recovered, or failed). */
@@ -14223,7 +14415,9 @@ var FECManager = class _FECManager {
14223
14415
  #pendingWorkerCleanupBounds;
14224
14416
  #blockSourceCounts;
14225
14417
  #blockSourceEsis;
14418
+ #blockRebuiltEsis;
14226
14419
  #blockAuthoredLengths;
14420
+ #isoSpanKeys;
14227
14421
  #ssbLengthConflictCount;
14228
14422
  #blockRepairRsIds;
14229
14423
  #blockRsbLengths;
@@ -14290,6 +14484,7 @@ var FECManager = class _FECManager {
14290
14484
  #decoderUnavailableEvents;
14291
14485
  #repairSymbolSizeMismatchCount;
14292
14486
  #onUndelimitedLoss;
14487
+ #onIsoHoleExpired;
14293
14488
  #encodeTrackName(catalogTrackName) {
14294
14489
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
14295
14490
  if (encoded === void 0) {
@@ -14761,7 +14956,10 @@ var FECManager = class _FECManager {
14761
14956
  timer.handle = null;
14762
14957
  this.#requestRepair(sbn, packetId, catalogTrackName);
14763
14958
  };
14764
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
14959
+ timer.handle = setTimeout(
14960
+ onFire,
14961
+ this.#receiptAtMs === void 0 ? Math.max(0, deadlineMs - performance.now()) : this.#receiptTimerDelayMs(deadlineMs, 0)
14962
+ );
14765
14963
  this.#repairDeadlines.set(key, timer);
14766
14964
  }
14767
14965
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -14905,8 +15103,14 @@ var FECManager = class _FECManager {
14905
15103
  * Vanished blocks are not enumerated here: their starts are unknown until a
14906
15104
  * repair states them. The SS_IDs between two stated blocks become one
14907
15105
  * repair-less span when the later block's repair arrives (placeIsoRepair).
15106
+ *
15107
+ * A `held` source arrived before its block was known and is fed only now
15108
+ * that a repair, a span or a closed hole placed it: how far its block start
15109
+ * then lies behind the frontier measures how long the receiver held it, not
15110
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
15111
+ * it (BLO-52085).
14908
15112
  */
14909
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
15113
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn, held = false) {
14910
15114
  const streamKey = this.#streamKey(packetId, catalogTrackName);
14911
15115
  const now = performance.now();
14912
15116
  const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
@@ -14945,7 +15149,7 @@ var FECManager = class _FECManager {
14945
15149
  return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
14946
15150
  };
14947
15151
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
14948
- 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))) {
15152
+ 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))) {
14949
15153
  discontinuity();
14950
15154
  return;
14951
15155
  }
@@ -15207,17 +15411,21 @@ var FECManager = class _FECManager {
15207
15411
  this.#blockWaitDeadlinesMs.delete(key);
15208
15412
  this.#repairHoldUntilMs.delete(key);
15209
15413
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
15210
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName);
15414
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs);
15211
15415
  };
15212
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)));
15416
+ timer.handle = setTimeout(
15417
+ onFire,
15418
+ this.#receiptAtMs === void 0 ? Math.max(1, Math.ceil(deadlineMs - nowMs)) : this.#receiptTimerDelayMs(deadlineMs, 1)
15419
+ );
15213
15420
  this.#activeBlocks.set(key, timer);
15214
15421
  this.#indexBlockKey(key, sbn, packetId);
15215
15422
  }
15216
15423
  /**
15217
15424
  * Hand a block whose delivery is over to its decoder for finalization: the
15218
- * datagram deadline fired, or the ordered relay moved past it.
15425
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
15426
+ * is when it was due: its deadline, or now.
15219
15427
  */
15220
- #finalizeExpiredBlock(sbn, packetId, catalogTrackName) {
15428
+ #finalizeExpiredBlock(sbn, packetId, catalogTrackName, dueAtMs = performance.now()) {
15221
15429
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
15222
15430
  if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
15223
15431
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -15233,7 +15441,7 @@ var FECManager = class _FECManager {
15233
15441
  if (workerClient) {
15234
15442
  this.#pendingWorkerCleanups.add(key);
15235
15443
  this.#pendingWorkerCleanupClients.set(key, workerClient);
15236
- this.#boundOwedCleanup(key, packetId, workerClient);
15444
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs);
15237
15445
  workerClient.cleanup(sbn);
15238
15446
  } else {
15239
15447
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
@@ -15545,7 +15753,9 @@ var FECManager = class _FECManager {
15545
15753
  }
15546
15754
  resetMap(this.#blockSourceCounts);
15547
15755
  resetMap(this.#blockSourceEsis);
15756
+ resetMap(this.#blockRebuiltEsis);
15548
15757
  resetMap(this.#blockAuthoredLengths);
15758
+ resetSet(this.#isoSpanKeys);
15549
15759
  resetMap(this.#blockRepairRsIds);
15550
15760
  resetMap(this.#blockRsbLengths);
15551
15761
  resetMap(this.#heldLayerStates);
@@ -15669,7 +15879,9 @@ var FECManager = class _FECManager {
15669
15879
  dropMap(this.#pendingWorkerCleanupClients);
15670
15880
  dropMap(this.#blockSourceCounts);
15671
15881
  dropMap(this.#blockSourceEsis);
15882
+ dropMap(this.#blockRebuiltEsis);
15672
15883
  dropMap(this.#blockAuthoredLengths);
15884
+ dropSet(this.#isoSpanKeys);
15673
15885
  dropMap(this.#blockRepairRsIds);
15674
15886
  dropMap(this.#blockRsbLengths);
15675
15887
  dropMap(this.#blockPathCounts);
@@ -15831,6 +16043,9 @@ var FECManager = class _FECManager {
15831
16043
  this.#unindexBlockKey(key);
15832
16044
  }
15833
16045
  }
16046
+ if (isSourceSymbol && source === "multicast") {
16047
+ this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), sbn + esi >>> 0, packetId, catalogTrackName);
16048
+ }
15834
16049
  return true;
15835
16050
  }
15836
16051
  #observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName) {
@@ -16009,8 +16224,9 @@ var FECManager = class _FECManager {
16009
16224
  return true;
16010
16225
  }
16011
16226
  /**
16012
- * Drop a block's repair hold: its FETCH ended without delivering. The block
16013
- * falls back to its multicast wait, which may already have passed.
16227
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
16228
+ * back only a repair that cannot complete it. The block falls back to its
16229
+ * multicast wait, which may already have passed.
16014
16230
  */
16015
16231
  releaseRepairHold(sbn, packetId, catalogTrackName) {
16016
16232
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -16148,6 +16364,8 @@ var FECManager = class _FECManager {
16148
16364
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
16149
16365
  const evictedBefore = locator.heldEvicted;
16150
16366
  const held = locator.hold(ssId, source);
16367
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
16368
+ if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
16151
16369
  const evicted = locator.heldEvicted - evictedBefore;
16152
16370
  if (evicted > 0) {
16153
16371
  const before = this.#isoHeldEvictedCount;
@@ -16168,17 +16386,20 @@ var FECManager = class _FECManager {
16168
16386
  * contradicts a known block is refused (counted) and must be dropped.
16169
16387
  */
16170
16388
  placeIsoRepair(packetId, catalogTrackName, ssStart, ssbLength) {
16171
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength);
16389
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
16390
+ const placement = locator.placeRepair(ssStart, ssbLength);
16391
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
16172
16392
  if (placement.status !== "placed") {
16173
16393
  this.#isoRepairRefusedCount++;
16174
16394
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
16175
16395
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`);
16176
16396
  }
16397
+ if (placement.ofSpan !== void 0) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName);
16177
16398
  return placement;
16178
16399
  }
16400
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName));
16179
16401
  if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
16180
16402
  if (placement.hole !== void 0) {
16181
- const locator = this.#isoLocatorFor(packetId, catalogTrackName);
16182
16403
  const hole = placement.hole.block;
16183
16404
  const previous = locator.blockEndingAt(hole.start);
16184
16405
  const loss = {
@@ -16199,17 +16420,29 @@ var FECManager = class _FECManager {
16199
16420
  * `handler`, instead of a repair-less span; null restores spans. Set by the
16200
16421
  * range repair scheduler; applies to every stream from its next gap. The
16201
16422
  * handler and the deferral are one setting, so no hole is ever created with
16202
- * nobody to close it.
16423
+ * nobody to close it. `onExpired` is told of each pending hole the stream
16424
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
16425
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
16426
+ * reported; otherwise the hole is discarded with its sources.
16203
16427
  */
16204
- setUndelimitedLossHandler(handler) {
16428
+ setUndelimitedLossHandler(handler, onExpired = null) {
16205
16429
  this.#onUndelimitedLoss = handler;
16430
+ this.#onIsoHoleExpired = handler === null ? null : onExpired;
16206
16431
  this.#deferIsoGaps = handler !== null;
16207
16432
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
16208
16433
  }
16434
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
16435
+ #settleExpiredIsoHoles(locator, packetId, catalogTrackName) {
16436
+ for (const hole of locator.takeExpiredHoles()) {
16437
+ const expired = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length };
16438
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length);
16439
+ }
16440
+ }
16209
16441
  /**
16210
- * The range repair for a hole ended: every hole still pending inside
16211
- * `[start, start + length)` becomes a repair-less span. Returns those spans
16212
- * with the held sources they placed, for the caller to feed (MmtpRouter).
16442
+ * The range repair for a hole ended: every hole inside `[start, start +
16443
+ * length)`, pending or expired, becomes a repair-less span. Returns those
16444
+ * spans with the held sources they placed, for the caller to feed
16445
+ * (MmtpRouter).
16213
16446
  */
16214
16447
  closeIsoHoles(packetId, catalogTrackName, start, length) {
16215
16448
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
@@ -16228,7 +16461,10 @@ var FECManager = class _FECManager {
16228
16461
  */
16229
16462
  #openIsoSpan(span, packetId, catalogTrackName) {
16230
16463
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
16231
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
16464
+ if (!this.#blockAuthoredLengths.has(key)) {
16465
+ this.#blockAuthoredLengths.set(key, span.block.length);
16466
+ this.#isoSpanKeys.add(key);
16467
+ }
16232
16468
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
16233
16469
  }
16234
16470
  /**
@@ -16569,11 +16805,14 @@ var FECManager = class _FECManager {
16569
16805
  });
16570
16806
  client.onCleanupComplete((sbn) => {
16571
16807
  if (this.#releasedWorkerClients.has(client)) return;
16572
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
16808
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
16809
+ const cleanupKeys = owed.filter((key) => {
16573
16810
  const block = this.#parseBlockKey(key);
16574
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
16811
+ return block.packetId === packetId && block.sbn === sbn;
16575
16812
  });
16576
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
16813
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
16814
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
16815
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
16577
16816
  });
16578
16817
  client.onError((msg, code) => {
16579
16818
  const requestedKind = code ?? msg;
@@ -16643,9 +16882,11 @@ var FECManager = class _FECManager {
16643
16882
  * fail deadline already passed, so failing it is the decision that deadline
16644
16883
  * made. A late ack then finds nothing owed and is a no-op.
16645
16884
  */
16646
- #boundOwedCleanup(key, packetId, client) {
16885
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
16647
16886
  this.#clearOwedCleanupBound(key);
16648
16887
  const bound = {
16888
+ dueAtMs,
16889
+ askedAtMs: performance.now(),
16649
16890
  handle: setTimeout(() => {
16650
16891
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
16651
16892
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -16743,7 +16984,15 @@ var FECManager = class _FECManager {
16743
16984
  this.#isoSourceOversizeCount++;
16744
16985
  return null;
16745
16986
  }
16746
- const sbn = located.block.start;
16987
+ return this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, located.block.start);
16988
+ }
16989
+ /**
16990
+ * Hand one placed source symbol to the stream's decoder: its Worker, which
16991
+ * answers through onFrame (null here), or its synchronous decoder, whose
16992
+ * recovered block is returned. `sbn` is the SS_Start of the block a repair
16993
+ * stated for `ssId`.
16994
+ */
16995
+ #feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn) {
16747
16996
  const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
16748
16997
  const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey);
16749
16998
  const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
@@ -16772,6 +17021,74 @@ var FECManager = class _FECManager {
16772
17021
  }
16773
17022
  return recovered;
16774
17023
  }
17024
+ /**
17025
+ * Feed a source symbol of this stream that another FEC instance over the
17026
+ * same packets rebuilt: a keyframe overlay recovery whose base SS_ID the
17027
+ * caller determined (draft-ramadan-moq-mmt-02 7.1, 7.4.4; joint decoding,
17028
+ * BLO-52085). It joins its block's decoder as a received source would, so
17029
+ * it reduces the erasures the block still has to solve, but it is not a
17030
+ * network arrival: no transport accounting, no classification evidence,
17031
+ * no deadline refresh, and it never makes a block clean.
17032
+ *
17033
+ * Only a block a repair stated takes one (a repair-less span has no
17034
+ * decoder block). A block that is terminal, or already holds that source,
17035
+ * does not. The symbol is the exact protected packet, unpadded, as
17036
+ * feedSourceSymbol takes it.
17037
+ *
17038
+ * `recovered` is the block the synchronous decoder completed with it; the
17039
+ * caller routes it and completes the block, as for any recovery. When
17040
+ * every source of the block is then present, received or rebuilt, and no
17041
+ * decoder returned it (a Worker answers asynchronously, and reports such a
17042
+ * block as clean on its own side), the block is completed here as
17043
+ * recovered, with nothing left to route.
17044
+ */
17045
+ feedRebuiltSourceSymbol(packetId, ssId, symbolData, catalogTrackName) {
17046
+ if (!this.#hasBlockProfile(packetId)) return NOT_TAKEN;
17047
+ const located = this.#isoLocatorFor(packetId, catalogTrackName).locate(ssId);
17048
+ if (located === null || located.block.span) return NOT_TAKEN;
17049
+ if (!ssbg1FitsSymbol(symbolData.byteLength, this.#trackConfig(packetId).symbolSize)) return NOT_TAKEN;
17050
+ const sbn = located.block.start;
17051
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
17052
+ if (this.#completedBlocks.has(key) || this.#blockSourceEsis.get(key)?.has(located.esi)) return NOT_TAKEN;
17053
+ let rebuilt = this.#blockRebuiltEsis.get(key);
17054
+ if (rebuilt?.has(located.esi)) return NOT_TAKEN;
17055
+ if (rebuilt === void 0) {
17056
+ rebuilt = /* @__PURE__ */ new Set();
17057
+ this.#blockRebuiltEsis.set(key, rebuilt);
17058
+ }
17059
+ const config = this.#trackConfigs.get(packetId);
17060
+ const wasShort = config !== void 0 && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) !== void 0;
17061
+ rebuilt.add(located.esi);
17062
+ const recovered = this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn);
17063
+ if (recovered === null && !this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName)) {
17064
+ if (wasShort && this.#activeBlocks.has(key) && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) === void 0) {
17065
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, this.#multicastWaitMs(config));
17066
+ }
17067
+ }
17068
+ return { taken: true, recovered };
17069
+ }
17070
+ /**
17071
+ * A block that holds every one of its `length` sources, received or
17072
+ * rebuilt by another instance, with at least one rebuilt, is recovered:
17073
+ * every packet of it was delivered, by its own arrival or by the instance
17074
+ * that rebuilt it, so nothing is routed. Returns whether it completed it.
17075
+ */
17076
+ #completeWhenSourcesPresent(key, sbn, length, packetId, catalogTrackName) {
17077
+ const rebuilt = this.#blockRebuiltEsis.get(key);
17078
+ if (rebuilt === void 0 || this.#completedBlocks.has(key)) return false;
17079
+ let present = rebuilt.size;
17080
+ for (const esi of this.#blockSourceEsis.get(key) ?? []) if (!rebuilt.has(esi)) present++;
17081
+ if (present < length) return false;
17082
+ this.#traceLifecycle("recovered", sbn, packetId, catalogTrackName);
17083
+ this.countRecovery(packetId, sbn, catalogTrackName);
17084
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
17085
+ if (catalogTrackName === void 0) {
17086
+ this.onBlockComplete?.(sbn, packetId);
17087
+ } else {
17088
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName);
17089
+ }
17090
+ return true;
17091
+ }
16775
17092
  /**
16776
17093
  * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
16777
17094
  * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
@@ -16974,8 +17291,75 @@ var FECManager = class _FECManager {
16974
17291
  this.#completeCleanBlock(blockKey, sbn, packetId, catalogTrackName);
16975
17292
  return null;
16976
17293
  }
17294
+ if (recovered === null) this.#shortenUnrecoverableWait(blockKey, sbn, packetId, catalogTrackName);
16977
17295
  return recovered;
16978
17296
  }
17297
+ /**
17298
+ * A first-arrival multicast source, held or placed. A datagram flow keeps
17299
+ * its sources in send order, so one that moves the stream's newest source
17300
+ * position past a block leaves the sources that block still misses
17301
+ * reordered behind it at best: it shortens the wait of every block it
17302
+ * passed that only a late source can complete. MoQ is left out: its streams
17303
+ * can overtake one another, so a MoQ source shows nothing about the sources
17304
+ * sent before it.
17305
+ */
17306
+ #noteMulticastSource(locator, ssId, packetId, catalogTrackName) {
17307
+ const previous = locator.newestSource;
17308
+ if (!locator.noteSource(ssId) || previous === void 0) return;
17309
+ for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
17310
+ if (block.span || !serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
17311
+ this.#shortenUnrecoverableWait(
17312
+ this.#blockKey(block.start, packetId, catalogTrackName),
17313
+ block.start,
17314
+ packetId,
17315
+ catalogTrackName
17316
+ );
17317
+ }
17318
+ }
17319
+ /**
17320
+ * The wait of a block that only a late source can complete (BLO-52085): a
17321
+ * repair stated it, its received sources plus every symbol its repair group
17322
+ * carries (RSB_length) are short of K' (the repair scheduler's
17323
+ * group-cannot-complete), and a later source of the stream has arrived, so
17324
+ * a source it misses is lost or reordered behind that one. The span, which
17325
+ * covers repair symbols paced after its sources, buys it nothing: it waits
17326
+ * the late-symbol allowance alone, the multicast wait less the span (the
17327
+ * catalog tolerance or the measured delivery gap). Undefined for any other
17328
+ * block.
17329
+ */
17330
+ #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
17331
+ const authoredLength = this.#blockAuthoredLengths.get(key);
17332
+ const rsbLength = this.#blockRsbLengths.get(key);
17333
+ if (authoredLength === void 0 || rsbLength === void 0) return void 0;
17334
+ let present = this.#blockSourceCounts.get(key) ?? 0;
17335
+ const received = this.#blockSourceEsis.get(key);
17336
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
17337
+ if (present + rsbLength >= authoredLength) return void 0;
17338
+ const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
17339
+ if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
17340
+ return void 0;
17341
+ }
17342
+ return this.#multicastWaitMs(config) - config.interleaveDepthMs;
17343
+ }
17344
+ /**
17345
+ * Bring an open block's wait in to its late-source wait, when it has one.
17346
+ * Never later than it is armed: only a source can complete such a block,
17347
+ * so a repair of its group (paced across the span) must not keep it open.
17348
+ */
17349
+ #shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName) {
17350
+ if (!this.#activeBlocks.has(key)) return;
17351
+ const config = this.#trackConfigs.get(packetId);
17352
+ if (config === void 0) return;
17353
+ const waitMs = this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config);
17354
+ if (waitMs === void 0) return;
17355
+ const armedAtMs = this.#blockWaitDeadlinesMs.get(key);
17356
+ this.#armBlockTimeout(
17357
+ sbn,
17358
+ packetId,
17359
+ catalogTrackName,
17360
+ armedAtMs === void 0 ? waitMs : Math.min(waitMs, armedAtMs - this.#receiptNow())
17361
+ );
17362
+ }
16979
17363
  /**
16980
17364
  * Record a block's authored SSB_length from a repair symbol. Returns false,
16981
17365
  * leaving the block unchanged, when the symbol contradicts the block: a
@@ -17073,12 +17457,13 @@ var FECManager = class _FECManager {
17073
17457
  * the inactivity deadline on each symbol, records the symbol's in-band
17074
17458
  * classification evidence, and marks the block clean when all of its
17075
17459
  * authored source symbols arrived: the SSB_length a repair symbol declared,
17076
- * otherwise K.
17460
+ * otherwise K. `held` marks a source held unplaced since it arrived and
17461
+ * placed only now (see #noteSbnSeen).
17077
17462
  *
17078
17463
  * Throws for a packetId that was never configured, so a classified block
17079
17464
  * never reads the manager-global K or timeout.
17080
17465
  */
17081
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
17466
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
17082
17467
  const trackConfig = this.#trackConfigs.get(packetId);
17083
17468
  if (trackConfig === void 0) {
17084
17469
  throw new Error(
@@ -17094,7 +17479,8 @@ var FECManager = class _FECManager {
17094
17479
  catalogTrackName,
17095
17480
  "source",
17096
17481
  evidence.packetSequenceNumber,
17097
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
17482
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
17483
+ held
17098
17484
  );
17099
17485
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
17100
17486
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -17130,6 +17516,15 @@ var FECManager = class _FECManager {
17130
17516
  this.#completeCleanBlock(key, sbn, packetId, catalogTrackName);
17131
17517
  return;
17132
17518
  }
17519
+ if (this.#blockRebuiltEsis.has(key) && this.#completeWhenSourcesPresent(
17520
+ key,
17521
+ sbn,
17522
+ this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? authoredLength,
17523
+ packetId,
17524
+ catalogTrackName
17525
+ )) {
17526
+ return;
17527
+ }
17133
17528
  this.noteBlockActivity(sbn, packetId, catalogTrackName, true);
17134
17529
  }
17135
17530
  #completeCleanBlock(key, sbn, packetId, catalogTrackName) {
@@ -17138,7 +17533,9 @@ var FECManager = class _FECManager {
17138
17533
  this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
17139
17534
  this.#blockSourceCounts.delete(key);
17140
17535
  this.#blockSourceEsis.delete(key);
17536
+ this.#blockRebuiltEsis.delete(key);
17141
17537
  this.#blockAuthoredLengths.delete(key);
17538
+ this.#isoSpanKeys.delete(key);
17142
17539
  this.#blockRepairRsIds.delete(key);
17143
17540
  this.#blockRsbLengths.delete(key);
17144
17541
  this.#markTerminal(key, sbn, packetId, true);
@@ -17169,6 +17566,19 @@ var FECManager = class _FECManager {
17169
17566
  #receiptNow() {
17170
17567
  return this.#receiptAtMs ?? performance.now();
17171
17568
  }
17569
+ /**
17570
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
17571
+ * scope: counted from the receipt time, as the timer of a symbol fed when
17572
+ * it was received was, less the whole ms since. So it fires on the tick
17573
+ * that timer would have, never later than a delay counted from now, and
17574
+ * its handler still re-arms a timer that fires before its deadline.
17575
+ * Counted from now, a deadline set from the receipt time is rounded up
17576
+ * from another fraction of a ms (BLO-52085).
17577
+ */
17578
+ #receiptTimerDelayMs(deadlineMs, minMs) {
17579
+ const receivedAtMs = this.#receiptAtMs;
17580
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
17581
+ }
17172
17582
  /**
17173
17583
  * A held packet admitted late arms from its (earlier) receipt time; that
17174
17584
  * never pulls in a deadline later activity already armed. Outside a
@@ -17204,10 +17614,20 @@ var FECManager = class _FECManager {
17204
17614
  this.#repairDeadlineMs(trackConfig)
17205
17615
  );
17206
17616
  }
17207
- this.#armBlockTimeout(sbn, packetId, catalogTrackName, timeoutMs);
17617
+ if (!sourceProgress && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) !== void 0) {
17618
+ this.#shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName);
17619
+ return;
17620
+ }
17621
+ this.#armBlockTimeout(
17622
+ sbn,
17623
+ packetId,
17624
+ catalogTrackName,
17625
+ this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) ?? timeoutMs
17626
+ );
17208
17627
  }
17209
17628
  #failBlock(sbn, packetId, catalogTrackName) {
17210
17629
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
17630
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
17211
17631
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
17212
17632
  this.#clearRepairDeadline(key);
17213
17633
  this.#clearBlockTimer(key);
@@ -17217,6 +17637,7 @@ var FECManager = class _FECManager {
17217
17637
  }
17218
17638
  this.#blockSourceCounts.delete(key);
17219
17639
  this.#blockSourceEsis.delete(key);
17640
+ this.#blockRebuiltEsis.delete(key);
17220
17641
  this.#blockAuthoredLengths.delete(key);
17221
17642
  this.#blockRepairRsIds.delete(key);
17222
17643
  this.#blockRsbLengths.delete(key);
@@ -17226,7 +17647,8 @@ var FECManager = class _FECManager {
17226
17647
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
17227
17648
  this.#fecStats.blocksFailed++;
17228
17649
  this.#statsForPacket(packetId).blocksFailed++;
17229
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
17650
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
17651
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
17230
17652
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
17231
17653
  }
17232
17654
  /**
@@ -17255,7 +17677,9 @@ var FECManager = class _FECManager {
17255
17677
  this.#retireBlockClass(key, block.sbn, block.packetId, block.catalogTrackName);
17256
17678
  this.#blockSourceCounts.delete(key);
17257
17679
  this.#blockSourceEsis.delete(key);
17680
+ this.#blockRebuiltEsis.delete(key);
17258
17681
  this.#blockAuthoredLengths.delete(key);
17682
+ this.#isoSpanKeys.delete(key);
17259
17683
  this.#blockRepairRsIds.delete(key);
17260
17684
  this.#blockRsbLengths.delete(key);
17261
17685
  this.#clearBlockTimer(key);
@@ -17346,7 +17770,9 @@ var FECManager = class _FECManager {
17346
17770
  this.#blockKeysBySbn.clear();
17347
17771
  this.#blockSourceCounts.clear();
17348
17772
  this.#blockSourceEsis.clear();
17773
+ this.#blockRebuiltEsis.clear();
17349
17774
  this.#blockAuthoredLengths.clear();
17775
+ this.#isoSpanKeys.clear();
17350
17776
  this.#blockRepairRsIds.clear();
17351
17777
  this.#blockRsbLengths.clear();
17352
17778
  this.#heldLayerStates.clear();
@@ -17902,9 +18328,21 @@ var IsoBmffTimingResolver = class {
17902
18328
  }
17903
18329
  #track = null;
17904
18330
  #fragments = /* @__PURE__ */ new Map();
18331
+ /** First sample of each pending fragment, kept in `#delivered` with its sample count. */
18332
+ #firstSamples = /* @__PURE__ */ new Map();
18333
+ /**
18334
+ * First sample and sample count of the newest fragments whose every slot was
18335
+ * cleared. Abandonment counts: `releaseSample` clears a slot too, which
18336
+ * matches the combiner, since it retires an abandoned sample as well.
18337
+ */
18338
+ #delivered = /* @__PURE__ */ new Map();
17905
18339
  #pendingSamples = 0;
17906
18340
  #evictedSamples = 0;
17907
18341
  #lastMovieFragmentRejection = null;
18342
+ /** True once an FT=0 has bound the track that FT=1 timing is read against. */
18343
+ get initialized() {
18344
+ return this.#track !== null;
18345
+ }
17908
18346
  get pendingSampleCount() {
17909
18347
  return this.#pendingSamples;
17910
18348
  }
@@ -17928,7 +18366,14 @@ var IsoBmffTimingResolver = class {
17928
18366
  this.#track = timing;
17929
18367
  return true;
17930
18368
  }
17931
- addMovieFragment(mpuSequenceNumber2, data, additionalSampleLimit = this.maxPendingSamples) {
18369
+ /**
18370
+ * `recovered` marks an FEC-recovered copy. A recovered block hands back
18371
+ * every FT=1 it holds, the received ones included, so a recovered copy of a
18372
+ * fragment whose samples are all done is a duplicate: admitting it again
18373
+ * would charge stale timing and could displace the live MPU's. A source
18374
+ * copy is still admitted again (a rendition switch re-arms timing that way).
18375
+ */
18376
+ addMovieFragment(mpuSequenceNumber2, data, additionalSampleLimit = this.maxPendingSamples, recovered = false) {
17932
18377
  this.#lastMovieFragmentRejection = null;
17933
18378
  if (!Number.isInteger(additionalSampleLimit) || additionalSampleLimit < 0) {
17934
18379
  this.#lastMovieFragmentRejection = "invalid";
@@ -17954,6 +18399,8 @@ var IsoBmffTimingResolver = class {
17954
18399
  (sample, index) => sample !== null && sameSample(sample, parsed.samples[index])
17955
18400
  );
17956
18401
  }
18402
+ const delivered = recovered ? this.#delivered.get(key) : void 0;
18403
+ if (delivered && delivered.sampleCount === parsed.samples.length && sameSample(delivered.first, parsed.samples[0])) return true;
17957
18404
  let freed = 0;
17958
18405
  while (this.#fragments.size > 0 && (this.#pendingSamples + parsed.samples.length > this.maxPendingSamples || parsed.samples.length - freed > additionalSampleLimit)) {
17959
18406
  freed += this.#evictOldestFragment();
@@ -17967,6 +18414,7 @@ var IsoBmffTimingResolver = class {
17967
18414
  return false;
17968
18415
  }
17969
18416
  this.#fragments.set(key, [...parsed.samples]);
18417
+ this.#firstSamples.set(key, parsed.samples[0]);
17970
18418
  this.#pendingSamples += parsed.samples.length;
17971
18419
  return true;
17972
18420
  }
@@ -18024,6 +18472,7 @@ var IsoBmffTimingResolver = class {
18024
18472
  let live = 0;
18025
18473
  for (const sample of samples) if (sample !== null) live++;
18026
18474
  this.#fragments.delete(oldest);
18475
+ this.#firstSamples.delete(oldest);
18027
18476
  this.#pendingSamples -= live;
18028
18477
  this.#evictedSamples += live;
18029
18478
  return live;
@@ -18039,12 +18488,23 @@ var IsoBmffTimingResolver = class {
18039
18488
  if (!samples || !samples[index]) return false;
18040
18489
  samples[index] = null;
18041
18490
  this.#pendingSamples--;
18042
- if (samples.every((value) => value === null)) this.#fragments.delete(key);
18491
+ if (samples.every((value) => value === null)) {
18492
+ this.#fragments.delete(key);
18493
+ const first = this.#firstSamples.get(key);
18494
+ this.#firstSamples.delete(key);
18495
+ this.#delivered.delete(key);
18496
+ this.#delivered.set(key, { first, sampleCount: samples.length });
18497
+ if (this.#delivered.size > this.maxPendingSamples) {
18498
+ this.#delivered.delete(this.#delivered.keys().next().value);
18499
+ }
18500
+ }
18043
18501
  return true;
18044
18502
  }
18045
18503
  reset() {
18046
18504
  this.#track = null;
18047
18505
  this.#fragments.clear();
18506
+ this.#firstSamples.clear();
18507
+ this.#delivered.clear();
18048
18508
  this.#pendingSamples = 0;
18049
18509
  }
18050
18510
  };
@@ -18214,6 +18674,9 @@ function authoredGap(before, after) {
18214
18674
  function ssIdAfter(a, b) {
18215
18675
  return (a - b | 0) > 0;
18216
18676
  }
18677
+ function holdsRebuilt(stream) {
18678
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
18679
+ }
18217
18680
  var FecReleaseSequencer = class {
18218
18681
  #streams = /* @__PURE__ */ new Map();
18219
18682
  #gate;
@@ -18276,6 +18739,7 @@ var FecReleaseSequencer = class {
18276
18739
  stream.lastSbn = void 0;
18277
18740
  stream.discontinuity = false;
18278
18741
  stream.rapSsId = void 0;
18742
+ stream.sourced = false;
18279
18743
  }
18280
18744
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
18281
18745
  this.#recordStat("droppedStale");
@@ -18302,6 +18766,7 @@ var FecReleaseSequencer = class {
18302
18766
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
18303
18767
  else hi = mid;
18304
18768
  }
18769
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
18305
18770
  stream.buf.splice(lo, 0, frame);
18306
18771
  this.#drainUnlessDeferred(stream);
18307
18772
  }
@@ -18337,6 +18802,41 @@ var FecReleaseSequencer = class {
18337
18802
  }
18338
18803
  return false;
18339
18804
  }
18805
+ /**
18806
+ * These streams' sink is being replaced by one that has seen no source
18807
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
18808
+ * release to the sink being replaced the frames the unanchored path had
18809
+ * already released to it (#cursorPassed): there they waited in its queue,
18810
+ * which its replacement flushes. A stream that holds none is not drained:
18811
+ * it holds nothing the anchor kept back, and a drain would still force out
18812
+ * a frame held past the hold limit, which before the anchor waited for the
18813
+ * next push. Then treat the streams as unsourced until a source frame is
18814
+ * released.
18815
+ */
18816
+ unsource(packetId, catalogTrackName) {
18817
+ for (const stream of this.#streams.values()) {
18818
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
18819
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
18820
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
18821
+ else this.#drain(stream, true);
18822
+ }
18823
+ stream.sourced = false;
18824
+ }
18825
+ }
18826
+ }
18827
+ /**
18828
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
18829
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
18830
+ * packetId.
18831
+ */
18832
+ holdsRebuilt(packetId, catalogTrackName) {
18833
+ for (const stream of this.#streams.values()) {
18834
+ if (stream.packetId !== packetId) continue;
18835
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
18836
+ if (holdsRebuilt(stream)) return true;
18837
+ }
18838
+ return false;
18839
+ }
18340
18840
  /** Re-evaluate held gaps after FEC state changed. */
18341
18841
  poke(streamKey) {
18342
18842
  if (streamKey !== void 0) {
@@ -18428,16 +18928,32 @@ var FecReleaseSequencer = class {
18428
18928
  last: null,
18429
18929
  lastSbn: void 0,
18430
18930
  discontinuity: false,
18431
- rapSsId: void 0
18931
+ rapSsId: void 0,
18932
+ sourced: false,
18933
+ draining: 0
18432
18934
  };
18433
18935
  this.#streams.set(streamKey, stream);
18434
18936
  }
18435
18937
  return stream;
18436
18938
  }
18437
- #drain(stream) {
18939
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
18940
+ #drain(stream, asUnanchored = false) {
18941
+ stream.draining++;
18942
+ try {
18943
+ this.#drainLoop(stream, asUnanchored);
18944
+ } finally {
18945
+ stream.draining--;
18946
+ }
18947
+ }
18948
+ #drainLoop(stream, asUnanchored) {
18438
18949
  while (stream.buf.length > 0 && stream.last !== null) {
18439
18950
  const head = stream.buf[0];
18440
18951
  const last = stream.last;
18952
+ if (compareFrameOrder(head, last) <= 0) {
18953
+ stream.buf.shift();
18954
+ this.#release(stream, head, void 0);
18955
+ continue;
18956
+ }
18441
18957
  if (stream.discontinuity) {
18442
18958
  stream.discontinuity = false;
18443
18959
  stream.buf.shift();
@@ -18451,9 +18967,10 @@ var FecReleaseSequencer = class {
18451
18967
  }
18452
18968
  const headSbn = head.meta.fecSbn;
18453
18969
  const from = stream.lastSbn ?? headSbn;
18454
- const to = headSbn ?? stream.lastSbn;
18970
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
18455
18971
  let lost = [];
18456
18972
  const unanchored = from === void 0 && to === void 0;
18973
+ let unresolved = false;
18457
18974
  if (from !== void 0 && to !== void 0) {
18458
18975
  const resolved = this.#gate.resolvedLoss(
18459
18976
  stream.packetId,
@@ -18462,7 +18979,8 @@ var FecReleaseSequencer = class {
18462
18979
  Math.max(from, to),
18463
18980
  from
18464
18981
  );
18465
- if (resolved === null) {
18982
+ unresolved = resolved === null;
18983
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored)) {
18466
18984
  const heldMs = performance.now() - head.arrivedAtMs;
18467
18985
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
18468
18986
  this.#recordStat("forcedWindowFlushes");
@@ -18470,22 +18988,56 @@ var FecReleaseSequencer = class {
18470
18988
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
18471
18989
  continue;
18472
18990
  }
18473
- lost = resolved;
18991
+ lost = resolved ?? [];
18474
18992
  }
18475
18993
  stream.buf.shift();
18476
18994
  this.#release(
18477
18995
  stream,
18478
18996
  head,
18479
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
18997
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
18480
18998
  );
18481
18999
  }
18482
19000
  }
19001
+ /**
19002
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
19003
+ * source cursor holds it unanchored, and neither does a later frame behind
19004
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
19005
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
19006
+ * like each frame that arrived in front of it since (stale there). The head
19007
+ * then goes, decided as it would be unanchored, once a frame the base path
19008
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
19009
+ * marked one: the base path has passed that one, so a frame still missing
19010
+ * before it can only come from a repair. It also goes while no source frame
19011
+ * has been released, when the direct path shows a recovered frame at once.
19012
+ * And it goes at once while a staged switch decides on when frames arrive
19013
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
19014
+ * sink being replaced: unanchored, it had already reached the sink.
19015
+ * The scan also writes: the `passed` marks it sets stay on the frames,
19016
+ * and push marks a frame it inserts in front of a marked one from them.
19017
+ */
19018
+ #cursorPassed(stream, asUnanchored) {
19019
+ let at2 = -1;
19020
+ for (let i = 0; i < stream.buf.length; i++) {
19021
+ const frame = stream.buf[i];
19022
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
19023
+ frame.passed = true;
19024
+ if (at2 < 0) at2 = i;
19025
+ } else if (frame.passed !== true) break;
19026
+ }
19027
+ if (at2 < 0) return false;
19028
+ 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));
19029
+ }
18483
19030
  #release(stream, frame, decision) {
19031
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
19032
+ if (stale) this.#recordStat("droppedStale");
18484
19033
  if (decision) frame.meta.gapBefore = decision;
18485
19034
  stream.last = frame;
18486
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
19035
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
19036
+ stream.lastSbn = frame.meta.fecSbn;
19037
+ }
19038
+ if (frame.meta.recovered !== true) stream.sourced = true;
18487
19039
  this.#gate.onReleased?.(frame.data, frame.meta);
18488
- this.#emit(frame.data, frame.meta);
19040
+ if (!stale) this.#emit(frame.data, frame.meta);
18489
19041
  }
18490
19042
  };
18491
19043
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -18526,6 +19078,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
18526
19078
  this.#reclaimedTimingSamples = 0;
18527
19079
  this.#evictedTimingSamples = 0;
18528
19080
  this.#rejectedMovieFragments = 0;
19081
+ this.#recoveredHeadsAwaitingTiming = {
19082
+ held: 0,
19083
+ expired: 0,
19084
+ discarded: 0,
19085
+ superseded: 0
19086
+ };
18529
19087
  this.#sequencers = /* @__PURE__ */ new Map();
18530
19088
  this.#fecGate = null;
18531
19089
  this.#fecSequencer = null;
@@ -18634,6 +19192,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
18634
19192
  #reclaimedTimingSamples;
18635
19193
  #evictedTimingSamples;
18636
19194
  #rejectedMovieFragments;
19195
+ #recoveredHeadsAwaitingTiming;
18637
19196
  #sequencers;
18638
19197
  #fecGate;
18639
19198
  #fecSequencer;
@@ -18739,11 +19298,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
18739
19298
  /**
18740
19299
  * Typed view of the ISO-BMFF timing-sample budget.
18741
19300
  *
18742
- * This is the acceptance signal for the budget ratchet: `pending` walking
18743
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
18744
- * and it is observable here rather than only as media silently stopping.
18745
- * Per repo policy this is a producer-owned counter -- never infer budget
18746
- * state by parsing logs.
19301
+ * Each stream admits timing against its own window of `capacity` slots
19302
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
19303
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
19304
+ * timing a stream declared and never delivered shows up there. `pending`
19305
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
19306
+ * a producer-owned counter -- never infer budget state by parsing logs.
18747
19307
  */
18748
19308
  get timingBudgetStats() {
18749
19309
  return {
@@ -18754,6 +19314,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
18754
19314
  rejectedMovieFragments: this.#rejectedMovieFragments
18755
19315
  };
18756
19316
  }
19317
+ /** Recovered heads parked for FT=1 timing (BLO-53369). Survives dispose(). */
19318
+ get recoveredHeadsAwaitingTiming() {
19319
+ let pending = 0;
19320
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
19321
+ for (const head of awaitingTiming) if (head.options?.recovered) pending++;
19322
+ }
19323
+ return { ...this.#recoveredHeadsAwaitingTiming, pending };
19324
+ }
18757
19325
  get reorderStats() {
18758
19326
  let bufferedFrames = this.#fecSequencer?.buffered ?? 0;
18759
19327
  for (const { sequencer } of this.#sequencers.values()) bufferedFrames += sequencer.buffered;
@@ -18795,6 +19363,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
18795
19363
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
18796
19364
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
18797
19365
  }
19366
+ /** See FecReleaseSequencer.unsource. */
19367
+ unsourceFecRelease(packetId, catalogTrackName) {
19368
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
19369
+ }
19370
+ /** See FecReleaseSequencer.holdsRebuilt. */
19371
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
19372
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
19373
+ }
18798
19374
  /** Re-evaluate held gaps after FEC block state changed. */
18799
19375
  pokeFecRelease(packetId, catalogTrackName) {
18800
19376
  if (!this.#fecSequencer) return;
@@ -18927,7 +19503,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
18927
19503
  const now = Date.now();
18928
19504
  for (const { awaitingTiming } of this.#timingStreams.values()) {
18929
19505
  while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
18930
- awaitingTiming.shift();
19506
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
18931
19507
  }
18932
19508
  }
18933
19509
  }
@@ -19045,11 +19621,16 @@ var MmtpContainerParser = class _MmtpContainerParser {
19045
19621
  if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
19046
19622
  return this.#drop("fragment-unexpected-fragmentation");
19047
19623
  const resolver2 = this.#timingResolver(streamKey, info.packetId, false);
19048
- if (!resolver2) return this.#drop("fragment-no-resolver");
19624
+ if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
19049
19625
  const pendingBefore = resolver2.pendingSampleCount;
19050
19626
  const evictedBefore = resolver2.evictedSampleCount;
19051
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
19052
- const admitted = resolver2.addMovieFragment(mpu.mpuSequenceNumber, data, remaining);
19627
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
19628
+ const admitted = resolver2.addMovieFragment(
19629
+ mpu.mpuSequenceNumber,
19630
+ data,
19631
+ remaining,
19632
+ options?.recovered === true
19633
+ );
19053
19634
  this.#pendingTimingSamples += resolver2.pendingSampleCount - pendingBefore;
19054
19635
  this.#evictedTimingSamples += resolver2.evictedSampleCount - evictedBefore;
19055
19636
  if (!admitted) {
@@ -19069,7 +19650,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19069
19650
  };
19070
19651
  }
19071
19652
  if (fragmentType !== 2) return this.#drop("unknown-fragment-type");
19072
- const resolver = this.#timingResolver(streamKey, info.packetId, false);
19653
+ const resolver = this.#timingResolver(streamKey, info.packetId, true);
19073
19654
  if (!resolver) return this.#drop("mfu-no-resolver");
19074
19655
  if (!Number.isSafeInteger(data.byteLength) || data.byteLength <= 0)
19075
19656
  return this.#drop("mfu-empty-payload");
@@ -19090,6 +19671,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19090
19671
  mpuSequenceNumber: mpu.mpuSequenceNumber,
19091
19672
  movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
19092
19673
  sampleNumber: mfuDuHeader.sampleNumber,
19674
+ sequenceNumber: info.sequenceNumber,
19093
19675
  arrivedAt: Date.now()
19094
19676
  });
19095
19677
  return this.#drop("mfu-sample-timing-missing");
@@ -19115,7 +19697,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
19115
19697
  info,
19116
19698
  resolver,
19117
19699
  options?.recovered === true,
19118
- options?.fecSbn
19700
+ options?.fecSbn,
19701
+ options?.fecSbnFirst
19119
19702
  );
19120
19703
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
19121
19704
  }
@@ -19208,7 +19791,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
19208
19791
  info,
19209
19792
  resolver,
19210
19793
  options?.recovered === true,
19211
- options?.fecSbn
19794
+ options?.fecSbn,
19795
+ options?.fecSbnFirst
19212
19796
  );
19213
19797
  if (outcome.record !== void 0) return outcome.record;
19214
19798
  return this.#drop(outcome.reason);
@@ -19228,7 +19812,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19228
19812
  * attribution exists to keep readable. Leaving the choice at the call site
19229
19813
  * is what keeps both true.
19230
19814
  */
19231
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
19815
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
19232
19816
  const timing = resolver.sampleTiming(
19233
19817
  combined.mpuSequenceNumber,
19234
19818
  combined.movieFragmentSequenceNumber,
@@ -19245,6 +19829,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19245
19829
  );
19246
19830
  if (!meta) return { reason: "combined-meta-build-failed" };
19247
19831
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
19832
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
19248
19833
  if (!resolver.consumeSample(
19249
19834
  combined.mpuSequenceNumber,
19250
19835
  combined.movieFragmentSequenceNumber,
@@ -19478,6 +20063,9 @@ var MmtpContainerParser = class _MmtpContainerParser {
19478
20063
  for (const { sequencer } of this.#sequencers.values()) sequencer.discard();
19479
20064
  this.#sequencers.clear();
19480
20065
  this.#fecSequencer?.discard();
20066
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
20067
+ for (const head of awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
20068
+ }
19481
20069
  this.#timingStreams.clear();
19482
20070
  this.#pendingTimingSamples = 0;
19483
20071
  this.#reliableMoqStartupGate.clear();
@@ -19496,10 +20084,23 @@ var MmtpContainerParser = class _MmtpContainerParser {
19496
20084
  return resolver;
19497
20085
  }
19498
20086
  #awaitTiming(streamKey, head) {
19499
- const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
19500
- if (!awaitingTiming) return;
20087
+ const state = this.#timingStreams.get(streamKey);
20088
+ if (!state) return;
20089
+ if (!head.options?.recovered) {
20090
+ const kept = state.awaitingTiming.filter((queued) => !queued.options?.recovered || queued.sequenceNumber !== head.sequenceNumber);
20091
+ this.#recoveredHeadsAwaitingTiming.superseded += state.awaitingTiming.length - kept.length;
20092
+ state.awaitingTiming = kept;
20093
+ }
20094
+ const awaitingTiming = state.awaitingTiming;
19501
20095
  awaitingTiming.push(head);
19502
- if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
20096
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming.held++;
20097
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) {
20098
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
20099
+ }
20100
+ }
20101
+ /** Count a recovered head leaving the queue other than by replay or its source copy. */
20102
+ #leaveAwaitingTiming(head, outcome) {
20103
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming[outcome]++;
19503
20104
  }
19504
20105
  /**
19505
20106
  * Feed again the heads whose timing the FT=1 just admitted declares. That
@@ -19527,6 +20128,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19527
20128
  const state = this.#timingStreams.get(streamKey);
19528
20129
  if (!state) return;
19529
20130
  this.#timingStreams.delete(streamKey);
20131
+ for (const head of state.awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
19530
20132
  this.#pendingTimingSamples -= state.resolver.pendingSampleCount;
19531
20133
  if (this.#pendingTimingSamples < 0) {
19532
20134
  throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");
@@ -22733,7 +23335,18 @@ function keyframeOverlaySsId(header) {
22733
23335
  if (ext?.type !== KEYFRAME_OVERLAY_EXTENSION_TYPE || ext.data.length !== 4) return void 0;
22734
23336
  return new DataView(ext.data.buffer, ext.data.byteOffset, 4).getUint32(0);
22735
23337
  }
23338
+ function overlayBaseSsId(anchor, overlaySsId, restoredPsn, headerPsn) {
23339
+ if (anchor.baseSsId === void 0 || headerPsn !== restoredPsn) return void 0;
23340
+ return serial32Add(anchor.baseSsId, overlaySsId - anchor.overlaySsId | 0);
23341
+ }
23342
+ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
23343
+ if (offset === void 0 || offset !== unstampedOffset) return void 0;
23344
+ return headerPsn + offset >>> 0;
23345
+ }
23346
+ var OVERLAY_ROUTED_LIMIT = 1024;
23347
+ var OVERLAY_PENDING_LIMIT = 256;
22736
23348
  var OVERLAY_OFFSET_MPUS = 16;
23349
+ var OVERLAY_REBUILT_LIMIT = 256;
22737
23350
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
22738
23351
  function assertStreamIdentity(role, stream) {
22739
23352
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -22844,6 +23457,7 @@ var MmtpRouter = class {
22844
23457
  #provenance = /* @__PURE__ */ new Map();
22845
23458
  #onFlowProtected = null;
22846
23459
  #unadmittedListedDrops = 0;
23460
+ #admittedSourceDatagrams = 0;
22847
23461
  #unlistedRepairSetAside = 0;
22848
23462
  #assistBlocks = /* @__PURE__ */ new Map();
22849
23463
  #assistFailures = /* @__PURE__ */ new Map();
@@ -22900,6 +23514,26 @@ var MmtpRouter = class {
22900
23514
  * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
22901
23515
  */
22902
23516
  #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
23517
+ /**
23518
+ * Per stream, the SS_ID offset at which a base recovery last showed the
23519
+ * sender's own packet_sequence_number: a recovered packet's header psn
23520
+ * equal to its SS_ID minus that offset. While it equals the stream's
23521
+ * current offset, no hop re-stamps the stream, and a packet's protected psn
23522
+ * names its base SS_ID within unstampedBaseSsId's limits (joint decoding of
23523
+ * an MPU no member of which arrived).
23524
+ */
23525
+ #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
23526
+ /**
23527
+ * The same, shown by the overlay alone, before any base recovery did: a
23528
+ * packet it rebuilt whose base copy carries its protected psn
23529
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
23530
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
23531
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
23532
+ * make the base drop a late base copy of a keyframe the overlay never
23533
+ * finished, and lift a block's late-source cut, which nothing before
23534
+ * this offset did.
23535
+ */
23536
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
22903
23537
  /**
22904
23538
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
22905
23539
  * not parsed, typically because its overlap copy was parsed first
@@ -22969,7 +23603,9 @@ var MmtpRouter = class {
22969
23603
  recovered: 0,
22970
23604
  restarts: 0,
22971
23605
  unsequencedDropped: 0,
22972
- protectedDropped: 0
23606
+ protectedDropped: 0,
23607
+ baseFed: 0,
23608
+ baseUndetermined: 0
22973
23609
  };
22974
23610
  /** Callback fired when a delta-track FEC block completes or fails. */
22975
23611
  #onDeltaBlockCompleteCb = null;
@@ -23142,7 +23778,7 @@ var MmtpRouter = class {
23142
23778
  const cb = this.#getFrameCallback(packetId);
23143
23779
  if (isVideo && !assembler) {
23144
23780
  if (frameMeta.recovered) {
23145
- this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb);
23781
+ this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb, meta.fecSbn);
23146
23782
  } else {
23147
23783
  this.#routeDirectSourceVideo(packetId, data, frameMeta, cb);
23148
23784
  }
@@ -23175,13 +23811,18 @@ var MmtpRouter = class {
23175
23811
  this.#onDeltaBlockCompleteCb?.(packetId, false);
23176
23812
  }
23177
23813
  };
23178
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
23814
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
23179
23815
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
23180
23816
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
23181
23817
  this.#onDeltaBlockCompleteCb?.(packetId, true);
23182
23818
  }
23183
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23184
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23819
+ if (span === void 0) {
23820
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23821
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23822
+ } else {
23823
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
23824
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
23825
+ }
23185
23826
  };
23186
23827
  }
23187
23828
  }
@@ -23226,8 +23867,9 @@ var MmtpRouter = class {
23226
23867
  }
23227
23868
  /**
23228
23869
  * FEC-recovered source symbols whose reconstructed header named a
23229
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
23230
- * a hop re-stamped the sequence after the sender protected the packet.
23870
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
23871
+ * or, rebuilt by the overlay, than their base copy carries: a hop
23872
+ * re-stamped the sequence after the sender protected the packet.
23231
23873
  */
23232
23874
  get restampedRecoveredSequenceCount() {
23233
23875
  return this.#restampedRecoveredSeqs;
@@ -23406,6 +24048,7 @@ var MmtpRouter = class {
23406
24048
  enableMseAssembler(packetId, config, catalogTrackName) {
23407
24049
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
23408
24050
  const previous = this.#mseAssemblers.get(assemblerKey);
24051
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
23409
24052
  if (previous) {
23410
24053
  previous.flush();
23411
24054
  previous.dispose();
@@ -23532,6 +24175,10 @@ var MmtpRouter = class {
23532
24175
  get keyframeOverlayStats() {
23533
24176
  return { ...this.#overlayStats };
23534
24177
  }
24178
+ /** Recovered FT=2 heads held for their FT=1, and how each left the wait (BLO-53369). */
24179
+ get recoveredHeadsAwaitingTiming() {
24180
+ return this.#parser.recoveredHeadsAwaitingTiming;
24181
+ }
23535
24182
  #isOverlayRepair(repairPacketId, repairTrackName) {
23536
24183
  return this.#overlayLegs.has(repairPacketId) || repairTrackName !== void 0 && this.#overlayRepairNames.has(repairTrackName);
23537
24184
  }
@@ -23552,7 +24199,8 @@ var MmtpRouter = class {
23552
24199
  fec,
23553
24200
  k,
23554
24201
  offsets: /* @__PURE__ */ new Map(),
23555
- moqBlocks: /* @__PURE__ */ new Set()
24202
+ moqBlocks: /* @__PURE__ */ new Set(),
24203
+ rebuilt: /* @__PURE__ */ new Map()
23556
24204
  };
23557
24205
  this.#overlays.set(repairPacketId, inst);
23558
24206
  return () => {
@@ -23582,12 +24230,18 @@ var MmtpRouter = class {
23582
24230
  */
23583
24231
  resetKeyframeOverlays(sourcePacketId, catalogTrackName) {
23584
24232
  for (const inst of this.#overlaysForSource(sourcePacketId, catalogTrackName)) this.#resetOverlay(inst);
24233
+ for (const [name, stream] of this.#streams.get(sourcePacketId) ?? []) {
24234
+ if (catalogTrackName !== void 0 && name !== catalogTrackName) continue;
24235
+ stream.overlayToBase.routed.clear();
24236
+ stream.overlayToBase.pending.clear();
24237
+ }
23585
24238
  }
23586
24239
  #resetOverlay(inst) {
23587
24240
  inst.fec.resetTrack(inst.repairPacketId, inst.streamName);
23588
24241
  inst.last = void 0;
23589
24242
  inst.offsets.clear();
23590
24243
  inst.moqBlocks.clear();
24244
+ inst.rebuilt.clear();
23591
24245
  }
23592
24246
  #overlaysForSource(sourcePacketId, catalogTrackName) {
23593
24247
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -23638,18 +24292,33 @@ var MmtpRouter = class {
23638
24292
  * A source packet that carries a 0x8B01 overlay SS_ID is also a symbol of
23639
24293
  * every overlay installed for its source, at that SS_ID, with the bytes the
23640
24294
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
23641
- * included (7.1, 7.4.3).
23642
- */
23643
- #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source) {
24295
+ * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
24296
+ * FEC reads it.
24297
+ *
24298
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
24299
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
24300
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
24301
+ * the stream unstamped at the SS_ID offset it states, for the release gate
24302
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
24303
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
24304
+ */
24305
+ #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
23644
24306
  if (this.#overlays.size === 0) return;
23645
24307
  const ssId = keyframeOverlaySsId(header);
23646
24308
  if (ssId === void 0) return;
24309
+ let rebuiltPsn;
23647
24310
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
23648
24311
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
24312
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
24313
+ inst.rebuilt.delete(ssId);
23649
24314
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
23650
24315
  if (identity !== null) {
23651
24316
  inst.offsets.delete(identity.mpuSequenceNumber);
23652
- inst.offsets.set(identity.mpuSequenceNumber, ssId - sequenceNumber >>> 0);
24317
+ inst.offsets.set(identity.mpuSequenceNumber, {
24318
+ psnOffset: ssId - sequenceNumber >>> 0,
24319
+ overlaySsId: ssId,
24320
+ ...baseSsId === void 0 ? {} : { baseSsId }
24321
+ });
23653
24322
  if (inst.offsets.size > OVERLAY_OFFSET_MPUS) inst.offsets.delete(inst.offsets.keys().next().value);
23654
24323
  }
23655
24324
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -23671,6 +24340,14 @@ var MmtpRouter = class {
23671
24340
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
23672
24341
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
23673
24342
  }
24343
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
24344
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
24345
+ if (rebuiltPsn !== sequenceNumber) {
24346
+ this.#restampedRecoveredSeqs++;
24347
+ } else if (baseSsId !== void 0) {
24348
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24349
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
24350
+ }
23674
24351
  }
23675
24352
  #noteOverlayMoqBlock(inst, blockStart) {
23676
24353
  inst.moqBlocks.add(blockStart);
@@ -23704,11 +24381,16 @@ var MmtpRouter = class {
23704
24381
  }
23705
24382
  /**
23706
24383
  * Route an overlay-recovered block's packets as source media of the
23707
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
23708
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
23709
- * base re-stamp, no block advance. Each packet's wire sequence is restored
23710
- * from its keyframe's own offset; without one, a stream the base never
23711
- * re-stamped keeps the header's sequence and any other drops the packet.
24384
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
24385
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
24386
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
24387
+ * base FEC recovered does, so it waits behind base frames still in flight,
24388
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
24389
+ * longer than unanchored; one whose base SS_ID is undetermined has no
24390
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
24391
+ * advance. Each packet's wire sequence is restored from its keyframe's own
24392
+ * offset; without one, a stream the base never re-stamped keeps the
24393
+ * header's sequence and any other drops the packet.
23712
24394
  */
23713
24395
  #routeOverlayRecovered(inst, blockStart, recovered) {
23714
24396
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -23728,22 +24410,139 @@ var MmtpRouter = class {
23728
24410
  const streamKey = this.#mediaStreamKey(sourcePacketId, sourceName);
23729
24411
  const restamped = this.#restampedStreams.has(streamKey);
23730
24412
  const restored = /* @__PURE__ */ new Set();
24413
+ const baseSsIds = /* @__PURE__ */ new Map();
24414
+ const gateOnly = /* @__PURE__ */ new Set();
23731
24415
  const symbols = result.symbols.flatMap((sym) => {
23732
- const offset = inst.offsets.get(sym.fragment.mpuSequenceNumber);
23733
- if (offset !== void 0) {
23734
- const packetSequenceNumber = serial32Add(blockStart, sym.index) - offset >>> 0;
24416
+ const overlaySsId = serial32Add(blockStart, sym.index);
24417
+ const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
24418
+ if (anchor !== void 0) {
24419
+ const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
23735
24420
  restored.add(packetSequenceNumber);
23736
- return [{ ...sym, packetSequenceNumber }];
24421
+ const out = { ...sym, packetSequenceNumber };
24422
+ const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
24423
+ if (baseSsId !== void 0) {
24424
+ baseSsIds.set(sym.index, baseSsId);
24425
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24426
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
24427
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
24428
+ }
24429
+ }
24430
+ return [out];
24431
+ }
24432
+ if (!restamped) {
24433
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24434
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
24435
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
24436
+ if (baseSsId !== void 0) {
24437
+ baseSsIds.set(sym.index, baseSsId);
24438
+ if (fedSsId === void 0) gateOnly.add(sym.index);
24439
+ } else {
24440
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
24441
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
24442
+ }
24443
+ return [sym];
23737
24444
  }
23738
- if (!restamped) return [sym];
23739
24445
  this.#overlayStats.unsequencedDropped++;
23740
24446
  return [];
23741
24447
  });
23742
24448
  this.#overlayStats.recovered++;
24449
+ const mpuFirst = /* @__PURE__ */ new Map();
24450
+ for (const sym of symbols) {
24451
+ const ssId = baseSsIds.get(sym.index);
24452
+ const mpu = sym.fragment.mpuSequenceNumber;
24453
+ const first = mpuFirst.get(mpu);
24454
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
24455
+ }
24456
+ const firstSsIds = /* @__PURE__ */ new Map();
24457
+ for (const sym of symbols) {
24458
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
24459
+ }
23743
24460
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
23744
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
24461
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
24462
+ baseSsIds,
24463
+ firstSsIds
23745
24464
  });
23746
24465
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
24466
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
24467
+ }
24468
+ /**
24469
+ * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
24470
+ * its base block too, once its base SS_ID is determined (overlayBaseSsId,
24471
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
24472
+ * base recovery showed; `baseSsIds` holds no other),
24473
+ * so it is fed to the base decoder as a rebuilt source
24474
+ * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
24475
+ * fewer to solve, and its repair can recover the block's other packets.
24476
+ * A base block no repair has stated yet takes it when one does
24477
+ * (#feedPendingRebuilt).
24478
+ *
24479
+ * The overlay route already handled each packet fed (delivered it, or
24480
+ * held an untimed head for its FT=1), so a base recovery routes none of
24481
+ * them again (#routeVerifiedFecSymbols): a second recovered copy of a
24482
+ * held head would wait in the parser for timing its first copy consumed.
24483
+ * Only an overlay block decoded from multicast symbols alone is fed: with
24484
+ * a MoQ symbol in it, the base block's recovery would depend on bytes
24485
+ * that crossed no multicast socket, which the provenance counted from the
24486
+ * block's own arrivals cannot show.
24487
+ */
24488
+ #feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds) {
24489
+ const fec = this.#fecManager;
24490
+ const owner = inst.leg.sourcePacketId;
24491
+ const name = inst.leg.sourceCatalogTrackName;
24492
+ if (!fec?.feedRebuiltSourceSymbol || inst.moqBlocks.has(blockStart)) return;
24493
+ if (this.#classifyPacketId(owner) === null || fec.isTrackConfigured?.(owner) === false) return;
24494
+ const { duplicates, overlayToBase: { routed } } = this.#stream(owner, name);
24495
+ const feeds = [];
24496
+ for (const sym of symbols) {
24497
+ if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
24498
+ const ssId = baseSsIds.get(sym.index);
24499
+ if (ssId === void 0) {
24500
+ this.#overlayStats.baseUndetermined++;
24501
+ continue;
24502
+ }
24503
+ routed.delete(ssId);
24504
+ routed.add(ssId);
24505
+ if (routed.size > OVERLAY_ROUTED_LIMIT) routed.delete(routed.values().next().value);
24506
+ feeds.push([ssId, sym.rawSymbol]);
24507
+ }
24508
+ for (const [ssId, symbolData] of feeds) {
24509
+ if (this.#classifyPacketId(owner) === null) return;
24510
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
24511
+ }
24512
+ }
24513
+ /** Feed one rebuilt source to its base block, or keep it until a repair states that block. */
24514
+ #feedRebuiltToBase(owner, name, ssId, symbolData) {
24515
+ const fec = this.#fecManager;
24516
+ if (!fec?.feedRebuiltSourceSymbol) return;
24517
+ const coords = fec.locateIsoSource?.(owner, name, ssId);
24518
+ if (coords == null) {
24519
+ const pending = this.#stream(owner, name).overlayToBase.pending;
24520
+ pending.delete(ssId);
24521
+ pending.set(ssId, symbolData.slice());
24522
+ if (pending.size > OVERLAY_PENDING_LIMIT) pending.delete(pending.keys().next().value);
24523
+ return;
24524
+ }
24525
+ const fed = fec.feedRebuiltSourceSymbol(owner, ssId, symbolData, name);
24526
+ if (!fed.taken) return;
24527
+ this.#overlayStats.baseFed++;
24528
+ if (fed.recovered === null) return;
24529
+ const sbn = coords.sbn;
24530
+ this.#routeRecoveredBlock(sbn, fed.recovered, owner, name, () => {
24531
+ fec.cancelBlockTimeout(sbn, owner, name);
24532
+ fec.countRecovery(owner, sbn, name);
24533
+ fec.markBlockCompleted(sbn, owner, name);
24534
+ });
24535
+ }
24536
+ /** A repair stated `block`: the rebuilt sources that waited for it join it now. */
24537
+ #feedPendingRebuilt(owner, name, block) {
24538
+ const pending = this.#streams.get(owner)?.get(name)?.overlayToBase.pending;
24539
+ if (pending === void 0 || pending.size === 0) return;
24540
+ for (const [ssId, symbolData] of [...pending]) {
24541
+ if (this.#classifyPacketId(owner) === null) return;
24542
+ if (serial32Distance(block.start, ssId) >= block.length) continue;
24543
+ pending.delete(ssId);
24544
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
24545
+ }
23747
24546
  }
23748
24547
  /** fec-multicast-00 §6.6: report each base block whose RAP MFU fragments
23749
24548
  * the overlay restored, when the keyframe's FT=0 and FT=1 are held too. A
@@ -23883,6 +24682,10 @@ var MmtpRouter = class {
23883
24682
  get unadmittedListedDropCount() {
23884
24683
  return this.#unadmittedListedDrops;
23885
24684
  }
24685
+ /** 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. */
24686
+ get admittedSourceDatagramCount() {
24687
+ return this.#admittedSourceDatagrams;
24688
+ }
23886
24689
  /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
23887
24690
  get unlistedRepairSetAsideCount() {
23888
24691
  return this.#unlistedRepairSetAside;
@@ -24369,6 +25172,8 @@ var MmtpRouter = class {
24369
25172
  )) return;
24370
25173
  fec.noteBlockActivity?.(blockStart, ownerPacketId, catalogTrackName);
24371
25174
  fec.noteRepairGroupLength?.(blockStart, ownerPacketId, repair.rsbLength, catalogTrackName);
25175
+ this.#feedPendingRebuilt(ownerPacketId, catalogTrackName, placement.block);
25176
+ if (this.#classifyPacketId(ownerPacketId) === null) return;
24372
25177
  const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
24373
25178
  const recovered = fec.feedRepairSymbol(
24374
25179
  ownerPacketId,
@@ -24419,7 +25224,7 @@ var MmtpRouter = class {
24419
25224
  catalogTrackName
24420
25225
  )) continue;
24421
25226
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
24422
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
25227
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
24423
25228
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
24424
25229
  }
24425
25230
  if (payload.oversized) continue;
@@ -24506,6 +25311,8 @@ var MmtpRouter = class {
24506
25311
  this.#droppedPreSyncVideo.delete(streamKey);
24507
25312
  this.#latestVideoSeqByStream.delete(streamKey);
24508
25313
  this.#ssIdSeqOffsetByStream.delete(streamKey);
25314
+ this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
25315
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
24509
25316
  this.#multicastRapTwinByStream.delete(streamKey);
24510
25317
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
24511
25318
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -24632,6 +25439,12 @@ var MmtpRouter = class {
24632
25439
  * the outgoing stream stops. The hold is bounded by the incoming stream's
24633
25440
  * own RAP cadence, so no timer is involved.
24634
25441
  *
25442
+ * While the switch is staged, the FEC release gate lets a keyframe the
25443
+ * overlay rebuilt reach it, on either side, when the keyframe did before
25444
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
25445
+ * decides on what each side delivered, and the commit discards the gate's
25446
+ * frames of the outgoing stream.
25447
+ *
24635
25448
  * The commit is one synchronous transition inside the frame path: the
24636
25449
  * outgoing stream's already-admitted frames are released (its queued FEC
24637
25450
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -24682,6 +25495,9 @@ var MmtpRouter = class {
24682
25495
  droppedIncomingFrames: 0
24683
25496
  };
24684
25497
  this.#staged = state;
25498
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
25499
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
25500
+ }
24685
25501
  return {
24686
25502
  cancel: () => {
24687
25503
  if (this.#staged !== state) return false;
@@ -24764,7 +25580,17 @@ var MmtpRouter = class {
24764
25580
  */
24765
25581
  #routeParsedFrame(data, meta) {
24766
25582
  if (this.#classifyPacketId(meta.packetId) === null) return;
24767
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
25583
+ if (this.#staged !== null) {
25584
+ let consumed = false;
25585
+ this.#fecPokeDepth++;
25586
+ try {
25587
+ consumed = this.#interceptSwitchFrame(data, meta);
25588
+ } finally {
25589
+ this.#fecPokeDepth--;
25590
+ this.#flushPendingFecPokes();
25591
+ }
25592
+ if (consumed) return;
25593
+ }
24768
25594
  this.#deliverParsedFrame(data, meta);
24769
25595
  }
24770
25596
  #commitStreamSwitch(state, rap, reason) {
@@ -24916,12 +25742,16 @@ var MmtpRouter = class {
24916
25742
  this.#parser.deferFecRelease(work);
24917
25743
  } finally {
24918
25744
  this.#fecPokeDepth--;
24919
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
24920
- const pokes = [...this.#pendingFecPokes.values()];
24921
- this.#pendingFecPokes.clear();
24922
- for (const poke of pokes) {
24923
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
24924
- }
25745
+ this.#flushPendingFecPokes();
25746
+ }
25747
+ }
25748
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
25749
+ #flushPendingFecPokes() {
25750
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
25751
+ const pokes = [...this.#pendingFecPokes.values()];
25752
+ this.#pendingFecPokes.clear();
25753
+ for (const poke of pokes) {
25754
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
24925
25755
  }
24926
25756
  }
24927
25757
  }
@@ -24999,6 +25829,14 @@ var MmtpRouter = class {
24999
25829
  onRap: (packetId, catalogTrackName, ssId) => {
25000
25830
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
25001
25831
  },
25832
+ // A staged switch commits on when each side's frames reach it
25833
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
25834
+ // they did unanchored.
25835
+ releaseUnanchored: (packetId, catalogTrackName) => {
25836
+ const staged = this.#staged;
25837
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
25838
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
25839
+ },
25002
25840
  onReleased: (data, meta) => {
25003
25841
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
25004
25842
  const timing = meta.authoredTiming;
@@ -25140,6 +25978,7 @@ var MmtpRouter = class {
25140
25978
  const parsed = this.#parser.parsePacket(packet);
25141
25979
  if (!parsed) return;
25142
25980
  const info = parsed.info;
25981
+ if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
25143
25982
  if (source === "multicast" && !manifestAdmitted) {
25144
25983
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
25145
25984
  }
@@ -25421,7 +26260,8 @@ var MmtpRouter = class {
25421
26260
  parsed.header,
25422
26261
  info.sequenceNumber,
25423
26262
  info.rapFlag,
25424
- source
26263
+ source,
26264
+ fecPayloadId?.ssId
25425
26265
  );
25426
26266
  }
25427
26267
  }
@@ -25447,7 +26287,8 @@ var MmtpRouter = class {
25447
26287
  source: parserOptions?.source,
25448
26288
  deliveryProvenance: parserOptions?.deliveryProvenance,
25449
26289
  catalogTrackName: parserOptions?.catalogTrackName,
25450
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
26290
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
26291
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
25451
26292
  };
25452
26293
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
25453
26294
  else this.#parser.feed(packet, feedOptions);
@@ -25571,7 +26412,8 @@ var MmtpRouter = class {
25571
26412
  if (stream === void 0) {
25572
26413
  stream = {
25573
26414
  key: JSON.stringify([packetId, catalogTrackName ?? null]),
25574
- duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId))
26415
+ duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId)),
26416
+ overlayToBase: { routed: /* @__PURE__ */ new Set(), pending: /* @__PURE__ */ new Map() }
25575
26417
  };
25576
26418
  byName.set(catalogTrackName, stream);
25577
26419
  }
@@ -25686,8 +26528,16 @@ var MmtpRouter = class {
25686
26528
  this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
25687
26529
  this.#emitDirectVideo(packetId, data, meta, cb);
25688
26530
  }
25689
- #routeDirectRecoveredVideo(packetId, data, meta, cb) {
26531
+ #routeDirectRecoveredVideo(packetId, data, meta, cb, fecSbn) {
25690
26532
  const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);
26533
+ if (this.#isFecTrack(packetId)) {
26534
+ const high = this.#deliveredVideoHighWaterByStream.get(streamKey);
26535
+ if (fecSbn !== void 0 || high !== void 0 && authoredAdjacent(high, meta)) {
26536
+ this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
26537
+ this.#emitDirectVideo(packetId, data, meta, cb);
26538
+ return;
26539
+ }
26540
+ }
25691
26541
  this.#enqueueDirectRecoveredVideo(packetId, data, meta);
25692
26542
  const lastSourceTs = this.#lastDirectSourceVideoTsByStream.get(streamKey);
25693
26543
  this.#drainDirectRecoveredVideo(
@@ -25841,6 +26691,13 @@ var MmtpRouter = class {
25841
26691
  * frames by epoch only if pre-protection input ever matters.
25842
26692
  */
25843
26693
  #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete, assisted = false) {
26694
+ const overlayRouted = ownerPacketId == null ? void 0 : this.#streams.get(ownerPacketId)?.get(catalogTrackName)?.overlayToBase.routed;
26695
+ if (overlayRouted !== void 0 && overlayRouted.size > 0) {
26696
+ result = {
26697
+ ...result,
26698
+ symbols: result.symbols.filter((sym) => !overlayRouted.has(this.#fecAnchorForRecovered(blockId, sym.index)))
26699
+ };
26700
+ }
25844
26701
  const entry = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
25845
26702
  const receiver = entry === void 0 || entry === "ambiguous" ? entry : entry.receiver;
25846
26703
  const userAgent = !assisted && entry !== void 0 && entry !== "ambiguous" && entry.protected === true && entry.userAgent === true;
@@ -25897,7 +26754,12 @@ var MmtpRouter = class {
25897
26754
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
25898
26755
  if (ownerPacketId == null) return;
25899
26756
  if (this.#classifyPacketId(ownerPacketId) === null) return;
25900
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
26757
+ const fecSbnOf = (index) => {
26758
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
26759
+ const fecSbn = overlay.baseSsIds.get(index);
26760
+ const fecSbnFirst = overlay.firstSsIds.get(index);
26761
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
26762
+ };
25901
26763
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
25902
26764
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
25903
26765
  if (ssIdSeqOffset !== void 0) {
@@ -25905,7 +26767,10 @@ var MmtpRouter = class {
25905
26767
  ...result,
25906
26768
  symbols: result.symbols.map((sym) => {
25907
26769
  const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
25908
- if (wire === sym.packetSequenceNumber) return sym;
26770
+ if (wire === sym.packetSequenceNumber) {
26771
+ this.#unstampedSsIdSeqOffsetByStream.set(streamKey, ssIdSeqOffset);
26772
+ return sym;
26773
+ }
25909
26774
  this.#restampedRecoveredSeqs++;
25910
26775
  this.#restampedStreams.add(streamKey);
25911
26776
  return { ...sym, packetSequenceNumber: wire };
@@ -25941,16 +26806,29 @@ var MmtpRouter = class {
25941
26806
  }
25942
26807
  );
25943
26808
  }
25944
- result = {
25945
- ...result,
25946
- 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(
25947
- ownerPacketId,
25948
- sym.fragment.mpuSequenceNumber,
25949
- sym.fragment.movieFragmentSequenceNumber,
25950
- sym.fragment.sampleNumber,
25951
- catalogTrackName
25952
- ))
25953
- };
26809
+ const untimedHead = (sym) => sym.fragmentType === 2 && sym.fragment.fragmentationIndicator === 1 && sym.fragment.movieFragmentSequenceNumber !== void 0 && sym.fragment.sampleNumber !== void 0 && !this.#parser.hasAuthoredTimingFor(
26810
+ ownerPacketId,
26811
+ sym.fragment.mpuSequenceNumber,
26812
+ sym.fragment.movieFragmentSequenceNumber,
26813
+ sym.fragment.sampleNumber,
26814
+ catalogTrackName
26815
+ );
26816
+ for (const sym of result.symbols) {
26817
+ if (!untimedHead(sym) || this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) continue;
26818
+ this.#feedViaParser(
26819
+ sym.rawSymbol,
26820
+ { packetId: ownerPacketId, sequenceNumber: sym.packetSequenceNumber },
26821
+ void 0,
26822
+ {
26823
+ skipFecPayloadId: true,
26824
+ recovered: true,
26825
+ deliveryProvenance,
26826
+ ...fecSbnOf(sym.index),
26827
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
26828
+ }
26829
+ );
26830
+ }
26831
+ result = { ...result, symbols: result.symbols.filter((sym) => !untimedHead(sym)) };
25954
26832
  const gated = this.#isFecTrack(ownerPacketId);
25955
26833
  const assembler = this.#mseAssemblerFor(ownerPacketId, catalogTrackName);
25956
26834
  if (assembler) {
@@ -27677,6 +28555,12 @@ function isNonNegativeSafeInteger(value) {
27677
28555
  function isSymbolCounts(value) {
27678
28556
  return isRecord(value) && hasExactKeys(value, ["multicast", "moq"]) && isNonNegativeSafeInteger(value["multicast"]) && isNonNegativeSafeInteger(value["moq"]);
27679
28557
  }
28558
+ function isSpanFailure(value) {
28559
+ if (!isRecord(value) || !hasExactKeys(value, ["length", "sources"])) return false;
28560
+ const length = value["length"];
28561
+ const sources = value["sources"];
28562
+ return Number.isSafeInteger(length) && length > 0 && isNonNegativeSafeInteger(sources) && sources < length;
28563
+ }
27680
28564
  function isNullableNonNegative(value) {
27681
28565
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
27682
28566
  }
@@ -27696,7 +28580,10 @@ function isRepairLifecycleEvent(value) {
27696
28580
  case "recovered":
27697
28581
  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"]);
27698
28582
  case "failed":
27699
- return hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]);
28583
+ return hasExactKeys(
28584
+ value,
28585
+ "span" in value ? ["version", "type", "block", "blockClass", "symbols", "span"] : ["version", "type", "block", "blockClass", "symbols"]
28586
+ ) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]) && (!("span" in value) || isSpanFailure(value["span"]));
27700
28587
  case "repair-preempted":
27701
28588
  case "repair-deferred":
27702
28589
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
@@ -27905,6 +28792,8 @@ var MulticastManager = class {
27905
28792
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
27906
28793
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
27907
28794
  #repairReleases = /* @__PURE__ */ new Map();
28795
+ /** Protected repair flows owned by each live repair-endpoint release. */
28796
+ #repairProvenanceFlows = /* @__PURE__ */ new Map();
27908
28797
  /** Each source's catalog keyframe overlay, from its `ok` binding. */
27909
28798
  #overlayBindings = /* @__PURE__ */ new Map();
27910
28799
  /** Installed overlay decoders (`setKeyframeOverlayDecoder`), by source. */
@@ -27962,7 +28851,7 @@ var MulticastManager = class {
27962
28851
  onPublisherRestart: (packetId, catalogTrackName) => {
27963
28852
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
27964
28853
  },
27965
- onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
28854
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass, span) => {
27966
28855
  const pathCount = this.#fec.blockPathCount(
27967
28856
  sbn,
27968
28857
  packetId,
@@ -27980,7 +28869,8 @@ var MulticastManager = class {
27980
28869
  symbols: {
27981
28870
  multicast: pathCount?.multicastSymbols ?? 0,
27982
28871
  moq: pathCount?.moqSymbols ?? 0
27983
- }
28872
+ },
28873
+ ...span === void 0 ? {} : { span }
27984
28874
  });
27985
28875
  },
27986
28876
  onFrameGap: (decision) => {
@@ -28570,6 +29460,9 @@ var MulticastManager = class {
28570
29460
  this.#transport.onFailback((reason) => {
28571
29461
  const joined = this.#provenanceJoin;
28572
29462
  if (joined !== null) this.#router.unprotectProvenanceFlow(joined.flow);
29463
+ for (const flows of this.#repairProvenanceFlows.values()) {
29464
+ for (const flow of flows) this.#router.unprotectProvenanceFlow(flow);
29465
+ }
28573
29466
  this.#onFailback?.(reason);
28574
29467
  });
28575
29468
  }
@@ -28604,6 +29497,12 @@ var MulticastManager = class {
28604
29497
  "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
28605
29498
  );
28606
29499
  }
29500
+ if (provenanceFlow !== void 0) {
29501
+ const flow = multicastProvenanceFlowKey(provenanceFlow);
29502
+ if ([...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
29503
+ throw new TypeError(`[MulticastManager] join: provenance flow already registered by a repair endpoint: ${flow}`);
29504
+ }
29505
+ }
28607
29506
  const staged = this.#renditionSwitch;
28608
29507
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
28609
29508
  this.configureFec(config);
@@ -28611,8 +29510,8 @@ var MulticastManager = class {
28611
29510
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
28612
29511
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
28613
29512
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
28614
- this.#releaseProvenanceJoin();
28615
29513
  const provenance = config.provenance;
29514
+ this.#releaseProvenanceJoin();
28616
29515
  const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
28617
29516
  const ingress = protectedTracks === void 0 ? void 0 : {
28618
29517
  tracks: Object.freeze(
@@ -28665,8 +29564,13 @@ var MulticastManager = class {
28665
29564
  * feeds the flow's receiver; media datagrams are held until one admits them.
28666
29565
  */
28667
29566
  #joinProvenance(provenance, ingress) {
29567
+ this.#router.registerProvenanceFlow(ingress, this.#provenanceReceiver(provenance));
29568
+ this.#hookFailback();
29569
+ this.#provenanceJoin = { flow: ingress.flow };
29570
+ }
29571
+ #provenanceReceiver(provenance) {
28668
29572
  const { flow, auth } = provenance;
28669
- const receiver = new BcProvenanceV2Receiver({
29573
+ return new BcProvenanceV2Receiver({
28670
29574
  ...provenance.receiver,
28671
29575
  // The caller's ctx when it passes one, else the catalog's: an explicit
28672
29576
  // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
@@ -28683,9 +29587,6 @@ var MulticastManager = class {
28683
29587
  maxAuthDelayMs: flow.maxAuthDelayMs,
28684
29588
  manifestTimerMs: flow.manifestTimerMs
28685
29589
  });
28686
- this.#router.registerProvenanceFlow(ingress, receiver);
28687
- this.#hookFailback();
28688
- this.#provenanceJoin = { flow: ingress.flow };
28689
29590
  }
28690
29591
  /** Un-protect: drop the flow's hold queues (no expiry counted). */
28691
29592
  #releaseProvenanceJoin() {
@@ -28716,8 +29617,25 @@ var MulticastManager = class {
28716
29617
  * callback delivers must come from a subscription opened on
28717
29618
  * `options.gateway`. A callback that also merges another source (a MoQ or
28718
29619
  * WebSocket repair feed) must not name a native provider here.
29620
+ *
29621
+ * An endpoint's `provenance` makes its group a protected flow of its own
29622
+ * (multicast-02 7.2.7), registered here and released with the group; its
29623
+ * records ride in band on the group's port. On the user-agent path a
29624
+ * flow-less repair group of a protected track is set aside, never read, so
29625
+ * a player joining a protected catalog's repair groups passes it.
28719
29626
  */
28720
29627
  joinRepairEndpoints(endpoints, provider, options) {
29628
+ for (const { provenance, flow, source, group, port: port2 } of endpoints) {
29629
+ if (provenance === void 0) continue;
29630
+ if (flow !== void 0) {
29631
+ throw new TypeError("[MulticastManager] joinRepairEndpoints: an endpoint names provenance or flow, never both");
29632
+ }
29633
+ if (!sameIpAddress(source, provenance.flow.source) || !sameIpAddress(group, provenance.flow.groupAddress) || port2 !== provenance.flow.port) {
29634
+ throw new RangeError(
29635
+ "[MulticastManager] joinRepairEndpoints: provenance flow (S, G, port) must match the endpoint's source, group and port"
29636
+ );
29637
+ }
29638
+ }
28721
29639
  const releases = [];
28722
29640
  let released = false;
28723
29641
  const safely = (each) => {
@@ -28727,17 +29645,36 @@ var MulticastManager = class {
28727
29645
  console.warn("[MulticastManager] repair group release failed", error);
28728
29646
  }
28729
29647
  };
29648
+ const usedFlows = /* @__PURE__ */ new Set();
29649
+ const preparedProvenance = endpoints.map((endpoint) => {
29650
+ if (endpoint.provenance === void 0) return void 0;
29651
+ const flow = multicastProvenanceFlowKey(endpoint.provenance.flow);
29652
+ if (usedFlows.has(flow) || this.#provenanceJoin?.flow === flow || [...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
29653
+ throw new TypeError(`[MulticastManager] joinRepairEndpoints: provenance flow already registered: ${flow}`);
29654
+ }
29655
+ usedFlows.add(flow);
29656
+ return { flow, receiver: this.#provenanceReceiver(endpoint.provenance) };
29657
+ });
29658
+ const provenanceFlows = [];
28730
29659
  const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners.map((owner) => owner.instance !== "keyframe" ? owner : {
28731
29660
  ...owner,
28732
29661
  ownerTrackName: endpoint.tracks.find((t) => t.packetId === owner.ownerPacketId)?.name,
28733
29662
  repairTrackName: endpoint.tracks.find((t) => t.packetId === owner.packetId)?.name
28734
29663
  }));
28735
29664
  this.#applyRepairOwners(repairOwners);
28736
- for (const endpoint of endpoints) {
29665
+ for (const [index, endpoint] of endpoints.entries()) {
29666
+ const flow = endpoint.provenance === void 0 ? endpoint.flow : multicastProvenanceFlowKey(endpoint.provenance.flow);
28737
29667
  const ingress = {
28738
29668
  tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
28739
- ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
29669
+ ...flow === void 0 ? {} : { flow }
28740
29670
  };
29671
+ if (endpoint.provenance !== void 0) {
29672
+ const prepared = preparedProvenance[index];
29673
+ if (prepared === void 0) throw new Error("[MulticastManager] repair provenance preparation missing");
29674
+ this.#router.registerProvenanceFlow(ingress, prepared.receiver);
29675
+ provenanceFlows.push(prepared.flow);
29676
+ releases.push(() => this.#router.releaseProvenanceFlow(flow));
29677
+ }
28741
29678
  let sender;
28742
29679
  const feed = (packet, sourceAddress, ingressToFeed) => {
28743
29680
  if (released) return;
@@ -28767,7 +29704,7 @@ var MulticastManager = class {
28767
29704
  packetIds: endpoint.packetIds,
28768
29705
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
28769
29706
  // A protected repair group's records ride in band on its port (7.2.3).
28770
- ...endpoint.flow === void 0 ? {} : { protected: true }
29707
+ ...flow === void 0 ? {} : { protected: true }
28771
29708
  }, ingress).then((joined) => {
28772
29709
  if (!joined && !released) fail(transport.lastJoinOutcome);
28773
29710
  });
@@ -28776,9 +29713,12 @@ var MulticastManager = class {
28776
29713
  if (released) return;
28777
29714
  released = true;
28778
29715
  this.#repairReleases.delete(release);
29716
+ this.#repairProvenanceFlows.delete(release);
28779
29717
  for (const each of releases.splice(0)) safely(each);
28780
29718
  };
28781
29719
  this.#repairReleases.set(release, repairOwners);
29720
+ this.#repairProvenanceFlows.set(release, provenanceFlows);
29721
+ if (provenanceFlows.length) this.#hookFailback();
28782
29722
  return release;
28783
29723
  }
28784
29724
  #applyRepairOwners(owners) {
@@ -29360,10 +30300,12 @@ var MulticastManager = class {
29360
30300
  * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
29361
30301
  * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
29362
30302
  * pending hole and reported here, and `closeIsoHoles` must be called for it
29363
- * once its range FETCH ends (or none is sent).
30303
+ * once its range FETCH ends (or none is sent). `onExpired` is told of a
30304
+ * pending hole the stream runs past the locator's horizon: returning true,
30305
+ * the caller closes it (`closeIsoHoles`); otherwise it is discarded.
29364
30306
  */
29365
- onUndelimitedLoss(cb) {
29366
- this.#fec.setUndelimitedLossHandler(cb);
30307
+ onUndelimitedLoss(cb, onExpired) {
30308
+ this.#fec.setUndelimitedLossHandler(cb, onExpired ?? null);
29367
30309
  }
29368
30310
  /**
29369
30311
  * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
@@ -29599,7 +30541,8 @@ var MulticastManager = class {
29599
30541
  "stream" in event ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
29600
30542
  ...event,
29601
30543
  block: Object.freeze({ ...event.block }),
29602
- ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {}
30544
+ ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {},
30545
+ ..."span" in event && event.span !== void 0 ? { span: Object.freeze({ ...event.span }) } : {}
29603
30546
  }
29604
30547
  );
29605
30548
  if (this.#logRepairLifecycle) {
@@ -32271,6 +33214,7 @@ var RepairLayerSubscriptions = class {
32271
33214
 
32272
33215
  // src/repair-fetch.ts
32273
33216
  var MOQT_PRIORITY_MAX = 255;
33217
+ var WALK_LEAD_MS = 3;
32274
33218
  var SOURCE_MEDIA_PRIORITY_MAX = REPAIR_PRIORITY_MIN - 1;
32275
33219
  function isMoqtPriority(value) {
32276
33220
  return Number.isSafeInteger(value) && value >= 0 && value <= MOQT_PRIORITY_MAX;
@@ -32321,8 +33265,17 @@ function wireRepairFetch(mc, opts) {
32321
33265
  mc.noteRepairScheduling(type, entry.sbn, entry.packetId, entry.catalogTrackName);
32322
33266
  };
32323
33267
  const clearEntry = (entry) => {
32324
- if (entry.range) mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, entry.range.holeLength);
32325
- else clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
33268
+ const { range } = entry;
33269
+ if (range) {
33270
+ atReport(range, () => mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, range.holeLength));
33271
+ } else {
33272
+ clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
33273
+ }
33274
+ };
33275
+ const atReport = (range, work) => {
33276
+ const fec = mc.fecManager;
33277
+ if (range.groups !== null || fec.withReceiptTime === void 0) work();
33278
+ else fec.withReceiptTime(range.reportedAt, work);
32326
33279
  };
32327
33280
  const releaseHold = (entry) => {
32328
33281
  if (entry.range) return;
@@ -32334,7 +33287,7 @@ function wireRepairFetch(mc, opts) {
32334
33287
  if (!run) return;
32335
33288
  entry.running = null;
32336
33289
  run.stopped = reason;
32337
- run.controller.abort();
33290
+ run.controller.abort(reason);
32338
33291
  if (reason === "preempted") releaseHold(entry);
32339
33292
  mc.noteRepairStopped?.(reason, entry.sbn, entry.packetId, entry.catalogTrackName);
32340
33293
  };
@@ -32389,21 +33342,42 @@ function wireRepairFetch(mc, opts) {
32389
33342
  const admit = (entry, now) => {
32390
33343
  const budgetMs = entry.deadlineAt - now;
32391
33344
  const rttMs = readRtt();
32392
- const reason = !entry.range && !groupCanComplete(entry.sbn, entry.packetId, entry.catalogTrackName) ? "group-cannot-complete" : rttMs === null ? "rtt-unmeasured" : rttMs < budgetMs ? null : "rtt-exceeds-budget";
33345
+ const reason = refusal(entry, now, rttMs);
32393
33346
  if (reason === null) return rttMs;
32394
33347
  skip(entry, reason, rttMs, budgetMs);
32395
33348
  return null;
32396
33349
  };
33350
+ 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";
32397
33351
  const retire = (entry) => {
32398
33352
  if (entries.get(entry.key) === entry) entries.delete(entry.key);
32399
33353
  if (entry.expiry !== void 0) clearTimeout(entry.expiry);
32400
33354
  };
32401
- const outstandingBelow = (priority) => {
33355
+ const holdsBack = (entry, priority, videoWalks = true) => {
33356
+ if (entry.priority >= priority) return false;
33357
+ const { walk } = entry;
33358
+ if (walk === void 0) return true;
33359
+ if (entry.priority !== 0 || !videoWalks) return false;
33360
+ return entry.running === null || walk.group !== null && !walk.group.controller.signal.aborted;
33361
+ };
33362
+ const outstandingBelow = (priority, videoWalks = true) => {
32402
33363
  for (const entry of entries.values()) {
32403
- if (entry.priority < priority) return true;
33364
+ if (holdsBack(entry, priority, videoWalks)) return true;
32404
33365
  }
32405
33366
  return false;
32406
33367
  };
33368
+ const yieldVideoWalks = (queued) => {
33369
+ const now = performance.now();
33370
+ const rttMs = readRtt();
33371
+ const due = queued.some((entry) => entry.priority !== 0 && entry.walk === void 0 && !outstandingBelow(entry.priority, false) && refusal(entry, now, rttMs) === null);
33372
+ if (!due) return;
33373
+ for (const entry of entries.values()) {
33374
+ const walk = entry.walk;
33375
+ if (entry.priority !== 0 || walk === void 0 || walk.group === null) continue;
33376
+ if (walk.group.controller.signal.aborted) continue;
33377
+ walk.yielded = true;
33378
+ walk.group.controller.abort();
33379
+ }
33380
+ };
32407
33381
  const preemptBestEffort = () => {
32408
33382
  for (const entry of entries.values()) {
32409
33383
  if (entry.priority === 0 || !entry.running) continue;
@@ -32432,7 +33406,8 @@ function wireRepairFetch(mc, opts) {
32432
33406
  }
32433
33407
  const rttMs = admit(entry, now);
32434
33408
  if (rttMs === null) return;
32435
- if (entry.priority === 0) preemptBestEffort();
33409
+ if (entry.priority === 0 && entry.walk === void 0) preemptBestEffort();
33410
+ if (entry.range === void 0) leaveWalkedGroup(entry);
32436
33411
  if (counted) entry.attempts++;
32437
33412
  mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName, {
32438
33413
  rttMs,
@@ -32454,6 +33429,14 @@ function wireRepairFetch(mc, opts) {
32454
33429
  }
32455
33430
  void execute(entry, run);
32456
33431
  };
33432
+ const leaveWalkedGroup = (block) => {
33433
+ for (const entry of entries.values()) {
33434
+ const group = entry.walk?.group;
33435
+ if (group?.sbn === block.sbn && entry.packetId === block.packetId && entry.catalogTrackName === block.catalogTrackName) {
33436
+ group.controller.abort();
33437
+ }
33438
+ }
33439
+ };
32457
33440
  const dispatch = () => {
32458
33441
  if (disposed) return;
32459
33442
  const now = performance.now();
@@ -32478,6 +33461,7 @@ function wireRepairFetch(mc, opts) {
32478
33461
  for (const entry of queued) {
32479
33462
  if (entry.priority === 0) start(entry);
32480
33463
  }
33464
+ yieldVideoWalks(queued);
32481
33465
  if (outstandingBelow(1)) return;
32482
33466
  for (const entry of queued) {
32483
33467
  if (entry.priority === 1) start(entry);
@@ -32504,6 +33488,16 @@ function wireRepairFetch(mc, opts) {
32504
33488
  }
32505
33489
  return counts.sources + counts.repairGroupLength >= counts.authoredLength;
32506
33490
  };
33491
+ const groupServed = (sbn, packetId, catalogTrackName) => {
33492
+ if (mc.fecManager.blockSymbolCounts === void 0) return false;
33493
+ const counts = symbolCounts(sbn, packetId, catalogTrackName);
33494
+ if (counts === void 0 || counts.authoredLength === void 0) return true;
33495
+ return counts.sources + counts.repairs >= counts.authoredLength || !groupCanComplete(sbn, packetId, catalogTrackName);
33496
+ };
33497
+ const statedEnd = (sbn, packetId, catalogTrackName) => {
33498
+ const length = symbolCounts(sbn, packetId, catalogTrackName)?.authoredLength;
33499
+ return length === void 0 ? void 0 : serial32Add(sbn, length);
33500
+ };
32507
33501
  const finish = (entry, run, fed, error) => {
32508
33502
  if (run.stopped !== null || entry.running !== run || entries.get(entry.key) !== entry) {
32509
33503
  return;
@@ -32548,27 +33542,81 @@ function wireRepairFetch(mc, opts) {
32548
33542
  signal: run.controller.signal,
32549
33543
  subscriberPriority: entry.subscriberPriority
32550
33544
  };
33545
+ const { range } = entry;
33546
+ const feed = (packet) => {
33547
+ if (entry.catalogTrackName === void 0) {
33548
+ mc.processRepairFromMoQ(packet, entry.packetId);
33549
+ } else {
33550
+ mc.processRepairFromMoQ(packet, entry.packetId, entry.catalogTrackName);
33551
+ }
33552
+ };
32551
33553
  try {
32552
- const packets = entry.range ? opts.rangeTransport({
33554
+ const packets = range === void 0 ? opts.transport({ ...common, sbn: entry.sbn }) : entry.walk !== void 0 ? walkHole(entry, entry.walk, range, common) : opts.rangeTransport({
32553
33555
  ...common,
32554
- startGroup: entry.range.startGroup,
32555
- endGroup: entry.range.endGroup,
32556
- lostSsId: entry.range.lostSsId
32557
- }) : opts.transport({ ...common, sbn: entry.sbn });
33556
+ startGroup: range.groups.startGroup,
33557
+ endGroup: range.groups.endGroup,
33558
+ lostSsId: range.lostSsId
33559
+ });
32558
33560
  for await (const packet of packets) {
32559
33561
  if (run.stopped !== null || entry.running !== run) break;
32560
33562
  fed++;
32561
- if (entry.catalogTrackName === void 0) {
32562
- mc.processRepairFromMoQ(packet, entry.packetId);
32563
- } else {
32564
- mc.processRepairFromMoQ(packet, entry.packetId, entry.catalogTrackName);
32565
- }
33563
+ if (range === void 0) feed(packet);
33564
+ else atReport(range, () => feed(packet));
32566
33565
  }
32567
33566
  finish(entry, run, fed, void 0);
32568
33567
  } catch (error) {
32569
33568
  finish(entry, run, fed, error ?? new Error("repair transport rejected"));
32570
33569
  }
32571
33570
  };
33571
+ async function* walkHole(entry, walk, hole, common) {
33572
+ const lostAt = serial32Distance(entry.sbn, hole.lostSsId);
33573
+ for (let first = true; !common.signal.aborted; first = false) {
33574
+ if (!first && entry.priority !== 0 && outstandingBelow(1)) {
33575
+ stop(entry, "preempted");
33576
+ note("repair-preempted", entry);
33577
+ return;
33578
+ }
33579
+ if (!first && entry.priority === 0) {
33580
+ dispatch();
33581
+ if (common.signal.aborted) return;
33582
+ }
33583
+ const sbn = walk.next;
33584
+ let next;
33585
+ if (entries.get(requestKey(sbn, entry.packetId, entry.catalogTrackName))?.running == null) {
33586
+ const rsIds = /* @__PURE__ */ new Set();
33587
+ const group = new AbortController();
33588
+ const cancel = () => group.abort(common.signal.reason);
33589
+ common.signal.addEventListener("abort", cancel, { once: true });
33590
+ walk.group = { sbn, controller: group };
33591
+ try {
33592
+ for await (const packet of opts.transport({ ...common, sbn, signal: group.signal })) {
33593
+ yield packet;
33594
+ const id = extractRepairFecPayloadId(packet);
33595
+ if (id === null || id.ssStart !== sbn || id.ssbLength === 0) continue;
33596
+ next ??= serial32Add(sbn, id.ssbLength);
33597
+ rsIds.add(id.rsId);
33598
+ if (rsIds.size >= id.rsbLength || groupServed(sbn, entry.packetId, entry.catalogTrackName)) {
33599
+ group.abort();
33600
+ break;
33601
+ }
33602
+ }
33603
+ } catch (error) {
33604
+ if (!group.signal.aborted || common.signal.aborted) throw error;
33605
+ } finally {
33606
+ common.signal.removeEventListener("abort", cancel);
33607
+ walk.group = null;
33608
+ }
33609
+ if (walk.yielded) {
33610
+ walk.yielded = false;
33611
+ continue;
33612
+ }
33613
+ }
33614
+ next ??= statedEnd(sbn, entry.packetId, entry.catalogTrackName);
33615
+ if (next === void 0) return;
33616
+ if (serial32Distance(entry.sbn, next) > lostAt) return;
33617
+ walk.next = next;
33618
+ }
33619
+ }
32572
33620
  const removeResetObserver = mc.addTrackResetObserver((packetId, catalogTrackName) => {
32573
33621
  for (const entry of [...entries.values()]) {
32574
33622
  if (entry.packetId !== packetId || entry.catalogTrackName !== catalogTrackName) continue;
@@ -32764,7 +33812,37 @@ function wireRepairFetch(mc, opts) {
32764
33812
  throw error;
32765
33813
  }
32766
33814
  };
32767
- if (opts.rangeTransport !== void 0) {
33815
+ const trackKind = (packetId) => {
33816
+ try {
33817
+ return mc.fecManager.trackKindFor?.(packetId);
33818
+ } catch {
33819
+ return void 0;
33820
+ }
33821
+ };
33822
+ const walkDeadlineAt = (packetId, now, deadlineAt) => {
33823
+ let repairDeadlineMs;
33824
+ try {
33825
+ repairDeadlineMs = mc.fecManager.repairDeadlineMsForPacket?.(packetId);
33826
+ } catch {
33827
+ repairDeadlineMs = void 0;
33828
+ }
33829
+ if (repairDeadlineMs === void 0 || !Number.isFinite(repairDeadlineMs)) return deadlineAt;
33830
+ return Math.min(deadlineAt, now + repairDeadlineMs - WALK_LEAD_MS);
33831
+ };
33832
+ const onHoleExpired = (hole) => {
33833
+ if (disposed) return false;
33834
+ 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);
33835
+ if (entry === void 0) return false;
33836
+ queueMicrotask(() => {
33837
+ if (entries.get(entry.key) !== entry) return;
33838
+ retire(entry);
33839
+ stop(entry, "expired");
33840
+ clearEntry(entry);
33841
+ dispatch();
33842
+ });
33843
+ return true;
33844
+ };
33845
+ if (mc.onUndelimitedLoss !== void 0 && mc.closeIsoHoles !== void 0) {
32768
33846
  mc.onUndelimitedLoss((loss) => {
32769
33847
  const { packetId, catalogTrackName, holeStart, holeLength } = loss;
32770
33848
  const close = () => mc.closeIsoHoles(packetId, catalogTrackName, holeStart, holeLength);
@@ -32772,9 +33850,11 @@ function wireRepairFetch(mc, opts) {
32772
33850
  const blockProfile = blockProfileOf(packetId);
32773
33851
  const target = opts.resolveTarget(packetId, catalogTrackName);
32774
33852
  if (!target) return close();
32775
- const priority = repairPriorityForClass("unknown");
32776
- const range = rangeFor(loss, target.repairTrack);
32777
- if (range === null) {
33853
+ const walked = opts.rangeTransport === void 0;
33854
+ const holeClass = walked && trackKind(packetId) === "audio" ? "audio" : "unknown";
33855
+ const priority = repairPriorityForClass(holeClass);
33856
+ const groups = walked ? null : rangeFor(loss, target.repairTrack);
33857
+ if (!walked && groups === null) {
32778
33858
  close();
32779
33859
  mc.noteRepairSkipped("range-no-anchor", { rttMs: readRtt(), budgetMs: 0, priority }, holeStart, packetId, catalogTrackName);
32780
33860
  return;
@@ -32785,8 +33865,10 @@ function wireRepairFetch(mc, opts) {
32785
33865
  packetId,
32786
33866
  ...catalogTrackName === void 0 ? {} : { catalogTrackName }
32787
33867
  };
32788
- const wire = wirePriority(identity, "unknown");
32789
- const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, performance.now(), "unknown");
33868
+ const wire = wirePriority(identity, holeClass);
33869
+ if (wire === null) return close();
33870
+ const now = performance.now();
33871
+ const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, now, holeClass);
32790
33872
  if (deadline === null) {
32791
33873
  close();
32792
33874
  mc.noteRepairSkipped(
@@ -32798,6 +33880,7 @@ function wireRepairFetch(mc, opts) {
32798
33880
  );
32799
33881
  return;
32800
33882
  }
33883
+ const deadlineAt = walked ? walkDeadlineAt(packetId, now, deadline.deadlineAt) : deadline.deadlineAt;
32801
33884
  const entry = {
32802
33885
  key: JSON.stringify(["range", packetId, catalogTrackName ?? null, holeStart]),
32803
33886
  ...identity,
@@ -32805,15 +33888,16 @@ function wireRepairFetch(mc, opts) {
32805
33888
  blockProfile,
32806
33889
  priority,
32807
33890
  subscriberPriority: wire.subscriberPriority,
32808
- deadlineAt: deadline.deadlineAt,
32809
- playoutDeadlineAt: deadline.deadlineAt - deadline.extensionMs,
33891
+ deadlineAt,
33892
+ playoutDeadlineAt: deadlineAt - deadline.extensionMs,
32810
33893
  anchorAt: deadline.anchorAt,
32811
33894
  delayMs: deadline.delayMs,
32812
33895
  bound: deadline.bound,
32813
33896
  order: enqueueOrder++,
32814
33897
  attempts: 0,
32815
33898
  running: null,
32816
- range: { ...range, lostSsId: loss.lostSsId, holeLength }
33899
+ range: { lostSsId: loss.lostSsId, holeLength, groups, reportedAt: now },
33900
+ ...walked ? { walk: { next: holeStart, group: null, yielded: false } } : {}
32817
33901
  };
32818
33902
  const previous = entries.get(entry.key);
32819
33903
  if (previous) {
@@ -32823,7 +33907,7 @@ function wireRepairFetch(mc, opts) {
32823
33907
  entries.set(entry.key, entry);
32824
33908
  entry.expiry = setTimeout(dispatch, Math.max(0, entry.deadlineAt - performance.now()) + 1);
32825
33909
  dispatch();
32826
- });
33910
+ }, onHoleExpired);
32827
33911
  }
32828
33912
  const removeRapObserver = mc.addRapCompleteObserver?.((packetId) => {
32829
33913
  queueMicrotask(() => {