All files / player-browser/src/session/play play-chart.ts

94.34% Statements 367/389
92.76% Branches 667/719
93.44% Functions 57/61
95.19% Lines 337/354

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 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467                                                                                                                                                                                                                                                        44x 208x                                                                                                                                                                                                                                                                                                       211x 211x           211x 21x 1x 20x 20x       1x   209x 184x 184x       368x             209x   211x           211x 211x 211x 211x     211x                                               211x     211x 418x   211x     366x         209x       8x           209x         360x                 209x                                           211x 211x 211x 211x                             211x 211x           211x                 211x         209x           1x     208x   22x   211x                                                                       27x 19x                               298x 239x                             210x             211x 211x 211x 211x 211x 211x   211x 211x 211x   211x 211x             208x 43x       86x 86x           43x 43x 43x               165x   165x         165x           165x         165x 1x 4x   1x     1x           165x 337x 223x 337x 337x 223x 337x   337x 337x       165x     165x     165x     165x       165x 2x                 165x       322x 322x 322x             165x 165x 80x   165x                               1498x   161x                     165x                               1498x   51x                           165x 5x                       165x 22x   4x   8x       8x 1x                       208x 208x 208x 208x 208x 1686x 1579x   107x   1686x 208x 788x     208x 208x               208x 208x       211x   81x                 211x       211x 211x 211x       211x 211x 211x   211x     211x   211x       211x   211x       211x         211x 211x 1619x 4x     211x     3x                       211x       211x   211x       211x   211x     51x         211x 211x 211x 211x 211x 211x 211x 211x 211x 211x 16x   211x 211x 832x     208x             211x 211x 211x   211x                                                         208x     208x 208x 208x 208x                         226x         208x 208x                       208x                     208x 208x 2x   206x                             208x             208x 208x 3x 208x               208x 184x                       214x 27x   187x 187x         187x 187x 1x   186x 186x                 46x 44x 44x 44x 22x 6x                                           104x 104x       9x 8x 8x                                                               556x 556x 556x 556x           556x 2x 554x 1x 553x 553x 2x 551x 2x 549x   549x   317x     556x                           136x 1223x   416x       136x                       136x 1639x                     1639x                                     136x                                                                                                                                   136x 1639x   136x     181x 556x 180x         556x   180x 180x 1375x 1375x   180x 186x 587x 587x         180x 44x 44x 295x   44x 44x     136x     46x 46x 46x 46x 338x 338x   46x 46x     90x   2x 2x 12x 12x   2x 2x   2x 1x   14x 2x     88x       88x 88x 88x 757x 757x       88x     88x 13x 48x 13x 13x   88x 88x                       7x 7x     44x                     209x 167x 2x     165x 209x 3x 3x         1686x       44x                 3x 3x 7x 7x 73x 7x 49x 24x 24x 24x   7x 49x 25x 49x     3x                           4x 4x 4x 4x 28x 28x 28x   4x 9x 94x 94x                 7x 36x 36x 36x 36x   7x    
import type { WebAudioSessionSlicePlayback } from '../../runtime/web-audio-session.ts';
import type { PlayJudgeSideState } from './play-presentation.ts';
import { collectLR2SortObjects } from './lr2-sort-objects.ts';
import {
  buildChartOptionTimeline,
  compileChartPlayOptions,
  isLegacyChartPlayOptionProgram,
  type BGAOpacityTimelines,
  type ChartOptionDiagnostic,
  type ChartPlayOptionProgram,
  type PlayerChartPlayOptions,
} from '@be-music/chart-model';
/**
 * Chart preparation for a play (`PlaySession`), whichever family draws it: resolves the chart's `#RANDOM` / `#SWITCH`
 * control flow, prepares the notes the engine judges and the view draws (one shared `PreparedPlaybackChartData`),
 * applies the lane options (DP FLIP, RANDOM / MIRROR / S-RANDOM) or a replay's recorded arrangement, and
 * resets the play's state for the new chart.
 *
 * `prepareChart` reads and writes the play's state through {@link PlayChartContext}; the play session passes itself.
 */
 
import { applySevenToNine } from '@be-music/player-engine/lanes';
 
import {
  isDuplicatedBattleChoice,
  isRandomModeChoice,
  normalizeFloatingLaneCover,
  type RandomMode,
} from '@be-music/player-scene-model';
import {
  resolveChartLongNoteMode,
  resolvePoorBGAMode,
  buildBGAOpacityTimelines,
  PLAY_MODE_LAYOUTS,
  buildKeyBoundBGATimeline,
  resolveChart,
  resolveChartReferenceBPM,
  type RandomDraws,
  type ResolvedChart,
  type TimedSampleTrigger,
  type TimingResolver,
  type ChartPlayVariant,
  createBeatAtSecondsResolverFromTimingResolver,
} from '@be-music/chart-model';
import type { BeMusicEvent, BeMusicJSON } from '@be-music/chart-source';
import {
  applyChartPlayOptions,
  arrangeChartPlayLanes,
  preparePlaybackChart,
  resolveChartNotesPlayVariant,
  resolvePlayChart,
  type ChartPlaySelection,
  type PreparedPlaybackChartData,
} from '@be-music/player-engine';
import { resolveChartPlayProgram } from '@be-music/player-engine/replay';
import {
  isPlayableInputChannel,
  randomizeSRandomNotes,
  createBeatorajaLaneRandom,
  drawLaneRandomIndex,
  parseLaneRandomSeed,
  randomizeLR2ConvergeNotes,
  randomizeLR2ScatterNotes,
  randomizeHRandomNotes,
  randomizeAllScratchNotes,
  randomizePMSConvergeNotes,
  randomizePMSPlayableLanes,
  randomizePMSPlayableNotes,
  randomizeSpiralNotes,
  resolveLaneOptionChannels,
  resolvePlayVariantLaneChannels,
} from '@be-music/player-engine/lanes';
import {
  createScrollDistanceMapper,
  createLR2ConstantScrollMapper,
  type ScrollDistanceMapperLike,
  type TimedLandmineNote,
  type TimedPlayableNote,
} from '@be-music/player-engine/display';
import type { PlayerGaugeSummary } from '@be-music/player-engine/signals';
import {
  createEmptyScore,
  resolveOptionSource,
  type GaugePick,
  type RulesetId,
  type ScoreSummary,
} from '@be-music/player-engine/ruleset';
import { collectChartVolumeMultipliers } from '../../chart/play-audio.ts';
import { resolvePoorBGAFallbackKey } from '../../chart/play-bga.ts';
import { applyReplayArrangement } from '../../chart/replay-arrangement.ts';
import {
  splitNonstopBGATimeline,
  toBrowserBGATimeline,
  type BGACue,
  type NonstopStageBGATimeline,
} from '../../chart/bga-timeline.ts';
import { resolvePlayTempoRange, type PlayTempoRange } from './tempo-range.ts';
import { resolvePlayerMineModifier, type PlaySessionOptions } from './play-options.ts';
import type { LongNoteTracker } from './long-note-tracker.ts';
import { changesScrollRate, collectResolvedLaneTimelineBeats } from '../../chart/note-draw-window.ts';
import { createPlaceholderGaugeState } from './placeholder-gauge.ts';
import {
  createHiSpeedState,
  createPlayState,
  gaugePercent,
  laneCoversFromPlayOptions,
  reducePlayState,
  resolveConstantVisibility,
  resolveHSFixMultiplier,
  resolveLibraryChartPlayVariant,
  SHUTTER_DEFAULT,
  type HiSpeedTransition,
  type LaneCoverState,
  type LibraryChart,
  type PlayState,
} from '@be-music/player-scene-model';
import { resolveLaneSides } from '../../chart/lane-sides.ts';
import { collectBPMGuideEvents, type BPMGuideEvent } from '../../chart/bpm-guide.ts';
import type { SecondPlayerState } from './play-state.ts';
import { isSilentJudgeTimingPlay } from './play-media.ts';
import { applyUndefinedLongNoteMode } from '@be-music/player-engine/course';
import { collectTriggerVoicePlayback } from '../../runtime/play-tempo.ts';
 
/** Whether a battle mode copies one SP chart onto both sides (each copy keeps a 2P source channel). */
const isDuplicatedBattle = (mode: string): boolean =>
  isDuplicatedBattleChoice(mode as Parameters<typeof isDuplicatedBattleChoice>[0]);
 
/** The play state {@link prepareChart} resets and fills for a new chart: the play session's fields of these names. */
 
