All files / chart-model/src fingerprint-chart-model.ts

96.62% Statements 401/415
88.51% Branches 239/270
100% Functions 54/54
96.42% Lines 378/392

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888                                                                                                                                                                                                                                                        4598x 4598x 4598x 4598x 3147x     1451x 1451x               1451x 1451x 1451x 3279x 4x   3275x                   3275x 3275x       3267x 7906x   3275x 3275x       3275x 1451x 8389x 8389x 3685x   8389x 8389x   1451x 3275x 3389x 2557x 2557x 2557x 1567x         1451x 1451x 3275x 3275x 3275x 1567x   1708x       1451x 1451x 1708x       1451x 1451x 1708x 1700x     1451x 1708x   1451x 313x   1138x 1138x     597x               1451x 1451x 1451x 5696x   1451x 12x   1451x           1451x 190134x 482x 482x 482x   482x   189652x 139733x   49919x 49919x     49919x 190134x   1451x                                 157514x 157514x 140830x   16684x 7422x   9262x               1451x 1451x 1451x 1451x 2949x 12x   2937x 6823x 6823x     6823x 1218x   6823x 6823x 3286x   3537x       1451x 3537x   1451x 190134x 422x 189712x 50386x 50386x 2068x       1451x         3275x 190126x 190126x 6034x   4x   6030x 6030x 2742x 2742x 2742x   3288x         969x 969x     480x 480x   478x   460x 478x       865x 865x   496x   3288x   184092x 133706x   50386x 467x   50386x 50386x 50386x 467x   49919x 47143x   47143x 48326x   47143x     2776x                     190126x 2776x 1900x   2776x 2358x                               3275x 3275x 71450x 71450x 8269x 8269x   63181x 1902x   63181x 6292x     3275x 190126x 190126x 139740x   50386x 50386x 3243x   47143x 48326x 48326x 48326x   2626x       3275x 7906x 15812x 1606x   15812x 8016x 8016x 16032x 16032x 4466x           3275x 8269x 8269x 3862x   4407x       4407x 4407x 4407x 7373x 4025x 3348x 344x 344x     4407x           996x 996x 996x       13089x 13089x 5467x 1577x     11512x         3389x 197x   3192x 1380x   1812x 1692x 1692x 980x     832x         3267x 3267x     3267x 11651x       11651x 6208x 6208x 11717x 11717x   6208x   11651x 7906x 7906x   3745x 8384x 8384x 8384x 8384x     3267x                 1708x 8x 8x 8x   8x   3275x 8x     1700x 943x 2549x   757x 757x 2324x 2324x       757x 757x 2324x 2324x 10816x 24689x           2324x   14630x   4474x 1700x                         17179x   29458x 29458x 29458x 78x     29380x 29380x 3479x   29380x 17179x     17179x 17179x   12201x 12201x 12201x 27758x 153817x 153817x   27758x 27758x 27758x 2727x   25031x     12201x   29380x 29380x       26207x 12039x       1700x       43098x 24728x   18370x 40130x     43098x         13600x 100640x 100640x 47532x 47532x 2x   47530x     100640x 13600x   87040x 60086x       13600x 13600x 4334x 549x     13600x               1700x 1700x 1700x 3400x 25160x 25160x 25160x 25160x     1700x 10200x 10200x 9965x   235x 650x 96x     1700x 1317x   383x 1721x                           430x           2903x 1721x 1721x   1182x 1182x 2520x 2520x 2520x     2520x     1182x       20597x               9185x 9185x 9185x   20065x 20065x 20065x 20065x     20065x     9185x           9185x 20065x 20065x   10966x 20065x                     1138x 1138x 1138x 1276x 8x 8x   1268x 12148x 24296x 1300x     12148x 122x   12148x 122x         1138x 1138x 6828x 6828x   1138x   1138x 1276x 8x   1268x   1138x 1138x 1138x                               4478x                 1138x 1276x 148x 1276x    
import { parseHDXLongNoteMode } from './hdx-long-note-mode.ts';
import { isChartPlayOptionDeclaration } from './chart-play-options.ts';
/**
 * The chart fingerprint's model of a chart with control flow (`docs/fingerprint-spec.md`, sections 3.6.3 – 3.6.6):
 * segments are grouped into interacting factors, each factor becomes a reduced decision tree of deltas, what every
 * outcome shares is hoisted, and the chart document is assembled.
 */
