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

95.34% Statements 471/494
86.02% Branches 351/408
98.78% Functions 81/82
95.74% Lines 450/470

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 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263                                                                                                                                                                                                                                                                                        597x                           488389x 488389x 488389x 1337393x 1337393x 1337393x   488389x       748557x 259879x   488678x 289x 289x   488389x 488389x       711432x       711432x                       36195x 36195x 36195x 36195x   36195x           737815x 737815x 27013x   710802x 737815x 737815x 737815x 737815x       2243262x 885137x   1358125x 1358125x 1358125x 1358125x             942194x       33426x 33426x 33426x                 597x 597x 597x               172332x 134758x   37574x 37574x 26425x   11149x 1409x   9740x 3162x   6578x 1602x   4976x 1817x   3159x 1719x   1440x             597x 597x     777558x 777558x 800x     800x 800x   777558x         69760x 69760x 777558x 777558x 7562x   769996x 769996x 605117x   164879x     69760x 164879x   69760x                 121773x 57240x 38765x 59533x 59533x 101998x   59533x   38765x       83004x 83004x 83004x 83004x   1327470x 535771x   83004x 83004x 83004x       164879x 544725x 21498x 21498x                             597x 597x                                                       513333x 57037x     57037x 171926x 57037x 148619x   57037x   17240x 27418x 27418x 27418x 27418x 13444x 13444x 13444x 201x   27418x   17240x   57037x   121201x   121201x     57037x 57037x 342222x 226858x       57037x                                   597x       27418x 27418x 27418x 27418x 329190x 658380x   329190x   27418x 164595x 164595x 164595x 164595x 164595x   27418x 27418x       14409x 14409x 14409x 63717x 63717x 63717x 31855x           62840x       435x     63282x               27418x 14409x   13444x         57037x 338x 338x         56699x   7x           57037x         54864x 54864x               725855x     54864x 54864x                               450x 450x 450x 450x               70481x 70481x 18474x   52007x 52007x 52007x 70481x 481148x 481148x 481148x 481148x 4039x   481148x 481148x 102821x 102821x   481148x 481148x 481148x 346503x   134645x     52007x       481148x 481148x   102197x   450x   180x       378321x         180x 180x 180x 180x 180x 35x   145x 145x 145x             180x 180x 180x 35x   145x 145x 145x 145x 290x 290x 149x 149x   141x     145x 145x 141x 141x 141x   4x 4x 4x         37259x 34402x   11446x               226858x 226858x   37443x   37915x   38495x   15109x     37955x   38197x   36853x   664x                             151500x 151500x 26089x 26089x     26089x 26089x 26089x 26089x 437x   25652x     151500x                 37915x 37915x 37915x   37915x 37915x 345x 7801x     37915x   11102x 11102x 7801x 7801x   3301x 3301x   11102x     11102x 11102x 11102x 1x   11101x     37915x         37443x 37443x 3531x 3531x 3531x 121x   3410x 3410x 3410x 3410x 73x   3337x     37443x       37554x 37554x 37554x   185x 431x 431x 431x 42x     185x   37369x 4613x     4613x 4613x     4613x 4613x 4613x 948x   3665x     37369x       115608x 63989x   51619x 51619x         38580x 38580x 38580x                                               38580x 38580x 38580x 338x   38242x 101x   38141x 38141x               7138x 7138x 7134x   4x 4x 4x 4x 4x 4x 4x 2x   2x                 38580x 38580x 38580x 34693x   3887x 302x   3585x                                                                                               716443x 716443x 365x 365x 365x   716078x 163920x 163920x   716078x     716078x       13264x       48567x       76547x       75857x 70450x   5407x       2249x 2249x             23500x 23500x 9125x 9125x   23500x     23500x       113x       688x       637x           575x 503x   72x           739x               301116x       1855652x 1855652x 1581167x   274485x 274485x 274485x                                 9484x           75898x                         38304x 38304x 119810x   38304x 38304x 229824x   38304x                     36855x                           70651x 70651x 602757x   70651x   200124x                                 29209x 25794x 2455x   23339x 11255x   12084x 25794x 25794x 28143x 2478x   25665x 25665x   12084x                       2455x 2455x 2455x 2455x 2455x 2455x 4108x 4108x 1250x   2858x     2455x 2455x 2858x 2858x 48x     2904x                               70649x             70649x 70649x 70649x 70649x 70649x 47953x 47953x 28521x   19432x     70649x 70649x 19432x   70649x 70649x 70649x 602753x           70649x 12540x   70649x 44282x   70649x   602753x               71787x 5539x 1035x 5065x    
/**
 * Exact play items of one chart for the Be-Music Fingerprint (`docs/fingerprint-spec.md`, sections 3.3 – 3.5).
 *
 * A chart is turned into **items** (notes, mines, timeline events, measure lengths, header values) grouped in
 * **buckets**: one per lane, one for mines, one per timeline type, one for measure lengths, and one for the header. A
 * bucket's items depend only on the chart events of that bucket and on the definitions it reads, so the chart
 * fingerprint can recompute just the buckets a `#RANDOM` outcome touches. Items keep everything the engine plays;
 * the drops that depend on the state in effect (a BPM change to the BPM already in effect, …) and the FREE ZONE rule
 * (which depends on the lane mode) are applied afterwards by {@link canonicalizeItems}.
 */
import {
  DEFAULT_BPM,
  LRX_TICKS_PER_BEAT,
  normalizeChannel,
  resolveBMSBase,
  type BeMusicEvent,
  type BeMusicJSON,
} from '@be-music/chart-source';
import {
  compareEvents,
  createBeatResolver,
  isLandmineChannel,
  isPlayableChannel,
  isScrollChannel,
  isStopChannel,
  isTempoChannel,
  mapBMSLongNoteChannelToPlayable,
  resolveChartPlayVariant,
  type ChartPlayVariant,
} from './index.ts';
import { compileChartPlayOptions, type ChartPlayOptions } from './chart-play-options.ts';
import { isLRXLaneType, isPMSChartPath } from './play-variant.ts';
import { resolveGenericBmsonKeyCount } from './generic-bmson.ts';
import { resolveKeyboardModeHint, type KeyboardModeHint } from './keyboard-mode-hint.ts';
import { collectExRankChanges, resolveJudgeRankFacts, resolveTotalFacts } from './resolved-chart.ts';
import {
  resolveBmsonLongNoteMode,
  resolveJudgedNoteEntries,
  resolveMineNotes,
  type JudgedNoteEntry,
  type ResolvedNoteContext,
  variantUsesFreeZone,
} from './resolved-notes.ts';
import { collectScrollChanges, collectSpeedChanges } from './timelines.ts';
import {
  collectStopChanges,
  collectTempoChanges,
  createTimingBuildContext,
  parseStpStop,
  type TimingResolver,
} from './timing.ts';
import {
  addRational,
  compareRational,
  createRational,
  divideRational,
  formatRational,
  isRationalEqual,
  parseDecimalRational,
  parseLeadingDecimalRational,
  RATIONAL_ONE,
  RATIONAL_ZERO,
  rationalFromNumber,
  snapMeasureLength,
  snapValue,
  type Rational,
} from './fingerprint-rational.ts';
 
