@blockcast/mmt-container 2.2.0-main.986a21fc9782 → 2.2.0-main.9c3e22d1cd4d

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 (60) hide show
  1. package/dist/browser-runtime.js +930 -149
  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 +71 -14
  10. package/dist/fec-manager.d.ts.map +1 -1
  11. package/dist/fec-manager.js +289 -58
  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 +1 -1
  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 +39 -13
  18. package/dist/iso-block-locator.d.ts.map +1 -1
  19. package/dist/iso-block-locator.js +80 -25
  20. package/dist/iso-block-locator.js.map +2 -2
  21. package/dist/media-router.js.map +1 -1
  22. package/dist/mmtp-container-parser.d.ts +42 -2
  23. package/dist/mmtp-container-parser.d.ts.map +1 -1
  24. package/dist/mmtp-container-parser.js +211 -12
  25. package/dist/mmtp-container-parser.js.map +2 -2
  26. package/dist/mmtp-container-parser.no-modules.js +210 -13
  27. package/dist/mmtp-container-parser.no-modules.js.map +3 -3
  28. package/dist/mmtp-decode-pipeline.js +211 -12
  29. package/dist/mmtp-decode-pipeline.js.map +2 -2
  30. package/dist/mmtp-router.d.ts +20 -9
  31. package/dist/mmtp-router.d.ts.map +1 -1
  32. package/dist/mmtp-router.js +371 -45
  33. package/dist/mmtp-router.js.map +3 -3
  34. package/dist/multicast-manager.d.ts +26 -3
  35. package/dist/multicast-manager.d.ts.map +1 -1
  36. package/dist/multicast-manager.js +750 -122
  37. package/dist/multicast-manager.js.map +3 -3
  38. package/dist/multicast-transport.js +2 -2
  39. package/dist/multicast-transport.js.map +2 -2
  40. package/dist/no-modules.js +211 -12
  41. package/dist/no-modules.js.map +3 -3
  42. package/dist/repair-fetch.d.ts +38 -8
  43. package/dist/repair-fetch.d.ts.map +1 -1
  44. package/dist/repair-fetch.js +286 -27
  45. package/dist/repair-fetch.js.map +3 -3
  46. package/dist/track-session.d.ts.map +1 -1
  47. package/dist/track-session.js +1 -0
  48. package/dist/track-session.js.map +2 -2
  49. package/dist/wasm-mmtp-container-parser.js +211 -12
  50. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  51. package/package.json +5 -5
  52. package/src/codec-utils.ts +121 -1
  53. package/src/fec-manager.ts +289 -32
  54. package/src/index.ts +2 -0
  55. package/src/iso-block-locator.ts +114 -31
  56. package/src/mmtp-container-parser.ts +209 -10
  57. package/src/mmtp-router.ts +263 -58
  58. package/src/multicast-manager.ts +134 -16
  59. package/src/repair-fetch.ts +366 -50
  60. 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
@@ -12951,6 +13063,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
12951
13063
  #newest;
12952
13064
  #newestSource;
12953
13065
  #holes;
13066
+ #expired;
13067
+ #newlyExpired;
13068
+ #closedBehind;
12954
13069
  static #checkedRetention(retentionBlocks) {
12955
13070
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
12956
13071
  throw new Error(
@@ -13020,17 +13135,29 @@ var IsoBlockLocator = class _IsoBlockLocator {
13020
13135
  }
13021
13136
  /** The known block or span containing `ssId`, with its ESI. */
13022
13137
  locate(ssId) {
13023
- for (let i = this.#blocks.length - 1; i >= 0; i--) {
13024
- const block = this.#blocks[i];
13025
- if (isoBlockContains(block.start, block.length, ssId)) {
13026
- return { block, esi: serial32Distance(block.start, ssId) };
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
+ }
13027
13144
  }
13028
13145
  }
13029
13146
  return null;
13030
13147
  }
13031
- /** Number of pending holes. */
13148
+ /** Number of holes not closed yet, pending or past the horizon. */
13032
13149
  get holeCount() {
13033
- 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);
13034
13161
  }
13035
13162
  /** The stated block (never a span) ending exactly at `end`. */