import {
  normalizeChannel,
  normalizeObjectKey,
  resolveBMSBase,
  type BeMusicEvent,
  type BeMusicJSON,
  type BMSControlFlowEntry,
} from '@be-music/chart-source';
import { formatRational, isRationalEqual } from './fingerprint-rational.ts';
import {
  analyzeControlFlow,
  classValueRanges,
  countOutcomePaths,
  type ControlFlowAnalysis,
  type ControlFlowVariable,
  type OutcomeNode,
} from './fingerprint-control-flow.ts';
import {
  bucketEvents,
  bucketOfChannel,
  compareMineItems,
  compareNoteItems,
  compareTime,
  compareTimelineItems,
  computeChartItems,
  dropNoOpChanges,
  eventTime,
  flattenItems,
  formatJudge,
  formatLengths,
  formatMine,
  formatNote,
  formatTimeline,
  formatTotal,
  TIMELINE_TYPES,
  type ChartItems,
  type FlatItems,
  type FpTime,
  type HeaderItems,
  type LaneModeExtension,
  type TimelineItem,
} from './fingerprint-items.ts';
import { sha256Hex } from '@be-music/shared-utils/hash';
import {
  type BeMusicChartFingerprintDocument,
  type BeMusicFingerprintDocument,
  FINGERPRINT_FACTOR_OUTCOME_LIMIT,
  FINGERPRINT_VERSION,
  type FingerprintBranch,
  type FingerprintControlFlowNode,
  type FingerprintRandomNode,
  assemblePlayDocument,
  canonicalizeJSONValue,
  formatPlayOptionsField,
} from './fingerprint-document.ts';
import {
  HEADER_FIELDS,
  INDEXED_DEFINITION_PATTERN,
  type ItemDelta,
  type Keyed,
  type ReplayContext,
  applyDelta,
  computeDelta,
  emptyLists,
  formatDelta,
  headerFieldText,
  isEmptyDelta,
  subtractKeyed,
  timeKey,
} from './fingerprint-delta.ts';
 
// ---------------------------------------------------------------------------------------------------------------------
// Chart model: segments, factors, decision trees
// ---------------------------------------------------------------------------------------------------------------------
 
interface SegmentPath {
  /** Variable index → classes this path takes. Variables not listed take any value. */
  classes: Map<number, number[]>;
  entries: number[];
}
 
interface SegmentModel {
  index: number;
  start: number;
  end: number;
  variables: number[];
  /** Paths and their deltas, or `undefined` for an opaque segment (over budget). */
  paths?: SegmentPath[];
  deltas?: ItemDelta[];
  sets: Set<string>;
  uses: Set<string>;
  timeKeys: Set<string>;
  /** Lane → [low, high] of the times the segment can affect in that lane (only lanes where long notes pair). */
  hulls: Map<string, [FpTime | null, FpTime | null]>;
}
 
/** A decision tree over the factor's variables in file order, reduced; leaves are deltas. */
type DeltaTree =
  | { kind: 'leaf'; delta: ItemDelta; text: string }
  | { kind: 'node'; variable: number; branches: Array<{ classes: number[]; tree: DeltaTree }>; text: string };
 
interface FactorModel {
  segments: SegmentModel[];
  tree?: DeltaTree;
  opaque?: string;
}
 
interface ChartModel {
  document: BeMusicFingerprintDocument;
  analysis?: ControlFlowAnalysis;
  /** Content every outcome plays, after hoisting, before the state-dependent drops. */
  topFlat?: FlatItems;
  factors: FactorModel[];
  extension: LaneModeExtension;
}
 