// ---------------------------------------------------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------------------------------------------------
 
/** A position: measure `m` and the exact fraction `n / d` of that measure (`0 <= n < d`, lowest terms). */
export interface FpTime {
  m: number;
  n: number;
  d: number;
}
 
export type FingerprintTimelineType = 'bpm' | 'stop' | 'stp' | 'scroll' | 'speed' | 'exrank';
 
export interface NoteItem {
  t: FpTime;
  lane: string;
  end?: FpTime;
  /** Long-note mode of a long note: 1 LN, 2 CN, 3 HCN. */
  ln?: number;
  /**
   * Set on a note of lane `17` / `27` that comes from a `1x` / `2x` object or a bmson note: the long-note mode it gets
   * when the lane mode turns that lane into a FREE ZONE (every mode but 9 / 24 / 48 KEY).
   */
  fz?: number;
}
 
export interface MineItem {
  t: FpTime;
  lane: string;
  damage: Rational;
}
 
export interface TimelineItem {
  t: FpTime;
  type: FingerprintTimelineType;
  v: Rational;
}
 
export type JudgeItem = { kind: 'rank'; v: Rational } | { kind: 'exRank'; v: Rational };
export type TotalItem = { kind: 'bms'; v: Rational } | { kind: 'bmson'; v: Rational } | null;
 
export interface HeaderItems {
  bpm: Rational;
  /** `#BASEBPM` as written (`null` when absent); it is dropped when it equals `bpm` at canonicalization. */
  baseBPM: Rational | null;
  judge: JudgeItem;
  total: TotalItem;
  /** `#PLAYER 3`, one of the lane-mode inputs. */
  player3: boolean;
  /** The explicit bmson keyboard or generic hint, one of the lane-mode inputs. */
  modeHint: KeyboardModeHint | `generic-${number}keys` | null;
  /** The LRX `lanetype` when it names a mode, one of the lane-mode inputs. */
  lrxLaneType: number | null;
  /** `false` only for a bmson chart with an explicit `lines: []` (no bar lines drawn). */
  barLines: boolean;
  /**
   * The chart-authored gameplay options its initial `#OPTION` declarations compile to (`compileChartPlayOptions`): they
   * change notes and judging, so they are part of the chart (#932). Empty for a chart without any.
   */
  playOptions: ChartPlayOptions;
}
 
export interface ChartItems {
  /** Notes by lane bucket (`lane:<lane>`). */
  lanes: Map<string, NoteItem[]>;
  mines: MineItem[];
  timeline: Map<FingerprintTimelineType, TimelineItem[]>;
  /** Snapped measure lengths other than 1, by measure. */
  lengths: Map<number, Rational>;
  header: HeaderItems;
}
 
export const TIMELINE_TYPES: ReadonlyArray<FingerprintTimelineType> = [
  'bpm',
  'stop',
  'stp',
  'scroll',
  'speed',
  'exrank',
];
 
// ---------------------------------------------------------------------------------------------------------------------
// Times
// ---------------------------------------------------------------------------------------------------------------------
 
function gcdNumber(left: number, right: number): number {
  let a = Math.abs(left);
  let b = Math.abs(right);
  while (b !== 0) {
    const t = a % b;
    a = b;
    b = t;
  }
  return a;
}
 
export function createTime(measure: number, numerator: number, denominator: number): FpTime {
  if (numerator <= 0) {
    return { m: measure, n: 0, d: 1 };
  }
  if (numerator >= denominator) {
    const carry = Math.floor(numerator / denominator);
    return createTime(measure + carry, numerator - carry * denominator, denominator);
  }
  const divisor = gcdNumber(numerator, denominator);
  return { m: measure, n: numerator / divisor, d: denominator / divisor };
}
 
function normalizePositionDenominator(value: number): number {
  return Number.isFinite(value) && value > 0 ? Math.max(1, Math.floor(value)) : 1;
}
 
function normalizePositionNumerator(value: number, denominator: number): number {
  return Number.isFinite(value) ? Math.max(0, Math.min(denominator - 1, Math.floor(value))) : 0;
}
 
/**
 * Event positions for the fingerprint being computed ({@link withEventTimes}): every outcome of a chart reads the same
 * events again. Kept for one computation only, so a caller that edits its events in place between two fingerprints is
 * never served an old position.
 */
let eventTimes: WeakMap<BeMusicEvent, FpTime> | undefined;
 
/** Runs `compute` with {@link eventTime} remembering each event's position (nested calls share the outer cache). */
export function withEventTimes<T>(compute: () => T): T {
  const outer = eventTimes;
  eventTimes ??= new WeakMap();
  try {
    return compute();
  } finally {
    eventTimes = outer;
  }
}
 
/** The exact position an object is written at: cell index / cell count of its measure line (spec 3.3). */
export function eventTime(event: BeMusicEvent): FpTime {
  const cached = eventTimes?.get(event);
  if (cached !== undefined) {
    return cached;
  }
  const measure = Number.isFinite(event.measure) ? Math.max(0, Math.floor(event.measure)) : 0;
  const denominator = normalizePositionDenominator(event.position[1]);
  const time = createTime(measure, normalizePositionNumerator(event.position[0], denominator), denominator);
  eventTimes?.set(event, time);
  return time;
}
 
export function compareTime(left: FpTime, right: FpTime): number {
  if (left.m !== right.m) {
    return left.m - right.m;
  }
  const a = left.n * right.d;
  const b = right.n * left.d;
  Eif (Number.isSafeInteger(a) && Number.isSafeInteger(b)) {
    return a - b;
  }
  const big = BigInt(left.n) * BigInt(right.d) - BigInt(right.n) * BigInt(left.d);
  return big < 0n ? -1 : big > 0n ? 1 : 0;
}
 
export function formatPosition(time: FpTime): string {
  return time.n === 0 ? '0' : `${time.n}/${time.d}`;
}
 
export function parseTime(m: string, p: string): FpTime {
  const slash = p.indexOf('/');
  const measure = Number.parseInt(m, 10);
  return slash < 0
    ? createTime(measure, Number.parseInt(p, 10), 1)
    : createTime(measure, Number.parseInt(p.slice(0, slash), 10), Number.parseInt(p.slice(slash + 1), 10));
}
 
// ---------------------------------------------------------------------------------------------------------------------
// Buckets
// ---------------------------------------------------------------------------------------------------------------------
 
export const MINES_BUCKET = 'mines';
export const LENGTHS_BUCKET = 'lengths';
export const HEADER_BUCKET = 'header';
 