13036
13163
  blockEndingAt(end) {
@@ -13086,9 +13213,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
13086
13213
  /**
13087
13214
  * Apply one repair symbol's `(SS_Start, SSB_length)`. The first repair of a
13088
13215
  * block states its range and places every held source in it; later repair
13089
- * symbols of the same block change nothing. A range that contradicts a
13090
- * known block (a different length, or an overlap with another block or a
13091
- * span) fails closed: the repair symbol is dropped and no block changes.
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.
13092
13221
  * A newly stated block retires behind its SS_Start (see the class note).
13093
13222
  * A block so far past `newest` that stating it would retire the position
13094
13223
  * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
@@ -13107,7 +13236,16 @@ var IsoBlockLocator = class _IsoBlockLocator {
13107
13236
  const known = this.blockAt(start);
13108
13237
  if (known !== void 0) {
13109
13238
  if (known.span) {
13110
- 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}` };
13111
13249
  }
13112
13250
  if (known.length !== length) {
13113
13251
  return {
@@ -13175,18 +13313,28 @@ var IsoBlockLocator = class _IsoBlockLocator {
13175
13313
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
13176
13314
  }
13177
13315
  /**
13178
- * Turn every pending hole inside `[start, start + length)` into a
13179
- * repair-less span, claiming its held sources: its range FETCH ended, so
13180
- * nothing more will state its blocks. Returns the spans, in SS_ID order.
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.
13181
13322
  */
13182
13323
  closeHolesWithin(start, length) {
13183
13324
  const closed = [];
13184
- for (const hole of [...this.#holes]) {
13185
- if (!isoBlockContains(start, length, hole.start)) continue;
13186
- this.#holes.splice(this.#holes.indexOf(hole), 1);
13187
- const spanBlock = { start: hole.start, length: hole.length, span: true };
13188
- closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
13189
- this.#blocks.push(spanBlock);
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
+ }
13190
13338
  }
13191
13339
  return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
13192
13340
  }
@@ -13200,15 +13348,17 @@ var IsoBlockLocator = class _IsoBlockLocator {
13200
13348
  return void 0;
13201
13349
  }
13202
13350
  /**
13203
- * Retire every block and span whose last SS_ID, and every held source,
13204
- * lies more than `retentionBlocks` blocks behind `position`, with the shared
13205
- * lower-bound metric (`isoBlocksBehindLowerBound`) every ISO interleave
13206
- * horizon uses. Returns the retired block starts.
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.
13207
13356
  */
13208
13357
  retireBehind(position) {
13209
13358
  this.observe(position);
13210
13359
  const horizon = this.#retentionBlocks;
13211
13360
  const retired = [];
13361
+ this.#closedBehind.length = 0;
13212
13362
  for (let i = this.#blocks.length - 1; i >= 0; i--) {
13213
13363
  const block = this.#blocks[i];
13214
13364
  const last = serial32Add(block.start, block.length - 1);
@@ -13220,10 +13370,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
13220
13370
  for (let i = this.#holes.length - 1; i >= 0; i--) {
13221
13371
  const hole = this.#holes[i];
13222
13372
  const last = serial32Add(hole.start, hole.length - 1);
13223
- 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);
13224
13377
  }
13225
13378
  for (const ssId of [...this.#held.keys()]) {
13226
- 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
+ }
13227
13382
  }
13228
13383
  return retired;
13229
13384
  }
@@ -13231,6 +13386,9 @@ var IsoBlockLocator = class _IsoBlockLocator {
13231
13386
  reset() {
13232
13387
  this.#blocks.length = 0;
13233
13388
  this.#holes.length = 0;
13389
+ this.#expired.length = 0;
13390
+ this.#newlyExpired.length = 0;
13391
+ this.#closedBehind.length = 0;
13234
13392
  this.#held.clear();
13235
13393
  this.#coverageEnd = void 0;
13236
13394
  this.#newest = void 0;
@@ -13948,6 +14106,10 @@ var FECManager = class _FECManager {
13948
14106
  // 'pending' forever, which would park every later frame of its stream in
13949
14107
  // the in-order release gate. Each entry owns its handle; the callback
13950
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
+ */
13951
14113
  this.#pendingWorkerCleanupBounds = /* @__PURE__ */ new Map();
13952
14114
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
13953
14115
  this.#blockSourceCounts = /* @__PURE__ */ new Map();
@@ -13964,10 +14126,14 @@ var FECManager = class _FECManager {
13964
14126
  // SSB_length source arrivals and recoverable from SSB_length received
13965
14127
  // symbols; waiting for K fails every one of them.
13966
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();
13967
14132
  this.#ssbLengthConflictCount = 0;
13968
14133
  this.#blockRepairRsIds = /* @__PURE__ */ new Map();
13969
14134
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
13970
- // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
14135
+ // symbols its repair group carries; 0 for a repair-less span no repair can
14136
+ // state (#openIsoSpan). Same lifecycle as #blockRepairRsIds.
13971
14137
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
13972
14138
  /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
13973
14139
  this.#heldLayerStates = /* @__PURE__ */ new Map();
@@ -14161,7 +14327,10 @@ var FECManager = class _FECManager {
14161
14327
  // arrives via onBlockRecovered callback.
14162
14328
  this.onBlockStarted = null;
14163
14329
  this.onBlockComplete = null;
14164
- /** A block reached its fail bound. `blockClass` is its class at failure. */
14330
+ /**
14331
+ * A block reached its fail bound. `blockClass` is its class at failure.
14332
+ * `span` is set when what failed is a repair-less span starting at `sbn`.
14333
+ */
14165
14334
  this.onBlockFailed = null;
14166
14335
  /**
14167
14336
  * Fired once per stream when its Worker decoder stops being routable.
@@ -14203,12 +14372,24 @@ var FECManager = class _FECManager {
14203
14372
  * for it, which it must be.
14204
14373
  */
14205
14374
  this.#onUndelimitedLoss = null;
14375
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
14376
+ this.#onIsoHoleExpired = null;
14206
14377
  /** A block every symbol of which vanished was created by SBN evidence. */
14207
14378
  this.onBlockVanished = null;
14208
14379
  /** A block reached a terminal state (completed, recovered, or failed). */
14209
14380
  this.onBlockResolved = null;
14210
14381
  /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
14211
14382
  this.onSourceDiscontinuity = null;
14383
+ /**
14384
+ * The span and tolerance the catalog states for a keyframe overlay
14385
+ * installed over a source track (draft-ramadan-moq-mmt-02 7.4.1: the
14386
+ * overlay instance's own interleaveDepthMs and reorderToleranceMs), or
14387
+ * undefined while none is installed. A stated block only a late source
14388
+ * can complete, and a frame whose gap may hide a RAP behind a span only a
14389
+ * late source can fill, also wait for that overlay's repair
14390
+ * (#overlayLateWaitMs).
14391
+ */
14392
+ this.keyframeOverlayTiming = null;
14212
14393
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
14213
14394
  /**
14214
14395
  * A recovered source symbol. Return false when admission refused the
@@ -14247,6 +14428,7 @@ var FECManager = class _FECManager {
14247
14428
  #blockSourceEsis;
14248
14429
  #blockRebuiltEsis;
14249
14430
  #blockAuthoredLengths;
14431
+ #isoSpanKeys;
14250
14432
  #ssbLengthConflictCount;
14251
14433
  #blockRepairRsIds;
14252
14434
  #blockRsbLengths;
@@ -14313,6 +14495,7 @@ var FECManager = class _FECManager {
14313
14495
  #decoderUnavailableEvents;
14314
14496
  #repairSymbolSizeMismatchCount;
14315
14497
  #onUndelimitedLoss;
14498
+ #onIsoHoleExpired;
14316
14499
  #encodeTrackName(catalogTrackName) {
14317
14500
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
14318
14501
  if (encoded === void 0) {
@@ -14784,7 +14967,10 @@ var FECManager = class _FECManager {
14784
14967
  timer.handle = null;
14785
14968
  this.#requestRepair(sbn, packetId, catalogTrackName);
14786
14969
  };
14787
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
14970
+ timer.handle = setTimeout(
14971
+ onFire,
14972
+ this.#receiptAtMs === void 0 ? Math.max(0, deadlineMs - performance.now()) : this.#receiptTimerDelayMs(deadlineMs, 0)
14973
+ );
14788
14974
  this.#repairDeadlines.set(key, timer);
14789
14975
  }
14790
14976
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -14928,8 +15114,14 @@ var FECManager = class _FECManager {
14928
15114
  * Vanished blocks are not enumerated here: their starts are unknown until a
14929
15115
  * repair states them. The SS_IDs between two stated blocks become one
14930
15116
  * repair-less span when the later block's repair arrives (placeIsoRepair).
15117
+ *
15118
+ * A `held` source arrived before its block was known and is fed only now
15119
+ * that a repair, a span or a closed hole placed it: how far its block start
15120
+ * then lies behind the frontier measures how long the receiver held it, not
15121
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
15122
+ * it (BLO-52085).
14931
15123
  */
14932
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
15124
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn, held = false) {
14933
15125
  const streamKey = this.#streamKey(packetId, catalogTrackName);
14934
15126
  const now = performance.now();
14935
15127
  const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
@@ -14968,7 +15160,7 @@ var FECManager = class _FECManager {
14968
15160
  return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
14969
15161
  };
14970
15162
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
14971
- if (symbol === "source" && window2 !== null && this.#blockPrecedes(sbn, previous.sbn) && (this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId) || psn !== void 0 && anchor !== void 0 && serial32Precedes(ssId, anchor.ssId) && psn !== anchor.psn && !sentInOrder({ ssId, psn }, anchor))) {
15163
+ if (symbol === "source" && window2 !== null && this.#blockPrecedes(sbn, previous.sbn) && (!held && this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId) || psn !== void 0 && anchor !== void 0 && serial32Precedes(ssId, anchor.ssId) && psn !== anchor.psn && !sentInOrder({ ssId, psn }, anchor))) {
14972
15164
  discontinuity();
14973
15165
  return;
14974
15166
  }
@@ -15230,17 +15422,21 @@ var FECManager = class _FECManager {
15230
15422
  this.#blockWaitDeadlinesMs.delete(key);
15231
15423
  this.#repairHoldUntilMs.delete(key);
15232
15424
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
15233
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName);
15425
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs);
15234
15426
  };
15235
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)));
15427
+ timer.handle = setTimeout(
15428
+ onFire,
15429
+ this.#receiptAtMs === void 0 ? Math.max(1, Math.ceil(deadlineMs - nowMs)) : this.#receiptTimerDelayMs(deadlineMs, 1)
15430
+ );
15236
15431
  this.#activeBlocks.set(key, timer);
15237
15432
  this.#indexBlockKey(key, sbn, packetId);
15238
15433
  }
15239
15434
  /**
15240
15435
  * Hand a block whose delivery is over to its decoder for finalization: the
15241
- * datagram deadline fired, or the ordered relay moved past it.
15436
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
15437
+ * is when it was due: its deadline, or now.
15242
15438
  */
15243
- #finalizeExpiredBlock(sbn, packetId, catalogTrackName) {
15439
+ #finalizeExpiredBlock(sbn, packetId, catalogTrackName, dueAtMs = performance.now()) {
15244
15440
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
15245
15441
  if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
15246
15442
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -15256,7 +15452,7 @@ var FECManager = class _FECManager {
15256
15452
  if (workerClient) {
15257
15453
  this.#pendingWorkerCleanups.add(key);
15258
15454
  this.#pendingWorkerCleanupClients.set(key, workerClient);
15259
- this.#boundOwedCleanup(key, packetId, workerClient);
15455
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs);
15260
15456
  workerClient.cleanup(sbn);
15261
15457
  } else {
15262
15458
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
@@ -15570,6 +15766,7 @@ var FECManager = class _FECManager {
15570
15766
  resetMap(this.#blockSourceEsis);
15571
15767
  resetMap(this.#blockRebuiltEsis);
15572
15768
  resetMap(this.#blockAuthoredLengths);
15769
+ resetSet(this.#isoSpanKeys);
15573
15770
  resetMap(this.#blockRepairRsIds);
15574
15771
  resetMap(this.#blockRsbLengths);
15575
15772
  resetMap(this.#heldLayerStates);
@@ -15695,6 +15892,7 @@ var FECManager = class _FECManager {
15695
15892
  dropMap(this.#blockSourceEsis);
15696
15893
  dropMap(this.#blockRebuiltEsis);
15697
15894
  dropMap(this.#blockAuthoredLengths);
15895
+ dropSet(this.#isoSpanKeys);
15698
15896
  dropMap(this.#blockRepairRsIds);
15699
15897
  dropMap(this.#blockRsbLengths);
15700
15898
  dropMap(this.#blockPathCounts);
@@ -15968,8 +16166,10 @@ var FECManager = class _FECManager {
15968
16166
  }
15969
16167
  /**
15970
16168
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
15971
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
15972
- * Undefined for a block that is not open.
16169
+ * (SSB_length) and RSB_length (each undefined until a repair stated it; a
16170
+ * repair-less span states its length, and RSB_length 0 when it is longer
16171
+ * than K, since no repair can reach it). Undefined for a block that is not
16172
+ * open.
15973
16173
  */
15974
16174
  blockSymbolCounts(sbn, packetId, catalogTrackName) {
15975
16175
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -16037,8 +16237,9 @@ var FECManager = class _FECManager {
16037
16237
  return true;
16038
16238
  }
16039
16239
  /**
16040
- * Drop a block's repair hold: its FETCH ended without delivering. The block
16041
- * falls back to its multicast wait, which may already have passed.
16240
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
16241
+ * back only a repair that cannot complete it. The block falls back to its
16242
+ * multicast wait, which may already have passed.
16042
16243
  */
16043
16244
  releaseRepairHold(sbn, packetId, catalogTrackName) {
16044
16245
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -16176,6 +16377,7 @@ var FECManager = class _FECManager {
16176
16377
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
16177
16378
  const evictedBefore = locator.heldEvicted;
16178
16379
  const held = locator.hold(ssId, source);
16380
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
16179
16381
  if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
16180
16382
  const evicted = locator.heldEvicted - evictedBefore;
16181
16383
  if (evicted > 0) {
@@ -16197,17 +16399,20 @@ var FECManager = class _FECManager {
16197
16399
  * contradicts a known block is refused (counted) and must be dropped.
16198
16400
  */
16199
16401
  placeIsoRepair(packetId, catalogTrackName, ssStart, ssbLength) {
16200
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength);
16402
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
16403
+ const placement = locator.placeRepair(ssStart, ssbLength);
16404
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
16201
16405
  if (placement.status !== "placed") {
16202
16406
  this.#isoRepairRefusedCount++;
16203
16407
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
16204
16408
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`);
16205
16409
  }
16410
+ if (placement.ofSpan !== void 0) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName);
16206
16411
  return placement;
16207
16412
  }
16413
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName));
16208
16414
  if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
16209
16415
  if (placement.hole !== void 0) {
16210
- const locator = this.#isoLocatorFor(packetId, catalogTrackName);
16211
16416
  const hole = placement.hole.block;
16212
16417
  const previous = locator.blockEndingAt(hole.start);
16213
16418
  const loss = {
@@ -16228,17 +16433,29 @@ var FECManager = class _FECManager {
16228
16433
  * `handler`, instead of a repair-less span; null restores spans. Set by the
16229
16434
  * range repair scheduler; applies to every stream from its next gap. The
16230
16435
  * handler and the deferral are one setting, so no hole is ever created with
16231
- * nobody to close it.
16436
+ * nobody to close it. `onExpired` is told of each pending hole the stream
16437
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
16438
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
16439
+ * reported; otherwise the hole is discarded with its sources.
16232
16440
  */
16233
- setUndelimitedLossHandler(handler) {
16441
+ setUndelimitedLossHandler(handler, onExpired = null) {
16234
16442
  this.#onUndelimitedLoss = handler;
16443
+ this.#onIsoHoleExpired = handler === null ? null : onExpired;
16235
16444
  this.#deferIsoGaps = handler !== null;
16236
16445
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
16237
16446
  }
16447
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
16448
+ #settleExpiredIsoHoles(locator, packetId, catalogTrackName) {
16449
+ for (const hole of locator.takeExpiredHoles()) {
16450
+ const expired = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length };
16451
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length);
16452
+ }
16453
+ }
16238
16454
  /**
16239
- * The range repair for a hole ended: every hole still pending inside
16240
- * `[start, start + length)` becomes a repair-less span. Returns those spans
16241
- * with the held sources they placed, for the caller to feed (MmtpRouter).
16455
+ * The range repair for a hole ended: every hole inside `[start, start +
16456
+ * length)`, pending or expired, becomes a repair-less span. Returns those
16457
+ * spans with the held sources they placed, for the caller to feed
16458
+ * (MmtpRouter).
16242
16459
  */
16243
16460
  closeIsoHoles(packetId, catalogTrackName, start, length) {
16244
16461
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
@@ -16254,10 +16471,25 @@ var FECManager = class _FECManager {
16254
16471
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
16255
16472
  * SS_ID of which vanished resolves through its deadline like any vanished
16256
16473
  * block.
16474
+ *
16475
+ * A span longer than K holds more than one block (SSB_length <= K), and the
16476
+ * locator states no block inside a span, only one exactly its range
16477
+ * (IsoBlockLocator.placeRepair): no repair, multicast or FETCHed, can ever
16478
+ * reach it. Its repair group is empty, so the repair scheduler FETCHes no
16479
+ * Group of it (group-cannot-complete). Every span still keeps its whole
16480
+ * wait (#lateSourceWaitMs): failing it early released the frames behind it
16481
+ * past a keyframe the overlay was still rebuilding (BLO-52085). The release
16482
+ * gate lets those frames go once only a late source can fill the gap
16483
+ * before them, as long after they arrived as the gap's decision allows
16484
+ * (isoRepairlessWaitMs).
16257
16485
  */
16258
16486
  #openIsoSpan(span, packetId, catalogTrackName) {
16259
16487
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
16260
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
16488
+ if (!this.#blockAuthoredLengths.has(key)) {
16489
+ this.#blockAuthoredLengths.set(key, span.block.length);
16490
+ this.#isoSpanKeys.add(key);
16491
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0);
16492
+ }
16261
16493
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
16262
16494
  }
16263
16495
  /**
@@ -16295,6 +16527,50 @@ var FECManager = class _FECManager {
16295
16527
  }
16296
16528
  return lost;
16297
16529
  }
16530
+ /**
16531
+ * The release gate's wait, from a frame's arrival, for the SS_IDs strictly
16532
+ * between two released frames' SS_IDs once only a late source can still
16533
+ * fill them, else undefined. That is when every one missing (neither
16534
+ * arrived nor held) lies in a repair-less span longer than K, which no
16535
+ * repair can state a block of (#openIsoSpan), and a multicast source at or
16536
+ * past `toSsId` arrived, so each is lost or reordered behind it (a MoQ
16537
+ * source shows nothing: MoQ streams overtake one another). The span itself
16538
+ * keeps its whole wait.
16539
+ *
16540
+ * The wait is the late-symbol allowance, unless `rapMayHide`: the gap may
16541
+ * hold a RAP packet an installed keyframe overlay can still rebuild (its
16542
+ * decision stalls, or it ends at a RAP that may lie past a whole MPU).
16543
+ * Then the frame waits as a stated block its group cannot complete does
16544
+ * (#overlayLateWaitMs): the allowance alone with no overlay installed, the
16545
+ * overlay's span plus the larger of the allowance and its tolerance, or,
16546
+ * for an overlay that states no span, the span's whole wait (undefined).
16547
+ */
16548
+ isoRepairlessWaitMs(packetId, catalogTrackName, fromSsId, toSsId, rapMayHide = false) {
16549
+ const config = this.#trackConfigs.get(packetId);
16550
+ if (config === void 0 || !_FECManager.#hasCatalogTiming(config)) return void 0;
16551
+ const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
16552
+ if (locator === void 0 || !locator.coversBetween(fromSsId, toSsId)) return void 0;
16553
+ const newestSource = locator.newestSource;
16554
+ if (newestSource === void 0 || serial32Precedes(newestSource, toSsId)) return void 0;
16555
+ let repairless = false;
16556
+ for (const block of locator.blocksBetween(fromSsId, toSsId)) {
16557
+ const key = this.#blockKey(block.start, packetId, catalogTrackName);
16558
+ if (this.#completedBlocks.has(key)) continue;
16559
+ if (block.span && block.length > locator.kMax) {
16560
+ repairless = true;
16561
+ continue;
16562
+ }
16563
+ const received = this.#blockSourceEsis.get(key);
16564
+ for (let esi = 0; esi < block.length; esi++) {
16565
+ const ssId = serial32Add(block.start, esi);
16566
+ if (!serial32Precedes(fromSsId, ssId) || !serial32Precedes(ssId, toSsId)) continue;
16567
+ if (!received?.has(esi) && !locator.isHeld(ssId)) return void 0;
16568
+ }
16569
+ }
16570
+ if (!repairless) return void 0;
16571
+ const waitMs = rapMayHide ? this.#overlayLateWaitMs(packetId, catalogTrackName, config) : this.#multicastWaitMs(config) - config.interleaveDepthMs;
16572
+ return waitMs === void 0 ? void 0 : Math.max(0, waitMs);
16573
+ }
16298
16574
  /**
16299
16575
  * iso-ssbg1-v1 block location: repair symbols it refused, oversize sources,
16300
16576
  * the sources held now for a block no repair has stated yet, and the held
@@ -16598,11 +16874,14 @@ var FECManager = class _FECManager {
16598
16874
  });
16599
16875
  client.onCleanupComplete((sbn) => {
16600
16876
  if (this.#releasedWorkerClients.has(client)) return;
16601
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
16877
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
16878
+ const cleanupKeys = owed.filter((key) => {
16602
16879
  const block = this.#parseBlockKey(key);
16603
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
16880
+ return block.packetId === packetId && block.sbn === sbn;
16604
16881
  });
16605
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
16882
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
16883
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
16884
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
16606
16885
  });
16607
16886
  client.onError((msg, code) => {
16608
16887
  const requestedKind = code ?? msg;
@@ -16672,9 +16951,11 @@ var FECManager = class _FECManager {
16672
16951
  * fail deadline already passed, so failing it is the decision that deadline
16673
16952
  * made. A late ack then finds nothing owed and is a no-op.
16674
16953
  */
16675
- #boundOwedCleanup(key, packetId, client) {
16954
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
16676
16955
  this.#clearOwedCleanupBound(key);
16677
16956
  const bound = {
16957
+ dueAtMs,
16958
+ askedAtMs: performance.now(),
16678
16959
  handle: setTimeout(() => {
16679
16960
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
16680
16961
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -17095,7 +17376,7 @@ var FECManager = class _FECManager {
17095
17376
  const previous = locator.newestSource;
17096
17377
  if (!locator.noteSource(ssId) || previous === void 0) return;
17097
17378
  for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
17098
- if (block.span || !serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
17379
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
17099
17380
  this.#shortenUnrecoverableWait(
17100
17381
  this.#blockKey(block.start, packetId, catalogTrackName),
17101
17382
  block.start,
@@ -17113,9 +17394,16 @@ var FECManager = class _FECManager {
17113
17394
  * covers repair symbols paced after its sources, buys it nothing: it waits
17114
17395
  * the late-symbol allowance alone, the multicast wait less the span (the
17115
17396
  * catalog tolerance or the measured delivery gap). Undefined for any other
17116
- * block.
17397
+ * block. While a keyframe overlay is installed, the block waits for its
17398
+ * repair too (#overlayLateWaitMs). A repair-less span keeps its whole
17399
+ * wait, even one longer than K whose group is empty (#openIsoSpan): its
17400
+ * resolution is what releases the frames behind it, and failing it early
17401
+ * released them past a keyframe the overlay was still rebuilding, which
17402
+ * then arrived stale. The release gate lets them go instead
17403
+ * (isoRepairlessWaitMs).
17117
17404
  */
17118
17405
  #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
17406
+ if (this.#isoSpanKeys.has(key)) return void 0;
17119
17407
  const authoredLength = this.#blockAuthoredLengths.get(key);
17120
17408
  const rsbLength = this.#blockRsbLengths.get(key);
17121
17409
  if (authoredLength === void 0 || rsbLength === void 0) return void 0;
@@ -17127,7 +17415,33 @@ var FECManager = class _FECManager {
17127
17415
  if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
17128
17416
  return void 0;
17129
17417
  }
17130
- return this.#multicastWaitMs(config) - config.interleaveDepthMs;
17418
+ return this.#overlayLateWaitMs(packetId, catalogTrackName, config);
17419
+ }
17420
+ /**
17421
+ * How long a loss only a late source or an installed keyframe overlay can
17422
+ * still fill waits once a later source passed it: the late-symbol
17423
+ * allowance alone (the multicast wait less the span) while no overlay is
17424
+ * installed. An installed one (keyframeOverlayTiming) may still rebuild a
17425
+ * RAP packet the loss took: a second FEC instance over the same packets
17426
+ * (draft-ramadan-moq-mmt-02 7.4), whose repair is paced across its own
17427
+ * span, unrelated to the base's. That packet can complete a stated block
17428
+ * (feedRebuiltSourceSymbol), or play behind a span; giving the loss up
17429
+ * first lets the release gate pass the keyframe, whose rebuild then lands
17430
+ * stale. The overlay repair of a packet the loss took goes out within the
17431
+ * overlay's span of that packet (fec-core-00 9.3), and the later source was
17432
+ * sent after it, so the loss waits that span plus the larger of the
17433
+ * allowance and the overlay's own tolerance. An overlay that states no
17434
+ * span (its block may then span keyframes), or one whose wait is not
17435
+ * shorter than the whole multicast wait, leaves the whole wait: undefined.
17436
+ */
17437
+ #overlayLateWaitMs(packetId, catalogTrackName, config) {
17438
+ const waitMs = this.#multicastWaitMs(config);
17439
+ const allowanceMs = waitMs - config.interleaveDepthMs;
17440
+ const overlay = this.keyframeOverlayTiming?.(packetId, catalogTrackName);
17441
+ if (overlay === void 0) return allowanceMs;
17442
+ const overlaySpanMs = overlay.interleaveDepthMs ?? 0;
17443
+ const overlayWaitMs = overlaySpanMs + Math.max(allowanceMs, overlay.reorderToleranceMs ?? 0);
17444
+ return overlaySpanMs > 0 && overlayWaitMs < waitMs ? overlayWaitMs : void 0;
17131
17445
  }
17132
17446
  /**
17133
17447
  * Bring an open block's wait in to its late-source wait, when it has one.
@@ -17245,12 +17559,13 @@ var FECManager = class _FECManager {
17245
17559
  * the inactivity deadline on each symbol, records the symbol's in-band
17246
17560
  * classification evidence, and marks the block clean when all of its
17247
17561
  * authored source symbols arrived: the SSB_length a repair symbol declared,
17248
- * otherwise K.
17562
+ * otherwise K. `held` marks a source held unplaced since it arrived and
17563
+ * placed only now (see #noteSbnSeen).
17249
17564
  *
17250
17565
  * Throws for a packetId that was never configured, so a classified block
17251
17566
  * never reads the manager-global K or timeout.
17252
17567
  */
17253
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
17568
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
17254
17569
  const trackConfig = this.#trackConfigs.get(packetId);
17255
17570
  if (trackConfig === void 0) {
17256
17571
  throw new Error(
@@ -17266,7 +17581,8 @@ var FECManager = class _FECManager {
17266
17581
  catalogTrackName,
17267
17582
  "source",
17268
17583
  evidence.packetSequenceNumber,
17269
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
17584
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
17585
+ held
17270
17586
  );
17271
17587
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
17272
17588
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -17321,6 +17637,7 @@ var FECManager = class _FECManager {
17321
17637
  this.#blockSourceEsis.delete(key);
17322
17638
  this.#blockRebuiltEsis.delete(key);
17323
17639
  this.#blockAuthoredLengths.delete(key);
17640
+ this.#isoSpanKeys.delete(key);
17324
17641
  this.#blockRepairRsIds.delete(key);
17325
17642
  this.#blockRsbLengths.delete(key);
17326
17643
  this.#markTerminal(key, sbn, packetId, true);
@@ -17351,6 +17668,19 @@ var FECManager = class _FECManager {
17351
17668
  #receiptNow() {
17352
17669
  return this.#receiptAtMs ?? performance.now();
17353
17670
  }
17671
+ /**
17672
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
17673
+ * scope: counted from the receipt time, as the timer of a symbol fed when
17674
+ * it was received was, less the whole ms since. So it fires on the tick
17675
+ * that timer would have, never later than a delay counted from now, and
17676
+ * its handler still re-arms a timer that fires before its deadline.
17677
+ * Counted from now, a deadline set from the receipt time is rounded up
17678
+ * from another fraction of a ms (BLO-52085).
17679
+ */
17680
+ #receiptTimerDelayMs(deadlineMs, minMs) {
17681
+ const receivedAtMs = this.#receiptAtMs;
17682
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
17683
+ }
17354
17684
  /**
17355
17685
  * A held packet admitted late arms from its (earlier) receipt time; that
17356
17686
  * never pulls in a deadline later activity already armed. Outside a
@@ -17399,6 +17729,7 @@ var FECManager = class _FECManager {
17399
17729
  }
17400
17730
  #failBlock(sbn, packetId, catalogTrackName) {
17401
17731
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
17732
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
17402
17733
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
17403
17734
  this.#clearRepairDeadline(key);
17404
17735
  this.#clearBlockTimer(key);
@@ -17418,7 +17749,8 @@ var FECManager = class _FECManager {
17418
17749
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
17419
17750
  this.#fecStats.blocksFailed++;
17420
17751
  this.#statsForPacket(packetId).blocksFailed++;
17421
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
17752
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
17753
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
17422
17754
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
17423
17755
  }
17424
17756
  /**
@@ -17449,6 +17781,7 @@ var FECManager = class _FECManager {
17449
17781
  this.#blockSourceEsis.delete(key);
17450
17782
  this.#blockRebuiltEsis.delete(key);
17451
17783
  this.#blockAuthoredLengths.delete(key);
17784
+ this.#isoSpanKeys.delete(key);
17452
17785
  this.#blockRepairRsIds.delete(key);
17453
17786
  this.#blockRsbLengths.delete(key);
17454
17787
  this.#clearBlockTimer(key);
@@ -17541,6 +17874,7 @@ var FECManager = class _FECManager {
17541
17874
  this.#blockSourceEsis.clear();
17542
17875
  this.#blockRebuiltEsis.clear();
17543
17876
  this.#blockAuthoredLengths.clear();
17877
+ this.#isoSpanKeys.clear();
17544
17878
  this.#blockRepairRsIds.clear();
17545
17879
  this.#blockRsbLengths.clear();
17546
17880
  this.#heldLayerStates.clear();
@@ -18442,6 +18776,9 @@ function authoredGap(before, after) {
18442
18776
  function ssIdAfter(a, b) {
18443
18777
  return (a - b | 0) > 0;
18444
18778
  }
18779
+ function holdsRebuilt(stream) {
18780
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
18781
+ }
18445
18782
  var FecReleaseSequencer = class {
18446
18783
  #streams = /* @__PURE__ */ new Map();
18447
18784
  #gate;
@@ -18504,6 +18841,7 @@ var FecReleaseSequencer = class {
18504
18841
  stream.lastSbn = void 0;
18505
18842
  stream.discontinuity = false;
18506
18843
  stream.rapSsId = void 0;
18844
+ stream.sourced = false;
18507
18845
  }
18508
18846
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
18509
18847
  this.#recordStat("droppedStale");
@@ -18530,6 +18868,7 @@ var FecReleaseSequencer = class {
18530
18868
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
18531
18869
  else hi = mid;
18532
18870
  }
18871
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
18533
18872
  stream.buf.splice(lo, 0, frame);
18534
18873
  this.#drainUnlessDeferred(stream);
18535
18874
  }
@@ -18565,6 +18904,41 @@ var FecReleaseSequencer = class {
18565
18904
  }
18566
18905
  return false;
18567
18906
  }
18907
+ /**
18908
+ * These streams' sink is being replaced by one that has seen no source
18909
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
18910
+ * release to the sink being replaced the frames the unanchored path had
18911
+ * already released to it (#cursorPassed): there they waited in its queue,
18912
+ * which its replacement flushes. A stream that holds none is not drained:
18913
+ * it holds nothing the anchor kept back, and a drain would still force out
18914
+ * a frame held past the hold limit, which before the anchor waited for the
18915
+ * next push. Then treat the streams as unsourced until a source frame is
18916
+ * released.
18917
+ */
18918
+ unsource(packetId, catalogTrackName) {
18919
+ for (const stream of this.#streams.values()) {
18920
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
18921
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
18922
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
18923
+ else this.#drain(stream, true);
18924
+ }
18925
+ stream.sourced = false;
18926
+ }
18927
+ }
18928
+ }
18929
+ /**
18930
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
18931
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
18932
+ * packetId.
18933
+ */
18934
+ holdsRebuilt(packetId, catalogTrackName) {
18935
+ for (const stream of this.#streams.values()) {
18936
+ if (stream.packetId !== packetId) continue;
18937
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
18938
+ if (holdsRebuilt(stream)) return true;
18939
+ }
18940
+ return false;
18941
+ }
18568
18942
  /** Re-evaluate held gaps after FEC state changed. */
18569
18943
  poke(streamKey) {
18570
18944
  if (streamKey !== void 0) {
@@ -18656,16 +19030,32 @@ var FecReleaseSequencer = class {
18656
19030
  last: null,
18657
19031
  lastSbn: void 0,
18658
19032
  discontinuity: false,
18659
- rapSsId: void 0
19033
+ rapSsId: void 0,
19034
+ sourced: false,
19035
+ draining: 0
18660
19036
  };
18661
19037
  this.#streams.set(streamKey, stream);
18662
19038
  }
18663
19039
  return stream;
18664
19040
  }
18665
- #drain(stream) {
19041
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
19042
+ #drain(stream, asUnanchored = false) {
19043
+ stream.draining++;
19044
+ try {
19045
+ this.#drainLoop(stream, asUnanchored);
19046
+ } finally {
19047
+ stream.draining--;
19048
+ }
19049
+ }
19050
+ #drainLoop(stream, asUnanchored) {
18666
19051
  while (stream.buf.length > 0 && stream.last !== null) {
18667
19052
  const head = stream.buf[0];
18668
19053
  const last = stream.last;
19054
+ if (compareFrameOrder(head, last) <= 0) {
19055
+ stream.buf.shift();
19056
+ this.#release(stream, head, void 0);
19057
+ continue;
19058
+ }
18669
19059
  if (stream.discontinuity) {
18670
19060
  stream.discontinuity = false;
18671
19061
  stream.buf.shift();
@@ -18679,9 +19069,10 @@ var FecReleaseSequencer = class {
18679
19069
  }
18680
19070
  const headSbn = head.meta.fecSbn;
18681
19071
  const from = stream.lastSbn ?? headSbn;
18682
- const to = headSbn ?? stream.lastSbn;
19072
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
18683
19073
  let lost = [];
18684
19074
  const unanchored = from === void 0 && to === void 0;
19075
+ let unresolved = false;
18685
19076
  if (from !== void 0 && to !== void 0) {
18686
19077
  const resolved = this.#gate.resolvedLoss(
18687
19078
  stream.packetId,
@@ -18690,7 +19081,8 @@ var FecReleaseSequencer = class {
18690
19081
  Math.max(from, to),
18691
19082
  from
18692
19083
  );
18693
- if (resolved === null) {
19084
+ unresolved = resolved === null;
19085
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored) && !this.#unrepairableWaitOver(last, head, from, to)) {
18694
19086
  const heldMs = performance.now() - head.arrivedAtMs;
18695
19087
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
18696
19088
  this.#recordStat("forcedWindowFlushes");
@@ -18698,22 +19090,61 @@ var FecReleaseSequencer = class {
18698
19090
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
18699
19091
  continue;
18700
19092
  }
18701
- lost = resolved;
19093
+ lost = resolved ?? [];
18702
19094
  }
18703
19095
  stream.buf.shift();
18704
19096
  this.#release(
18705
19097
  stream,
18706
19098
  head,
18707
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
19099
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
18708
19100
  );
18709
19101
  }
18710
19102
  }
19103
+ /** The head has waited out a gap only a late source can still fill (FecReleaseGate.unrepairableWaitMs). */
19104
+ #unrepairableWaitOver(last, head, from, to) {
19105
+ const waitMs = this.#gate.unrepairableWaitMs?.(last, head, from, to);
19106
+ return waitMs !== void 0 && performance.now() - head.arrivedAtMs >= waitMs;
19107
+ }
19108
+ /**
19109
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
19110
+ * source cursor holds it unanchored, and neither does a later frame behind
19111
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
19112
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
19113
+ * like each frame that arrived in front of it since (stale there). The head
19114
+ * then goes, decided as it would be unanchored, once a frame the base path
19115
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
19116
+ * marked one: the base path has passed that one, so a frame still missing
19117
+ * before it can only come from a repair. It also goes while no source frame
19118
+ * has been released, when the direct path shows a recovered frame at once.
19119
+ * And it goes at once while a staged switch decides on when frames arrive
19120
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
19121
+ * sink being replaced: unanchored, it had already reached the sink.
19122
+ * The scan also writes: the `passed` marks it sets stay on the frames,
19123
+ * and push marks a frame it inserts in front of a marked one from them.
19124
+ */
19125
+ #cursorPassed(stream, asUnanchored) {
19126
+ let at2 = -1;
19127
+ for (let i = 0; i < stream.buf.length; i++) {
19128
+ const frame = stream.buf[i];
19129
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
19130
+ frame.passed = true;
19131
+ if (at2 < 0) at2 = i;
19132
+ } else if (frame.passed !== true) break;
19133
+ }
19134
+ if (at2 < 0) return false;
19135
+ 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));
19136
+ }
18711
19137
  #release(stream, frame, decision) {
19138
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
19139
+ if (stale) this.#recordStat("droppedStale");
18712
19140
  if (decision) frame.meta.gapBefore = decision;
18713
19141
  stream.last = frame;
18714
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
19142
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
19143
+ stream.lastSbn = frame.meta.fecSbn;
19144
+ }
19145
+ if (frame.meta.recovered !== true) stream.sourced = true;
18715
19146
  this.#gate.onReleased?.(frame.data, frame.meta);
18716
- this.#emit(frame.data, frame.meta);
19147
+ if (!stale) this.#emit(frame.data, frame.meta);
18717
19148
  }
18718
19149
  };
18719
19150
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -19039,6 +19470,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
19039
19470
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
19040
19471
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
19041
19472
  }
19473
+ /** See FecReleaseSequencer.unsource. */
19474
+ unsourceFecRelease(packetId, catalogTrackName) {
19475
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
19476
+ }
19477
+ /** See FecReleaseSequencer.holdsRebuilt. */
19478
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
19479
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
19480
+ }
19042
19481
  /** Re-evaluate held gaps after FEC block state changed. */
19043
19482
  pokeFecRelease(packetId, catalogTrackName) {
19044
19483
  if (!this.#fecSequencer) return;
@@ -19365,7 +19804,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
19365
19804
  info,
19366
19805
  resolver,
19367
19806
  options?.recovered === true,
19368
- options?.fecSbn
19807
+ options?.fecSbn,
19808
+ options?.fecSbnFirst
19369
19809
  );
19370
19810
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
19371
19811
  }
@@ -19458,7 +19898,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
19458
19898
  info,
19459
19899
  resolver,
19460
19900
  options?.recovered === true,
19461
- options?.fecSbn
19901
+ options?.fecSbn,
19902
+ options?.fecSbnFirst
19462
19903
  );
19463
19904
  if (outcome.record !== void 0) return outcome.record;
19464
19905
  return this.#drop(outcome.reason);
@@ -19478,7 +19919,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19478
19919
  * attribution exists to keep readable. Leaving the choice at the call site
19479
19920
  * is what keeps both true.
19480
19921
  */
19481
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
19922
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
19482
19923
  const timing = resolver.sampleTiming(
19483
19924
  combined.mpuSequenceNumber,
19484
19925
  combined.movieFragmentSequenceNumber,
@@ -19495,6 +19936,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19495
19936
  );
19496
19937
  if (!meta) return { reason: "combined-meta-build-failed" };
19497
19938
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
19939
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
19498
19940
  if (!resolver.consumeSample(
19499
19941
  combined.mpuSequenceNumber,
19500
19942
  combined.movieFragmentSequenceNumber,
@@ -23011,6 +23453,7 @@ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
23011
23453
  var OVERLAY_ROUTED_LIMIT = 1024;
23012
23454
  var OVERLAY_PENDING_LIMIT = 256;
23013
23455
  var OVERLAY_OFFSET_MPUS = 16;
23456
+ var OVERLAY_REBUILT_LIMIT = 256;
23014
23457
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
23015
23458
  function assertStreamIdentity(role, stream) {
23016
23459
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -23187,6 +23630,17 @@ var MmtpRouter = class {
23187
23630
  * an MPU no member of which arrived).
23188
23631
  */
23189
23632
  #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
23633
+ /**
23634
+ * The same, shown by the overlay alone, before any base recovery did: a
23635
+ * packet it rebuilt whose base copy carries its protected psn
23636
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
23637
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
23638
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
23639
+ * make the base drop a late base copy of a keyframe the overlay never
23640
+ * finished, and lift a block's late-source cut, which nothing before
23641
+ * this offset did.
23642
+ */
23643
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
23190
23644
  /**
23191
23645
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
23192
23646
  * not parsed, typically because its overlap copy was parsed first
@@ -23464,13 +23918,18 @@ var MmtpRouter = class {
23464
23918
  this.#onDeltaBlockCompleteCb?.(packetId, false);
23465
23919
  }
23466
23920
  };
23467
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
23921
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
23468
23922
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
23469
23923
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
23470
23924
  this.#onDeltaBlockCompleteCb?.(packetId, true);
23471
23925
  }
23472
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23473
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23926
+ if (span === void 0) {
23927
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23928
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23929
+ } else {
23930
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
23931
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
23932
+ }
23474
23933
  };
23475
23934
  }
23476
23935
  }
@@ -23515,8 +23974,9 @@ var MmtpRouter = class {
23515
23974
  }
23516
23975
  /**
23517
23976
  * FEC-recovered source symbols whose reconstructed header named a
23518
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
23519
- * a hop re-stamped the sequence after the sender protected the packet.
23977
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
23978
+ * or, rebuilt by the overlay, than their base copy carries: a hop
23979
+ * re-stamped the sequence after the sender protected the packet.
23520
23980
  */
23521
23981
  get restampedRecoveredSequenceCount() {
23522
23982
  return this.#restampedRecoveredSeqs;
@@ -23695,6 +24155,7 @@ var MmtpRouter = class {
23695
24155
  enableMseAssembler(packetId, config, catalogTrackName) {
23696
24156
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
23697
24157
  const previous = this.#mseAssemblers.get(assemblerKey);
24158
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
23698
24159
  if (previous) {
23699
24160
  previous.flush();
23700
24161
  previous.dispose();
@@ -23845,7 +24306,8 @@ var MmtpRouter = class {
23845
24306
  fec,
23846
24307
  k,
23847
24308
  offsets: /* @__PURE__ */ new Map(),
23848
- moqBlocks: /* @__PURE__ */ new Set()
24309
+ moqBlocks: /* @__PURE__ */ new Set(),
24310
+ rebuilt: /* @__PURE__ */ new Map()
23849
24311
  };
23850
24312
  this.#overlays.set(repairPacketId, inst);
23851
24313
  return () => {
@@ -23886,6 +24348,7 @@ var MmtpRouter = class {
23886
24348
  inst.last = void 0;
23887
24349
  inst.offsets.clear();
23888
24350
  inst.moqBlocks.clear();
24351
+ inst.rebuilt.clear();
23889
24352
  }
23890
24353
  #overlaysForSource(sourcePacketId, catalogTrackName) {
23891
24354
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -23938,13 +24401,23 @@ var MmtpRouter = class {
23938
24401
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
23939
24402
  * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
23940
24403
  * FEC reads it.
24404
+ *
24405
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
24406
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
24407
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
24408
+ * the stream unstamped at the SS_ID offset it states, for the release gate
24409
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
24410
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
23941
24411
  */
23942
24412
  #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
23943
24413
  if (this.#overlays.size === 0) return;
23944
24414
  const ssId = keyframeOverlaySsId(header);
23945
24415
  if (ssId === void 0) return;
24416
+ let rebuiltPsn;
23946
24417
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
23947
24418
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
24419
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
24420
+ inst.rebuilt.delete(ssId);
23948
24421
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
23949
24422
  if (identity !== null) {
23950
24423
  inst.offsets.delete(identity.mpuSequenceNumber);
@@ -23974,6 +24447,14 @@ var MmtpRouter = class {
23974
24447
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
23975
24448
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
23976
24449
  }
24450
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
24451
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
24452
+ if (rebuiltPsn !== sequenceNumber) {
24453
+ this.#restampedRecoveredSeqs++;
24454
+ } else if (baseSsId !== void 0) {
24455
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24456
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
24457
+ }
23977
24458
  }
23978
24459
  #noteOverlayMoqBlock(inst, blockStart) {
23979
24460
  inst.moqBlocks.add(blockStart);
@@ -24007,11 +24488,16 @@ var MmtpRouter = class {
24007
24488
  }
24008
24489
  /**
24009
24490
  * Route an overlay-recovered block's packets as source media of the
24010
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
24011
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
24012
- * base re-stamp, no block advance. Each packet's wire sequence is restored
24013
- * from its keyframe's own offset; without one, a stream the base never
24014
- * re-stamped keeps the header's sequence and any other drops the packet.
24491
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
24492
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
24493
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
24494
+ * base FEC recovered does, so it waits behind base frames still in flight,
24495
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
24496
+ * longer than unanchored; one whose base SS_ID is undetermined has no
24497
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
24498
+ * advance. Each packet's wire sequence is restored from its keyframe's own
24499
+ * offset; without one, a stream the base never re-stamped keeps the
24500
+ * header's sequence and any other drops the packet.
24015
24501
  */
24016
24502
  #routeOverlayRecovered(inst, blockStart, recovered) {
24017
24503
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -24032,40 +24518,65 @@ var MmtpRouter = class {
24032
24518
  const restamped = this.#restampedStreams.has(streamKey);
24033
24519
  const restored = /* @__PURE__ */ new Set();
24034
24520
  const baseSsIds = /* @__PURE__ */ new Map();
24521
+ const gateOnly = /* @__PURE__ */ new Set();
24035
24522
  const symbols = result.symbols.flatMap((sym) => {
24523
+ const overlaySsId = serial32Add(blockStart, sym.index);
24036
24524
  const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
24037
24525
  if (anchor !== void 0) {
24038
- const overlaySsId = serial32Add(blockStart, sym.index);
24039
24526
  const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
24040
24527
  restored.add(packetSequenceNumber);
24041
24528
  const out = { ...sym, packetSequenceNumber };
24042
24529
  const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
24043
- if (baseSsId !== void 0) baseSsIds.set(out, baseSsId);
24530
+ if (baseSsId !== void 0) {
24531
+ baseSsIds.set(sym.index, baseSsId);
24532
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24533
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
24534
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
24535
+ }
24536
+ }
24044
24537
  return [out];
24045
24538
  }
24046
24539
  if (!restamped) {
24047
- const baseSsId = unstampedBaseSsId(
24048
- this.#ssIdSeqOffsetByStream.get(streamKey),
24049
- this.#unstampedSsIdSeqOffsetByStream.get(streamKey),
24050
- sym.packetSequenceNumber
24051
- );
24052
- if (baseSsId !== void 0) baseSsIds.set(sym, baseSsId);
24540
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24541
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
24542
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
24543
+ if (baseSsId !== void 0) {
24544
+ baseSsIds.set(sym.index, baseSsId);
24545
+ if (fedSsId === void 0) gateOnly.add(sym.index);
24546
+ } else {
24547
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
24548
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
24549
+ }
24053
24550
  return [sym];
24054
24551
  }
24055
24552
  this.#overlayStats.unsequencedDropped++;
24056
24553
  return [];
24057
24554
  });
24058
24555
  this.#overlayStats.recovered++;
24556
+ const mpuFirst = /* @__PURE__ */ new Map();
24557
+ for (const sym of symbols) {
24558
+ const ssId = baseSsIds.get(sym.index);
24559
+ const mpu = sym.fragment.mpuSequenceNumber;
24560
+ const first = mpuFirst.get(mpu);
24561
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
24562
+ }
24563
+ const firstSsIds = /* @__PURE__ */ new Map();
24564
+ for (const sym of symbols) {
24565
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
24566
+ }
24059
24567
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
24060
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
24568
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
24569
+ baseSsIds,
24570
+ firstSsIds
24061
24571
  });
24062
24572
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
24063
- this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds);
24573
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
24064
24574
  }
24065
24575
  /**
24066
24576
  * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
24067
24577
  * its base block too, once its base SS_ID is determined (overlayBaseSsId,
24068
- * from a received member of its MPU, else unstampedBaseSsId),
24578
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
24579
+ * base recovery showed; `baseSsIds` holds no other),
24069
24580
  * so it is fed to the base decoder as a rebuilt source
24070
24581
  * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
24071
24582
  * fewer to solve, and its repair can recover the block's other packets.
@@ -24091,7 +24602,7 @@ var MmtpRouter = class {
24091
24602
  const feeds = [];
24092
24603
  for (const sym of symbols) {
24093
24604
  if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
24094
- const ssId = baseSsIds.get(sym);
24605
+ const ssId = baseSsIds.get(sym.index);
24095
24606
  if (ssId === void 0) {
24096
24607
  this.#overlayStats.baseUndetermined++;
24097
24608
  continue;
@@ -24820,7 +25331,7 @@ var MmtpRouter = class {
24820
25331
  catalogTrackName
24821
25332
  )) continue;
24822
25333
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
24823
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
25334
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
24824
25335
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
24825
25336
  }
24826
25337
  if (payload.oversized) continue;
@@ -24908,6 +25419,7 @@ var MmtpRouter = class {
24908
25419
  this.#latestVideoSeqByStream.delete(streamKey);
24909
25420
  this.#ssIdSeqOffsetByStream.delete(streamKey);
24910
25421
  this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
25422
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
24911
25423
  this.#multicastRapTwinByStream.delete(streamKey);
24912
25424
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
24913
25425
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -25034,6 +25546,12 @@ var MmtpRouter = class {
25034
25546
  * the outgoing stream stops. The hold is bounded by the incoming stream's
25035
25547
  * own RAP cadence, so no timer is involved.
25036
25548
  *
25549
+ * While the switch is staged, the FEC release gate lets a keyframe the
25550
+ * overlay rebuilt reach it, on either side, when the keyframe did before
25551
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
25552
+ * decides on what each side delivered, and the commit discards the gate's
25553
+ * frames of the outgoing stream.
25554
+ *
25037
25555
  * The commit is one synchronous transition inside the frame path: the
25038
25556
  * outgoing stream's already-admitted frames are released (its queued FEC
25039
25557
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -25084,6 +25602,9 @@ var MmtpRouter = class {
25084
25602
  droppedIncomingFrames: 0
25085
25603
  };
25086
25604
  this.#staged = state;
25605
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
25606
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
25607
+ }
25087
25608
  return {
25088
25609
  cancel: () => {
25089
25610
  if (this.#staged !== state) return false;
@@ -25166,7 +25687,17 @@ var MmtpRouter = class {
25166
25687
  */
25167
25688
  #routeParsedFrame(data, meta) {
25168
25689
  if (this.#classifyPacketId(meta.packetId) === null) return;
25169
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
25690
+ if (this.#staged !== null) {
25691
+ let consumed = false;
25692
+ this.#fecPokeDepth++;
25693
+ try {
25694
+ consumed = this.#interceptSwitchFrame(data, meta);
25695
+ } finally {
25696
+ this.#fecPokeDepth--;
25697
+ this.#flushPendingFecPokes();
25698
+ }
25699
+ if (consumed) return;
25700
+ }
25170
25701
  this.#deliverParsedFrame(data, meta);
25171
25702
  }
25172
25703
  #commitStreamSwitch(state, rap, reason) {
@@ -25318,12 +25849,16 @@ var MmtpRouter = class {
25318
25849
  this.#parser.deferFecRelease(work);
25319
25850
  } finally {
25320
25851
  this.#fecPokeDepth--;
25321
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
25322
- const pokes = [...this.#pendingFecPokes.values()];
25323
- this.#pendingFecPokes.clear();
25324
- for (const poke of pokes) {
25325
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
25326
- }
25852
+ this.#flushPendingFecPokes();
25853
+ }
25854
+ }
25855
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
25856
+ #flushPendingFecPokes() {
25857
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
25858
+ const pokes = [...this.#pendingFecPokes.values()];
25859
+ this.#pendingFecPokes.clear();
25860
+ for (const poke of pokes) {
25861
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
25327
25862
  }
25328
25863
  }
25329
25864
  }
@@ -25392,6 +25927,26 @@ var MmtpRouter = class {
25392
25927
  if (!fec?.terminalRetentionMsForPacket) return Infinity;
25393
25928
  return fec.terminalRetentionMsForPacket(packetId) ?? 0;
25394
25929
  },
25930
+ // Once no repair can fill a gap (FECManager.isoRepairlessWaitMs: only a
25931
+ // late source can), its frame waits the late-symbol allowance when the
25932
+ // gap holds no RAP an installed keyframe overlay could still rebuild:
25933
+ // lost deltas of one MPU (delta-lost), the tail of the MPU before a RAP
25934
+ // that opens the next one while MPU boundaries bound RAPs (rap-next), or
25935
+ // an audio gap. A gap that may hold one (rap-lost, rap-unknown, or any
25936
+ // other rap-next, whose gap may hold a whole MPU and the keyframe the
25937
+ // overlay protects) waits for that overlay's repair too (BLO-52085
25938
+ // D4). The FEC check comes first: most held gaps are not behind such a
25939
+ // span, and deciding one scans both frames' bitstreams.
25940
+ unrepairableWaitMs: (before, after, fromSbn, toSbn) => {
25941
+ const fec = this.#fecManager;
25942
+ const { packetId, catalogTrackName } = after.meta;
25943
+ const allowanceMs = fec?.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn);
25944
+ if (!fec || allowanceMs === void 0) return void 0;
25945
+ const decision = this.#decideGap(before, after, [], false);
25946
+ const mpu = before.meta.mpuSequenceNumber;
25947
+ const intoNextMpu = decision.reason === "rap-next" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu + 1 >>> 0 && fec.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
25948
+ return decision.action === "stall" || decision.reason === "rap-next" && !intoNextMpu ? fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, true) : allowanceMs;
25949
+ },
25395
25950
  decide: (before, after, lostBlocks, discontinuity) => {
25396
25951
  const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
25397
25952
  this.#onFrameGap?.(decision);
@@ -25401,6 +25956,14 @@ var MmtpRouter = class {
25401
25956
  onRap: (packetId, catalogTrackName, ssId) => {
25402
25957
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
25403
25958
  },
25959
+ // A staged switch commits on when each side's frames reach it
25960
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
25961
+ // they did unanchored.
25962
+ releaseUnanchored: (packetId, catalogTrackName) => {
25963
+ const staged = this.#staged;
25964
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
25965
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
25966
+ },
25404
25967
  onReleased: (data, meta) => {
25405
25968
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
25406
25969
  const timing = meta.authoredTiming;
@@ -25851,7 +26414,8 @@ var MmtpRouter = class {
25851
26414
  source: parserOptions?.source,
25852
26415
  deliveryProvenance: parserOptions?.deliveryProvenance,
25853
26416
  catalogTrackName: parserOptions?.catalogTrackName,
25854
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
26417
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
26418
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
25855
26419
  };
25856
26420
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
25857
26421
  else this.#parser.feed(packet, feedOptions);
@@ -26317,7 +26881,12 @@ var MmtpRouter = class {
26317
26881
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
26318
26882
  if (ownerPacketId == null) return;
26319
26883
  if (this.#classifyPacketId(ownerPacketId) === null) return;
26320
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
26884
+ const fecSbnOf = (index) => {
26885
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
26886
+ const fecSbn = overlay.baseSsIds.get(index);
26887
+ const fecSbnFirst = overlay.firstSsIds.get(index);
26888
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
26889
+ };
26321
26890
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
26322
26891
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
26323
26892
  if (ssIdSeqOffset !== void 0) {
@@ -28113,6 +28682,12 @@ function isNonNegativeSafeInteger(value) {
28113
28682
  function isSymbolCounts(value) {
28114
28683
  return isRecord(value) && hasExactKeys(value, ["multicast", "moq"]) && isNonNegativeSafeInteger(value["multicast"]) && isNonNegativeSafeInteger(value["moq"]);
28115
28684
  }
28685
+ function isSpanFailure(value) {
28686
+ if (!isRecord(value) || !hasExactKeys(value, ["length", "sources"])) return false;
28687
+ const length = value["length"];
28688
+ const sources = value["sources"];
28689
+ return Number.isSafeInteger(length) && length > 0 && isNonNegativeSafeInteger(sources) && sources < length;
28690
+ }
28116
28691
  function isNullableNonNegative(value) {
28117
28692
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
28118
28693
  }
@@ -28132,7 +28707,10 @@ function isRepairLifecycleEvent(value) {
28132
28707
  case "recovered":
28133
28708
  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"]);
28134
28709
  case "failed":
28135
- return hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]);
28710
+ return hasExactKeys(
28711
+ value,
28712
+ "span" in value ? ["version", "type", "block", "blockClass", "symbols", "span"] : ["version", "type", "block", "blockClass", "symbols"]
28713
+ ) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]) && (!("span" in value) || isSpanFailure(value["span"]));
28136
28714
  case "repair-preempted":
28137
28715
  case "repair-deferred":
28138
28716
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
@@ -28341,6 +28919,8 @@ var MulticastManager = class {
28341
28919
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
28342
28920
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
28343
28921
  #repairReleases = /* @__PURE__ */ new Map();
28922
+ /** Protected repair flows owned by each live repair-endpoint release. */
28923
+ #repairProvenanceFlows = /* @__PURE__ */ new Map();
28344
28924
  /** Each source's catalog keyframe overlay, from its `ok` binding. */
28345
28925
  #overlayBindings = /* @__PURE__ */ new Map();
28346
28926
  /** Installed overlay decoders (`setKeyframeOverlayDecoder`), by source. */
@@ -28398,7 +28978,7 @@ var MulticastManager = class {
28398
28978
  onPublisherRestart: (packetId, catalogTrackName) => {
28399
28979
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
28400
28980
  },
28401
- onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
28981
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass, span) => {
28402
28982
  const pathCount = this.#fec.blockPathCount(
28403
28983
  sbn,
28404
28984
  packetId,
@@ -28416,7 +28996,8 @@ var MulticastManager = class {
28416
28996
  symbols: {
28417
28997
  multicast: pathCount?.multicastSymbols ?? 0,
28418
28998
  moq: pathCount?.moqSymbols ?? 0
28419
- }
28999
+ },
29000
+ ...span === void 0 ? {} : { span }
28420
29001
  });
28421
29002
  },
28422
29003
  onFrameGap: (decision) => {
@@ -28504,6 +29085,11 @@ var MulticastManager = class {
28504
29085
  this.#fec.onBlockVanished = (_sbn, packetId, catalogTrackName) => {
28505
29086
  this.#statsFor(packetId, catalogTrackName).vanishedBlocks++;
28506
29087
  };
29088
+ this.#fec.keyframeOverlayTiming = (packetId, catalogTrackName) => {
29089
+ const binding = this.#overlayInstalls.has(packetId) ? this.#overlayBindings.get(packetId) : void 0;
29090
+ if (binding === void 0) return void 0;
29091
+ return catalogTrackName === void 0 || catalogTrackName === binding.sourceCatalogTrackName ? binding.geometry : void 0;
29092
+ };
28507
29093
  this.#fec.onDecoderUnavailable = (event) => {
28508
29094
  this.#emitRepairLifecycle({
28509
29095
  version: 2,
@@ -29006,6 +29592,9 @@ var MulticastManager = class {
29006
29592
  this.#transport.onFailback((reason) => {
29007
29593
  const joined = this.#provenanceJoin;
29008
29594
  if (joined !== null) this.#router.unprotectProvenanceFlow(joined.flow);
29595
+ for (const flows of this.#repairProvenanceFlows.values()) {
29596
+ for (const flow of flows) this.#router.unprotectProvenanceFlow(flow);
29597
+ }
29009
29598
  this.#onFailback?.(reason);
29010
29599
  });
29011
29600
  }
@@ -29040,6 +29629,12 @@ var MulticastManager = class {
29040
29629
  "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
29041
29630
  );
29042
29631
  }
29632
+ if (provenanceFlow !== void 0) {
29633
+ const flow = multicastProvenanceFlowKey(provenanceFlow);
29634
+ if ([...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
29635
+ throw new TypeError(`[MulticastManager] join: provenance flow already registered by a repair endpoint: ${flow}`);
29636
+ }
29637
+ }
29043
29638
  const staged = this.#renditionSwitch;
29044
29639
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
29045
29640
  this.configureFec(config);
@@ -29047,8 +29642,8 @@ var MulticastManager = class {
29047
29642
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
29048
29643
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
29049
29644
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
29050
- this.#releaseProvenanceJoin();
29051
29645
  const provenance = config.provenance;
29646
+ this.#releaseProvenanceJoin();
29052
29647
  const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
29053
29648
  const ingress = protectedTracks === void 0 ? void 0 : {
29054
29649
  tracks: Object.freeze(
@@ -29101,8 +29696,13 @@ var MulticastManager = class {
29101
29696
  * feeds the flow's receiver; media datagrams are held until one admits them.
29102
29697
  */
29103
29698
  #joinProvenance(provenance, ingress) {
29699
+ this.#router.registerProvenanceFlow(ingress, this.#provenanceReceiver(provenance));
29700
+ this.#hookFailback();
29701
+ this.#provenanceJoin = { flow: ingress.flow };
29702
+ }
29703
+ #provenanceReceiver(provenance) {
29104
29704
  const { flow, auth } = provenance;
29105
- const receiver = new BcProvenanceV2Receiver({
29705
+ return new BcProvenanceV2Receiver({
29106
29706
  ...provenance.receiver,
29107
29707
  // The caller's ctx when it passes one, else the catalog's: an explicit
29108
29708
  // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
@@ -29119,9 +29719,6 @@ var MulticastManager = class {
29119
29719
  maxAuthDelayMs: flow.maxAuthDelayMs,
29120
29720
  manifestTimerMs: flow.manifestTimerMs
29121
29721
  });
29122
- this.#router.registerProvenanceFlow(ingress, receiver);
29123
- this.#hookFailback();
29124
- this.#provenanceJoin = { flow: ingress.flow };
29125
29722
  }
29126
29723
  /** Un-protect: drop the flow's hold queues (no expiry counted). */
29127
29724
  #releaseProvenanceJoin() {
@@ -29152,8 +29749,25 @@ var MulticastManager = class {
29152
29749
  * callback delivers must come from a subscription opened on
29153
29750
  * `options.gateway`. A callback that also merges another source (a MoQ or
29154
29751
  * WebSocket repair feed) must not name a native provider here.
29752
+ *
29753
+ * An endpoint's `provenance` makes its group a protected flow of its own
29754
+ * (multicast-02 7.2.7), registered here and released with the group; its
29755
+ * records ride in band on the group's port. On the user-agent path a
29756
+ * flow-less repair group of a protected track is set aside, never read, so
29757
+ * a player joining a protected catalog's repair groups passes it.
29155
29758
  */
29156
29759
  joinRepairEndpoints(endpoints, provider, options) {
29760
+ for (const { provenance, flow, source, group, port: port2 } of endpoints) {
29761
+ if (provenance === void 0) continue;
29762
+ if (flow !== void 0) {
29763
+ throw new TypeError("[MulticastManager] joinRepairEndpoints: an endpoint names provenance or flow, never both");
29764
+ }
29765
+ if (!sameIpAddress(source, provenance.flow.source) || !sameIpAddress(group, provenance.flow.groupAddress) || port2 !== provenance.flow.port) {
29766
+ throw new RangeError(
29767
+ "[MulticastManager] joinRepairEndpoints: provenance flow (S, G, port) must match the endpoint's source, group and port"
29768
+ );
29769
+ }
29770
+ }
29157
29771
  const releases = [];
29158
29772
  let released = false;
29159
29773
  const safely = (each) => {
@@ -29163,17 +29777,36 @@ var MulticastManager = class {
29163
29777
  console.warn("[MulticastManager] repair group release failed", error);
29164
29778
  }
29165
29779
  };
29780
+ const usedFlows = /* @__PURE__ */ new Set();
29781
+ const preparedProvenance = endpoints.map((endpoint) => {
29782
+ if (endpoint.provenance === void 0) return void 0;
29783
+ const flow = multicastProvenanceFlowKey(endpoint.provenance.flow);
29784
+ if (usedFlows.has(flow) || this.#provenanceJoin?.flow === flow || [...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
29785
+ throw new TypeError(`[MulticastManager] joinRepairEndpoints: provenance flow already registered: ${flow}`);
29786
+ }
29787
+ usedFlows.add(flow);
29788
+ return { flow, receiver: this.#provenanceReceiver(endpoint.provenance) };
29789
+ });
29790
+ const provenanceFlows = [];
29166
29791
  const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners.map((owner) => owner.instance !== "keyframe" ? owner : {
29167
29792
  ...owner,
29168
29793
  ownerTrackName: endpoint.tracks.find((t) => t.packetId === owner.ownerPacketId)?.name,
29169
29794
  repairTrackName: endpoint.tracks.find((t) => t.packetId === owner.packetId)?.name
29170
29795
  }));
29171
29796
  this.#applyRepairOwners(repairOwners);
29172
- for (const endpoint of endpoints) {
29797
+ for (const [index, endpoint] of endpoints.entries()) {
29798
+ const flow = endpoint.provenance === void 0 ? endpoint.flow : multicastProvenanceFlowKey(endpoint.provenance.flow);
29173
29799
  const ingress = {
29174
29800
  tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
29175
- ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
29801
+ ...flow === void 0 ? {} : { flow }
29176
29802
  };
29803
+ if (endpoint.provenance !== void 0) {
29804
+ const prepared = preparedProvenance[index];
29805
+ if (prepared === void 0) throw new Error("[MulticastManager] repair provenance preparation missing");
29806
+ this.#router.registerProvenanceFlow(ingress, prepared.receiver);
29807
+ provenanceFlows.push(prepared.flow);
29808
+ releases.push(() => this.#router.releaseProvenanceFlow(flow));
29809
+ }
29177
29810
  let sender;
29178
29811
  const feed = (packet, sourceAddress, ingressToFeed) => {
29179
29812
  if (released) return;
@@ -29203,7 +29836,7 @@ var MulticastManager = class {
29203
29836
  packetIds: endpoint.packetIds,
29204
29837
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
29205
29838
  // A protected repair group's records ride in band on its port (7.2.3).
29206
- ...endpoint.flow === void 0 ? {} : { protected: true }
29839
+ ...flow === void 0 ? {} : { protected: true }
29207
29840
  }, ingress).then((joined) => {
29208
29841
  if (!joined && !released) fail(transport.lastJoinOutcome);
29209
29842
  });
@@ -29212,9 +29845,12 @@ var MulticastManager = class {
29212
29845
  if (released) return;
29213
29846
  released = true;
29214
29847
  this.#repairReleases.delete(release);
29848
+ this.#repairProvenanceFlows.delete(release);
29215
29849
  for (const each of releases.splice(0)) safely(each);
29216
29850
  };
29217
29851
  this.#repairReleases.set(release, repairOwners);
29852
+ this.#repairProvenanceFlows.set(release, provenanceFlows);
29853
+ if (provenanceFlows.length) this.#hookFailback();
29218
29854
  return release;
29219
29855
  }
29220
29856
  #applyRepairOwners(owners) {
@@ -29700,7 +30336,8 @@ var MulticastManager = class {
29700
30336
  blockProfile: parseFecBlockProfile(
29701
30337
  geometry2.blockProfile,
29702
30338
  `tracks[${JSON.stringify(track.name)}].fec keyframe overlay blockProfile`
29703
- )
30339
+ ),
30340
+ geometry: geometry2
29704
30341
  });
29705
30342
  }
29706
30343
  }
@@ -29739,7 +30376,7 @@ var MulticastManager = class {
29739
30376
  for (const [sourcePacketId, install] of [...this.#overlayInstalls]) {
29740
30377
  const before = this.#overlayBindings.get(sourcePacketId);
29741
30378
  const after = overlayBindings.get(sourcePacketId);
29742
- const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => after[key] === before[key]);
30379
+ const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => key === "geometry" || after[key] === before[key]);
29743
30380
  if (!same) install.dispose();
29744
30381
  else if (this.#router.hasKeyframeOverlay(after.repairPacketId)) this.#router.resetKeyframeOverlays(sourcePacketId);
29745
30382
  else install.reattach();
@@ -29796,10 +30433,12 @@ var MulticastManager = class {
29796
30433
  * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
29797
30434
  * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
29798
30435
  * pending hole and reported here, and `closeIsoHoles` must be called for it
29799
- * once its range FETCH ends (or none is sent).
30436
+ * once its range FETCH ends (or none is sent). `onExpired` is told of a
30437
+ * pending hole the stream runs past the locator's horizon: returning true,
30438
+ * the caller closes it (`closeIsoHoles`); otherwise it is discarded.
29800
30439
  */
29801
- onUndelimitedLoss(cb) {
29802
- this.#fec.setUndelimitedLossHandler(cb);
30440
+ onUndelimitedLoss(cb, onExpired) {
30441
+ this.#fec.setUndelimitedLossHandler(cb, onExpired ?? null);
29803
30442
  }
29804
30443
  /**
29805
30444
  * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
@@ -30035,7 +30674,8 @@ var MulticastManager = class {
30035
30674
  "stream" in event ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
30036
30675
  ...event,
30037
30676
  block: Object.freeze({ ...event.block }),
30038
- ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {}
30677
+ ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {},
30678
+ ..."span" in event && event.span !== void 0 ? { span: Object.freeze({ ...event.span }) } : {}
30039
30679
  }
30040
30680
  );
30041
30681
  if (this.#logRepairLifecycle) {
@@ -32707,6 +33347,7 @@ var RepairLayerSubscriptions = class {
32707
33347
 
32708
33348
  // src/repair-fetch.ts
32709
33349
  var MOQT_PRIORITY_MAX = 255;
33350
+ var WALK_LEAD_MS = 3;
32710
33351
  var SOURCE_MEDIA_PRIORITY_MAX = REPAIR_PRIORITY_MIN - 1;
32711
33352
  function isMoqtPriority(value) {
32712
33353
  return Number.isSafeInteger(value) && value >= 0 && value <= MOQT_PRIORITY_MAX;
@@ -32757,8 +33398,17 @@ function wireRepairFetch(mc, opts) {
32757
33398
  mc.noteRepairScheduling(type, entry.sbn, entry.packetId, entry.catalogTrackName);
32758
33399
  };
32759
33400
  const clearEntry = (entry) => {
32760
- if (entry.range) mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, entry.range.holeLength);
32761
- else clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
33401
+ const { range } = entry;
33402
+ if (range) {
33403
+ atReport(range, () => mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, range.holeLength));
33404
+ } else {
33405
+ clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
33406
+ }
33407
+ };
33408
+ const atReport = (range, work) => {
33409
+ const fec = mc.fecManager;
33410
+ if (range.groups !== null || fec.withReceiptTime === void 0) work();
33411
+ else fec.withReceiptTime(range.reportedAt, work);
32762
33412
  };
32763
33413
  const releaseHold = (entry) => {
32764
33414
  if (entry.range) return;
@@ -32770,7 +33420,7 @@ function wireRepairFetch(mc, opts) {
32770
33420
  if (!run) return;
32771
33421
  entry.running = null;
32772
33422
  run.stopped = reason;
32773
- run.controller.abort();
33423
+ run.controller.abort(reason);
32774
33424
  if (reason === "preempted") releaseHold(entry);
32775
33425
  mc.noteRepairStopped?.(reason, entry.sbn, entry.packetId, entry.catalogTrackName);
32776
33426
  };
@@ -32825,21 +33475,42 @@ function wireRepairFetch(mc, opts) {
32825
33475
  const admit = (entry, now) => {
32826
33476
  const budgetMs = entry.deadlineAt - now;
32827
33477
  const rttMs = readRtt();
32828
- const reason = !entry.range && !groupCanComplete(entry.sbn, entry.packetId, entry.catalogTrackName) ? "group-cannot-complete" : rttMs === null ? "rtt-unmeasured" : rttMs < budgetMs ? null : "rtt-exceeds-budget";
33478
+ const reason = refusal(entry, now, rttMs);
32829
33479
  if (reason === null) return rttMs;
32830
33480
  skip(entry, reason, rttMs, budgetMs);
32831
33481
  return null;
32832
33482
  };
33483
+ 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";
32833
33484
  const retire = (entry) => {
32834
33485
  if (entries.get(entry.key) === entry) entries.delete(entry.key);
32835
33486
  if (entry.expiry !== void 0) clearTimeout(entry.expiry);
32836
33487
  };
32837
- const outstandingBelow = (priority) => {
33488
+ const holdsBack = (entry, priority, videoWalks = true) => {
33489
+ if (entry.priority >= priority) return false;
33490
+ const { walk } = entry;
33491
+ if (walk === void 0) return true;
33492
+ if (entry.priority !== 0 || !videoWalks) return false;
33493
+ return entry.running === null || walk.group !== null && !walk.group.controller.signal.aborted;
33494
+ };
33495
+ const outstandingBelow = (priority, videoWalks = true) => {
32838
33496
  for (const entry of entries.values()) {
32839
- if (entry.priority < priority) return true;
33497
+ if (holdsBack(entry, priority, videoWalks)) return true;
32840
33498
  }
32841
33499
  return false;
32842
33500
  };
33501
+ const yieldVideoWalks = (queued) => {
33502
+ const now = performance.now();
33503
+ const rttMs = readRtt();
33504
+ const due = queued.some((entry) => entry.priority !== 0 && entry.walk === void 0 && !outstandingBelow(entry.priority, false) && refusal(entry, now, rttMs) === null);
33505
+ if (!due) return;
33506
+ for (const entry of entries.values()) {
33507
+ const walk = entry.walk;
33508
+ if (entry.priority !== 0 || walk === void 0 || walk.group === null) continue;
33509
+ if (walk.group.controller.signal.aborted) continue;
33510
+ walk.yielded = true;
33511
+ walk.group.controller.abort();
33512
+ }
33513
+ };
32843
33514
  const preemptBestEffort = () => {
32844
33515
  for (const entry of entries.values()) {
32845
33516
  if (entry.priority === 0 || !entry.running) continue;
@@ -32868,7 +33539,8 @@ function wireRepairFetch(mc, opts) {
32868
33539
  }
32869
33540
  const rttMs = admit(entry, now);
32870
33541
  if (rttMs === null) return;
32871
- if (entry.priority === 0) preemptBestEffort();
33542
+ if (entry.priority === 0 && entry.walk === void 0) preemptBestEffort();
33543
+ if (entry.range === void 0) leaveWalkedGroup(entry);
32872
33544
  if (counted) entry.attempts++;
32873
33545
  mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName, {
32874
33546
  rttMs,
@@ -32890,6 +33562,14 @@ function wireRepairFetch(mc, opts) {
32890
33562
  }
32891
33563
  void execute(entry, run);
32892
33564
  };
33565
+ const leaveWalkedGroup = (block) => {
33566
+ for (const entry of entries.values()) {
33567
+ const group = entry.walk?.group;
33568
+ if (group?.sbn === block.sbn && entry.packetId === block.packetId && entry.catalogTrackName === block.catalogTrackName) {
33569
+ group.controller.abort();
33570
+ }
33571
+ }
33572
+ };
32893
33573
  const dispatch = () => {
32894
33574
  if (disposed) return;
32895
33575
  const now = performance.now();
@@ -32914,6 +33594,7 @@ function wireRepairFetch(mc, opts) {
32914
33594
  for (const entry of queued) {
32915
33595
  if (entry.priority === 0) start(entry);
32916
33596
  }
33597
+ yieldVideoWalks(queued);
32917
33598
  if (outstandingBelow(1)) return;
32918
33599
  for (const entry of queued) {
32919
33600
  if (entry.priority === 1) start(entry);
@@ -32940,6 +33621,16 @@ function wireRepairFetch(mc, opts) {
32940
33621
  }
32941
33622
  return counts.sources + counts.repairGroupLength >= counts.authoredLength;
32942
33623
  };
33624
+ const groupServed = (sbn, packetId, catalogTrackName) => {
33625
+ if (mc.fecManager.blockSymbolCounts === void 0) return false;
33626
+ const counts = symbolCounts(sbn, packetId, catalogTrackName);
33627
+ if (counts === void 0 || counts.authoredLength === void 0) return true;
33628
+ return counts.sources + counts.repairs >= counts.authoredLength || !groupCanComplete(sbn, packetId, catalogTrackName);
33629
+ };
33630
+ const statedEnd = (sbn, packetId, catalogTrackName) => {
33631
+ const length = symbolCounts(sbn, packetId, catalogTrackName)?.authoredLength;
33632
+ return length === void 0 ? void 0 : serial32Add(sbn, length);
33633
+ };
32943
33634
  const finish = (entry, run, fed, error) => {
32944
33635
  if (run.stopped !== null || entry.running !== run || entries.get(entry.key) !== entry) {
32945
33636
  return;
@@ -32984,27 +33675,81 @@ function wireRepairFetch(mc, opts) {
32984
33675
  signal: run.controller.signal,
32985
33676
  subscriberPriority: entry.subscriberPriority
32986
33677
  };
33678
+ const { range } = entry;
33679
+ const feed = (packet) => {
33680
+ if (entry.catalogTrackName === void 0) {
33681
+ mc.processRepairFromMoQ(packet, entry.packetId);
33682
+ } else {
33683
+ mc.processRepairFromMoQ(packet, entry.packetId, entry.catalogTrackName);
33684
+ }
33685
+ };
32987
33686
  try {
32988
- const packets = entry.range ? opts.rangeTransport({
33687
+ const packets = range === void 0 ? opts.transport({ ...common, sbn: entry.sbn }) : entry.walk !== void 0 ? walkHole(entry, entry.walk, range, common) : opts.rangeTransport({
32989
33688
  ...common,
32990
- startGroup: entry.range.startGroup,
32991
- endGroup: entry.range.endGroup,
32992
- lostSsId: entry.range.lostSsId
32993
- }) : opts.transport({ ...common, sbn: entry.sbn });
33689
+ startGroup: range.groups.startGroup,
33690
+ endGroup: range.groups.endGroup,
33691
+ lostSsId: range.lostSsId
33692
+ });
32994
33693
  for await (const packet of packets) {
32995
33694
  if (run.stopped !== null || entry.running !== run) break;
32996
33695
  fed++;
32997
- if (entry.catalogTrackName === void 0) {
32998
- mc.processRepairFromMoQ(packet, entry.packetId);
32999
- } else {
33000
- mc.processRepairFromMoQ(packet, entry.packetId, entry.catalogTrackName);
33001
- }
33696
+ if (range === void 0) feed(packet);
33697
+ else atReport(range, () => feed(packet));
33002
33698
  }
33003
33699
  finish(entry, run, fed, void 0);
33004
33700
  } catch (error) {
33005
33701
  finish(entry, run, fed, error ?? new Error("repair transport rejected"));
33006
33702
  }
33007
33703
  };
33704
+ async function* walkHole(entry, walk, hole, common) {
33705
+ const lostAt = serial32Distance(entry.sbn, hole.lostSsId);
33706
+ for (let first = true; !common.signal.aborted; first = false) {
33707
+ if (!first && entry.priority !== 0 && outstandingBelow(1)) {
33708
+ stop(entry, "preempted");
33709
+ note("repair-preempted", entry);
33710
+ return;
33711
+ }
33712
+ if (!first && entry.priority === 0) {
33713
+ dispatch();
33714
+ if (common.signal.aborted) return;
33715
+ }
33716
+ const sbn = walk.next;
33717
+ let next;
33718
+ if (entries.get(requestKey(sbn, entry.packetId, entry.catalogTrackName))?.running == null) {
33719
+ const rsIds = /* @__PURE__ */ new Set();
33720
+ const group = new AbortController();
33721
+ const cancel = () => group.abort(common.signal.reason);
33722
+ common.signal.addEventListener("abort", cancel, { once: true });
33723
+ walk.group = { sbn, controller: group };
33724
+ try {
33725
+ for await (const packet of opts.transport({ ...common, sbn, signal: group.signal })) {
33726
+ yield packet;
33727
+ const id = extractRepairFecPayloadId(packet);
33728
+ if (id === null || id.ssStart !== sbn || id.ssbLength === 0) continue;
33729
+ next ??= serial32Add(sbn, id.ssbLength);
33730
+ rsIds.add(id.rsId);
33731
+ if (rsIds.size >= id.rsbLength || groupServed(sbn, entry.packetId, entry.catalogTrackName)) {
33732
+ group.abort();
33733
+ break;
33734
+ }
33735
+ }
33736
+ } catch (error) {
33737
+ if (!group.signal.aborted || common.signal.aborted) throw error;
33738
+ } finally {
33739
+ common.signal.removeEventListener("abort", cancel);
33740
+ walk.group = null;
33741
+ }
33742
+ if (walk.yielded) {
33743
+ walk.yielded = false;
33744
+ continue;
33745
+ }
33746
+ }
33747
+ next ??= statedEnd(sbn, entry.packetId, entry.catalogTrackName);
33748
+ if (next === void 0) return;
33749
+ if (serial32Distance(entry.sbn, next) > lostAt) return;
33750
+ walk.next = next;
33751
+ }
33752
+ }
33008
33753
  const removeResetObserver = mc.addTrackResetObserver((packetId, catalogTrackName) => {
33009
33754
  for (const entry of [...entries.values()]) {
33010
33755
  if (entry.packetId !== packetId || entry.catalogTrackName !== catalogTrackName) continue;
@@ -33200,7 +33945,37 @@ function wireRepairFetch(mc, opts) {
33200
33945
  throw error;
33201
33946
  }
33202
33947
  };
33203
- if (opts.rangeTransport !== void 0) {
33948
+ const trackKind = (packetId) => {
33949
+ try {
33950
+ return mc.fecManager.trackKindFor?.(packetId);
33951
+ } catch {
33952
+ return void 0;
33953
+ }
33954
+ };
33955
+ const walkDeadlineAt = (packetId, now, deadlineAt) => {
33956
+ let repairDeadlineMs;
33957
+ try {
33958
+ repairDeadlineMs = mc.fecManager.repairDeadlineMsForPacket?.(packetId);
33959
+ } catch {
33960
+ repairDeadlineMs = void 0;
33961
+ }
33962
+ if (repairDeadlineMs === void 0 || !Number.isFinite(repairDeadlineMs)) return deadlineAt;
33963
+ return Math.min(deadlineAt, now + repairDeadlineMs - WALK_LEAD_MS);
33964
+ };
33965
+ const onHoleExpired = (hole) => {
33966
+ if (disposed) return false;
33967
+ 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);
33968
+ if (entry === void 0) return false;
33969
+ queueMicrotask(() => {
33970
+ if (entries.get(entry.key) !== entry) return;
33971
+ retire(entry);
33972
+ stop(entry, "expired");
33973
+ clearEntry(entry);
33974
+ dispatch();
33975
+ });
33976
+ return true;
33977
+ };
33978
+ if (mc.onUndelimitedLoss !== void 0 && mc.closeIsoHoles !== void 0) {
33204
33979
  mc.onUndelimitedLoss((loss) => {
33205
33980
  const { packetId, catalogTrackName, holeStart, holeLength } = loss;
33206
33981
  const close = () => mc.closeIsoHoles(packetId, catalogTrackName, holeStart, holeLength);
@@ -33208,9 +33983,11 @@ function wireRepairFetch(mc, opts) {
33208
33983
  const blockProfile = blockProfileOf(packetId);
33209
33984
  const target = opts.resolveTarget(packetId, catalogTrackName);
33210
33985
  if (!target) return close();
33211
- const priority = repairPriorityForClass("unknown");
33212
- const range = rangeFor(loss, target.repairTrack);
33213
- if (range === null) {
33986
+ const walked = opts.rangeTransport === void 0;
33987
+ const holeClass = walked && trackKind(packetId) === "audio" ? "audio" : "unknown";
33988
+ const priority = repairPriorityForClass(holeClass);
33989
+ const groups = walked ? null : rangeFor(loss, target.repairTrack);
33990
+ if (!walked && groups === null) {
33214
33991
  close();
33215
33992
  mc.noteRepairSkipped("range-no-anchor", { rttMs: readRtt(), budgetMs: 0, priority }, holeStart, packetId, catalogTrackName);
33216
33993
  return;
@@ -33221,8 +33998,10 @@ function wireRepairFetch(mc, opts) {
33221
33998
  packetId,
33222
33999
  ...catalogTrackName === void 0 ? {} : { catalogTrackName }
33223
34000
  };
33224
- const wire = wirePriority(identity, "unknown");
33225
- const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, performance.now(), "unknown");
34001
+ const wire = wirePriority(identity, holeClass);
34002
+ if (wire === null) return close();
34003
+ const now = performance.now();
34004
+ const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, now, holeClass);
33226
34005
  if (deadline === null) {
33227
34006
  close();
33228
34007
  mc.noteRepairSkipped(
@@ -33234,6 +34013,7 @@ function wireRepairFetch(mc, opts) {
33234
34013
  );
33235
34014
  return;
33236
34015
  }
34016
+ const deadlineAt = walked ? walkDeadlineAt(packetId, now, deadline.deadlineAt) : deadline.deadlineAt;
33237
34017
  const entry = {
33238
34018
  key: JSON.stringify(["range", packetId, catalogTrackName ?? null, holeStart]),
33239
34019
  ...identity,
@@ -33241,15 +34021,16 @@ function wireRepairFetch(mc, opts) {
33241
34021
  blockProfile,
33242
34022
  priority,
33243
34023
  subscriberPriority: wire.subscriberPriority,
33244
- deadlineAt: deadline.deadlineAt,
33245
- playoutDeadlineAt: deadline.deadlineAt - deadline.extensionMs,
34024
+ deadlineAt,
34025
+ playoutDeadlineAt: deadlineAt - deadline.extensionMs,
33246
34026
  anchorAt: deadline.anchorAt,
33247
34027
  delayMs: deadline.delayMs,
33248
34028
  bound: deadline.bound,
33249
34029
  order: enqueueOrder++,
33250
34030
  attempts: 0,
33251
34031
  running: null,
33252
- range: { ...range, lostSsId: loss.lostSsId, holeLength }
34032
+ range: { lostSsId: loss.lostSsId, holeLength, groups, reportedAt: now },
34033
+ ...walked ? { walk: { next: holeStart, group: null, yielded: false } } : {}
33253
34034
  };
33254
34035
  const previous = entries.get(entry.key);
33255
34036
  if (previous) {
@@ -33259,7 +34040,7 @@ function wireRepairFetch(mc, opts) {
33259
34040
  entries.set(entry.key, entry);
33260
34041
  entry.expiry = setTimeout(dispatch, Math.max(0, entry.deadlineAt - performance.now()) + 1);
33261
34042
  dispatch();
33262
- });
34043
+ }, onHoleExpired);
33263
34044
  }
33264
34045
  const removeRapObserver = mc.addRapCompleteObserver?.((packetId) => {
33265
34046
  queueMicrotask(() => {