export interface PlayChartContext {
  readonly options: Readonly<
    Pick<
      PlaySessionOptions,
      | 'visualConstant'
      | 'judgeTimingAutoAdjust'
      | 'hsFix'
      | 'classicHiSpeed'
      | 'floatingHiSpeed'
      | 'fixedDisplayArea'
      | 'normalHiSpeedLevel'
      | 'preResolved'
      | 'hiSpeedLocked'
      | 'hiddenSudden1P'
      | 'hiddenSudden2P'
      | 'lift1P'
      | 'lift2P'
      | 'liftOn1P'
      | 'liftOn2P'
      | 'shutter'
      | 'laneCover'
      | 'coverStart'
      | 'replay'
      | 'fixedArrangement'
      | 'chartSHA256'
      | 'chartMD5'
      | 'dpFlip'
      | 'randomSeed1P'
      | 'randomSeed2P'
      | 'randomFixedLane1P'
      | 'randomFixedLane2P'
      | 'lr2RandomScratch1P'
      | 'lr2RandomScratch2P'
      | 'hRandomThresholdBPM'
      | 'random1P'
      | 'random2P'
      | 'course'
      | 'nonstop'
      | 'judgeRuleset'
      | 'longNoteModifier'
      | 'longNoteRate'
      | 'sevenToNinePattern'
      | 'sevenToNineType'
      | 'battleMode'
      | 'dBattleScratch'
      | 'practiceRange'
      | 'mRan1P'
      | 'mRan2P'
      | 'longNoteMode'
      | 'lr2ExtraMode'
      | 'lr2ExtraLevel'
      | 'lr2Mania'
      | 'tempo'
      | 'extraNoteDepth'
      | 'extraNoteScratch'
      | 'laneKeys'
      | 'scrollSection'
      | 'scrollRate'
      | 'scrollModifier'
      | 'mineModifier'
      | 'crazyAddMine'
      | 'crazyJudge'
      | 'crazyHellJudge'
      | 'crazyNotes'
      | 'autoScratch1P'
      | 'autoScratch2P'
    >
  >;
  chart: LibraryChart | undefined;
  resolvedChart: BeMusicJSON | undefined;
  resolvedPlayChart: ResolvedChart | undefined;
  randomDraws: RandomDraws | undefined;
  randomSeeds?: { p1?: string; p2?: string };
  /**
   * The chart's own gameplay options (#844, #932): the program the play runs and records (a replay's recorded one, else
   * the compiled one narrowed to what takes effect), the lane / mine selection after the chart's choices replaced the
   * player's, and the declarations that lost their effect here (a NOTES COPY in a course).
   */
  chartPlay:
    | {
        program: ChartPlayOptionProgram | undefined;
        /** The options of {@link program} the player added (#1243), which the replay records apart from the chart's. */
        player: PlayerChartPlayOptions;
        selection: ChartPlaySelection;
        diagnostics: readonly ChartOptionDiagnostic[];
      }
    | undefined;
  beatAtSeconds: ((seconds: number) => number) | undefined;
  scrollMapper: ScrollDistanceMapperLike | undefined;
  laneTimelineBeats: Float64Array;
  preparedChart: PreparedPlaybackChartData | undefined;
  notes: TimedPlayableNote[];
  drawNotes: TimedPlayableNote[];
  mineNotes: TimedLandmineNote[];
  invisibleNotes: TimedPlayableNote[];
  maxLongNoteBeatSpan: number;
  chartLastNoteEndSeconds: number;
  chartDurationSeconds: number;
  laneChannels: string[];
  chartPlayVariant: ChartPlayVariant;
  battleSourceVariant: ChartPlayVariant | undefined;
  touchTokenByChannel: Map<string, string> | undefined;
  wavCmdVolumeMultipliers: Map<string, number>;
  bmsonSlicePlayback: Map<BeMusicEvent, WebAudioSessionSlicePlayback> | undefined;
  autoSampleTriggers: TimedSampleTrigger[];
  score: ScoreSummary;
  playState: PlayState;
  secondPlayer: SecondPlayerState | undefined;
  readonly scrollHiSpeed: HiSpeedTransition;
  readonly longNotes: LongNoteTracker;
  chartBPMRange: PlayTempoRange | undefined;
  autoScratchChannels: ReadonlySet<string>;
  playMoments: {
    failedAtMs?: number;
    allNotesDoneAtMs?: number;
    outroAtMs?: number;
    gaugeRiseAtMs?: number;
    gaugeMaxAtMs?: number;
  };
  readonly lanePressedAt: Map<string, number>;
  readonly laneReleasedAt: Map<string, number>;
  lastJudge: string;
  lastJudgeUntil: number;
  judgeSideState: Record<'1P' | '2P', PlayJudgeSideState>;
  gaugeState: PlayerGaugeSummary;
  fastCount: number;
  slowCount: number;
  fullComboFired: boolean;
  timingResolver: TimingResolver | undefined;
  /** The chart's BPM GUIDE labels: its BPM changes, STOPs and `#SCROLL` / `#SPEED` changes. */
  bpmGuideEvents: readonly BPMGuideEvent[];
  nonstopBGATimelines: NonstopStageBGATimeline[] | undefined;
  bgaTimeline: { base: BGACue[]; layer: BGACue[]; layer2?: BGACue[]; poor: BGACue[]; opacity?: BGAOpacityTimelines };
  poorBGAMode: 0 | 1 | 2;
  poorBGAFallbackKey: string | undefined;
  poorBGAFallbackUntilSeconds: number;
  hasBGA: boolean;
  displayedScore: number;
  chartEnded: boolean;
  /** The gauge the run plays on (a replay's recorded pick wins). */
  resolveSelectedGauge(): GaugePick;
}
 