/**
 * The bucket an event of the given normalized channel feeds, or `undefined` for channels the fingerprint ignores. The
 * channel families are the chart's own (`isPlayableChannel`, `mapBMSLongNoteChannelToPlayable`, `isLandmineChannel`,
 * …), so the fingerprint reads exactly the objects the Resolved layer plays.
 */
export function bucketOfChannel(channel: string): string | undefined {
  if (isPlayableChannel(channel)) {
    return `lane:${channel}`;
  }
  const longNoteLane = mapBMSLongNoteChannelToPlayable(channel);
  if (longNoteLane !== undefined) {
    return `lane:${longNoteLane}`;
  }
  if (isLandmineChannel(channel)) {
    return MINES_BUCKET;
  }
  if (isTempoChannel(channel)) {
    return 'tl:bpm';
  }
  if (isStopChannel(channel)) {
    return 'tl:stop';
  }
  if (isScrollChannel(channel)) {
    return 'tl:scroll';
  }
  if (channel === 'SP') {
    return 'tl:speed';
  }
  return channel === 'A0' ? 'tl:exrank' : undefined;
}
 
/**
 * `bucketOfChannel` of an event's raw channel, remembered: a chart has a few dozen channels but thousands of events.
 * `null` records a channel the fingerprint ignores. Cleared if odd input ever fills it.
 */
const BUCKET_BY_RAW_CHANNEL = new Map<string, string | null>();
const BUCKET_CACHE_LIMIT = 4096;
 
function bucketOfEventChannel(channel: string): string | undefined {
  let bucket = BUCKET_BY_RAW_CHANNEL.get(channel);
  if (bucket === undefined) {
    Iif (BUCKET_BY_RAW_CHANNEL.size >= BUCKET_CACHE_LIMIT) {
      BUCKET_BY_RAW_CHANNEL.clear();
    }
    bucket = bucketOfChannel(normalizeChannel(channel)) ?? null;
    BUCKET_BY_RAW_CHANNEL.set(channel, bucket);
  }
  return bucket ?? undefined;
}
 
/** Events of a chart grouped by bucket, each bucket in the engine's event order. */
export function bucketEvents(events: ReadonlyArray<BeMusicEvent>): Map<string, BeMusicEvent[]> {
  const buckets = new Map<string, BeMusicEvent[]>();
  for (const event of events) {
    const bucket = bucketOfEventChannel(event.channel);
    if (bucket === undefined) {
      continue;
    }
    const list = buckets.get(bucket);
    if (list) {
      list.push(event);
    } else {
      buckets.set(bucket, [event]);
    }
  }
  for (const list of buckets.values()) {
    sortEventsInPlace(list);
  }
  return buckets;
}
 
/**
 * The concatenation of `lists` in the engine's event order, as a stable sort of it would give, when each list is in that
 * order already (`bucketEvents` sorts every bucket): adjacent lists merge pairwise, the earlier list first on a tie. The
 * note resolver then finds its events sorted instead of sorting every lane of every outcome again.
 */
export function mergeSortedEvents(lists: ReadonlyArray<ReadonlyArray<BeMusicEvent>>): BeMusicEvent[] {
  let runs = lists.filter((list) => list.length > 0);
  if (runs.length === 0) return [];
  while (runs.length > 1) {
    const next: Array<ReadonlyArray<BeMusicEvent>> = [];
    for (let index = 0; index < runs.length; index += 2) {
      next.push(index + 1 < runs.length ? mergeTwo(runs[index]!, runs[index + 1]!) : runs[index]!);
    }
    runs = next;
  }
  return [...runs[0]!];
}
 
function mergeTwo(left: ReadonlyArray<BeMusicEvent>, right: ReadonlyArray<BeMusicEvent>): BeMusicEvent[] {
  const merged: BeMusicEvent[] = [];
  let i = 0;
  let j = 0;
  while (i < left.length && j < right.length) {
    // `<=` keeps the left (earlier) list's event first on a tie, as a stable sort of the concatenation does.
    if (compareEvents(left[i]!, right[j]!) <= 0) merged.push(left[i++]!);
    else merged.push(right[j++]!);
  }
  while (i < left.length) merged.push(left[i++]!);
  while (j < right.length) merged.push(right[j++]!);
  return merged;
}
 
function sortEventsInPlace(events: BeMusicEvent[]): void {
  for (let index = 1; index < events.length; index += 1) {
    if (compareEvents(events[index - 1]!, events[index]!) > 0) {
      events.sort(compareEvents);
      return;
    }
  }
}
 
// ---------------------------------------------------------------------------------------------------------------------
// Item computation
// ---------------------------------------------------------------------------------------------------------------------
//
// The items are read with the resolvers the Resolved layer (`resolveChart`) is built from, so the fingerprint follows
// Be-Music's interpretation instead of repeating it: judged notes, long-note pairing, FREE ZONE and one note per lane
// and position (`resolved-notes.ts`), mine damage (`note-rules.ts`), BPM / STOP / `#STP` (`timing.ts`), SCROLL / SPEED
// (`timelines.ts`), and the judge-rank / TOTAL facts (`resolved-chart.ts`). Only the coordinates are the
// fingerprint's own: positions are read exactly from the source events instead of as beats.
 
const DEFAULT_LONG_NOTE_TYPE = 1;
const STOP_UNITS_PER_BEAT: Rational = { n: 48n, d: 1n };
 
/** Context shared by every bucket of one chart. */
interface ItemContext {
  json: BeMusicJSON;
  base: 36 | 62;
  /** `#LNTYPE` as Be-Music resolves it for the whole chart (explicit, else inferred from the `5x` / `6x` objects). */
  lnType: 1 | 2;
  bmson?: BmsonGeometry;
}
 
interface BmsonGeometry {
  resolution: number;
  ticksPerMeasure: number;
  lines: ReadonlyArray<number>;
}
 
/**
 * Computes the items of `json`. With `only`, just those buckets are computed and every other bucket is taken from
 * `reuse` (which must be the items of a chart that differs from `json` only in those buckets).
 */