export function buildChartModel(json: BeMusicJSON, extension: LaneModeExtension): ChartModel {
  const entries = json.bms.controlFlow;
  const topBuckets = bucketEvents(json.events);
  const topItems = computeChartItems(json, topBuckets);
  if (entries.length === 0) {
    return { document: assemblePlayDocument(flattenItems(topItems), extension), factors: [], extension };
  }
 
  const analysis = analyzeControlFlow(entries);
  const context: ReplayContext = {
    measureLimit: resolveMeasureLimit(topItems, entries, json),
    top: json,
    topBuckets,
    topItems,
    base: resolveBMSBase(json),
    laneCache: new Map(),
  };
  const pairing = resolvePairingStreams(json, entries, topBuckets);
  const segments: SegmentModel[] = [];
  for (const segment of analysis.segments) {
    if (!segment.hasContent) {
      continue;
    }
    const model: SegmentModel = {
      index: segments.length,
      start: segment.start,
      end: segment.end,
      variables: segment.variables,
      sets: new Set(),
      uses: new Set(),
      timeKeys: new Set(),
      hulls: new Map(),
    };
    collectStaticKeys(model, entries, context.base);
    if (
      segment.root &&
      countOutcomePaths(segment.root, FINGERPRINT_FACTOR_OUTCOME_LIMIT) <= FINGERPRINT_FACTOR_OUTCOME_LIMIT
    ) {
      model.paths = enumeratePaths(segment.root);
      model.deltas = model.paths.map((path) => computeDelta(context, entries, path.entries));
    }
    collectDynamicKeys(model, entries, pairing);
    segments.push(model);
  }
 
  // Factors: segments whose outcomes interact are evaluated together.
  const parent = segments.map((_, index) => index);
  const find = (index: number): number => {
    let root = index;
    while (parent[root] !== root) {
      root = parent[root]!;
    }
    parent[index] = root;
    return root;
  };
  for (let left = 0; left < segments.length; left += 1) {
    for (let right = left + 1; right < segments.length; right += 1) {
      if (segmentsInteract(segments[left]!, segments[right]!)) {
        const a = find(left);
        const b = find(right);
        if (a !== b) {
          parent[Math.max(a, b)] = Math.min(a, b);
        }
      }
    }
  }
  const groups = new Map<number, SegmentModel[]>();
  for (const segment of segments) {
    const root = find(segment.index);
    const group = groups.get(root);
    if (group) {
      group.push(segment);
    } else {
      groups.set(root, [segment]);
    }
  }
 
  const factors: FactorModel[] = [];
  for (const group of groups.values()) {
    factors.push(buildFactor(group, entries, context, analysis));
  }
 
  // Hoist what every outcome of a factor does into the content outside control flow.
  const topFlat = flattenItems(topItems);
  for (const factor of factors) {
    if (factor.tree) {
      factor.tree = hoistCommon(factor.tree, topFlat);
    }
  }
  const liveFactors = factors.filter(
    (factor) => factor.opaque !== undefined || (factor.tree && !isEmptyTree(factor.tree)),
  );
  if (liveFactors.length === 0) {
    return { document: assemblePlayDocument(topFlat, extension), analysis, topFlat, factors: [], extension };
  }
  const document = assembleChartDocument(topFlat, liveFactors, extension, analysis, context.measureLimit);
  return { document, analysis, topFlat, factors: liveFactors, extension };
}
 
const STP_MEASURE_PATTERN = /^\s*(\d{3})/;
 
/**
 * One more than the last measure any outcome can hold an included event in: the events outside control flow, and every
 * object of an included channel and every `#STP` in control-flow lines (plus the measure after a `5x` / `6x` object,
 * where an `#LNTYPE 2` run can end). Spec 3.6.6.
 */
function resolveMeasureLimit(top: ChartItems, entries: ReadonlyArray<BMSControlFlowEntry>, json: BeMusicJSON): number {
  let last = -1;
  const flat = flattenItems(top);
  for (const note of flat.notes) {
    last = Math.max(last, note.t.m, note.end?.m ?? -1);
  }
  for (const item of [...flat.mines, ...flat.timeline]) {
    last = Math.max(last, item.t.m);
  }
  for (const raw of json.bms.stp) {
    const match = STP_MEASURE_PATTERN.exec(raw);
    if (match) {
      last = Math.max(last, Number.parseInt(match[1]!, 10));
    }
  }
  for (const entry of entries) {
    if (entry.kind === 'header' && entry.command === 'STP') {
      const match = STP_MEASURE_PATTERN.exec(entry.value);
      Eif (match) {
        last = Math.max(last, Number.parseInt(match[1]!, 10));
      }
      continue;
    }
    if (entry.kind !== 'object' || entry.events.length === 0) {
      continue;
    }
    const channel = normalizeChannel(entry.channel);
    Iif (bucketOfChannel(channel) === undefined) {
      continue;
    }
    const legacy = streamOfChannel(channel)?.legacy === true;
    last = Math.max(last, entry.measure + (legacy ? 1 : 0));
  }
  return last + 1;
}
 
/**
 * Pairing streams (spec 3.6.3): the sequences of objects whose order decides which objects pair into long notes. Per
 * lane, `obj:<lane>` holds the `1x` / `2x` objects (`#LNOBJ` ends pair with the object before them) and `ln:<lane>`
 * the `5x` / `6x` objects (`#LNTYPE` pairs them by order). A stream counts only when it can pair at all: `obj:` when
 * some `#LNOBJ` exists, `ln:` when the lane has `5x` / `6x` objects anywhere. Each stream lists the times of its
 * objects outside control flow.
 */
interface PairingStreams {
  obj: boolean;
  lnLanes: Set<string>;
  topTimes: Map<string, FpTime[]>;
}
 