export function prepareChart(ctx: PlayChartContext, chartEntry: LibraryChart): void {
  const arrangement = ctx.options.replay ?? ctx.options.fixedArrangement;
  const sevenToNine = {
    sevenToNinePattern: arrangement ? (arrangement.play.sevenToNinePattern ?? 0) : ctx.options.sevenToNinePattern,
    sevenToNineType: arrangement ? (arrangement.play.sevenToNineType ?? 0) : ctx.options.sevenToNineType,
    hRandomThresholdBPM: arrangement ? arrangement.play.sevenToNineThresholdBPM : ctx.options.hRandomThresholdBPM,
    laneKeys: ctx.options.laneKeys,
  };
  if (ctx.options.fixedArrangement !== undefined && ctx.options.replay === undefined) {
    if ((ctx.options.judgeRuleset ?? 'lr2') !== (ctx.options.fixedArrangement.play.judgeRuleset ?? 'lr2'))
      throw new RangeError('The previous arrangement was played under other judgment rules.');
    const recorded = ctx.options.fixedArrangement.chart;
    if (
      (recorded.sha256 && ctx.options.chartSHA256 && recorded.sha256 !== ctx.options.chartSHA256) ||
      (recorded.md5 && ctx.options.chartMD5 && recorded.md5 !== ctx.options.chartMD5)
    )
      throw new RangeError('The previous arrangement belongs to a different source chart.');
  }
  if (ctx.options.replay === undefined) {
    const ruleset = ctx.options.judgeRuleset ?? 'lr2';
    for (const [mode, duplicated1P] of [
      [ctx.options.random1P, isDuplicatedBattleChoice(ctx.options.battleMode)],
      [ctx.options.random2P, false],
    ] as const) {
      Iif (mode !== undefined && !isRandomModeChoice(mode, duplicated1P))
        throw new RangeError(`${String(mode)} is unavailable for ${ruleset}.`);
    }
  }
  // Resolve `#RANDOM` / `#SETRANDOM` / `#SWITCH` control flow once, first, so every play-time consumer below and the
  // engine see the same chosen branches. The draws are fresh each play (LR2 re-rolls each play); a replay resolves
  // with the draws its log recorded, so it plays the recorded branches.
  const preResolved = arrangement === undefined ? ctx.options.preResolved : undefined;
  const { chart: branchResolved, randomDraws } =
    preResolved ??
    resolvePlayChart(
      chartEntry.chart,
      arrangement?.play.randomDraws !== undefined ? { randomDraws: arrangement.play.randomDraws } : {},
    );
  // A chart's conditional LONGMODE must be known before filling the user's default.
  const resolved = resolvePlayerLongNoteChart(ctx, branchResolved, arrangement?.chart.lnMode);
  ctx.resolvedChart = resolved;
  ctx.randomDraws = randomDraws;
  ctx.randomSeeds = {};
  // BMS spec — `#WAVCMD 01 xx vv` and `#EXWAVxx` per-slot volumes, collected once so every sample trigger is a single
  // Map lookup; slots without an entry take the unity-gain fast path.
  ctx.wavCmdVolumeMultipliers = collectChartVolumeMultipliers(resolved);
  // Build the chart's playable / landmine / invisible note arrays via the engine's own `preparePlaybackChartData`
  // so the renderer holds the exact same `TimedPlayableNote[]` / `TimedLandmineNote[]` instances the engine
  // will judge against. We keep a reference to the entire prepared bundle and forward it through
  // `engineOptions.preparedChart` later, telling the engine to skip its own internal extract pass.
  //
  // This is the structural fix for the whole class of view ↔ engine drift bugs the Phase-4c shared-engine
  // migration kept tripping over: an `inferBmsLNTypeWhenMissing` flag missing on one side, a
  // `bms.controlFlow` array re-resolved on the engine side, a `random1P: 'OFF'` truthy-check evaluating to
  // `false` because `'OFF'` is a non-empty string, a missing `laneModeExtension` mapping PMS to That-Which-Must-Not-Be-Named 10-key
  // DP, … each one shifted the index alignment of the renderer's parallel `this.notes` arrays vs the
  // engine's, and `applyEngineFrame` ended up mirroring `judged` flags onto the wrong note. Sharing the
  // instance means the parallel arrays are no longer parallel — they're the same array, the engine mutates
  // `judged` directly, and the renderer just reads it. There is no second extract that could disagree.
  // Resolve the chart's intended play variant up front so the lane-binding pass sees the host's
  // classification (instead of falling back to the engine's content heuristic). Without this:
  //   - `.bme` POPN-9 charts (full `11..19` on `#PLAYER 1`) classify as `'7'` via the engine's heuristic
  //     and lose the POPN-9 `f/v/g/b` lane bindings on channels `16..19`.
  //   - `.bms` / `.bme` charts that author PMS-STD content (`11..15 + 22..25`, no scratch) classify as
  //     `'10'` (That-Which-Must-Not-Be-Named 5K DP) and route the right-side POPN columns through the That-Which-Must-Not-Be-Named 2P key bindings.
  // `resolveChartPlayVariant` already encodes the right rules for both (see `@be-music/chart-model`); threading
  // the result here gives the engine + adapter + renderer a single source of truth without each one
  // re-running its own heuristic. Classify the RESOLVED chart: lanes that only a chosen `#RANDOM` / `#SWITCH`
  // branch adds are not in `song.chart.events`, and missing them would lay out (and judge) a 7 KEY play as 5 KEY.
  let playVariant = arrangement?.play.battleSourceVariant ?? resolveLibraryChartPlayVariant(chartEntry, resolved);
  // A source-qualified lane option runs its source's algorithm; a bare RANDOM, S-RANDOM or CONVERGE is the judge
  // ruleset's own (ADR 0019).
  const laneSources = [ctx.options.random1P, ctx.options.random2P].map((mode) =>
    resolveOptionSource(mode ?? 'OFF', ctx.options.judgeRuleset ?? 'lr2'),
  );
  Iif (
    ctx.options.replay === undefined &&
    laneSources.some(
      ({ source, name }) => (name === 'CONVERGE' && source === 'lr2') || name === 'CONVERGE-CORRECTED',
    ) &&
    !['5', '7', '9', '10', '14'].includes(playVariant)
  )
    throw new RangeError('LR2 CONVERGE supports 5/7/9/10/14 KEY charts.');
  Iif (
    ctx.options.replay === undefined &&
    playVariant === '9' &&
    [ctx.options.random1P, ctx.options.random2P].some(
      (mode) => mode === 'ALL-SCR' || mode === 'RANDOM-EX' || mode === 'S-RANDOM-EX',
    )
  )
    throw new RangeError(
      'beatoraja PMS uses its own arrangements; ALL-SCR and RANDOM-EX/S-RANDOM-EX require scratch lanes.',
    );
  Iif (
    ctx.options.replay === undefined &&
    playVariant !== '9' &&
    laneSources.some(
      ({ source, name }) =>
        (name === 'CONVERGE' && source === 'beatoraja') || name === 'RANDOM_PLAYABLE' || name === 'S_RANDOM_PLAYABLE',
    )
  )
    throw new RangeError('beatoraja CONVERGE and playable RANDOM/S-RANDOM are PMS arrangements.');
  // A chart's RANDOM and ADDMINE (#844) replace the player's lane and mine options, as the chart author's staging. A
  // replay's recorded notes already hold their result, so only its recorded program is kept (for the engine's judging).
  // Its NOTES conversion (#932) runs in the engine's chart preparation; COPY makes the chart double-play (outside a course,
  // whose stages keep one key mode), so the arrangement maps onto the double-play lanes.
  const chartPlayEffect =
    arrangement === undefined
      ? resolveChartPlayProgram(
          compileChartPlayOptions(buildChartOptionTimeline(resolved)),
          {
            ...(ctx.options.crazyJudge === 'GOOD2BAD' || ctx.options.crazyJudge === 'GREAT2BAD'
              ? { judge: ctx.options.crazyJudge }
              : {}),
            ...(ctx.options.crazyHellJudge === true ? { hellJudge: true as const } : {}),
            ...(ctx.options.crazyNotes !== undefined && ctx.options.crazyNotes !== 'OFF'
              ? { notes: ctx.options.crazyNotes }
              : {}),
          },
          {
            playVariant,
            course: ctx.options.course !== undefined,
          },
        )
      : {
          program: arrangement.chart.chartPlayOptions,
          diagnostics: [],
          playerOptions: { ...arrangement.play.playerChartPlayOptions },
        };
  const chartPlayProgram = chartPlayEffect.program;
  const chartNotes = chartPlayProgram?.options.notes;
  const arrangedVariant = resolveChartNotesPlayVariant(playVariant, chartNotes);
  const chartArrangement = applyChartPlayOptions(
    {
      random1P: ctx.options.random1P,
      random2P: ctx.options.random2P,
      randomFixedLane1P: ctx.options.randomFixedLane1P,
      randomFixedLane2P: ctx.options.randomFixedLane2P,
      lr2RandomScratch1P: ctx.options.lr2RandomScratch1P,
      lr2RandomScratch2P: ctx.options.lr2RandomScratch2P,
      mRan1P: ctx.options.mRan1P,
      mRan2P: ctx.options.mRan2P,
      mineModifier: resolvePlayerMineModifier(ctx.options),
    },
    arrangement === undefined ? chartPlayProgram : undefined,
    { doublePlay: ['10', '14', '48'].includes(arrangedVariant), hasScratch: arrangedVariant !== '9' },
  );
  const lanes = chartArrangement.selection;
  ctx.chartPlay = {
    program: chartPlayProgram,
    player: chartPlayEffect.playerOptions,
    selection: lanes,
    diagnostics: chartPlayEffect.diagnostics,
  };
  let resolvedPlay = resolveChart(resolved, {
    randomDraws,
    playVariant: playVariant,
    inferBmsLNTypeWhenMissing: false,
  });
 
  // The invisible / keysound array is always prepared even when the overlay is off — so the Tweakpane toggle can flip
  // the visualization on mid-song without a chart restart; the per-frame render loop is gated on
  // `showInvisibleNotes`. The audio horizon is left at 0: the engine recomputes its own from realtime triggers.
  Iif (
    (arrangement?.play.scrollModifier === 'SOFTLANDING-1' || arrangement?.play.scrollModifier === 'SOFTLANDING-2') &&
    arrangement.play.scrollModifierTimeline === undefined
  )
    throw new RangeError('A recorded SOFTLANDING requires its effective timeline.');
  if (
    arrangement?.play.scrollModifier === 'ADD' &&
    (arrangement.play.scrollModifierTimeline === undefined ||
      arrangement.play.scrollSection === undefined ||
      arrangement.play.scrollRate === undefined)
  )
    throw new RangeError('A recorded scroll ADD requires its effective timeline.');
  // A recorded copy's 2P side (a duplicated BATTLE, a chart NOTES COPY) is rebuilt from the 1P side's placements.
  const modifierNotes =
    arrangement !== undefined &&
    (isDuplicatedBattle(arrangement.play.battleMode ?? 'OFF') || chartNotes === 'COPY' || chartNotes === 'DBLCOPY')
      ? arrangement.chart.notes.filter((note) => !(note.sourceChannel ?? note.channel).startsWith('2'))
      : arrangement?.chart.notes;
  const prepared = preparePlaybackChart(
    resolvedPlay,
    {
      laneModeExtension: extractChartExtension(ctx.chart?.chartPath),
      laneKeys: ctx.options.laneKeys,
      longNoteModifier: arrangement?.play.longNoteModifier ?? ctx.options.longNoteModifier,
      longNoteRate: arrangement?.play.longNoteRate ?? ctx.options.longNoteRate,
      judgeRuleset: arrangement?.play.judgeRuleset ?? ctx.options.judgeRuleset,
      battleMode: arrangement ? (arrangement.play.battleMode ?? 'OFF') : ctx.options.battleMode,
      dBattleScratch: arrangement
        ? (arrangement.play.dBattleScratch ?? false)
        : ctx.options.dBattleScratch || lanes.lr2RandomScratch1P || lanes.lr2RandomScratch2P,
      // A PRACTICE play loops its range (`play-engine.ts`), which a seamless loop's drawn notes need to know.
      practice:
        arrangement || ctx.options.practiceRange === undefined
          ? undefined
          : { ...ctx.options.practiceRange, loop: true },
      autoScratch1P: arrangement
        ? (arrangement.play.battleAssist1P ?? arrangement.play.autoScratch1P ?? arrangement.play.autoScratch)
        : ctx.options.autoScratch1P,
      autoScratch2P: arrangement
        ? (arrangement.play.battleAssist2P ?? arrangement.play.autoScratch2P ?? arrangement.play.autoScratch)
        : ctx.options.autoScratch2P,
      lr2ExtraMode: arrangement ? (arrangement.play.lr2ExtraMode ?? false) : ctx.options.lr2ExtraMode,
      lr2ExtraLevel: arrangement ? (arrangement.play.lr2ExtraLevel ?? 0) : ctx.options.lr2ExtraLevel,
      // A recorded play rebuilds its generated chart from the recorded rates and seed.
      lr2Mania: arrangement ? arrangement.play.lr2Mania : ctx.options.lr2Mania,
      speed: arrangement
        ? (arrangement.play.battleTempo ?? arrangement.play.lr2ExtraTempo ?? arrangement.play.tempo ?? 1)
        : ctx.options.tempo,
      course: ctx.options.course,
      extraNoteDepth: arrangement ? (arrangement.play.extraNoteDepth ?? 0) : ctx.options.extraNoteDepth,
      extraNoteScratch: arrangement ? (arrangement.play.extraNoteScratch ?? false) : ctx.options.extraNoteScratch,
      ...(arrangement?.play.longNoteModifier?.startsWith('ADD_')
        ? {
            longNoteModifierPlacements: modifierNotes!
              .filter((note) => note.generatedLongNote)
              .map((note) => ({
                sourceChannel: note.sourceChannel ?? note.channel,
                timeUs: note.timeUs,
                endTimeUs: note.endTimeUs!,
                lnMode: note.lnMode!,
              })),
          }
        : {}),
      mineModifier: arrangement?.play.mineModifier ?? lanes.mineModifier,
      scrollModifier: arrangement?.play.scrollModifier ?? ctx.options.scrollModifier,
      scrollSection: arrangement?.play.scrollSection ?? ctx.options.scrollSection,
      scrollRate: arrangement?.play.scrollRate ?? ctx.options.scrollRate,
      scrollModifierTimeline: arrangement?.play.scrollModifierTimeline,
      ...(arrangement?.play.mineModifier?.startsWith('ADD_') || arrangement?.play.mineModifier === 'NANASI_ADD'
        ? {
            mineModifierPlacements: modifierNotes!
              .filter((note) => note.type === 'mine')
              .map((note) => ({
                channel: note.channel,
                sourceChannel: note.sourceChannel,
                timeUs: note.timeUs,
                damage: note.damage,
                silent: note.silent,
              })),
          }
        : {}),
      chartNotes,
      chartNotesLegacy: chartPlayProgram !== undefined && isLegacyChartPlayOptionProgram(chartPlayProgram),
      // LR2 copies 1P's arranged lanes to 2P, mines included, when both players pick the same lane option (#1086). A
      // replay rebuilds its 2P mines only when it recorded them.
      twoPlayerMines: arrangement
        ? arrangement.chart.notes.some(
            (note) => note.type === 'mine' && (note.sourceChannel ?? note.channel).startsWith('2'),
          )
        : (lanes.random1P ?? 'OFF') === (lanes.random2P ?? 'OFF'),
    },
    0,
    Math.random,
  );
  resolvedPlay = prepared.resolvedChart;
  playVariant = resolvedPlay.playVariant;
  ctx.resolvedPlayChart = resolvedPlay;
  ctx.preparedChart = prepared;
  ctx.touchTokenByChannel = undefined;
  ctx.notes = prepared.notes;
  // The same notes, and past a seamless PRACTICE loop's end the next round's: drawn only.
  ctx.drawNotes = prepared.renderNotes;
  ctx.mineNotes = prepared.landmineNotes;
  ctx.invisibleNotes = prepared.invisibleNotes;
  // The recorded rates and seed must rebuild what the play recorded: a different count means another chart.
  const recordedMania = arrangement?.play.lr2Mania;
  Iif (
    recordedMania !== undefined &&
    (['addNotes', 'loudness', 'addLongNotes', 'addMines'] as const).some(
      (field) => prepared.lr2Mania?.changes[field] !== recordedMania.changes[field],
    )
  )
    throw new RangeError('The recorded LR2 mania chart could not be rebuilt from its seed.');
  if (arrangement !== undefined) {
    for (const [side, key] of [
      ['p1', 'randomSeed1P'],
      ['p2', 'randomSeed2P'],
    ] as const) {
      const seed = parseLaneRandomSeed(arrangement.play.options?.[key]);
      if (seed !== undefined) ctx.randomSeeds![side] = seed;
    }
    // Replay playback — the recorded replay carries the FINAL note arrangement (post-flip, post-shuffle), so
    // instead of re-rolling the lane transforms we re-apply the recorded channels onto the freshly prepared
    // notes. A mismatch means the loaded chart is not the one the log was recorded against (different `#RANDOM`
    // roll or a different file) — surface it as a prepare failure rather than replaying garbage.
    applySevenToNine(prepared, sevenToNine);
    const arranged = applyReplayArrangement(arrangement.chart.notes, prepared);
    Iif (!arranged.ok) {
      throw new Error(`replay replay chart mismatch: ${arranged.reason}`);
    }
  } else {
    // DP FLIP — swap 1P / 2P channels in place. Cheap O(n) walk because we already iterate `notes` for sorting; SP
    // charts skip every entry (no `2x` channels exist). Mine notes are flipped together so they stay anchored to the
    // same visual lane after the flip.
    // A duplicated BATTLE chart has identical sides; its source applies no DP FLIP to it.
    const battleDuplicated = isDuplicatedBattle(prepared.battleMode ?? 'OFF');
    // A chart that copied itself onto the 2P side (#932) authored both sides, so DP FLIP leaves them too.
    const chartCopied = prepared.chartNotes === 'COPY' || prepared.chartNotes === 'DBLCOPY';
    // LR2 decides DP FLIP on the source chart's key mode (OpenLR2 `LR2f.cpp` L27318): SP TO DP never flips its doubled
    // chart, and a DP-TO-SP merge flips every note onto the 2P side, out of reach. The corrected SP TO DP leaves the
    // merge unflipped (#1084).
    const flipVariant =
      prepared.battleMode === 'SP-TO-DP'
        ? ctx.options.battleMode === 'SP-TO-DP-CORRECTED'
          ? undefined
          : prepared.battleSourceVariant
        : playVariant;
    const dpFlipped =
      ctx.options.dpFlip === true &&
      !battleDuplicated &&
      !chartCopied &&
      flipVariant !== undefined &&
      ['10', '14', '48'].includes(flipVariant);
    if (dpFlipped) {
      for (const note of ctx.notes) {
        note.channel = flipDPChannel(note.channel);
      }
      for (const mine of ctx.mineNotes) {
        mine.channel = flipDPChannel(mine.channel);
      }
      for (const invisible of ctx.invisibleNotes) {
        invisible.channel = flipDPChannel(invisible.channel);
      }
    }
    // Every lane random draws from the side's seed through Java's `Random`, as beatoraja's modifiers do, whatever the
    // judge rules and the option's source (#933): the seed reproduces the arrangement and is recorded with the play.
    const laneRandom = (side: '1P' | '2P'): (() => number) => {
      if (resolveLaneOptionChannels(side, playVariant, prepared.laneBindings).length === 0) return Math.random;
      const picked = side === '1P' ? ctx.options.randomSeed1P : ctx.options.randomSeed2P;
      const seed = parseLaneRandomSeed(picked ?? '-1');
      Iif (seed === undefined) throw new RangeError('Invalid lane random seed.');
      const resolvedSeed = seed === '-1' ? String(Math.floor(Math.random() * 16777216)) : seed;
      ctx.randomSeeds![side === '1P' ? 'p1' : 'p2'] = resolvedSeed;
      // The upstream chart-wide PMS playable randomizer ignores its modifier seed.
      const mode = side === '1P' ? lanes.random1P : lanes.random2P;
      return mode === 'RANDOM_PLAYABLE' ? Math.random : createBeatorajaLaneRandom(resolvedSeed);
    };
    // Arrange each side independently at chart preparation. LR2 can include the scratch in its draw.
    const battleRandom =
      lanes.random1P === 'SYNCHRONIZE-RANDOM' || lanes.random1P === 'SYMMETRY-RANDOM' ? lanes.random1P : undefined;
    // Two players with the same lane option play one arrangement: LR2 copies 1P's lanes after shuffling them
    // (`battle == 1 && random[0] == random[1]`), as That-Which-Must-Not-Be-Named does for two players' equal options.
    const twoPlayer = prepared.battleMode === 'TWO-PLAYER' || prepared.battleMode === 'COUPLE';
    // A DP chart's two players (LR2 COUPLE) keep their own sides.
    const copied =
      prepared.battleMode === 'TWO-PLAYER' &&
      (prepared.battleSourceVariant === '5' || prepared.battleSourceVariant === '7');
    const twins =
      twoPlayer && copied && (lanes.random1P ?? 'OFF') === (lanes.random2P ?? 'OFF')
        ? pairTwoPlayerTwins([ctx.notes, ctx.mineNotes, ctx.invisibleNotes])
        : undefined;
    // Outside a BATTLE chart the source does not offer these; they leave the chart unchanged.
    if (battleRandom && battleDuplicated)
      applyBattleRandomMode(
        battleRandom,
        resolveLaneOptionChannels('1P', playVariant, prepared.laneBindings),
        resolveLaneOptionChannels('2P', playVariant, prepared.laneBindings),
        laneRandom('1P'),
        ctx.notes,
        ctx.mineNotes,
        ctx.invisibleNotes,
      );
    const usesLR2Sort = [
      { mode: lanes.random1P, includeScratch: lanes.lr2RandomScratch1P },
      { mode: lanes.random2P, includeScratch: lanes.lr2RandomScratch2P },
    ].some(({ mode, includeScratch }) => {
      const ruleset = ctx.options.judgeRuleset ?? 'lr2';
      const selectedMode = mode ?? 'OFF';
      return (
        (playVariant === '14' && usesLR2DoubleRandom(selectedMode, ruleset)) ||
        (includeScratch === true &&
          usesLR2Scratch(selectedMode, playVariant, ruleset) &&
          ['S-RANDOM', 'SCATTER', 'CONVERGE'].includes(resolveOptionSource(selectedMode, ruleset).name))
      );
    });
    const lr2Objects = usesLR2Sort ? collectLR2SortObjects(resolvedPlay, ctx.options.course !== undefined) : undefined;
    const sourceChannels = usesLR2Sort
      ? new Map([...ctx.notes, ...ctx.mineNotes, ...ctx.invisibleNotes].map((note) => [note, note.channel]))
      : undefined;
    applyRandomMode(
      ctx.notes as Array<{ channel: string }>,
      resolveLaneOptionChannels('1P', playVariant, prepared.laneBindings),
      battleRandom ? 'OFF' : (lanes.random1P ?? 'OFF'),
      laneRandom('1P'),
      {
        ruleset: ctx.options.judgeRuleset ?? 'lr2',
        hRandomThresholdBPM: ctx.options.hRandomThresholdBPM,
        fixedLane: lanes.randomFixedLane1P,
        lr2RandomScratch: lanes.lr2RandomScratch1P,
        lr2ScratchSourceVariant: prepared.battleSourceVariant,
        scratch: playVariant === '9' ? undefined : '16',
        scratchLanes:
          playVariant === '9'
            ? []
            : PLAY_MODE_LAYOUTS[playVariant].lanes
                .filter((lane) => lane.side === '1P' && lane.kind !== 'key')
                .sort((a, b) => a.slot - b.slot)
                .map((lane) => lane.channel),
        doublePlay: playVariant === '10' || playVariant === '14' || playVariant === '48',
        side: '1P',
        flipped: dpFlipped,
        playVariant: playVariant,
        lr2Objects,
        sourceChannels,
      },
      ctx.mineNotes as Array<{ channel: string }>,
      ctx.invisibleNotes as Array<{ channel: string }>,
    );
    applyRandomMode(
      ctx.notes as Array<{ channel: string }>,
      resolveLaneOptionChannels('2P', playVariant, prepared.laneBindings),
      battleRandom || twins ? 'OFF' : (lanes.random2P ?? 'OFF'),
      laneRandom('2P'),
      {
        ruleset: ctx.options.judgeRuleset ?? 'lr2',
        hRandomThresholdBPM: ctx.options.hRandomThresholdBPM,
        fixedLane: lanes.randomFixedLane2P,
        lr2RandomScratch: lanes.lr2RandomScratch2P,
        lr2ScratchSourceVariant: prepared.battleSourceVariant,
        scratch: playVariant === '9' ? undefined : '26',
        scratchLanes:
          playVariant === '9'
            ? []
            : PLAY_MODE_LAYOUTS[playVariant].lanes
                .filter((lane) => lane.side === '2P' && lane.kind !== 'key')
                .sort((a, b) => a.slot - b.slot)
                .map((lane) => lane.channel),
        doublePlay: playVariant === '10' || playVariant === '14' || playVariant === '48',
        side: '2P',
        flipped: dpFlipped,
        playVariant: playVariant,
        lr2Objects,
        sourceChannels,
      },
      ctx.mineNotes as Array<{ channel: string }>,
      ctx.invisibleNotes as Array<{ channel: string }>,
    );
    // Chart ALL / ALL+ (#844): one shuffle across both sides' keys, with ALL+ their scratch lanes too. It is
    // nanasigroove's, drawn as the engine draws it for every host and judge ruleset, not through an LR2 or beatoraja
    // lane option (#1245).
    if (chartArrangement.crossSide !== undefined) {
      arrangeChartPlayLanes(
        [
          ctx.notes as Array<{ channel: string }>,
          ctx.mineNotes as Array<{ channel: string }>,
          ctx.invisibleNotes as Array<{ channel: string }>,
        ],
        chartArrangement.crossSide.scratch ? 'ALL+' : 'ALL',
        playVariant,
        laneRandom('1P'),
        prepared.laneBindings,
      );
    }
    if (twoPlayer) {
      for (const [second, first] of twins ?? []) second.channel = `2${first.channel.slice(1)}`;
      // M-RAN mirrors a player's side after its RANDOM-type option, under every ruleset with two-player play (#774).
      for (const side of ['1P', '2P'] as const) {
        // The lane option in force (the chart's RANDOM replaces the player's, #844), by name without its source.
        const mode = resolveOptionSource(
          (side === '1P' ? lanes.random1P : lanes.random2P) ?? 'OFF',
          ctx.options.judgeRuleset ?? 'lr2',
        ).name;
        if ((side === '1P' ? lanes.mRan1P : lanes.mRan2P) && M_RAN_RANDOM_MODES.has(mode))
          applyRandomMode(
            ctx.notes as Array<{ channel: string }>,
            resolveLaneOptionChannels(side, playVariant, prepared.laneBindings),
            'MIRROR',
            Math.random,
            {},
            ctx.mineNotes as Array<{ channel: string }>,
            ctx.invisibleNotes as Array<{ channel: string }>,
          );
      }
    }
  }
  if (!arrangement) applySevenToNine(prepared, sevenToNine);
  resolvedPlay = prepared.resolvedChart;
  playVariant = resolvedPlay.playVariant;
  ctx.resolvedPlayChart = resolvedPlay;
  ctx.maxLongNoteBeatSpan = ctx.notes.reduce((max, note) => {
    if (note.endBeat === undefined) {
      return max;
    }
    return Math.max(max, Math.max(0, note.endBeat - note.beat));
  }, 0);
  ctx.chartLastNoteEndSeconds = ctx.notes.reduce((acc, note) => Math.max(acc, note.endSeconds ?? note.seconds), 0);
  ctx.chartLastNoteEndSeconds = ctx.mineNotes.reduce(
    (end, mine) => Math.max(end, mine.seconds),
    ctx.chartLastNoteEndSeconds,
  );
  ctx.chartDurationSeconds = ctx.chartLastNoteEndSeconds;
  ctx.chartEnded = false;
  // Drop the previous chart's active-sample tracking. Stale entries would otherwise let a `c=true` note on the new
  // chart suppress its own first trigger because a same-key node from the old play looks "still playing" until it
  // ends naturally.
 
  // Lay out the whole keyboard of the chart's play variant (5 / 7 / 9 / 10 / 14 / 24 / 48 KEY), not just the lanes
  // the chart happens to use, so a sparse chart still plays on full lanes. The variant also decides channel `17`
  // (a lane in 9 KEY, FREE ZONE in That-Which-Must-Not-Be-Named) and the 9 KEY layout the LR2 default 9-keys play skin expects.
  ctx.chartPlayVariant = playVariant;
  ctx.battleSourceVariant =
    prepared.battleMode !== undefined && prepared.battleMode !== 'OFF' ? prepared.battleSourceVariant : undefined;
  // Keep the source PMS layout even when an arrangement empties its distinguishing channels.
  // Original LR2 SCATTER may place an object outside it; that object must not create a tenth input/display lane.
  ctx.laneChannels =
    ctx.chartPlayVariant === '9'
      ? prepared.laneBindings.map((binding) => binding.channel)
      : resolvePlayVariantLaneChannels(ctx.notes, ctx.chartPlayVariant);
  // Initialize from `prepared.scorableNotes.length` so the view's initial `score.total` matches the engine's
  // authoritative `summary.total` (= same `scorableNotes` filter, with Free-Zone channels excluded). Without
  // this, charts that use a Free-Zone channel had a renderer-side total larger than the engine's by the
  // Free-Zone count, and `maybeFireFullCombo`'s `combo === score.total` predicate became
  // unreachable — combo could only ever climb to the engine's smaller scorable count, and the FC cue never
  // fired. `applyEngineFrame` still mirrors `summary.total` defensively each frame, but that's now a no-op
  // on the common path.
  ctx.score = createEmptyScore(prepared.scorableNotes.length);
  // Wipe per-side judge / combo snapshots so a fresh chart doesn't briefly paint the previous play's verdict on its
  // first frame (the `until` chart-time is in the previous chart's coordinate system; comparing it to the new chart's
  // `currentSeconds()` would render stale state until the new play crosses that mark).
  ctx.lastJudge = '';
  ctx.lastJudgeUntil = 0;
  ctx.judgeSideState = {
    '1P': { judge: '', until: 0, combo: 0 },
    '2P': { judge: '', until: 0, combo: 0 },
  };
  const resolver = resolvedPlay.timing;
  ctx.timingResolver = resolver;
  ctx.bpmGuideEvents = collectBPMGuideEvents(resolver, resolvedPlay.scroll, resolvedPlay.speed);
  // Build a STOP-aware seconds→beat resolver for `currentBeat`.
  ctx.beatAtSeconds = createBeatAtSecondsResolverFromTimingResolver(resolver);
  // Build the #SCROLL / #SPEED distance integrator. Skipped when the chart has no such events, or only ones at 1, so
  // the common case stays on the plain beat-diff path with no extra cost (and on its ruleset's drawing rules).
  const scrollTimeline = resolvedPlay.scroll;
  // CONSTANT ignores `#SPEED`, unless a NO_SPEED course turns it off.
  const constant = resolveConstantVisibility({
    enabled: ctx.options.visualConstant,
    noSpeed: ctx.options.hiSpeedLocked,
  });
  const speedTimeline = constant.enabled ? [] : resolvedPlay.speed;
  const lr2Constant =
    ctx.options.hsFix === 'CONSTANT' &&
    !ctx.options.floatingHiSpeed &&
    !ctx.options.classicHiSpeed &&
    !((ctx.options.normalHiSpeedLevel ?? 0) > 0);
  ctx.scrollMapper = lr2Constant
    ? createLR2ConstantScrollMapper(resolver.tempoPoints)
    : changesScrollRate(scrollTimeline, speedTimeline)
      ? createScrollDistanceMapper(scrollTimeline, speedTimeline, { invalidDistance: 0 })
      : undefined;
  ctx.laneTimelineBeats = collectResolvedLaneTimelineBeats(resolvedPlay);
  ctx.autoSampleTriggers = resolvedPlay.sampleTriggers
    .filter((trigger) => !isPlayableInputChannel(trigger.channel))
    .sort((left, right) => left.seconds - right.seconds);
  // Use the model's source-channel slicing, including boundaries whose up event has no matching LN.
  // Recomputing from displayed notes would omit those silent boundaries and lengthen the preceding slice.
  ctx.bmsonSlicePlayback =
    resolved.sourceFormat === 'bmson'
      ? new Map(
          resolvedPlay.sampleTriggers.map((trigger) => [
            trigger.event,
            {
              offsetSeconds: trigger.sampleOffsetSeconds,
              durationSeconds: trigger.sampleDurationSeconds,
              sliceId: trigger.sampleSliceId ?? `${trigger.sampleKey}:beat:${trigger.beat}`,
            },
          ]),
        )
      : resolved.sourceFormat === 'lrx'
        ? collectTriggerVoicePlayback(resolvedPlay.sampleTriggers)
        : undefined;
  ctx.chartDurationSeconds = Math.max(ctx.chartLastNoteEndSeconds, ctx.autoSampleTriggers.at(-1)?.seconds ?? 0);
  // Initialize gauge with the actual playable-note count and the chart's #TOTAL value so PG/GR gain matches LR2: a
  // long chart with TOTAL=300 and 1000 notes gets +0.3 per PG/GR, while a short TOTAL=160 100-note chart gets +1.6
  // per PG/GR.
  ctx.gaugeState = createPlaceholderGaugeState(ctx.resolveSelectedGauge(), resolveCourseStartGaugeInput(ctx));
  // The one BPM range of the play: HS-FIX, the HUD and the replay's visible time all take the main BPM from it.
  ctx.chartBPMRange = resolvePlayTempoRange(
    resolvedPlay,
    resolved.metadata.bpm > 0 ? resolved.metadata.bpm : ctx.chart?.bpm,
  );
  ctx.playState = createChartPlayState(ctx, resolver, resolveChartReferenceBPM(resolved, ctx.chart?.bpm));
  // A two-player play's 2P player starts from the same clean slate; the engine's frames fill its gauge in.
  ctx.secondPlayer =
    prepared.battleMode === 'TWO-PLAYER' || prepared.battleMode === 'COUPLE'
      ? {
          score: createEmptyScore(prepared.scorableNotes.filter((note) => note.channel.startsWith('2')).length),
          playState: createPlayState({ totalSeconds: ctx.chartDurationSeconds }),
        }
      : undefined;
  // Chart setup, before the notes are on screen — no glide.
  ctx.scrollHiSpeed.jump(ctx.playState.view.hiSpeed.drawn);
  ctx.fastCount = 0;
  ctx.slowCount = 0;
  ctx.fullComboFired = false;
  ctx.displayedScore = 0;
  ctx.longNotes.clear();
  ctx.playMoments = {};
  ctx.lanePressedAt.clear();
  ctx.laneReleasedAt.clear();
  ctx.autoScratchChannels = resolveAutoScratchEnabled(ctx)
    ? new Set(prepared.laneBindings.filter((binding) => binding.isScratch).map((binding) => binding.channel))
    : new Set();
  ctx.bgaTimeline = toBrowserBGATimeline(resolvedPlay.bga);
  const opacity = buildBGAOpacityTimelines(resolvedPlay.source, resolvedPlay.timing);
  Iif ([opacity.base, opacity.layer, opacity.layer2, opacity.poor].some((cues) => cues.length > 0)) {
    ctx.bgaTimeline.opacity = opacity;
  }
  ctx.nonstopBGATimelines =
    ctx.options.nonstop !== undefined
      ? splitNonstopBGATimeline(ctx.bgaTimeline, ctx.options.nonstop.stages)
      : undefined;
  // BMS spec — when `#BMP00` exists (and `#POORBGA` is not 2), BMP00 becomes the implicit POOR placeholder until an
  // explicit `#xxx06` cue fires. Mirrors the TUI BGA renderer's `poorFallbackKey` so the web side stops showing a
  // black POOR plate on misses for charts that rely on this convention.
  ctx.poorBGAMode = resolvePoorBGAMode(resolved.bms.poorBGA);
  ctx.poorBGAFallbackKey = resolvePoorBGAFallbackKey(resolved);
  ctx.poorBGAFallbackUntilSeconds = ctx.bgaTimeline.poor[0]?.seconds ?? Number.POSITIVE_INFINITY;
  // LR2's SILENT automatic judge timing loads no BGA.
  ctx.hasBGA =
    !isSilentJudgeTimingPlay(ctx.options) &&
    (ctx.bgaTimeline.base.length > 0 ||
      ctx.bgaTimeline.layer.length > 0 ||
      (ctx.bgaTimeline.layer2?.length ?? 0) > 0 ||
      ctx.bgaTimeline.poor.length > 0 ||
      (resolved.lrx?.bga?.length ?? 0) > 0 ||
      (ctx.options.nonstop?.bmsonBGA?.some((cue) => cue.sequences.length > 0) ?? false) ||
      (ctx.options.nonstop?.keyBoundBGA ?? buildKeyBoundBGATimeline(resolvedPlay.source, resolvedPlay.timing)).length >
        0);
}
 