export function computeChartItems(
  json: BeMusicJSON,
  bucketed: Map<string, BeMusicEvent[]>,
  only?: ReadonlySet<string>,
  reuse?: ChartItems,
  laneCache?: LaneNotesCache,
): ChartItems {
  const wants = (bucket: string): boolean => only === undefined || only.has(bucket);
  const context = createItemContext(json);
 
  // Lanes are independent once `#LNTYPE` is fixed for the whole chart, so the requested lanes resolve together.
  const lanes = new Map<string, NoteItem[]>(only === undefined ? [] : reuse!.lanes);
  let laneBuckets = [...(only ?? bucketed.keys())].filter((bucket) => bucket.startsWith('lane:'));
  for (const bucket of laneBuckets) {
    lanes.delete(bucket);
  }
  if (laneCache !== undefined) {
    // A lane whose events (and the chart's `#LNTYPE`) another outcome already resolved takes that result.
    for (const bucket of laneBuckets) {
      const events = bucketed.get(bucket) ?? [];
      const key = `${context.lnType}|${bucket}|${hashLaneEvents(events)}`;
      let notes = lookupLaneNotes(laneCache, key, events);
      if (notes === undefined) {
        notes = computeLaneNotes(context, events).get(bucket) ?? [];
        const entries = laneCache.get(key);
        if (entries === undefined) laneCache.set(key, [{ events, notes }]);
        else entries.push({ events, notes });
      }
      Eif (notes.length > 0) lanes.set(bucket, notes);
    }
    laneBuckets = [];
  }
  for (const [bucket, notes] of computeLaneNotes(
    context,
    mergeSortedEvents(laneBuckets.map((bucket) => bucketed.get(bucket) ?? [])),
  )) {
    lanes.set(bucket, notes);
  }
 
  const timeline = new Map<FingerprintTimelineType, TimelineItem[]>(only === undefined ? [] : reuse!.timeline);
  for (const type of TIMELINE_TYPES) {
    if (wants(`tl:${type}`)) {
      timeline.set(type, computeTimeline(context, type, bucketed.get(`tl:${type}`) ?? []));
    }
  }
 
  return {
    lanes,
    mines: wants(MINES_BUCKET) ? computeMines(context, bucketed.get(MINES_BUCKET) ?? []) : reuse!.mines,
    timeline,
    lengths: wants(LENGTHS_BUCKET) ? computeLengths(context) : reuse!.lengths,
    header: wants(HEADER_BUCKET) ? computeHeader(json) : reuse!.header,
  };
}
 
/**
 * Resolved notes of lanes, by `#LNTYPE`, lane and a hash of the lane's events (each entry keeps its events, which a hit
 * compares field by field): what `computeDelta` reuses across the outcomes of a chart's factors, which mostly leave a
 * lane in one of a few states. Valid only among outcomes whose chart differs from the top-level one in its events alone
 * (no header, no measure length), as a lane's notes then depend on nothing else.
 */
export type LaneNotesCache = Map<string, Array<{ events: ReadonlyArray<BeMusicEvent>; notes: NoteItem[] }>>;
 
/** {@link hashLaneEvents} per events array: the top-level lanes come back unchanged in many outcomes. */
const LANE_EVENTS_HASHES = new WeakMap<ReadonlyArray<BeMusicEvent>, number>();
 
/** FNV-1a over a lane's events: only narrows the cache lookup, which compares the events themselves. */
function hashLaneEvents(events: ReadonlyArray<BeMusicEvent>): number {
  let hash = LANE_EVENTS_HASHES.get(events);
  Iif (hash !== undefined) return hash;
  hash = 0x811c9dc5;
  const mix = (text: string): void => {
    for (let index = 0; index < text.length; index += 1) {
      hash = Math.imul(hash! ^ text.charCodeAt(index), 0x01000193);
    }
    hash = Math.imul(hash! ^ 0x1f, 0x01000193);
  };
  for (const event of events) {
    hash = Math.imul(hash ^ (event.measure | 0), 0x01000193);
    mix(event.channel);
    mix(event.value);
    hash = Math.imul(hash ^ (event.position[0] | 0), 0x01000193);
    hash = Math.imul(hash ^ (event.position[1] | 0), 0x01000193);
  }
  LANE_EVENTS_HASHES.set(events, hash);
  return hash;
}
 
function sameLaneEvents(left: ReadonlyArray<BeMusicEvent>, right: ReadonlyArray<BeMusicEvent>): boolean {
  Iif (left === right) return true;
  Iif (left.length !== right.length) return false;
  for (let index = 0; index < left.length; index += 1) {
    const a = left[index]!;
    const b = right[index]!;
    if (a === b) continue;
    if (
      a.measure !== b.measure ||
      a.channel !== b.channel ||
      a.value !== b.value ||
      a.bmsLineOrder !== b.bmsLineOrder ||
      a.position.length !== b.position.length ||
      a.position.some((part, at) => part !== b.position[at]) ||
      (a.bmson === undefined) !== (b.bmson === undefined) ||
      (a.bmson !== undefined && JSON.stringify(a.bmson) !== JSON.stringify(b.bmson))
    ) {
      return false;
    }
  }
  return true;
}
 
function lookupLaneNotes(
  cache: LaneNotesCache,
  key: string,
  events: ReadonlyArray<BeMusicEvent>,
): NoteItem[] | undefined {
  for (const entry of cache.get(key) ?? []) {
    if (sameLaneEvents(entry.events, events)) return entry.notes;
  }
  return undefined;
}
 
function createItemContext(json: BeMusicJSON): ItemContext {
  let bmson: BmsonGeometry | undefined;
  if (json.sourceFormat === 'bmson') {
    const resolution = Math.max(1, json.bmson.info.resolution || 240);
    bmson = {
      resolution,
      ticksPerMeasure: Math.max(1, Math.floor(resolution * 4)),
      lines: json.preservation.bmson.lines,
    };
  } else if (json.sourceFormat === 'lrx') {
    // An LRX long note's length is in ticks over measures that start at the chart's measure ticks, as bmson pulses are.
    bmson = {
      resolution: LRX_TICKS_PER_BEAT,
      ticksPerMeasure: LRX_TICKS_PER_BEAT * 4,
      lines: json.lrx?.barTicks ?? [],
    };
  }
  return { json, base: resolveBMSBase(json), lnType: json.bms.lnType === 2 ? 2 : DEFAULT_LONG_NOTE_TYPE, bmson };
}
 
/** `json` reduced to `events`, sharing everything else (the resolvers only read it). */
function withEvents(context: ItemContext, events: BeMusicEvent[]): BeMusicJSON {
  const { json } = context;
  return { ...json, events, bms: { ...json.bms, lnType: context.lnType } };
}
 
/**
 * The note resolver stamps each note with its time in seconds; the fingerprint reads positions only and never a time,
 * so it hands the resolver this stand-in instead of building a BPM / STOP timing resolver for every lane set of every
 * outcome.
 */
const NO_SECONDS = { beatToSeconds: () => 0 } as unknown as TimingResolver;
 
function noteContext(json: BeMusicJSON, freeZone: boolean): ResolvedNoteContext {
  const timingContext = createTimingBuildContext(json);
  return {
    json,
    timing: NO_SECONDS,
    beatResolver: timingContext.beatResolver,
    sortedEvents: timingContext.sortedEvents,
    idBase: resolveBMSBase(json),
    // FREE ZONE depends on the lane mode, which a chart document only knows per outcome: the notes are read without
    // it and `canonicalizeItems` applies it (see `NoteItem.fz`).
    resolvePlayVariant: () => '9',
    freeZone,
    inferBmsLNTypeWhenMissing: false,
  };
}
 
/** The cell right after an object: where an `#LNTYPE 2` run that ends on it stops. */
function nextCellTime(event: BeMusicEvent): FpTime {
  const measure = Math.max(0, Math.floor(event.measure));
  const denominator = normalizePositionDenominator(event.position[1]);
  const numerator = normalizePositionNumerator(event.position[0], denominator);
  return createTime(measure, numerator + 1, denominator);
}
 