function streamOfChannel(channel: string): { stream: string; legacy: boolean } | undefined {
  const side = channel.charCodeAt(0);
  if (side === 0x31 || side === 0x32) {
    return { stream: `obj:${channel}`, legacy: false };
  }
  if (side === 0x35 || side === 0x36) {
    return { stream: `ln:${side === 0x35 ? '1' : '2'}${channel[1]}`, legacy: true };
  }
  return undefined;
}
 
function resolvePairingStreams(
  json: BeMusicJSON,
  entries: ReadonlyArray<BMSControlFlowEntry>,
  topBuckets: Map<string, BeMusicEvent[]>,
): PairingStreams {
  let obj = json.sourceFormat === 'bms' && (json.bms.lnObjs ?? []).length > 0;
  const lnLanes = new Set<string>();
  const topTimes = new Map<string, FpTime[]>();
  for (const [bucket, events] of topBuckets) {
    if (!bucket.startsWith('lane:')) {
      continue;
    }
    for (const event of events) {
      const target = streamOfChannel(normalizeChannel(event.channel));
      Iif (!target) {
        continue;
      }
      if (target.legacy) {
        lnLanes.add(target.stream.slice(3));
      }
      const list = topTimes.get(target.stream);
      if (list) {
        list.push(eventTime(event));
      } else {
        topTimes.set(target.stream, [eventTime(event)]);
      }
    }
  }
  for (const list of topTimes.values()) {
    list.sort(compareTime);
  }
  for (const entry of entries) {
    if (entry.kind === 'header' && entry.command === 'LNOBJ' && entry.value.length > 0) {
      obj = true;
    } else if (entry.kind === 'object') {
      const target = streamOfChannel(normalizeChannel(entry.channel));
      if (target?.legacy) {
        lnLanes.add(target.stream.slice(3));
      }
    }
  }
  return { obj, lnLanes, topTimes };
}
 
/** Definitions a segment sets and uses, from every line it holds (whatever the outcome). */
function collectStaticKeys(model: SegmentModel, entries: ReadonlyArray<BMSControlFlowEntry>, base: 36 | 62): void {
  for (let index = model.start; index < model.end; index += 1) {
    const entry = entries[index]!;
    if (entry.kind === 'header') {
      if (entry.overriddenByLaterHeader === true) {
        // A later top-level line defines the same header, so this one never applies (file order).
        continue;
      }
      const indexed = INDEXED_DEFINITION_PATTERN.exec(entry.command);
      if (indexed) {
        const keyRaw = base === 62 ? (entry.commandRaw ?? entry.command).slice(indexed[1]!.length) : indexed[2]!;
        model.sets.add(`D:${indexed[1]}:${normalizeObjectKey(keyRaw, base)}`);
        continue;
      }
      switch (entry.command) {
        case 'BPM':
        case 'BASEBPM':
        case 'TOTAL':
        case 'PLAYER':
          model.sets.add(`H:${entry.command}`);
          break;
        case 'RANK':
        case 'DEFEXRANK':
          model.sets.add('H:JUDGE');
          break;
        case 'OPTION':
          if (parseHDXLongNoteMode(entry.value) !== undefined) model.sets.add('D:LN');
          // Gameplay options compile in declaration order, so two segments declaring them depend on each other.
          else Eif (isChartPlayOptionDeclaration(entry.value)) model.sets.add('H:OPTION');
          break;
        case 'LNOBJ':
        case 'LNTYPE':
        case 'LNMODE':
          model.sets.add('D:LN');
          break;
        default:
          break;
      }
      continue;
    }
    if (entry.kind !== 'object') {
      continue;
    }
    if (typeof entry.measureLength === 'number' && entry.measureLength > 0) {
      model.sets.add(`M:${entry.measure}`);
    }
    const channel = normalizeChannel(entry.channel);
    const bucket = bucketOfChannel(channel);
    if (bucket === undefined) {
      continue;
    }
    if (bucket.startsWith('lane:')) {
      model.uses.add('D:LN');
      // A lane keeps one judged note per position, so notes of two segments at one position compete.
      for (const event of entry.events) {
        model.timeKeys.add(`${bucket}|${timeKey(eventTime({ ...event, measure: entry.measure }))}`);
      }
      continue;
    }
    const definition =
      channel === '08'
        ? 'BPM'
        : channel === '09'
          ? 'STOP'
          : channel === 'SC'
            ? 'SCROLL'
            : channel === 'SP'
              ? 'SPEED'
              : channel === 'A0'
                ? 'EXRANK'
                : undefined;
    for (const event of entry.events) {
      if (definition !== undefined) {
        model.uses.add(`D:${definition}:${normalizeObjectKey(event.value, base)}`);
      }
      if (bucket.startsWith('tl:')) {
        model.timeKeys.add(`${bucket}|${timeKey(eventTime({ ...event, measure: entry.measure }))}`);
      }
    }
  }
}
 