/**
 * The play state a new chart starts from: the starting gauge (LR2's 20 %, a course stage's carried-in gauge) seeding
 * the graphs at the chart's start, the chart's length the graphs are taken over, a course stage's carried-in combo,
 * and the view — the player's hi-speed (the one in force, so a host's setting before the chart is kept) under the
 * chart's HS-FIX, and each side's lane covers from the play options.
 *
 * HS-FIX keeps the player's hi-speed at the chart's reference BPM (`#BASEBPM`, else the start BPM:
 * `resolveChartReferenceBPM` prefers `#BASEBPM` so a chart whose `#BPM` is its peak or average still calibrates at the
 * speed the author intended) and rescales it at the chart's MAXBPM, MINBPM or main BPM (`resolveHSFixMultiplier`), the
 * main BPM being the play's (`chartBPMRange`), which the replay's visible time reads too.
 */
function createChartPlayState(
  ctx: PlayChartContext,
  resolver: TimingResolver,
  referenceBPM: number | undefined,
): PlayState {
  const hsFix =
    ctx.options.floatingHiSpeed || ctx.options.classicHiSpeed || (ctx.options.normalHiSpeedLevel ?? 0) > 0
      ? 'OFF'
      : (ctx.options.hsFix ?? 'OFF');
  const mainBPM = ctx.chartBPMRange?.mainBPM;
  const covers = resolveStartingCovers(ctx);
  const firstCover = covers[0];
  const hiSpeed = createHiSpeedState({
    hiSpeed: ctx.playState.view.hiSpeed.player,
    classic: ctx.options.classicHiSpeed,
    floating: ctx.options.floatingHiSpeed,
    visibleFraction: Math.max(
      0,
      1 - (firstCover?.suddenOn ? firstCover.sudden : 0) - (firstCover?.liftOn ? firstCover.lift : 0),
    ),
    normalLevel: ctx.options.classicHiSpeed ? undefined : ctx.options.normalHiSpeedLevel,
    bpm: resolver.bpmAtBeat(0),
    multiplier: resolveHSFixMultiplier(hsFix, {
      ...(referenceBPM !== undefined ? { referenceBPM } : {}),
      startBPM: ctx.resolvedChart?.metadata.bpm || ctx.chart?.bpm || resolver.tempoPoints[0]?.bpm,
      bpms: resolver.tempoPoints.map((point) => point.bpm),
      ...(mainBPM !== undefined ? { mainBPM } : {}),
    }),
    locked: ctx.options.hiSpeedLocked === true,
  });
  const course = ctx.options.course;
  const started = createPlayState({
    gauge: gaugePercent(ctx.gaugeState),
    totalSeconds: ctx.chartDurationSeconds,
    ...(course !== undefined ? { courseCarryIn: course.carryIn ?? { combo: 0, maxCombo: 0 } } : {}),
    view: {
      hiSpeed,
      covers,
      ...(ctx.options.fixedDisplayArea ? { fixedDisplayArea: true as const } : {}),
      hsFix,
    },
  });
  // The starting gauge's type and verdict, so a play given up before the engine's first frame still names its gauge.
  return reducePlayState(started, {
    type: 'frame',
    frame: { totalSeconds: ctx.chartDurationSeconds, summary: { exScore: 0, gauge: ctx.gaugeState } },
  });
}
 