/**
 * The judged notes of the given lane events, by lane bucket: `resolveJudgedNoteEntries` (the Resolved layer's notes)
 * without FREE ZONE, with exact start and end positions.
 */
function computeLaneNotes(context: ItemContext, events: BeMusicEvent[]): Map<string, NoteItem[]> {
  const lanes = new Map<string, NoteItem[]>();
  if (events.length === 0) {
    return lanes;
  }
  const json = withEvents(context, events);
  const lnType = json.bmson.info.lnType;
  const chartLongNoteType = lnType === 1 || lnType === 2 || lnType === 3 ? lnType : undefined;
  for (const entry of resolveJudgedNoteEntries(noteContext(json, false)).notes) {
    const time = eventTime(entry.event);
    const note: NoteItem = { t: time, lane: entry.channel };
    const sourceChannel = normalizeChannel(entry.event.channel);
    if (sourceChannel === '17' || sourceChannel === '27') {
      note.fz = resolveBmsonLongNoteMode(entry.event, chartLongNoteType);
    }
    const end = resolveTailTime(context, entry);
    if (end !== undefined && entry.lnMode !== undefined && compareTime(end, time) > 0) {
      note.end = end;
      note.ln = entry.lnMode;
    }
    const bucket = `lane:${entry.channel}`;
    const list = lanes.get(bucket);
    if (list) {
      list.push(note);
    } else {
      lanes.set(bucket, [note]);
    }
  }
  return lanes;
}
 
function resolveTailTime(context: ItemContext, entry: JudgedNoteEntry): FpTime | undefined {
  const tail = entry.tail;
  switch (tail?.kind) {
    case 'event':
      return eventTime(tail.event);
    case 'after-event':
      return nextCellTime(tail.event);
    case 'pulses':
      return context.bmson === undefined
        ? undefined
        : bmsonPulseToTime(context.bmson, bmsonEventPulse(context.bmson, entry.event) + Math.round(tail.pulses));
    default:
      return undefined;
  }
}
 
function bmsonEventPulse(geometry: BmsonGeometry, event: BeMusicEvent): number {
  const measure = Math.max(0, Math.floor(event.measure));
  const denominator = normalizePositionDenominator(event.position[1]);
  const numerator = normalizePositionNumerator(event.position[0], denominator);
  const { lines, ticksPerMeasure } = geometry;
  if (lines.length < 2) {
    return measure * ticksPerMeasure + numerator;
  }
  const last = lines.length - 1;
  Eif (measure < last) {
    return lines[measure]! + numerator;
  }
  return lines[last]! + (measure - last) * ticksPerMeasure + numerator;
}
 
/** Exact inverse of the parser's bmson position mapping: pulse `y` to (measure, position) through `lines`. */
export function bmsonPulseToTime(geometry: BmsonGeometry, pulse: number): FpTime {
  const y = Math.max(0, Math.round(pulse));
  const { lines, ticksPerMeasure } = geometry;
  if (lines.length < 2) {
    return createTime(Math.floor(y / ticksPerMeasure), y % ticksPerMeasure, ticksPerMeasure);
  }
  let low = 0;
  let high = lines.length - 1;
  let index = 0;
  while (low <= high) {
    const middle = (low + high) >> 1;
    if (lines[middle]! <= y) {
      index = middle;
      low = middle + 1;
    } else {
      high = middle - 1;
    }
  }
  const last = lines.length - 1;
  if (index < last) {
    const start = lines[index]!;
    const span = Math.max(1, lines[index + 1]! - start);
    return createTime(index, Math.min(span - 1, y - start), span);
  }
  const offset = y - lines[last]!;
  const measureOffset = Math.floor(offset / ticksPerMeasure);
  return createTime(last + measureOffset, offset - measureOffset * ticksPerMeasure, ticksPerMeasure);
}
 
/** Mines with their damage (`resolveMineNotes`: bmson `damage`, else the BMS value in base 36, else 4). */
function computeMines(context: ItemContext, events: BeMusicEvent[]): MineItem[] {
  if (events.length === 0) {
    return [];
  }
  return resolveMineNotes(noteContext(withEvents(context, events), false)).map((mine) => ({
    t: eventTime(mine.event),
    lane: mine.channel,
    damage: snapValue(rationalFromNumber(mine.damage ?? 0) ?? RATIONAL_ZERO),
  }));
}
 
function computeTimeline(context: ItemContext, type: FingerprintTimelineType, events: BeMusicEvent[]): TimelineItem[] {
  const { json } = context;
  switch (type) {
    case 'stp':
      return computeStp(json);
    case 'stop':
      return computeStops(context, events);
    case 'bpm':
      return lastChangePerTime(
        type,
        collectTempoChanges(json, events).map((change) => ({ event: change.event, value: change.bpm })),
      );
    case 'scroll':
      return lastChangePerTime(type, collectScrollChanges(json, events));
    case 'speed':
      return lastChangePerTime(type, collectSpeedChanges(json, events));
    case 'exrank':
      return lastChangePerTime(
        type,
        collectExRankChanges(json, events, context.base).map((change) => ({
          event: change.event,
          value: parseLeadingDecimalRational(change.raw),
        })),
      );
    default:
      return [];
  }
}
 
/** Changes of one type in chart order; of several at one time the last one is the one Be-Music applies. */
function lastChangePerTime(
  type: FingerprintTimelineType,
  changes: ReadonlyArray<{ event: BeMusicEvent; value: number | Rational | undefined }>,
): TimelineItem[] {
  const items: TimelineItem[] = [];
  for (const change of changes) {
    const exact = typeof change.value === 'number' ? rationalFromNumber(change.value) : change.value;
    Iif (exact === undefined) {
      continue;
    }
    const value = snapValue(exact);
    const time = eventTime(change.event);
    const last = items[items.length - 1];
    if (last && compareTime(last.t, time) === 0) {
      last.v = value;
    } else {
      items.push({ t: time, type, v: value });
    }
  }
  return items;
}
 
/**
 * STOPs in beats (`collectStopChanges`: of several BMS `#STOPxx` at one position the last wins, bmson stops on one pulse
 * add up). A bmson stop's length is read exactly from its `duration` in pulses. A negative BMS `#STOPxx` is the
 * `-1/48` beat LR2 plays for it.
 */