/**
 * Times a segment touches: the timeline times of its deltas, and for each pairing stream the stretch it can affect —
 * from the last object of the stream outside control flow before the segment's first object (or the deltas' first
 * note) to the first one after its last (spec 3.6.3).
 */
function collectDynamicKeys(
  model: SegmentModel,
  entries: ReadonlyArray<BMSControlFlowEntry>,
  pairing: PairingStreams,
): void {
  const raw = new Map<string, [FpTime, FpTime]>();
  const widen = (stream: string, time: FpTime): void => {
    const hull = raw.get(stream);
    if (!hull) {
      raw.set(stream, [time, time]);
      return;
    }
    if (compareTime(time, hull[0]) < 0) {
      hull[0] = time;
    }
    if (compareTime(time, hull[1]) > 0) {
      hull[1] = time;
    }
  };
  for (let index = model.start; index < model.end; index += 1) {
    const entry = entries[index]!;
    if (entry.kind !== 'object') {
      continue;
    }
    const target = streamOfChannel(normalizeChannel(entry.channel));
    if (!target) {
      continue;
    }
    for (const event of entry.events) {
      const time = eventTime({ ...event, measure: entry.measure });
      widen(target.stream, time);
      if (target.legacy) {
        // A `5x` / `6x` object also resets `#LNOBJ` pairing at its tick.
        widen(`obj:${target.stream.slice(3)}`, time);
      }
    }
  }
  for (const delta of model.deltas ?? []) {
    for (const lists of [delta.add, delta.remove]) {
      for (const { item } of lists.timeline) {
        model.timeKeys.add(`tl:${item.type}|${timeKey(item.t)}`);
      }
      for (const { item } of lists.notes) {
        model.timeKeys.add(`lane:${item.lane}|${timeKey(item.t)}`);
        for (const stream of [`obj:${item.lane}`, `ln:${item.lane}`]) {
          widen(stream, item.t);
          if (item.end) {
            widen(stream, item.end);
          }
        }
      }
    }
  }
  for (const [stream, [low, high]] of raw) {
    const pairs = stream.startsWith('obj:') ? pairing.obj : pairing.lnLanes.has(stream.slice(3));
    if (!pairs) {
      continue;
    }
    Iif (!model.deltas) {
      model.hulls.set(stream, [null, null]);
      continue;
    }
    let before: FpTime | null = null;
    let after: FpTime | null = null;
    for (const time of pairing.topTimes.get(stream) ?? []) {
      if (compareTime(time, low) < 0) {
        before = time;
      } else if (compareTime(time, high) > 0) {
        after = time;
        break;
      }
    }
    model.hulls.set(stream, [before, after]);
  }
}
 
function hullsOverlap(left: [FpTime | null, FpTime | null], right: [FpTime | null, FpTime | null]): boolean {
  // Closed intervals; `null` is −∞ for a low end and +∞ for a high end.
  const leftLowBeforeRightHigh = left[0] === null || right[1] === null || compareTime(left[0], right[1]) <= 0;
  const rightLowBeforeLeftHigh = right[0] === null || left[1] === null || compareTime(right[0], left[1]) <= 0;
  return leftLowBeforeRightHigh && rightLowBeforeLeftHigh;
}
 
function intersects(left: Set<string>, right: Set<string>): boolean {
  const [small, large] = left.size <= right.size ? [left, right] : [right, left];
  for (const key of small) {
    if (large.has(key)) {
      return true;
    }
  }
  return false;
}
 
/** Spec 3.6.3: two segments interact when one's outcome can change how the other's content plays. */
function segmentsInteract(left: SegmentModel, right: SegmentModel): boolean {
  if (intersects(left.sets, right.sets) || intersects(left.sets, right.uses) || intersects(right.sets, left.uses)) {
    return true;
  }
  if (intersects(left.timeKeys, right.timeKeys)) {
    return true;
  }
  for (const [bucket, hull] of left.hulls) {
    const other = right.hulls.get(bucket);
    if (other && hullsOverlap(hull, other)) {
      return true;
    }
  }
  return false;
}
 