/**
 * Each side's lane covers as the play starts: from the play options (`laneCoversFromPlayOptions`), or every cover at 0
 * and off for a play that starts without them (`coverStart: 'none'`).
 */
function resolveStartingCovers(ctx: PlayChartContext): LaneCoverState[] {
  const sides = resolveLaneSides(ctx.laneChannels);
  if (ctx.options.coverStart === 'none' || ctx.options.hiSpeedLocked === true) {
    return sides.map((side) => ({ side, sudden: 0, suddenOn: false, hidden: 0, hiddenOn: false, lift: 0 }));
  }
  const covers = laneCoversFromPlayOptions(
    {
      hiddenSudden1P: ctx.options.hiddenSudden1P ?? 'OFF',
      hiddenSudden2P: ctx.options.hiddenSudden2P ?? 'OFF',
      shutter: ctx.options.shutter ?? SHUTTER_DEFAULT,
      lift1P: ctx.options.lift1P ?? 0.1,
      lift2P: ctx.options.lift2P ?? 0.1,
      liftOn1P: ctx.options.liftOn1P ?? false,
      liftOn2P: ctx.options.liftOn2P ?? false,
 
      laneCover: ctx.options.laneCover !== false,
      floatingHiSpeed: ctx.options.floatingHiSpeed,
    },
    sides,
  );
  return ctx.options.floatingHiSpeed || ctx.options.classicHiSpeed || (ctx.options.normalHiSpeedLevel ?? 0) > 0
    ? covers.map(normalizeFloatingLaneCover)
    : covers;
}
 