function computeStops(context: ItemContext, events: BeMusicEvent[]): TimelineItem[] {
  const { json, bmson } = context;
  const items: TimelineItem[] = [];
  const beatResolver = createBeatResolver(json);
  // Resource keys deduplicate durations and use the chart's radix; they are not source-event indices.
  const preservedDurationByUnits = new Map<number, number>();
  if (bmson) {
    for (const stop of json.preservation.bmson.stopEvents) {
      preservedDurationByUnits.set((stop.duration * 48) / bmson.resolution, stop.duration);
    }
  }
  for (const stop of collectStopChanges(json, events, beatResolver)) {
    let beats: Rational | undefined;
    const duration = preservedDurationByUnits.get(stop.duration);
    if (bmson && duration !== undefined && duration > 0) {
      const pulses = rationalFromNumber(duration);
      beats = pulses && divideRational(snapValue(pulses), createRational(BigInt(bmson.resolution)));
    } else {
      const units = rationalFromNumber(stop.duration);
      beats = units && divideRational(snapValue(units), STOP_UNITS_PER_BEAT);
    }
    Iif (beats === undefined || beats.n === 0n) {
      continue;
    }
    const time = eventTime(stop.event);
    const last = items[items.length - 1];
    if (last && compareTime(last.t, time) === 0) {
      last.v = addRational(last.v, beats);
    } else {
      items.push({ t: time, type: 'stop', v: beats });
    }
  }
  return items;
}
 
/** `#STP xxx.yyy ms` (`parseStpStop`): at position yyy/1000 of measure xxx, in milliseconds; several at one time add up. */
function computeStp(json: BeMusicJSON): TimelineItem[] {
  const byTime = new Map<string, TimelineItem>();
  for (const raw of json.bms.stp) {
    const stop = parseStpStop(raw);
    const duration = stop && parseDecimalRational(stop.durationText);
    if (stop === undefined || duration === undefined) {
      continue;
    }
    const time = createTime(stop.measure, stop.position, 1000);
    const key = `${time.m}:${time.n}/${time.d}`;
    const existing = byTime.get(key);
    if (existing) {
      existing.v = addRational(existing.v, snapValue(duration));
    } else {
      byTime.set(key, { t: time, type: 'stp', v: snapValue(duration) });
    }
  }
  return [...byTime.values()].sort((left, right) => compareTime(left.t, right.t));
}
 
function computeLengths(context: ItemContext): Map<number, Rational> {
  const lengths = new Map<number, Rational>();
  const { json, bmson } = context;
  if (bmson && bmson.lines.length >= 2) {
    // Exact lengths from the integer pulses of `lines`.
    for (let index = 0; index + 1 < bmson.lines.length; index += 1) {
      const ticks = Math.max(1, bmson.lines[index + 1]! - bmson.lines[index]!);
      const length = snapMeasureLength(createRational(BigInt(ticks), BigInt(bmson.ticksPerMeasure)));
      if (!isRationalEqual(length, RATIONAL_ONE)) {
        lengths.set(index, length);
      }
    }
    return lengths;
  }
  for (const measure of json.measures) {
    Iif (!(measure.length > 0)) {
      continue;
    }
    const exact = rationalFromNumber(measure.length);
    Iif (exact === undefined) {
      continue;
    }
    const index = Math.max(0, Math.floor(measure.index));
    const length = snapMeasureLength(exact);
    if (isRationalEqual(length, RATIONAL_ONE)) {
      lengths.delete(index);
    } else {
      lengths.set(index, length);
    }
  }
  return lengths;
}
 
function optionalSnapped(value: number | undefined): Rational | undefined {
  if (typeof value !== 'number') {
    return undefined;
  }
  const rational = rationalFromNumber(value);
  return rational === undefined ? undefined : snapValue(rational);
}
 
/** Header values, from the same chart facts the Resolved layer exposes (`judgeRank`, `total`, `barLinesSuppressed`). */
function computeHeader(json: BeMusicJSON): HeaderItems {
  const bpm = optionalSnapped(json.metadata.bpm);
  const genericKeys = resolveGenericBmsonKeyCount(json.bmson?.info?.modeHint);
  return {
    bpm: bpm !== undefined && bpm.n > 0n ? bpm : createRational(BigInt(DEFAULT_BPM)),
    baseBPM:
      (typeof json.bms.baseBPM === 'number' && json.bms.baseBPM > 0 && optionalSnapped(json.bms.baseBPM)) || null,
    judge: resolveJudge(json),
    total: resolveTotal(json),
    player3: json.bms.player === 3,
    modeHint:
      genericKeys !== undefined
        ? `generic-${genericKeys}keys`
        : (resolveKeyboardModeHint(json.bmson?.info?.modeHint) ?? null),
    lrxLaneType: json.sourceFormat === 'lrx' && isLRXLaneType(json.lrx?.laneType) ? json.lrx.laneType : null,
    barLines: json.bmson.barlinesSuppressed !== true,
    playOptions: compileChartPlayOptions({
      initial: json.bms.options ?? (json.bms.option ? [json.bms.option] : []),
    }).options,
  };
}
 
/**
 * The judge axis: bmson `judge_rank` (100 when absent or not positive); otherwise a positive `#DEFEXRANK`; otherwise
 * `#RANK` (NORMAL when absent), from `resolveJudgeRankFacts`.
 */
function resolveJudge(json: BeMusicJSON): JudgeItem {
  const { rank, exRank } = resolveJudgeRankFacts(json);
  const positiveExRank = exRank !== undefined && exRank > 0 ? optionalSnapped(exRank) : undefined;
  if (json.sourceFormat === 'bmson') {
    return { kind: 'exRank', v: positiveExRank ?? createRational(100n) };
  }
  if (positiveExRank !== undefined) {
    return { kind: 'exRank', v: positiveExRank };
  }
  const snappedRank = optionalSnapped(rank);
  return { kind: 'rank', v: snappedRank === undefined ? createRational(2n) : normalizeRank(snappedRank) };
}
 
/**
 * `#RANK` values every ruleset reads as NORMAL become `2`: LR2 truncates and maps anything outside 0..4 (and 4) to
 * NORMAL; beatoraja maps anything but the integers 0..4 to NORMAL. Values the rulesets disagree on stay as written.
 */
export function normalizeRank(rank: Rational): Rational {
  const isInteger = rank.d === 1n;
  if (isInteger) {
    return rank.n >= 0n && rank.n <= 4n ? rank : createRational(2n);
  }
  const two = createRational(2n);
  const three = createRational(3n);
  const four = createRational(4n);
  const minusOne = createRational(-1n);
  const between = (low: Rational, high: Rational): boolean =>
    compareRational(rank, low) > 0 && compareRational(rank, high) < 0;
  if (compareRational(rank, minusOne) <= 0 || between(two, three) || compareRational(rank, four) > 0) {
    return two;
  }
  return rank;
}
 
/**
 * TOTAL from `resolveTotalFacts`, on its own axis: a positive `#TOTAL` (absolute), or a positive bmson `total` other
 * than 100 (a percentage of the ruleset's default). Everything the rulesets read as their default TOTAL is `null`: a
 * BMS chart without a positive `#TOTAL`, and a bmson chart whose `total` is absent, 0 or below, or 100 (100 %).
 */