/** All paths of a segment's diagram, iteratively. */
function enumeratePaths(root: OutcomeNode): SegmentPath[] {
  const paths: SegmentPath[] = [];
  const stack: Array<{ node: OutcomeNode; classes: Map<number, number[]>; entries: number[] }> = [
    { node: root, classes: new Map(), entries: [] },
  ];
  while (stack.length > 0) {
    let { node, classes, entries } = stack.pop()!;
    // A run of emitted lines is gathered first and appended once: appending line by line copied the path so far for
    // every line, quadratic in a branch that holds a whole chart. `entries` is shared with sibling paths, so it is
    // never changed in place.
    if (node.kind === 'emit') {
      const run: number[] = [];
      while (node.kind === 'emit') {
        run.push(node.entry);
        node = node.next;
      }
      entries = entries.concat(run);
    }
    if (node.kind === 'end') {
      paths.push({ classes, entries });
      continue;
    }
    for (let index = node.branches.length - 1; index >= 0; index -= 1) {
      const branch = node.branches[index]!;
      const next = new Map(classes);
      next.set(node.variable, branch.classes);
      stack.push({ node: branch.node, classes: next, entries });
    }
  }
  return paths;
}
 
function buildFactor(
  segments: SegmentModel[],
  entries: ReadonlyArray<BMSControlFlowEntry>,
  context: ReplayContext,
  analysis: ControlFlowAnalysis,
): FactorModel {
  const opaque = (): FactorModel => {
    const lines: BMSControlFlowEntry[] = [];
    for (const segment of segments) {
      lines.push(...entries.slice(segment.start, segment.end));
    }
    return { segments, opaque: sha256Hex(canonicalizeJSONValue(lines)) };
  };
  if (segments.some((segment) => segment.paths === undefined)) {
    return opaque();
  }
  let joint: Array<{ classes: Map<number, number[]>; delta: ItemDelta }>;
  if (segments.length === 1) {
    const [segment] = segments;
    joint = segment!.paths!.map((path, index) => ({ classes: path.classes, delta: segment!.deltas![index]! }));
  } else {
    let total = 1;
    for (const segment of segments) {
      total *= segment.paths!.length;
      Iif (total > FINGERPRINT_FACTOR_OUTCOME_LIMIT) {
        return opaque();
      }
    }
    let combos: SegmentPath[] = [{ classes: new Map(), entries: [] }];
    for (const segment of segments) {
      const next: SegmentPath[] = [];
      for (const combo of combos) {
        for (const path of segment.paths!) {
          next.push({
            classes: new Map([...combo.classes, ...path.classes]),
            entries: [...combo.entries, ...path.entries],
          });
        }
      }
      combos = next;
    }
    joint = combos.map((combo) => ({ classes: combo.classes, delta: computeDelta(context, entries, combo.entries) }));
  }
  const variables = segments.flatMap((segment) => segment.variables).map((index) => analysis.variables[index]!);
  return { segments, tree: buildDeltaTree(variables, 0, joint) };
}
 
/**
 * Reduced ordered decision tree over `variables[from..]` for paths that partition the outcomes (spec 3.6.4). Subtrees
 * are compared by a text that includes the variables they test, so the tree maps every outcome to its own delta;
 * {@link formatTree} later merges branches whose documents are equal.
 */
function buildDeltaTree(
  variables: ReadonlyArray<ControlFlowVariable>,
  from: number,
  paths: ReadonlyArray<{ classes: Map<number, number[]>; delta: ItemDelta }>,
  memo: Map<string, DeltaTree> = new Map(),
  indices: ReadonlyArray<number> = paths.map((_, index) => index),
): DeltaTree {
  const memoKey = `${from}|${indices.join(',')}`;
  const known = memo.get(memoKey);
  if (known) {
    return known;
  }
  let tree: DeltaTree;
  let level = from;
  while (level < variables.length && !indices.some((index) => paths[index]!.classes.has(variables[level]!.index))) {
    level += 1;
  }
  if (level >= variables.length) {
    Iif (indices.length !== 1) {
      throw new Error('fingerprint: control-flow paths do not partition the outcomes');
    }
    const delta = paths[indices[0]!]!.delta;
    tree = { kind: 'leaf', delta, text: canonicalizeJSONValue(formatDelta(delta)) };
  } else {
    const variable = variables[level]!;
    const groups = new Map<string, { classes: number[]; tree: DeltaTree }>();
    for (const value of variable.classes) {
      const matching = indices.filter((index) => {
        const classes = paths[index]!.classes.get(variable.index);
        return classes === undefined || classes.includes(value);
      });
      const child = buildDeltaTree(variables, level + 1, paths, memo, matching);
      const group = groups.get(child.text);
      if (group) {
        group.classes.push(value);
      } else {
        groups.set(child.text, { classes: [value], tree: child });
      }
    }
    tree = groups.size === 1 ? [...groups.values()][0]!.tree : createNode(variable.index, [...groups.values()]);
  }
  memo.set(memoKey, tree);
  return tree;
}
 