/** The course stage the play runs (a replay's recorded one wins), with its ruleset, for the placeholder gauge. */
function resolveCourseStartGaugeInput(ctx: PlayChartContext): Parameters<typeof createPlaceholderGaugeState>[1] {
  const stage = ctx.options.replay !== undefined ? ctx.options.replay.play.course : ctx.options.course;
  if (stage === undefined) return undefined;
  const ruleset = ctx.options.replay?.play.judgeRuleset ?? ctx.options.judgeRuleset ?? 'lr2';
  return { stage, ruleset };
}
 
/**
 * Whether the engine runs with auto-scratch, mirroring the `autoScratch` engine option: a replay's recorded flag, or
 * either side's toggle (the engine has one flag for both scratch lanes).
 */
function resolveAutoScratchEnabled(ctx: PlayChartContext): boolean {
  if (ctx.options.replay !== undefined) return ctx.options.replay.play.autoScratch === true;
  return ctx.options.autoScratch1P === true || ctx.options.autoScratch2P === true;
}
 
/**
 * Returns the lowercased filename extension (including the leading dot, e.g. `.pms` / `.bme` / `.bms`) of
 * `chartPath`, or `undefined` if the path doesn't include a recognizable suffix. The engine's
 * `resolveLaneMode` consumes this via `laneModeExtension` so PMS / BME / BMS charts route to the right binding
 * family even when the chart's content alone is ambiguous (e.g. PMS charts that don't use channel `17`, or
 * BME charts on `#PLAYER 1` that omit the 6 / 7 keys). Returning `undefined` falls back to the engine's
 * content-based heuristics, matching the pre-fix behavior on chart paths the host doesn't surface.
 */
export function extractChartExtension(chartPath: string | undefined): string | undefined {
  if (typeof chartPath !== 'string' || chartPath.length === 0) {
    return undefined;
  }
  const lastDot = chartPath.lastIndexOf('.');
  Iif (lastDot < 0) {
    return undefined;
  }
  // Anchor on the last path segment so `.` characters that appear in directory names (e.g. `Bok.fps/01.bms`)
  // don't get mistaken for the chart's own extension.
  const lastSlash = Math.max(chartPath.lastIndexOf('/'), chartPath.lastIndexOf('\\'));
  if (lastDot < lastSlash) {
    return undefined;
  }
  const ext = chartPath.slice(lastDot).toLowerCase();
  return ext.length > 1 ? ext : undefined;
}
 
/**
 * Swaps a BMS channel's side digit (1↔2) so a 1P-side channel becomes its 2P-side counterpart and vice versa. Used to
 * apply DP FLIP at chart-prepare time. Non-side channels (BGM, BGA, any single-character channel) pass through
 * unchanged.
 */
export function flipDPChannel(channel: string): string {
  if (channel.length !== 2) return channel;
  const side = channel[0];
  const lane = channel[1]!;
  if (side === '1') return '2' + lane;
  if (side === '2') return '1' + lane;
  return channel;
}
 