function resolveTotal(json: BeMusicJSON): TotalItem {
  const { value, unit } = resolveTotalFacts(json);
  const snapped = optionalSnapped(value);
  if (snapped === undefined || snapped.n <= 0n) {
    return null;
  }
  if (unit === 'percent') {
    return isRationalEqual(snapped, createRational(100n)) ? null : { kind: 'bmson', v: snapped };
  }
  return { kind: 'bms', v: snapped };
}
 
// ---------------------------------------------------------------------------------------------------------------------
// Formatted (document) items
// ---------------------------------------------------------------------------------------------------------------------
 
export interface FingerprintTime {
  m: string;
  p: string;
}
 
export interface FingerprintNote {
  m: string;
  p: string;
  lane: string;
  end?: FingerprintTime;
  /** Long-note mode: `"1"` LN, `"2"` CN, `"3"` HCN. On long notes and FREE ZONE notes. */
  ln?: string;
  /**
   * FREE ZONE. In a play document: `true` on a note the engine plays as a FREE ZONE note (a long note one beat long
   * with mode `ln`). In a chart document with `random` nodes: the mode such a note of lane `17` / `27` gets if the lane
   * mode of the outcome uses FREE ZONE.
   */
  fz?: true | string;
}
 
export interface FingerprintMine {
  m: string;
  p: string;
  lane: string;
  damage: string;
}
 
export interface FingerprintTimelineEvent {
  m: string;
  p: string;
  type: FingerprintTimelineType;
  v: string;
}
 
export type FingerprintLength = [measure: string, length: string];
 
export type FingerprintJudge = { rank: string } | { exRank: string };
 
export type FingerprintTotal = { bms: string } | { bmson: string } | null;
 
export function formatNote(note: NoteItem, freeZone: 'raw' | 'apply' | 'drop'): FingerprintNote {
  const formatted: FingerprintNote = { m: String(note.t.m), p: formatPosition(note.t), lane: note.lane };
  if (note.fz !== undefined && freeZone === 'apply') {
    formatted.ln = String(note.fz);
    formatted.fz = true;
    return formatted;
  }
  if (note.end !== undefined && note.ln !== undefined) {
    formatted.end = { m: String(note.end.m), p: formatPosition(note.end) };
    formatted.ln = String(note.ln);
  }
  Iif (note.fz !== undefined && freeZone === 'raw') {
    formatted.fz = String(note.fz);
  }
  return formatted;
}
 
export function formatMine(mine: MineItem): FingerprintMine {
  return { m: String(mine.t.m), p: formatPosition(mine.t), lane: mine.lane, damage: formatRational(mine.damage) };
}
 
export function formatTimeline(item: TimelineItem): FingerprintTimelineEvent {
  return { m: String(item.t.m), p: formatPosition(item.t), type: item.type, v: formatRational(item.v) };
}
 
export function formatJudge(judge: JudgeItem): FingerprintJudge {
  return judge.kind === 'rank' ? { rank: formatRational(judge.v) } : { exRank: formatRational(judge.v) };
}
 
export function formatTotal(total: TotalItem): FingerprintTotal {
  if (total === null) {
    return null;
  }
  return total.kind === 'bms' ? { bms: formatRational(total.v) } : { bmson: formatRational(total.v) };
}
 
function parseRationalText(text: string): Rational {
  const slash = text.indexOf('/');
  return slash < 0
    ? createRational(BigInt(text))
    : createRational(BigInt(text.slice(0, slash)), BigInt(text.slice(slash + 1)));
}
 
/** Reads a note of a chart document (raw FREE ZONE form) back into an item. */
export function parseNote(note: FingerprintNote): NoteItem {
  const item: NoteItem = { t: parseTime(note.m, note.p), lane: note.lane };
  if (note.end !== undefined && note.ln !== undefined) {
    item.end = parseTime(note.end.m, note.end.p);
    item.ln = Number.parseInt(note.ln, 10);
  }
  Iif (typeof note.fz === 'string') {
    item.fz = Number.parseInt(note.fz, 10);
  }
  return item;
}
 
export function parseMine(mine: FingerprintMine): MineItem {
  return { t: parseTime(mine.m, mine.p), lane: mine.lane, damage: parseRationalText(mine.damage) };
}
 
export function parseTimeline(item: FingerprintTimelineEvent): TimelineItem {
  return { t: parseTime(item.m, item.p), type: item.type, v: parseRationalText(item.v) };
}
 
export function parseJudge(judge: FingerprintJudge): JudgeItem {
  return 'rank' in judge
    ? { kind: 'rank', v: parseRationalText(judge.rank) }
    : { kind: 'exRank', v: parseRationalText(judge.exRank) };
}
 
export function parseTotal(total: FingerprintTotal): TotalItem {
  if (total === null) {
    return null;
  }
  return 'bms' in total
    ? { kind: 'bms', v: parseRationalText(total.bms) }
    : { kind: 'bmson', v: parseRationalText(total.bmson) };
}
 
export function parseRational(text: string): Rational {
  return parseRationalText(text);
}
 
// ---------------------------------------------------------------------------------------------------------------------
// Sorting and canonical lists
// ---------------------------------------------------------------------------------------------------------------------
 
function compareStrings(left: string, right: string): number {
  return left < right ? -1 : left > right ? 1 : 0;
}
 
export function compareNoteItems(left: NoteItem, right: NoteItem): number {
  const byTime = compareTime(left.t, right.t);
  if (byTime !== 0) {
    return byTime;
  }
  const byLane = compareStrings(left.lane, right.lane);
  Eif (byLane !== 0) {
    return byLane;
  }
  if (left.end === undefined || right.end === undefined) {
    const byEnd = (left.end === undefined ? 0 : 1) - (right.end === undefined ? 0 : 1);
    if (byEnd !== 0) {
      return byEnd;
    }
  } else {
    const byEnd = compareTime(left.end, right.end);
    if (byEnd !== 0) {
      return byEnd;
    }
  }
  return (left.ln ?? 0) - (right.ln ?? 0) || (left.fz ?? 0) - (right.fz ?? 0);
}
 
export function compareMineItems(left: MineItem, right: MineItem): number {
  return (
    compareTime(left.t, right.t) || compareStrings(left.lane, right.lane) || compareRational(left.damage, right.damage)
  );
}
 
export function compareTimelineItems(left: TimelineItem, right: TimelineItem): number {
  return compareTime(left.t, right.t) || compareStrings(left.type, right.type) || compareRational(left.v, right.v);
}
 
/** Items of a whole chart (or a composed outcome), flattened out of their buckets. */
export interface FlatItems {
  notes: NoteItem[];
  mines: MineItem[];
  timeline: TimelineItem[];
  lengths: Map<number, Rational>;
  header: HeaderItems;
}
 
export function flattenItems(items: ChartItems): FlatItems {
  const notes: NoteItem[] = [];
  for (const list of items.lanes.values()) {
    notes.push(...list);
  }
  const timeline: TimelineItem[] = [];
  for (const list of items.timeline.values()) {
    timeline.push(...list);
  }
  return { notes, mines: [...items.mines], timeline, lengths: items.lengths, header: items.header };
}
 