function createNode(variable: number, branches: Array<{ classes: number[]; tree: DeltaTree }>): DeltaTree {
  const text = `{${variable}:${branches.map((branch) => `${branch.classes.join(',')}=${branch.tree.text}`).join(';')}}`;
  return { kind: 'node', variable, branches, text };
}
 
function isEmptyTree(tree: DeltaTree): boolean {
  return tree.kind === 'leaf' && isEmptyDelta(tree.delta);
}
 
function treeLeaves(tree: DeltaTree, out: ItemDelta[] = []): ItemDelta[] {
  if (tree.kind === 'leaf') {
    out.push(tree.delta);
  } else {
    for (const branch of tree.branches) {
      treeLeaves(branch.tree, out);
    }
  }
  return out;
}
 
function commonKeyed<T>(lists: ReadonlyArray<ReadonlyArray<Keyed<T>>>): Array<Keyed<T>> {
  let counts: Map<string, { item: Keyed<T>; count: number }> | undefined;
  for (const list of lists) {
    const local = new Map<string, { item: Keyed<T>; count: number }>();
    for (const entry of list) {
      const existing = local.get(entry.key);
      if (existing) {
        existing.count += 1;
      } else {
        local.set(entry.key, { item: entry, count: 1 });
      }
    }
    if (counts === undefined) {
      counts = local;
    } else {
      for (const [key, value] of counts) {
        value.count = Math.min(value.count, local.get(key)?.count ?? 0);
      }
    }
  }
  const common: Array<Keyed<T>> = [];
  for (const { item, count } of counts?.values() ?? []) {
    for (let index = 0; index < count; index += 1) {
      common.push(item);
    }
  }
  return common;
}
 
/**
 * Moves what every leaf of a factor does into `top` (spec 3.6.5) and rebuilds the factor's tree without it. A factor
 * whose leaves are then all empty plays the same for every outcome.
 */
function hoistCommon(tree: DeltaTree, top: FlatItems): DeltaTree {
  const leaves = treeLeaves(tree);
  const common: ItemDelta = { add: emptyLists(), remove: emptyLists(), header: {} };
  for (const side of ['add', 'remove'] as const) {
    common[side] = {
      notes: commonKeyed(leaves.map((leaf) => leaf[side].notes)),
      mines: commonKeyed(leaves.map((leaf) => leaf[side].mines)),
      timeline: commonKeyed(leaves.map((leaf) => leaf[side].timeline)),
      lengths: commonKeyed(leaves.map((leaf) => leaf[side].lengths)),
    };
  }
  for (const field of HEADER_FIELDS) {
    const first = leaves[0]!.header;
    if (!(field in first)) {
      continue;
    }
    const text = headerFieldText(first, field);
    if (leaves.every((leaf) => field in leaf.header && headerFieldText(leaf.header, field) === text)) {
      (common.header as Record<string, unknown>)[field] = first[field];
    }
  }
  if (isEmptyDelta(common)) {
    return tree;
  }
  applyDelta(top, common);
  return mapTree(tree, (delta) => ({
    add: {
      notes: subtractKeyed(delta.add.notes, common.add.notes),
      mines: subtractKeyed(delta.add.mines, common.add.mines),
      timeline: subtractKeyed(delta.add.timeline, common.add.timeline),
      lengths: subtractKeyed(delta.add.lengths, common.add.lengths),
    },
    remove: {
      notes: subtractKeyed(delta.remove.notes, common.remove.notes),
      mines: subtractKeyed(delta.remove.mines, common.remove.mines),
      timeline: subtractKeyed(delta.remove.timeline, common.remove.timeline),
      lengths: subtractKeyed(delta.remove.lengths, common.remove.lengths),
    },
    header: Object.fromEntries(
      Object.entries(delta.header).filter(([field]) => !(field in common.header)),
    ) as Partial<HeaderItems>,
  }));
}
 
function mapTree(tree: DeltaTree, transform: (delta: ItemDelta) => ItemDelta): DeltaTree {
  if (tree.kind === 'leaf') {
    const delta = transform(tree.delta);
    return { kind: 'leaf', delta, text: canonicalizeJSONValue(formatDelta(delta)) };
  }
  const groups = new Map<string, { classes: number[]; tree: DeltaTree }>();
  for (const branch of tree.branches) {
    const mapped = mapTree(branch.tree, transform);
    const group = groups.get(mapped.text);
    Iif (group) {
      group.classes.push(...branch.classes);
    } else {
      groups.set(mapped.text, { classes: [...branch.classes], tree: mapped });
    }
  }
  return groups.size === 1 ? [...groups.values()][0]!.tree : createNode(tree.variable, [...groups.values()]);
}
 