/**
 * Shuffles `notes` in place per the chosen arrangement mode. Only `allLanes` — one side's keyboard lanes, from
 * `resolveLaneOptionChannels` — are touched; scratches, the keyboard modes' wheel, and the other side pass through
 * untouched. Every supported mode uses the complete mode domain, even on sparse charts.
 *
 * - `MIRROR` — deterministic reversal of the full mode key set
 * - `RANDOM` — chart-wide permutation of the full mode key set, one option for every source (beatoraja's draw, then
 *   LR2's fixed key)
 * - `S-RANDOM` — source-specific pure randomizer with active-LN reservations and beatoraja jack avoidance
 *
 * S-RANDOM and CONVERGE run their qualified source's algorithm (`lr2:S-RANDOM`, `beatoraja:CONVERGE`), and a bare one
 * `options.ruleset`'s own (ADR 0019); AC's S-RANDOM is LR2's.
 * - `SCATTER` — LR2 previous-row avoidance with active-LN reservations and source DP scratch masks
 
 */
/** A lane option without its source qualifier. */
type BareRandomMode = Exclude<RandomMode, `${string}:${string}`>;
 
function usesLR2DoubleRandom(mode: string, ruleset: RulesetId): boolean {
  const { name, source } = resolveOptionSource(mode, ruleset);
  return source === 'lr2' && (name === 'CONVERGE' || name === 'S-RANDOM');
}
 
function usesLR2Scratch(mode: RandomMode, variant: ChartPlayVariant | undefined, ruleset: RulesetId): boolean {
  if (variant !== '5' && variant !== '7' && variant !== '10' && variant !== '14') return false;
  const { name, source } = resolveOptionSource(mode, ruleset);
  return (
    name === 'MIRROR' ||
    name === 'RANDOM' ||
    name === 'SCATTER' ||
    (source === 'lr2' && (name === 'S-RANDOM' || name === 'CONVERGE'))
  );
}
 
export function applyRandomMode(
  notes: Array<{ channel: string }>,
  allLanes: readonly string[],
  selectedMode: RandomMode,
  rng: () => number,
  options: {
    ruleset?: RulesetId;
    hRandomThresholdBPM?: number;
    fixedLane?: number;
    lr2RandomScratch?: boolean;
    lr2ScratchSourceVariant?: ChartPlayVariant;
    scratch?: string;
    scratchLanes?: readonly string[];
    doublePlay?: boolean;
    flipped?: boolean;
    side?: '1P' | '2P';
    playVariant?: ChartPlayVariant;
    lr2Objects?: ReturnType<typeof collectLR2SortObjects>;
    sourceChannels?: ReadonlyMap<{ channel: string }, string>;
  } = {},
  // Extra channel-bearing arrays: mines first, then invisible notes. Chart permutations share the same lane map;
  // S-RANDOM applies the active ruleset's policy for each event kind.
  ...secondary: Array<Array<{ channel: string }>>
): void {
  const resolvedMode = resolveOptionSource(selectedMode, options.ruleset ?? 'lr2');
  const mode = resolvedMode.name as BareRandomMode;
  const source = resolvedMode.source ?? options.ruleset ?? 'lr2';
  Iif (
    (mode === 'SCATTER' || mode === 'SCATTER-CORRECTED') &&
    options.playVariant &&
    !['5', '7', '9', '10', '14'].includes(options.playVariant)
  )
    throw new RangeError('LR2 SCATTER requires a five-, seven- or nine-key domain.');
  if (mode === 'SCATTER-CORRECTED' && options.playVariant !== '9')
    throw new RangeError('Corrected SCATTER is a nine-key arrangement.');
  if (mode === 'S-RANDOM-CORRECTED' && options.playVariant !== '9')
    throw new RangeError(`${mode} is a nine-key arrangement.`);
  Iif (mode === 'CONVERGE' && source === '____') throw new RangeError('CONVERGE is unavailable for this ruleset.');
  if (mode === 'CONVERGE' && source === 'beatoraja' && options.playVariant !== '9')
    throw new RangeError('beatoraja CONVERGE is a PMS arrangement.');
  if ((mode === 'RANDOM_PLAYABLE' || mode === 'S_RANDOM_PLAYABLE') && options.playVariant !== '9')
    throw new RangeError(`${mode} is a PMS arrangement.`);
  Iif (mode === 'S-RANDOM-EX' && allLanes.length > 0 && (options.scratchLanes?.length ?? 0) === 0)
    throw new RangeError('S-RANDOM-EX requires scratch lanes.');
  if (mode === 'OFF' || allLanes.length === 0) return;
  const includeScratch =
    options.lr2RandomScratch === true &&
    options.scratch !== undefined &&
    usesLR2Scratch(selectedMode, options.playVariant, options.ruleset ?? 'lr2');
  if (
    mode === 'S-RANDOM' ||
    mode === 'SCATTER' ||
    mode === 'SCATTER-CORRECTED' ||
    mode === 'S-RANDOM-CORRECTED' ||
    mode === 'CONVERGE-CORRECTED' ||
    mode === 'S-RANDOM-EX' ||
    mode === 'SPIRAL' ||
    mode === 'H-RANDOM' ||
    mode === 'CONVERGE' ||
    mode === 'ALL-SCR' ||
    mode === 'RANDOM_PLAYABLE' ||
    mode === 'S_RANDOM_PLAYABLE'
  ) {
    const entries = [
      ...notes.map((note) => ({ note, kind: 'note' as const })),
      ...secondary.flatMap((arr, index) =>
        arr.map((note) => ({ note, kind: index === 0 ? ('mine' as const) : ('invisible' as const) })),
      ),
    ];
    const lr2Double =
      options.scratch !== undefined &&
      (includeScratch || (options.playVariant === '14' && usesLR2DoubleRandom(selectedMode, options.ruleset ?? 'lr2')))
        ? {
            scratch: options.scratch,
            flipped: options.flipped,
            objects: options.lr2Objects,
            includeScratch,
            avoidFarKeys:
              (includeScratch ? (options.lr2ScratchSourceVariant ?? options.playVariant) : options.playVariant) ===
              '14',
          }
        : undefined;
    const timedNotes = entries.map(({ note, kind }) => {
      const timed = note as {
        channel: string;
        seconds?: number;
        endSeconds?: number;
        beat?: number;
        endBeat?: number;
        event?: BeMusicEvent;
        generatedLongNote?: true;
      };
      // Group by whole microseconds, as the source timelines do: a modifier that recomputes some objects' seconds
      // (scroll REMOVE) can leave a mine one ulp off the notes it shares a timeline with.
      return {
        channel: timed.channel,
        timeMs: toTimelineMs(timed.seconds ?? timed.beat ?? 0),
        ...(timed.endSeconds !== undefined || timed.endBeat !== undefined
          ? { endTimeMs: toTimelineMs(timed.endSeconds ?? timed.endBeat!) }
          : {}),
        kind,
        ...(lr2Double === undefined
          ? {}
          : {
              beat: timed.beat,
              endBeat: timed.endBeat,
              sourceChannel: options.sourceChannels?.get(note),
              lr2OpOffset: /^[56]/.test(timed.event?.channel ?? '') ? 40 : 0,
              lr2SyntheticTail: timed.generatedLongNote,
            }),
      };
    });
    const channels =
      mode === 'SCATTER' || mode === 'SCATTER-CORRECTED'
        ? randomizeLR2ScatterNotes(timedNotes, allLanes, {
            random: rng,
            side: options.side,
            scratch: options.scratch,
            doublePlay: options.doublePlay,
            flipped: options.flipped,
            correctedNineKey: mode === 'SCATTER-CORRECTED',
            lr2Scratch: includeScratch ? lr2Double : undefined,
          })
        : mode === 'S-RANDOM-EX'
          ? randomizeSRandomNotes(timedNotes, [...allLanes, ...options.scratchLanes!], {
              ruleset: 'beatoraja',
              random: rng,
            })
          : mode === 'S_RANDOM_PLAYABLE'
            ? randomizePMSPlayableNotes(timedNotes, allLanes, {
                random: rng,
                thresholdBPM: options.hRandomThresholdBPM,
              })
            : mode === 'RANDOM_PLAYABLE'
              ? randomizePMSPlayableLanes(timedNotes, allLanes, rng)
              : mode === 'ALL-SCR'
                ? randomizeAllScratchNotes(timedNotes, [...allLanes, ...(options.scratchLanes ?? [])], {
                    random: rng,
                    scratchLanes: options.scratchLanes ?? [],
                    thresholdBPM: options.hRandomThresholdBPM,
                    doublePlay: options.doublePlay,
                    side: options.side,
                  })
                : mode === 'CONVERGE' || mode === 'CONVERGE-CORRECTED'
                  ? mode === 'CONVERGE' && source === 'beatoraja'
                    ? randomizePMSConvergeNotes(timedNotes, allLanes, {
                        random: rng,
                        thresholdBPM: options.hRandomThresholdBPM,
                      })
                    : randomizeLR2ConvergeNotes(timedNotes, allLanes, {
                        target: includeScratch
                          ? (allLanes[(options.fixedLane ?? 0) - 1] ?? options.scratch!)
                          : mode === 'CONVERGE' && options.side === '2P'
                            ? resolveLR2SecondSideConvergeTarget(allLanes, options.fixedLane ?? 0)
                            : (allLanes[(options.fixedLane ?? 0) - 1] ?? options.scratch ?? allLanes[4]!),
                        scratch: options.scratch,
                        random: rng,
                        targetOutside: mode === 'CONVERGE' && options.side === '2P',
                        lr2Double,
                        // LR2's nine-key draw reaches the 2P scratch; the corrected option keeps to the nine keys.
                        ...(mode === 'CONVERGE' && options.playVariant === '9' ? { outside: '26' } : {}),
                      })
                  : mode === 'SPIRAL'
                    ? randomizeSpiralNotes(timedNotes, allLanes, rng)
                    : mode === 'H-RANDOM'
                      ? randomizeHRandomNotes(timedNotes, allLanes, {
                          random: rng,
                          thresholdBPM: options.hRandomThresholdBPM,
                        })
                      : randomizeSRandomNotes(timedNotes, allLanes, {
                          ruleset: mode === 'S-RANDOM-CORRECTED' ? 'lr2' : source,
                          lr2Double,
                          random: rng,
                          ...(options.playVariant === '9' ? { mode: 'pms' as const } : {}),
                          // LR2's nine-key draw reaches the 2P scratch; the corrected option keeps to the nine keys.
                          ...(mode === 'S-RANDOM' && source !== 'beatoraja' && options.playVariant === '9'
                            ? { outside: '26' }
                            : {}),
                        });
    entries.forEach(({ note }, index) => {
      note.channel = channels[index]!;
    });
    return;
  }
  // nanasigroove's RANDOM+ (a chart's `774:RANDOM_RANDOM+`, #1244) shuffles the keys and the scratch as RANDOM-EX does.
  const withScratch = mode === 'RANDOM-EX' || mode === 'RANDOM+';
  if (withScratch && (options.scratchLanes?.length ?? 0) === 0) throw new RangeError(`${mode} requires scratch lanes.`);
  const domainLanes = includeScratch
    ? [options.scratch!, ...allLanes]
    : withScratch
      ? [...allLanes, ...options.scratchLanes!]
      : allLanes;
  Iif (domainLanes.length < 2) return;
 
  const remapAll = (map: Map<string, string>): void => {
    for (const note of notes) {
      const target = map.get(note.channel);
      if (target) note.channel = target;
    }
    for (const arr of secondary) {
      for (const entry of arr) {
        const target = map.get(entry.channel);
        if (target) entry.channel = target;
      }
    }
  };
 
  if (mode === 'MIRROR') {
    const map = new Map<string, string>();
    for (let index = 0; index < domainLanes.length; index += 1) {
      map.set(domainLanes[index]!, domainLanes[domainLanes.length - 1 - index]!);
    }
    remapAll(map);
    return;
  }
 
  if (mode === 'R-RANDOM') {
    // beatoraja 0.8.9 LaneRotateShuffleModifier: destination -> source, excluding
    // identity (forward start 0) and mirror (reverse start N - 1).
    const forward = drawLaneRandomIndex(2, rng) === 1;
    const start = drawLaneRandomIndex(domainLanes.length - 1, rng) + (forward ? 1 : 0);
    const map = new Map<string, string>();
    for (let lane = 0; lane < domainLanes.length; lane += 1) {
      const source = (start + (forward ? lane : -lane) + domainLanes.length) % domainLanes.length;
      map.set(domainLanes[source]!, domainLanes[lane]!);
    }
    remapAll(map);
    return;
  }
 
  if (mode === 'RANDOM' && includeScratch) {
    // LR2 shuffles scratch (slot 0) and the keys in source-lane order.
    const destinations = [...domainLanes];
    for (let source = 0; source < destinations.length - 1; source++) {
      const other = source + drawLaneRandomIndex(destinations.length - source, rng);
      [destinations[source], destinations[other]] = [destinations[other]!, destinations[source]!];
    }
    const scratchSource = destinations.indexOf(options.scratch!);
    const fixed = options.fixedLane ?? 0;
    // The native randFix check is on the 1P table and scans only key slots for the scratch destination.
    if (options.side !== '2P' && fixed > 0 && fixed < destinations.length && scratchSource > 0) {
      [destinations[fixed], destinations[scratchSource]] = [destinations[scratchSource]!, destinations[fixed]!];
    }
    remapAll(new Map(domainLanes.map((lane, index) => [lane, destinations[index]!])));
    return;
  }
 
  Eif (mode === 'RANDOM' || withScratch) {
    // LR2, beatoraja and That-Which-Must-Not-Be-Named define RANDOM alike, one chart-wide shuffle of the keys, so every
    // source draws it as beatoraja 0.8.9's LaneRandomShuffleModifier does: the seed then gives beatoraja's arrangement.
    // RANDOM-EX, and nanasigroove's RANDOM+, are the same draw over the keys and the scratch.
    const available = [...domainLanes];
    const map = new Map<string, string>();
    for (const target of domainLanes) {
      const source = available.splice(drawLaneRandomIndex(available.length, rng), 1)[0]!;
      map.set(source, target);
    }
    // LR2 applies randFix to 1P RANDOM outside nine-key play.
    const fixed =
      mode === 'RANDOM' && options.side !== '2P' && options.playVariant !== '9'
        ? domainLanes[(options.fixedLane ?? 0) - 1]
        : undefined;
    if (fixed !== undefined) {
      const first = domainLanes[0]!;
      const displaced = [...map].find(([, target]) => target === fixed)![0];
      map.set(displaced, map.get(first)!);
      map.set(first, fixed);
    }
    remapAll(map);
    return;
  }
}
 