/** The chart-file extension the lane mode reads (spec 3.5, `.n2s` reads as `.pms`); any other counts as none. */
export type LaneModeExtension = '.pms' | null;
 
/**
 * The lane-mode extension of a chart path or bare extension: only the last path segment counts, as in
 * `resolveChartPlayVariant`. A Nanasi Groove 2 `.n2s` chart holds a `.pms` file and reads as `.pms`.
 */
export function resolveLaneModeExtension(chartPath: string | undefined): LaneModeExtension {
  return isPMSChartPath(chartPath) ? '.pms' : null;
}
 
/**
 * Lane mode from the lane-mode inputs: the lanes that hold notes, the extension, `#PLAYER 3`, the bmson keyboard
 * `mode_hint` and the LRX `lanetype` (spec 3.5).
 */
export function resolveFingerprintLaneMode(
  notes: ReadonlyArray<NoteItem>,
  extension: LaneModeExtension,
  player3: boolean,
  modeHint: KeyboardModeHint | `generic-${number}keys` | null,
  lrxLaneType: number | null = null,
): ChartPlayVariant {
  const lanes = new Set<string>();
  for (const note of notes) {
    lanes.add(note.lane);
  }
  return resolveChartPlayVariant({
    chartPath: extension ?? undefined,
    events: [...lanes].map((channel) => ({ channel })),
    bms: { player: player3 ? 3 : 1 },
    ...(modeHint !== null ? { bmson: { info: { modeHint } } } : {}),
    ...(lrxLaneType !== null ? { lrx: { laneType: lrxLaneType } } : {}),
  });
}
 
/**
 * Applies the drops that depend on the state in effect (spec 3.4) to one timeline type, in time order: a BPM change to
 * the BPM in effect, a SCROLL change to the SCROLL in effect, an `#EXRANK` change to the previous `#EXRANK`, and the
 * SPEED keyframes whose removal leaves the speed curve unchanged.
 */
export function dropNoOpChanges(
  type: FingerprintTimelineType,
  items: ReadonlyArray<TimelineItem>,
  initialBPM: Rational,
): TimelineItem[] {
  const sorted = [...items].sort((left, right) => compareTime(left.t, right.t));
  if (type === 'speed') {
    return dropRedundantSpeedKeyframes(sorted);
  }
  if (type !== 'bpm' && type !== 'scroll' && type !== 'exrank') {
    return sorted;
  }
  let current: Rational | undefined = type === 'bpm' ? initialBPM : type === 'scroll' ? RATIONAL_ONE : undefined;
  const kept: TimelineItem[] = [];
  for (const item of sorted) {
    if (current !== undefined && isRationalEqual(current, item.v)) {
      continue;
    }
    current = item.v;
    kept.push(item);
  }
  return kept;
}
 
/**
 * SPEED is interpolated linearly (in beats) between keyframes and holds the last one's value after it. Before the first
 * keyframe it ramps from 1 at measure 0, position 0, as beatoraja ramps from 1.0 at time 0; a keyframe at that position
 * applies at once instead. So the curve runs through a head keyframe (0, 1), replaced by a keyframe at 0, and the
 * keyframes. Within each maximal run of equal consecutive values (head included) only the run's first and last
 * keyframes matter, and the trailing run only its first. The head is written only when a keyframe at 0 sets a value
 * other than 1, so a curve that is 1 throughout has no keyframes.
 */
function dropRedundantSpeedKeyframes(sorted: ReadonlyArray<TimelineItem>): TimelineItem[] {
  const origin: FpTime = { m: 0, n: 0, d: 1 };
  const explicitHead = sorted[0] !== undefined && compareTime(sorted[0].t, origin) === 0 ? sorted[0] : undefined;
  const head: TimelineItem = explicitHead ?? { t: origin, type: 'speed', v: RATIONAL_ONE };
  const points = explicitHead ? sorted : [head, ...sorted];
  const runs: Array<{ first: TimelineItem; last: TimelineItem }> = [];
  for (const item of points) {
    const run = runs[runs.length - 1];
    if (run && isRationalEqual(run.last.v, item.v)) {
      run.last = item;
    } else {
      runs.push({ first: item, last: item });
    }
  }
  const kept: TimelineItem[] = [];
  runs.forEach((run, index) => {
    kept.push(run.first);
    if (index < runs.length - 1 && run.last !== run.first) {
      kept.push(run.last);
    }
  });
  return isRationalEqual(head.v, RATIONAL_ONE) ? kept.filter((item) => item !== head) : kept;
}
 
export interface CanonicalLists {
  laneMode: ChartPlayVariant;
  notes: FingerprintNote[];
  mines: FingerprintMine[];
  timeline: FingerprintTimelineEvent[];
  /** Last measure holding an included event, `-1` when there is none. */
  maxMeasure: number;
}
 
/**
 * Canonical play lists of a fully resolved outcome: lane mode, FREE ZONE, the state-dependent drops, and sorting.
 */
export function canonicalizeItems(items: FlatItems, extension: LaneModeExtension): CanonicalLists {
  const laneMode = resolveFingerprintLaneMode(
    items.notes,
    extension,
    items.header.player3,
    items.header.modeHint,
    items.header.lrxLaneType,
  );
  const freeZone = variantUsesFreeZone(laneMode) ? 'apply' : 'drop';
  const notes = [...items.notes].sort(compareNoteItems);
  const mines = [...items.mines].sort(compareMineItems);
  const byType = new Map<FingerprintTimelineType, TimelineItem[]>();
  for (const item of items.timeline) {
    const list = byType.get(item.type);
    if (list) {
      list.push(item);
    } else {
      byType.set(item.type, [item]);
    }
  }
  const timeline: TimelineItem[] = [];
  for (const [type, list] of byType) {
    timeline.push(...dropNoOpChanges(type, list, items.header.bpm));
  }
  timeline.sort(compareTimelineItems);
  let maxMeasure = -1;
  for (const note of notes) {
    maxMeasure = Math.max(
      maxMeasure,
      note.t.m,
      freeZone === 'apply' && note.fz !== undefined ? -1 : (note.end?.m ?? -1),
    );
  }
  for (const item of mines) {
    maxMeasure = Math.max(maxMeasure, item.t.m);
  }
  for (const item of timeline) {
    maxMeasure = Math.max(maxMeasure, item.t.m);
  }
  return {
    laneMode,
    notes: notes.map((note) => formatNote(note, freeZone)),
    mines: mines.map(formatMine),
    timeline: timeline.map(formatTimeline),
    maxMeasure,
  };
}
 
export function formatLengths(lengths: Map<number, Rational>, count: number): FingerprintLength[] {
  return [...lengths.entries()]
    .filter(([measure, length]) => measure < count && !isRationalEqual(length, RATIONAL_ONE))
    .sort((left, right) => left[0] - right[0])
    .map(([measure, length]): FingerprintLength => [String(measure), formatRational(length)]);
}