function formatValueRanges(ranges: ReadonlyArray<[number, number]>): string[] {
  return ranges.map(([low, high]) => (low === high ? String(low) : `${low}-${high}`));
}
 
/**
 * The document node of a tree. Branches whose documents are equal merge (their outcomes play alike, whichever later
 * variable decides them), and a node left with one branch is that branch's nested node.
 */
function formatTree(tree: DeltaTree & { kind: 'node' }, analysis: ControlFlowAnalysis): FingerprintRandomNode {
  const variable = analysis.variables[tree.variable]!;
  const groups = new Map<string, { classes: number[]; content: Omit<FingerprintBranch, 'values'> }>();
  for (const branch of tree.branches) {
    const content: Omit<FingerprintBranch, 'values'> =
      branch.tree.kind === 'node' ? { next: formatTree(branch.tree, analysis) } : formatDelta(branch.tree.delta);
    const text = canonicalizeJSONValue(content);
    const group = groups.get(text);
    Iif (group) {
      group.classes.push(...branch.classes);
    } else {
      groups.set(text, { classes: [...branch.classes], content });
    }
  }
  Iif (groups.size === 1) {
    const only = [...groups.values()][0]!.content;
    if (only.next) {
      return only.next;
    }
  }
  const branches = [...groups.values()].map(({ classes, content }) => {
    const ranges = classValueRanges(variable, classes);
    return { first: ranges[0]![0], branch: { values: formatValueRanges(ranges), ...content } as FingerprintBranch };
  });
  branches.sort((left, right) => left.first - right.first);
  return { random: String(variable.max), branches: branches.map((entry) => entry.branch) };
}
 
function assembleChartDocument(
  top: FlatItems,
  factors: ReadonlyArray<FactorModel>,
  extension: LaneModeExtension,
  analysis: ControlFlowAnalysis,
  count: number,
): BeMusicChartFingerprintDocument {
  // State kinds some factor can change: their no-op drops depend on the outcome (spec 3.4).
  const touched = new Set<string>();
  let anyOpaque = false;
  for (const factor of factors) {
    if (factor.opaque !== undefined || !factor.tree) {
      anyOpaque = true;
      continue;
    }
    for (const leaf of treeLeaves(factor.tree)) {
      for (const lists of [leaf.add, leaf.remove]) {
        for (const { item } of lists.timeline) {
          touched.add(item.type);
        }
      }
      if ('bpm' in leaf.header) {
        touched.add('bpm');
      }
      if ('bpm' in leaf.header || 'baseBPM' in leaf.header) {
        touched.add('baseBPM');
      }
    }
  }
 
  const timeline: TimelineItem[] = [];
  for (const type of TIMELINE_TYPES) {
    const items = top.timeline.filter((item) => item.type === type);
    timeline.push(...(anyOpaque || touched.has(type) ? items : dropNoOpChanges(type, items, top.header.bpm)));
  }
  timeline.sort(compareTimelineItems);
 
  const random = factors.map((factor): FingerprintControlFlowNode => {
    if (factor.opaque !== undefined || !factor.tree || factor.tree.kind !== 'node') {
      return { opaque: factor.opaque ?? '' };
    }
    return formatTree(factor.tree, analysis);
  });
  const { header } = top;
  const baseBPMIsBPM = header.baseBPM !== null && isRationalEqual(header.baseBPM, header.bpm);
  return {
    v: FINGERPRINT_VERSION,
    lanes: {
      extension,
      player3: header.player3,
      ...(header.modeHint !== null ? { modeHint: header.modeHint } : {}),
      ...(header.lrxLaneType !== null ? { lrxLaneType: header.lrxLaneType } : {}),
    },
    bpm: formatRational(header.bpm),
    baseBPM:
      header.baseBPM === null || (baseBPMIsBPM && !anyOpaque && !touched.has('baseBPM'))
        ? null
        : formatRational(header.baseBPM),
    judge: formatJudge(header.judge),
    total: formatTotal(header.total),
    measures: { count: String(count), lengths: formatLengths(top.lengths, count) },
    notes: [...top.notes].sort(compareNoteItems).map((note) => formatNote(note, 'raw')),
    mines: [...top.mines].sort(compareMineItems).map(formatMine),
    timeline: timeline.map(formatTimeline),
    random: sortByCanonicalText(random),
    ...formatPlayOptionsField(header.playOptions),
  };
}
 
function sortByCanonicalText<T>(values: T[]): T[] {
  return values
    .map((value) => ({ value, text: canonicalizeJSONValue(value) }))
    .sort((left, right) => (left.text < right.text ? -1 : left.text > right.text ? 1 : 0))
    .map((entry) => entry.value);
}