/**
 * LR2's 2P CONVERGE target. LR2 adds the 2P start lane to the fixed key (`randFix[1] + startlane`, OpenLR2 `LR2f.cpp`
 * L27374-L27380), one more than 1P's `randFix[0]`, so key `n` lands one lane to the right: 0 (the default) is key 1
 * rather than the scratch, and the last key points past the keys, where nothing can hit the note. A fixed key past the
 * mode's range is reset to 0, as LR2 does (L27325-L27331). Past the keys is the next LR2 lane: `28` on 10KEY, and on
 * 14KEY, which has no channel for it, `2A`, which no 10 / 14KEY layout has.
 */
function resolveLR2SecondSideConvergeTarget(keys: readonly string[], fixedLane: number): string {
  const index = fixedLane > keys.length ? 0 : fixedLane;
  return keys[index] ?? (keys.length === 5 ? '28' : '2A');
}
 
const LONG_NOTE_MODE_VALUES = { LN: 1, CN: 2, HCN: 3 } as const;
 
/**
 * beatoraja's LN MODE (`PlayerConfig.lnmode`) for a chart whose long-note mode is undefined; a chart (or course)
 * mode takes precedence. A replay applies the effective chart mode it recorded.
 */
function resolvePlayerLongNoteChart(
  ctx: Pick<PlayChartContext, 'options'>,
  chart: BeMusicJSON,
  recordedMode: 1 | 2 | 3 | undefined,
): BeMusicJSON {
  if (recordedMode !== undefined && resolveChartLongNoteMode(chart) === recordedMode) return chart;
  if (recordedMode !== undefined)
    return chart.sourceFormat === 'bms'
      ? { ...chart, bms: { ...chart.bms, lnMode: recordedMode } }
      : { ...chart, bmson: { ...chart.bmson, info: { ...chart.bmson.info, lnType: recordedMode } } };
  const mode = ctx.options.longNoteMode ?? 'LN';
  if (mode === 'LN') return chart;
  Iif (ctx.options.judgeRuleset !== 'beatoraja') throw new RangeError('LN MODE is available only for beatoraja.');
  return applyUndefinedLongNoteMode(chart, LONG_NOTE_MODE_VALUES[mode]);
}
 
/** A time in seconds as the milliseconds of its whole-microsecond timeline. */
function toTimelineMs(seconds: number): number {
  return Math.round(seconds * 1_000_000) / 1000;
}
 
/** The RANDOM-type lane options That-Which-Must-Not-Be-Named's M-RAN mirrors after. */
const M_RAN_RANDOM_MODES: ReadonlySet<string> = new Set(['RANDOM', 'R-RANDOM', 'S-RANDOM']);
 
/**
 * Each 2P copy of a two-player chart with the 1P object it was copied from (same time, same lane number and kind), so
 * the 2P side can take 1P's arrangement after 1P is shuffled.
 */
export function pairTwoPlayerTwins(
  arrays: ReadonlyArray<ReadonlyArray<{ channel: string; seconds: number; endSeconds?: number }>>,
): Array<[{ channel: string }, { channel: string }]> {
  const pairs: Array<[{ channel: string }, { channel: string }]> = [];
  for (const objects of arrays) {
    const firsts = new Map<string, Array<{ channel: string }>>();
    const key = (object: { channel: string; seconds: number; endSeconds?: number }): string =>
      `${object.seconds}|${object.channel.slice(1)}|${object.endSeconds ?? ''}`;
    for (const object of objects)
      if (object.channel.startsWith('1')) {
        const list = firsts.get(key(object)) ?? [];
        list.push(object);
        firsts.set(key(object), list);
      }
    for (const object of objects) {
      if (!object.channel.startsWith('2')) continue;
      const first = firsts.get(key(object))?.shift();
      if (first !== undefined) pairs.push([object, first]);
    }
  }
  return pairs;
}
 
/**
 * That-Which-Must-Not-Be-Named BATTLE arrangements: one RANDOM permutation of the 1P keys, then the 2P keys take
 * the same lane numbers (`SYNCHRONIZE-RANDOM`) or their mirror image (`SYMMETRY-RANDOM`). Scratch never moves.
 */
export function applyBattleRandomMode(
  mode: 'SYNCHRONIZE-RANDOM' | 'SYMMETRY-RANDOM',
  lanes1P: readonly string[],
  lanes2P: readonly string[],
  rng: () => number,
  ...arrays: Array<Array<{ channel: string }>>
): void {
  Iif (lanes1P.length !== lanes2P.length) throw new RangeError('BATTLE random requires matching sides.');
  const perm = shuffleArray([...lanes1P], rng);
  const map = new Map<string, string>();
  lanes1P.forEach((lane, index) => {
    const target = lanes1P.indexOf(perm[index]!);
    map.set(lane, perm[index]!);
    map.set(lanes2P[index]!, lanes2P[mode === 'SYNCHRONIZE-RANDOM' ? target : lanes2P.length - 1 - target]!);
  });
  for (const array of arrays)
    for (const entry of array) {
      const target = map.get(entry.channel);
      if (target) entry.channel = target;
    }
}
 
/**
 * In-place Fisher-Yates shuffle. Returns the same array for call-chaining — callers usually just discard the return
 * value since the array is mutated.
 */
export function shuffleArray<T>(array: T[], rng: () => number): T[] {
  for (let index = array.length - 1; index > 0; index -= 1) {
    const target = Math.floor(rng() * (index + 1));
    const swap = array[target]!;
    array[target] = array[index]!;
    array[index] = swap;
  }
  return array;
}