All files / player-engine/src/course/nonstop compose.ts

95.48% Statements 486/509
91.75% Branches 434/473
98.68% Functions 75/76
98.75% Lines 396/401

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                                                                                                                  401x 401x 1604x 1604x   401x                         261x     261x                                                                                                                                                                                                                         261x 261x   261x   261x 261x 261x               261x                                                                                     213x     213x 1x 212x                 214x 2x   212x     212x 417x 210x 209x 2x 4x 2x 1x   208x   415x   208x 391x 207x 28858x 214x 411x   411x 17x 17x     3963x 2x   411x   408x 6x 3x   407x 203x 407x       203x 33745x 407x       203x       7327x 214x 31x 203x 203x 203x 203x 203x 203x 203x 203x 203x 203x       214x 214x   214x   214x 214x       214x 407x 214x 214x 334x 203x 53x 53x 53x                         53x   203x 203x 203x 203x 407x 407x   203x 407x 407x 407x 407x 407x     407x 407x 41504x 41504x 41420x 28885x 28885x   28885x 7826x 28885x 28885x 28885x 28885x   28885x   28885x 28885x 28885x 3x         12x 3x 6x   28885x 6x 6x 6x     41420x   407x           176x   407x               29831x 29747x                 29831x     407x 407x 407x 407x 407x               407x 407x 407x 407x 407x 407x 407x 405x 369x 369x 369x   369x       369x 3x 3x   369x       3x         369x       738x       738x 738x         6x 6x 5x 5x 5x 5x   6x 6x           369x 3x 3x 3x       405x     12x   11x 11x 10x     405x   405x   407x 407x 3928x 3928x 3764x       405x 401x           405x 405x 405x 137x 63x 63x 27x 33x   27x 27x 27x   63x   137x   201x   2x 2x 2x 2x   201x 46x 99x 57x     201x 201x 201x 201x 1x 1x 1x     201x 201x 201x 201x 201x 401x 401x   201x   201x 802x 802x   401x 401x 201x 201x 201x 201x 201x 1x 201x 214x   401x   405x                                   201x 201x 53x   53x   53x         53x 53x   201x             17x                 399x       420x 366x       401x 401x 401x 401x 401x 401x 401x                                                                                                       407x 407x 15770x 407x               29802x   29802x                     29802x   407x 19125x 19125x 19125x 11857x 11858x 11857x 1x 7268x 19x 19x 19x   7249x     405x 355x 405x 21x 405x 23x 21x                 2x   405x 29867x 29867x 29867x 19398x   405x 113x           452x   95x       405x                                           2x 2x 8x 6x 6x   2x 4x   4x 4x   2x 10x 10x 10x 10x 4x 6x   2x                             369x           369x 369x 738x 738x 738x   369x 369x 369x         54774x 54774x 13054x 12982x 12982x                 201x 200x 200x   8264x 19668x 196x 8262x 176x 124x 347x   196x 196x 8262x 116x 116x   196x 19668x                   15130x 401x         797x 797x 797x 109759x 31074x 797x 31692x 31692x 31692x 36x 36x 36x   31656x 31656x   797x         48068x 48068x 347x 111x   48068x                           201x 48068x 201x 3618x 3542x 3542x   22211x 201x 201x 3528x 3528x   201x 22221x 22221x 8381536x 22221x 22221x 22221x 22221x   201x 22211x 22211x 45x       22166x     22211x                         22211x               201x 10x 10x       10x 10x   201x   32786x             22221x 22221x 102995x 22221x       14x 2x 2x    
import { placeNonstopChartOptions, type NonstopChartOptionDiagnostic } from './chart-options.ts';
export type { NonstopChartOptionDiagnostic } from './chart-options.ts';
import type { ChartTextStage } from '../../core/chart-text.ts';
import {
  isHeldLongNote,
  buildChartTextTimeline,
  CHART_OPTION_PROGRAM_VERSION,
  type ChartOptionProgram,
  type ChartOptionStateCue,
  resolvePoorBGAMode,
  type PoorBGAMode,
  resolveChart,
  resolveBmsWAVResources,
  parseBMSExWAV,
  resolveBmsExWAVDeclarations,
  parseBmsWAVCmd,
  volWAVToLinearGain,
  type ResolvedChart,
  type BGAOpacityTimelines,
  type KeyBoundBGACue,
  type BmsonBGAEventCue,
} from '@be-music/chart-model';
import {
  createEmptyJSON,
  LRX_TICKS_PER_BEAT,
  resolveBMSBase,
  normalizeChannel,
  normalizeObjectKey,
  type BeMusicEvent,
  type BeMusicJSON,
  type LRXEventExtensions,
} from '@be-music/chart-source';
import type { NonstopConnection } from '../definition.ts';
import { NonstopKeyAllocator } from './ids.ts';
import {
  planNonstopCourse,
  resolveNonstopLastMeasure,
  type NonstopPlanOptions,
  type NonstopStagePlacement,
} from './plan.ts';
import {
  resolveNonstopStageRanks,
  resolveNonstopTempo,
  type NonstopStageRank,
  type NonstopTempoPoint,
} from './readouts.ts';
import { createNonstopStageTiming } from './stage.ts';
import type { NonstopSongInfo } from './song-info.ts';
import { flattenNonstopBGAOpacity, hasBGAOpacity, placeNonstopBGAOpacity } from './bga-opacity.ts';
import { placeNonstopBmsonBGA } from './bmson-bga.ts';
import { placeNonstopKeyBoundBGA } from './key-bound-bga.ts';
import { createNonstopBMPAllocator } from './bga-resources.ts';
import { placeNonstopKeyframes } from './scroll-speed.ts';
 
/** One stage to stitch: its BMS or bmson chart with control flow resolved, and whether it is a `.pms` chart. */
/** A stage chart's song, as its metadata names it (blank names left out). */
function stageSongInfo(chart: BeMusicJSON): NonstopSongInfo {
  const info: NonstopSongInfo = {};
  for (const key of ['title', 'subtitle', 'artist', 'genre'] as const) {
    const value = chart.metadata[key]?.trim();
    if (value) info[key] = value;
  }
  return info;
}
 
export interface NonstopStageInput {
  chart: BeMusicJSON;
  pms?: boolean;
}
 
/**
 * The version of the stitching rules {@link stitchNonstopCourse} follows. A NONSTOP replay records it
 * (`ReplayNonstopRun.stitch`), so a stitched chart is rebuilt by the rules it was played on. Raise it whenever a change
 * moves a stitched note, sound, rank or timing, or changes gauge inputs; keep earlier rules reachable through `options.stitch`.
 */
export const NONSTOP_STITCH_VERSION = 4;
 
/** The stitching rule versions {@link stitchNonstopCourse} can follow. */
export const NONSTOP_STITCH_VERSIONS: readonly number[] = [1, 2, 3, 4];
 
export interface StitchNonstopOptions extends NonstopPlanOptions {
  /** The stitching rules to follow ({@link NONSTOP_STITCH_VERSION} by default); one it does not know is refused. */
  stitch?: number;
  /** The connection after each stage but the last (`CourseDefinition.connections`); missing ones read as `fade`. */
  connections: readonly NonstopConnection[];
  /** The stitched chart's title, e.g. the course name. */
  title?: string;
  /**
   * The path a stitched resource is loaded from: a stage's WAV / BMP path as its chart names it. Hosts put each
   * stage's files under their own prefix (stage charts can come from different folders); defaults to the path itself.
   */
  assetPath?: (stage: number, kind: 'wav' | 'bmp', path: string) => string;
}
 
/** A sound or BGA fade, in stitched seconds: the level ramps from one end to the other over `[start, end]`. */
export interface NonstopFade {
  start: number;
  end: number;
}
 
/** What the host needs about one stage of a stitched chart. */
export interface NonstopStitchStage {
  placement: NonstopStagePlacement;
  /** The stitched seconds the stage owns: its notes, bar lines and STOPs fall in `[windowStart, windowEnd)`. */
  windowStart: number;
  windowEnd: number;
  /**
   * The stitched WAV / BMP keys that belong to this stage (those without a file included), for its sound bus and BGA
   * layer, and to tell which stage a note comes from.
   */
  wavKeys: string[];
  bmpKeys: string[];
  /** This stage’s miss-image mode; omitted means replacement. */
  poorBGAMode?: PoorBGAMode;
  /** Independent stage opacity/RGB histories, on the stitched clock, for BGA crossfades. Omitted means opaque white. */
  bgaOpacity?: BGAOpacityTimelines;
  /** Fades of the stage's background sound (LR2 fades the stage BGM channel; keysounds play at full level). */
  soundFadeIn?: NonstopFade;
  soundFadeOut?: NonstopFade;
  /** Crossfade of the stage's BGA layers (3 s at every boundary). */
  bgaFadeIn?: NonstopFade;
  bgaFadeOut?: NonstopFade;
  /** Whether LR2 announces the stage when it starts (ops 280-289, title text): only after a BLANK connection. */
  lr2StageMarker: boolean;
  /** The stage's song, as its chart names it, for the play screen ({@link resolveNonstopSongInfoState}). */
  songInfo?: NonstopSongInfo;
  /**
   * The stage's `#BACKBMP`, through `assetPath`, for the play screen to show while the stage is shown. The stitched
   * chart's own `#BACKBMP` is the first stage's.
   */
  backBMP?: string;
  /**
   * The stage's `#STAGEFILE` and `#BANNER`, through `assetPath`, and its `#PLAYLEVEL` and `#DIFFICULTY` (#1073). The
   * stitched chart's own are the first stage's, as its library entry is: LR2's loader reads none of them while it
   * stitches (OpenLR2 `ParseBMSFile`), so no stage's value is the source's.
   */
  stageFile?: string;
  banner?: string;
  playLevel?: BeMusicJSON['metadata']['playLevel'];
  difficulty?: number;
}
 
export interface NonstopStitchMap {
  /** Stage-owned effective option program on the course microsecond clock. */
  chartOptions?: ChartOptionProgram;
  /** Unsupported or malformed stage declarations with source/course provenance. */
  chartOptionDiagnostics?: NonstopChartOptionDiagnostic[];
  /** Source text programs with stage ownership and FIT time mapping. */
  chartText?: ChartTextStage[];
  /** Remapped input-bound BGA selections, with stage ownership windows on the stitched clock. */
  keyBoundBGA?: KeyBoundBGACue[];
  /** Resolved conditional animations, remapped to stage-owned resources and FIT time. */
  bmsonBGA?: BmsonBGAEventCue[];
  /**
   * The slot each stage's mines explode with (its own `#WAV00`, rule version 4), from its window on, for the engine's
   * `landmineSampleKeys` option; a cue without `sampleKey` is a stage without `#WAV00`. Omitted when no stage has one.
   */
  landmineSampleKeys?: { seconds: number; sampleKey?: string }[];
  stages: NonstopStitchStage[];
  /**
   * What the BPM readouts show over the play ({@link resolveNonstopTempo}, look it up with `nonstopBPMAt`): each
   * stage's own BPM, scaled by its FIT rate, where the stitched chart itself runs at 150 BPM.
   */
  tempo: NonstopTempoPoint[];
  /**
   * The judge rank changes after the first stage ({@link resolveNonstopStageRanks}), for the engine's `stageRanks`
   * option; the stitched chart's `#RANK` is the first stage's.
   */
  stageRanks: NonstopStageRank[];
}
 
export type StitchNonstopResult =
  | { ok: true; chart: BeMusicJSON; map: NonstopStitchMap }
  | {
      ok: false;
      reason:
        | 'bmson'
        | 'id-space'
        | 'no-stage'
        | 'stitch-version'
        | 'generic-layout-mismatch'
        | 'lrx-mixed'
        | 'lrx-layout-mismatch';
      stage?: number;
    };
 
/** The stitched chart's tempo: LR2 scrolls a NONSTOP play at `realtime × 1.2` per 1920-unit measure, 150 BPM. */
const STITCHED_BPM = 150;
const MEASURE_SECONDS = 240 / STITCHED_BPM;
/** Positions are placed on a grid this fine per 150-BPM measure (~0.17 ms). */
const GRID_PER_MEASURE = 9600;
/** A note of the next stage this close to the previous stage's last note becomes background sound (OpenLR2 L26988). */
const OVERLAP_SECONDS = 0.1;
const BGA_CHANNELS = new Set(['04', '06', '07', '0A']);
const FADES: Readonly<Record<NonstopConnection, { out?: number; in?: number }>> = {
  fade: { out: 10, in: 5 },
  'fade-fit': { in: 5 },
  cut: { out: 0.2, in: 0.2 },
  'cut-fit': { out: 0.2, in: 0.2 },
  blank1: { in: 5 },
  blank2: {},
};
const BGA_FADE_SECONDS = 3;
 
/** One object of the stitched chart before it is laid on the grid. */
interface StitchedObject {
  seconds: number;
  channel: string;
  value: string;
  stage: number;
  bmson?: BeMusicEvent['bmson'];
  /** An LRX stage's per-note values, carried into an LRX course (a long note's `length` is set on the grid). */
  lrx?: LRXEventExtensions;
  endSeconds?: number;
}
 
interface StitchedStop {
  seconds: number;
  duration: number;
}
 
/**
 * Stitches a NONSTOP course into one BMS chart (bmson when any stage is bmson), placed by {@link planNonstopCourse}.
 *
 * LR2 scrolls a NONSTOP play by time (a constant 150-BPM scroll, OpenLR2 `LR2f.cpp` L26529 / L27067), so the stitched
 * chart runs at 150 BPM and each object sits where its stage's own timing puts it: notes keep their judge times
 * exactly (to the 9600th of a measure). Each stage owns a window from the previous boundary to its own:
 *
 * - its bar lines in the window become the stitched chart's measures (`#xxx02` lengths), so they show where they did;
 * - its STOPs in the window freeze the scroll there; STOPs outside it are dropped;
 * - its notes, invisible notes, mines, BGM and BGA keep their place wherever they fall.
 *
 * A note of a later stage that lands before the previous stage's last note, or within 0.1 s of it on a lane that
 * note's stage also used there, becomes background sound, as LR2 does at the seam. Keysound and BGA keys are renumbered
 * into one base-62 space (`#BASE 62`); bmson output uses longer keys. BMS output holds at most 3843 of either, so from
 * rule version 3 a course of BMS stages past that (four or five keysound-heavy charts often are) is stitched as bmson
 * instead, as one with CN / HCN long notes is; earlier versions refuse it (`id-space`). The chart's
 * judge rank is the first stage's (the map's `stageRanks` change it for later stages). LR2 keeps the last TOTAL
 * declaration across the stage loop, including when later stages omit it. Version 1 retains its former last-stage-only
 * TOTAL rule for existing replays. A stitching rule version it does not know is refused (`stitch-version`).
 */
export function stitchNonstopCourse(
  stages: readonly NonstopStageInput[],
  options: StitchNonstopOptions,
): StitchNonstopResult {
  const result = stitchNonstopCourseAs(stages, options, false);
  // A course BMS output cannot key is stitched as bmson: this changes no course that stitched before, so the replays of
  // earlier runs stitch as they did.
  if (!result.ok && result.reason === 'id-space' && (options.stitch ?? NONSTOP_STITCH_VERSION) >= 3)
    return stitchNonstopCourseAs(stages, options, true);
  return result;
}
 
/** {@link stitchNonstopCourse}, with bmson output forced by `bmsonOutput`. */
function stitchNonstopCourseAs(
  stages: readonly NonstopStageInput[],
  options: StitchNonstopOptions,
  bmsonOutput: boolean,
): StitchNonstopResult {
  if (!NONSTOP_STITCH_VERSIONS.includes(options.stitch ?? NONSTOP_STITCH_VERSION)) {
    return { ok: false, reason: 'stitch-version' };
  }
  if (stages.length === 0) return { ok: false, reason: 'no-stage' };
  // A course of LRX stages stitches into an LRX chart, which keeps each note's own values. LRX does not mix with BMS
  // or bmson: neither output could carry them.
  const lrxOutput = stages.every((stage) => stage.chart.sourceFormat === 'lrx');
  const lrxStage = stages.findIndex((stage) => stage.chart.sourceFormat === 'lrx');
  if (!lrxOutput && lrxStage >= 0) return { ok: false, reason: 'lrx-mixed', stage: lrxStage };
  if (lrxOutput) {
    const laneType = stages[0]!.chart.lrx?.laneType;
    const other = stages.findIndex((stage) => stage.chart.lrx?.laneType !== laneType);
    if (other >= 0) return { ok: false, reason: 'lrx-layout-mismatch', stage: other };
    Iif (bmsonOutput) return { ok: false, reason: 'id-space' };
  }
  const unsupported = stages.findIndex(
    (stage) =>
      stage.chart.sourceFormat !== 'bms' && stage.chart.sourceFormat !== 'bmson' && stage.chart.sourceFormat !== 'lrx',
  );
  if (unsupported >= 0) return { ok: false, reason: 'bmson', stage: unsupported };
  const bmsonStage = stages.findIndex((stage) => stage.chart.sourceFormat === 'bmson');
  if (bmsonStage >= 0 && options.placement === 'lr2') return { ok: false, reason: 'bmson', stage: bmsonStage };
  const assetPath = options.assetPath ?? ((_stage, _kind, path) => path);
  let resolved = stages.map((stage) => {
    let source = stage.chart;
    // Historical stitching predates HDX LONGMODE, including BMS stages in mixed bmson courses.
    if ((options.stitch ?? NONSTOP_STITCH_VERSION) < 3 && source.sourceFormat === 'bms') {
      const mode = source.bms.lnMode;
      if (mode !== 1 && mode !== 2 && mode !== 3) source = { ...source, bms: { ...source.bms, lnMode: 1 } };
    }
    // It also predates bmson `up`, which then left the slice an ordinary judged note.
    if ((options.stitch ?? NONSTOP_STITCH_VERSION) < 3 && source.events.some((event) => event.bmson?.up === true)) {
      source = { ...source, events: source.events.map(withoutBmsonUp) };
    }
    return resolveChart(source, bmsonStage >= 0 && stage.pms === true ? { chartPath: '.pms' } : {});
  });
  if (resolved.some((chart) => chart.playVariant.startsWith('generic-'))) {
    const incompatible = resolved.findIndex((chart) => chart.playVariant !== resolved[0]!.playVariant);
    if (incompatible >= 0) return { ok: false, reason: 'generic-layout-mismatch', stage: incompatible };
  }
  const timings = stages.map((stage) => createNonstopStageTiming(stage.chart, { pms: stage.pms === true }));
  const placements = planNonstopCourse(timings, options.connections, options);
  const windows = placements.map((placement, index) => ({
    start: index === 0 ? Number.NEGATIVE_INFINITY : placements[index - 1]!.boundarySeconds,
    end: index === placements.length - 1 ? Number.POSITIVE_INFINITY : placement.boundarySeconds,
  }));
  const stitchedSeconds = (stage: number, seconds: number): number =>
    placements[stage]!.offsetSeconds + seconds / placements[stage]!.rate;
  const stageOpacity = resolved.map((source, index) => placeNonstopBGAOpacity(source, placements[index]!));
 
  // BMS has one global LNMODE. Version 3 uses per-note bmson types when a BMS stage needs CN/HCN.
  const asBmson =
    !lrxOutput &&
    (bmsonOutput ||
      bmsonStage >= 0 ||
      ((options.stitch ?? NONSTOP_STITCH_VERSION) >= 3 &&
        resolved.some((stage) => stage.notes.some((note) => isHeldLongNote(note) && note.lnMode !== 1))));
  if (asBmson && bmsonStage < 0)
    resolved = stages.map((stage) => resolveChart(stage.chart, stage.pms === true ? { chartPath: '.pms' } : {}));
  const wavKeys = new NonstopKeyAllocator(asBmson);
  const bmpKeys = new NonstopKeyAllocator(asBmson);
  const keyBoundBGA: KeyBoundBGACue[] = [];
  const bmsonBGA: BmsonBGAEventCue[] = [];
  const chartText: ChartTextStage[] = [];
  const chartOptionCues: ChartOptionStateCue[] = [];
  const chartOptionDiagnostics: NonstopChartOptionDiagnostic[] = [];
  let hasChartOptions = false;
  const stopKeys = new NonstopKeyAllocator(asBmson);
  const chart = createEmptyJSON(asBmson ? 'bmson' : 'bms');
  // Rule version 4 keeps more of each stage's own rules: per-slot BMS playback and BGA keying in bmson output,
  // `#DEFEXRANK` in BMS output, `#EXRANKxx`, 97 / 98 volume, SCROLL and SPEED changes, each stage's `#WAV00`, and a
  // negative-BPM reversal, which freezes the rest of the play as it does in LR2.
  const perStageRules = (options.stitch ?? NONSTOP_STITCH_VERSION) >= 4;
  const bpmKeys = new NonstopKeyAllocator(asBmson);
  let reversal: { seconds: number; stage: number } | undefined;
  const volumeChannels = new Set<string>();
  // SCROLL (`SC`) and SPEED (`SP`): the channels an earlier stage set, and one key per distinct value.
  const keyframeChannels = new Set<string>();
  const keyframeKeys = {
    SC: { allocator: new NonstopKeyAllocator(asBmson), byValue: new Map<number, string>(), table: chart.bms.scroll },
    SP: { allocator: new NonstopKeyAllocator(asBmson), byValue: new Map<number, string>(), table: chart.bms.speed },
  };
  const landmineSampleKeys: { seconds: number; sampleKey?: string }[] = [];
  const exRankChanges: { seconds: number; exRank: number }[][] = stages.map(() => []);
  let totalStage = stages.length - 1;
  if ((options.stitch ?? NONSTOP_STITCH_VERSION) >= 2)
    while (totalStage >= 0 && stages[totalStage]!.chart.metadata.total === undefined) totalStage--;
  if (asBmson) {
    chart.bmson.info.resolution = 2400;
    const variant = resolved[0]!.playVariant;
    chart.bmson.info.modeHint = variant.startsWith('generic-')
      ? `${variant}keys`
      : (
          {
            '5': 'beat-5k',
            '7': 'beat-7k',
            '9': 'popn-9k',
            '10': 'beat-10k',
            '14': 'beat-14k',
            '24': 'keyboard-24k',
            '48': 'keyboard-24k-double',
          } as const
        )[variant as '5' | '7' | '9' | '10' | '14' | '24' | '48'];
    chart.bmson.info.totalUnit = resolved[totalStage < 0 ? stages.length - 1 : totalStage]!.total.unit;
  }
  chart.bms.base = 62;
  const objects: StitchedObject[] = [];
  const stops: StitchedStop[] = [];
  const barLines: number[] = [];
  const stageWAV: string[][] = stages.map(() => []);
  const stageBMP: string[][] = stages.map(() => []);
 
  for (let index = 0; index < stages.length; index += 1) {
    const source = stages[index]!.chart;
    const wavResources = resolveBmsWAVResources(source);
    const wavCommands = source.bms.wavCmds.map((line) => parseBmsWAVCmd(line, resolveBMSBase(source)));
    const chartIndex = resolved[index]!;
    const window = windows[index]!;
    // Every source key gets its own stitched key, even one without a file (it then stays silent), so two stages'
    // keys never meet.
    const known = new Set<string>();
    const wav = (key: string): string | undefined => {
      const stitched = wavKeys.keyFor(index, key);
      if (stitched === undefined) return undefined;
      if (!known.has(`w${stitched}`)) {
        known.add(`w${stitched}`);
        stageWAV[index]!.push(stitched);
        // A BMS stage's slot keeps BMS playback (one voice per slot) in bmson output.
        if (perStageRules && asBmson && source.sourceFormat === 'bms')
          (chart.resources.wavSourceFormat ??= {})[stitched] = 'bms';
        const path = wavResources[key];
        if (path !== undefined) chart.resources.wav[stitched] = assetPath(index, 'wav', path);
        const intrinsicGain = (source.resources.wavGain?.[key] ?? 1) * volWAVToLinearGain(source.bms.volWAV);
        Iif (!Number.isFinite(intrinsicGain) || intrinsicGain < 0)
          throw new RangeError(`Invalid stage WAV gain: ${key}`);
        if (intrinsicGain !== 1) (chart.resources.wavGain ??= {})[stitched] = intrinsicGain;
        // Only an EXWAV no later #WAV of the slot redefined carries over (#1197).
        const rawExWAV = resolveBmsExWAVDeclarations(source)[key];
        const exWAV = rawExWAV === undefined ? undefined : parseBMSExWAV(rawExWAV);
        if (exWAV && rawExWAV !== undefined) {
          const parameters = [
            ['p', exWAV.pan],
            ['v', exWAV.volumeMillibels],
            ['f', exWAV.frequencyHz],
            ['r', exWAV.rate],
          ].filter((entry) => entry[1] !== undefined);
          chart.bms.exWAV[stitched] =
            `${parameters.map(([flag]) => flag).join('')} ${parameters.map(([, value]) => value).join(' ')} ${assetPath(index, 'wav', exWAV.filename)}`;
        }
        for (const command of wavCommands) {
          Iif (command?.slot !== key) continue;
          const parameter = command.param === 'pitch' ? '00' : command.param === 'volume' ? '01' : '02';
          chart.bms.wavCmds.push(`${parameter} ${stitched} ${command.value}`);
        }
      }
      return stitched;
    };
    const bmp = createNonstopBMPAllocator({
      source,
      target: chart,
      stage: index,
      keys: bmpKeys,
      stageKeys: stageBMP[index]!,
      assetPath: (path) => assetPath(index, 'bmp', path),
    });
    const push = (
      seconds: number,
      channel: string,
      value: string | undefined,
      bmson?: BeMusicEvent['bmson'],
      endSeconds?: number,
      lrx?: LRXEventExtensions,
    ): boolean => {
      if (value === undefined) return false;
      objects.push({
        seconds: stitchedSeconds(index, seconds),
        channel,
        value,
        stage: index,
        ...(bmson !== undefined ? { bmson } : {}),
        ...(lrx !== undefined ? { lrx } : {}),
        ...(endSeconds !== undefined ? { endSeconds: stitchedSeconds(index, endSeconds) } : {}),
      });
      return true;
    };
 
    const placedOptions = placeNonstopChartOptions(chartIndex, placements[index]!, window, index);
    chartOptionCues.push(...placedOptions.cues);
    chartOptionDiagnostics.push(...placedOptions.diagnostics);
    hasChartOptions ||= placedOptions.hasOperations;
    chartText.push({
      startSeconds: Math.max(0, window.start),
      endSeconds: window.end,
      offsetSeconds: placements[index]!.offsetSeconds,
      rate: placements[index]!.rate,
      timeline: buildChartTextTimeline(chartIndex.source, chartIndex.timing),
      ...(chartIndex.reversal ? { freezeSeconds: chartIndex.reversal.seconds } : {}),
    });
    const keyBound = placeNonstopKeyBoundBGA(chartIndex, placements[index]!, window, index, bmp);
    Iif (!keyBound) return { ok: false, reason: 'id-space', stage: index };
    keyBoundBGA.push(...keyBound);
    const bmson = placeNonstopBmsonBGA(chartIndex, placements[index]!, window, index, bmp);
    Iif (!bmson) return { ok: false, reason: 'id-space', stage: index };
    bmsonBGA.push(...bmson);
    if (!addStageObjects(chartIndex, push, wav, bmp, asBmson)) return { ok: false, reason: 'id-space', stage: index };
    if (perStageRules) {
      const inWindow = (seconds: number): boolean => seconds >= window.start && seconds < window.end;
      const explosion = wavResources['00'] !== undefined ? wav('00') : undefined;
      Iif (wavResources['00'] !== undefined && explosion === undefined)
        return { ok: false, reason: 'id-space', stage: index };
      landmineSampleKeys.push({
        seconds: Math.max(0, window.start),
        ...(explosion !== undefined ? { sampleKey: explosion } : {}),
      });
      for (const change of chartIndex.judgeRank.changes) {
        const seconds = stitchedSeconds(index, change.seconds);
        Eif (inWindow(seconds)) exRankChanges[index]!.push({ seconds, exRank: change.exRankValue });
      }
      objects.push(
        ...placeNonstopVolumeChanges(
          chartIndex,
          window,
          (seconds) => stitchedSeconds(index, seconds),
          index,
          volumeChannels,
        ),
      );
      for (const [channel, timeline, interpolate] of [
        ['SC', chartIndex.scroll, false],
        ['SP', chartIndex.speed, true],
      ] as const) {
        const own = timeline.map((point) => ({
          seconds: stitchedSeconds(index, chartIndex.timing.beatToSeconds(point.beat)),
          value: point.speed,
        }));
        const keys = keyframeKeys[channel];
        for (const keyframe of placeNonstopKeyframes(own, window, {
          interpolate,
          carried: keyframeChannels.has(channel),
          origin: placements[index]!.offsetSeconds,
        })) {
          let key = keys.byValue.get(keyframe.value);
          if (key === undefined) {
            key = keys.allocator.fresh();
            Iif (key === undefined) return { ok: false, reason: 'id-space', stage: index };
            keys.table[key] = keyframe.value;
            keys.byValue.set(keyframe.value, key);
          }
          objects.push({ seconds: keyframe.seconds, channel, value: key, stage: index });
          keyframeChannels.add(channel);
        }
      }
      // LR2 freezes its event pump at a negative BPM for the rest of the play, later stages included (OpenLR2
      // `LR2f.cpp` L12610, L12717-L12723). Like the stage's other BPM changes, it counts only in the stage's window
      // (LR2 drops those from the last-measure line on, L26970-L26976).
      if (chartIndex.reversal !== undefined) {
        const seconds = stitchedSeconds(index, chartIndex.reversal.seconds);
        const counts = options.placement === 'lr2' ? seconds < window.end : inWindow(seconds);
        if (counts && (reversal === undefined || seconds < reversal.seconds)) reversal = { seconds, stage: index };
      }
    }
 
    for (const stop of chartIndex.timing.stopPoints) {
      // A negative STOP (LR2's negative `#STOPxx`) only moves later objects earlier, which their stitched times
      // already carry; it has no pause to write.
      if (!(stop.seconds > 0)) continue;
      // `beatToSeconds` at a STOP's own beat is its start (the STOP counts from just after it).
      const seconds = stitchedSeconds(index, chartIndex.timing.beatToSeconds(stop.beat));
      if (seconds >= window.start && seconds < window.end) {
        stops.push({ seconds, duration: stop.seconds / placements[index]!.rate });
      }
    }
    const timing = timings[index]!;
    // A later stage shows its bar lines from the one nearest its first note (OpenLR2 L26476-L26485, L26979).
    const firstLine = index === 0 ? 0 : resolveNonstopLastMeasure(timing.firstNote);
    // Up to a measure past the last note: the grid extends itself past the last object.
    const lastLine = Math.min(999, Math.ceil(timing.lastNote) + 1);
    for (let measure = firstLine; measure <= lastLine; measure += 1) {
      const seconds = stitchedSeconds(index, timing.secondsAt(measure));
      if (seconds >= window.end) break;
      if (seconds >= window.start) barLines.push(seconds);
    }
  }
 
  const planeControls = flattenNonstopBGAOpacity(
    stageOpacity.map((opacity, index) => ({
      opacity,
      windowStart: windows[index]!.start,
      windowEnd: windows[index]!.end,
    })),
  );
  const argbKeys = new NonstopKeyAllocator(asBmson);
  const argbValues = new Map<string, string>();
  for (const control of planeControls) {
    if (control.channel.startsWith('A')) {
      let key = argbValues.get(control.value);
      if (key === undefined) {
        do {
          key = argbKeys.fresh();
        } while (key !== undefined && chart.bms.argb[key] !== undefined);
        Iif (key === undefined) return { ok: false, reason: 'id-space', stage: control.stage };
        chart.bms.argb[key] = control.value;
        argbValues.set(control.value, key);
      }
      control.value = key;
    }
    objects.push(control);
  }
  if (reversal !== undefined) {
    // `|BPM|` keeps the 150-BPM scroll; the sign arms the reversal.
    const key = bpmKeys.fresh();
    Iif (key === undefined) return { ok: false, reason: 'id-space', stage: reversal.stage };
    chart.resources.bpm[key] = -STITCHED_BPM;
    objects.push({ seconds: reversal.seconds, channel: '08', value: key, stage: reversal.stage });
  }
  if (perStageRules && asBmson) {
    stages.forEach((stage, index) => {
      if (stage.chart.sourceFormat !== 'bms') return;
      for (const key of stageBMP[index]!) (chart.resources.bmpSourceFormat ??= {})[key] = 'bms';
    });
  }
  convertSeamNotes(objects, stages.length);
  layOnGrid(chart, objects, stops, barLines, stopKeys);
  Iif (chart.events.length === 0 && objects.length > 0) return { ok: false, reason: 'id-space' };
  if (lrxOutput) {
    chart.sourceFormat = 'lrx';
    const laneType = stages[0]!.chart.lrx?.laneType;
    chart.lrx = laneType !== undefined ? { laneType } : {};
  }
 
  const first = stages[0]!.chart.metadata;
  chart.metadata.bpm = STITCHED_BPM;
  if (options.title !== undefined) chart.metadata.title = options.title;
  if (first.rank !== undefined) chart.metadata.rank = first.rank;
  const backBMPs = stages.map((stage, index) => {
    const path = stage.chart.metadata.backBMP?.trim();
    return path ? assetPath(index, 'bmp', path) : undefined;
  });
  if (backBMPs[0] !== undefined) chart.metadata.backBMP = backBMPs[0];
  // The decide and play screens read these from the chart; the stitched one takes the first stage's, as #BACKBMP.
  const stageImage = (index: number, path: string | undefined): string | undefined => {
    const trimmed = path?.trim();
    return trimmed ? assetPath(index, 'bmp', trimmed) : undefined;
  };
  const stageFiles = stages.map((stage, index) => stageImage(index, stage.chart.metadata.stageFile));
  const banners = stages.map((stage, index) => stageImage(index, stage.chart.metadata.banner));
  if (stageFiles[0] !== undefined) chart.metadata.stageFile = stageFiles[0];
  if (banners[0] !== undefined) chart.metadata.banner = banners[0];
  if (first.playLevel !== undefined) chart.metadata.playLevel = first.playLevel;
  if (first.difficulty !== undefined) chart.metadata.difficulty = first.difficulty;
  if (perStageRules && !asBmson && stages[0]!.chart.bms.defExRank !== undefined)
    chart.bms.defExRank = stages[0]!.chart.bms.defExRank;
  const total = stages[totalStage]?.chart.metadata.total;
  if (total !== undefined) chart.metadata.total = total;
 
  const readouts = stages.map((stage, index) => ({
    ...stageNoteHeads(objects, index),
    tempo: resolved[index]!.timing.tempoPoints.map((point) => ({
      seconds: point.seconds,
      bpm: point.displayBPM ?? point.bpm,
    })),
    headerBPM: stage.chart.metadata.bpm,
    ...(stage.chart.metadata.rank !== undefined ? { rank: stage.chart.metadata.rank } : {}),
    exRankChanges: exRankChanges[index]!,
    ...(asBmson || perStageRules
      ? {
          sourceFormat: stage.chart.sourceFormat === 'bmson' ? ('bmson' as const) : ('bms' as const),
          ...(stage.chart.bms.defExRank !== undefined ? { exRank: stage.chart.bms.defExRank } : {}),
          ...(stage.chart.bmson.info.judgeRank !== undefined
            ? { bmsonJudgeRank: stage.chart.bmson.info.judgeRank }
            : {}),
        }
      : {}),
  }));
 
  const stageRanks = resolveNonstopStageRanks(readouts, placements, options);
  if (asBmson) {
    const firstStage = stages[0]!.chart;
    const table =
      firstStage.sourceFormat === 'bmson' ? 'bmson' : firstStage.bms.defExRank !== undefined ? 'bms-exrank' : 'chart';
    const rank =
      table === 'bmson'
        ? (firstStage.bmson.info.judgeRank ?? 100)
        : table === 'bms-exrank'
          ? firstStage.bms.defExRank!
          : (firstStage.metadata.rank ?? 2);
    stageRanks.unshift({ seconds: 0, rank, table });
    chart.bmson.info.judgeRank = firstStage.sourceFormat === 'bmson' ? (firstStage.bmson.info.judgeRank ?? 100) : 100;
  }
  return {
    ok: true,
    chart,
    map: {
      ...(hasChartOptions
        ? {
            chartOptions: {
              version: chartOptionCues.some(({ state }) => state.bgaMode !== undefined)
                ? CHART_OPTION_PROGRAM_VERSION
                : 3,
              initial: { ...chartOptionCues[0]?.state },
              cues: chartOptionCues.slice(1),
            },
          }
        : {}),
      ...(chartOptionDiagnostics.length > 0 ? { chartOptionDiagnostics } : {}),
      ...(chartText.some((stage) => stage.timeline.cues.length > 0 || stage.timeline.missText !== undefined)
        ? { chartText }
        : {}),
      ...(keyBoundBGA.length > 0 ? { keyBoundBGA } : {}),
      ...(bmsonBGA.some((cue) => cue.sequences.length > 0) ? { bmsonBGA } : {}),
      ...(landmineSampleKeys.some((cue) => cue.sampleKey !== undefined) ? { landmineSampleKeys } : {}),
      tempo: resolveNonstopTempo(readouts, placements, options),
      stageRanks,
      stages: placements.map((placement, index) => {
        const after = index < placements.length - 1 ? (options.connections[index] ?? 'fade') : undefined;
        const before = index > 0 ? (options.connections[index - 1] ?? 'fade') : undefined;
        const boundary = placement.boundarySeconds;
        const previousBoundary = index > 0 ? placements[index - 1]!.boundarySeconds : 0;
        const fadeOut = after !== undefined ? FADES[after].out : undefined;
        const fadeIn = before !== undefined ? FADES[before].in : undefined;
        return {
          placement,
          windowStart: Math.max(0, windows[index]!.start),
          windowEnd: windows[index]!.end,
          wavKeys: stageWAV[index]!,
          bmpKeys: stageBMP[index]!,
          ...(hasBGAOpacity(stageOpacity[index]!) ? { bgaOpacity: stageOpacity[index]! } : {}),
          ...(resolvePoorBGAMode(stages[index]!.chart.bms.poorBGA) !== 0
            ? { poorBGAMode: resolvePoorBGAMode(stages[index]!.chart.bms.poorBGA) }
            : {}),
          ...(fadeOut !== undefined ? { soundFadeOut: { start: boundary, end: boundary + fadeOut } } : {}),
          ...(fadeIn !== undefined ? { soundFadeIn: { start: previousBoundary - fadeIn, end: previousBoundary } } : {}),
          ...(after !== undefined ? { bgaFadeOut: { start: boundary, end: boundary + BGA_FADE_SECONDS } } : {}),
          ...(before !== undefined
            ? { bgaFadeIn: { start: previousBoundary - BGA_FADE_SECONDS, end: previousBoundary } }
            : {}),
          lr2StageMarker: before === 'blank1' || before === 'blank2',
          songInfo: stageSongInfo(stages[index]!.chart),
          ...(backBMPs[index] !== undefined ? { backBMP: backBMPs[index] } : {}),
          ...(stageFiles[index] !== undefined ? { stageFile: stageFiles[index] } : {}),
          ...(banners[index] !== undefined ? { banner: banners[index] } : {}),
          ...(stages[index]!.chart.metadata.playLevel !== undefined
            ? { playLevel: stages[index]!.chart.metadata.playLevel }
            : {}),
          ...(stages[index]!.chart.metadata.difficulty !== undefined
            ? { difficulty: stages[index]!.chart.metadata.difficulty }
            : {}),
        };
      }),
    },
  };
}
 
/**
 * Collects a stage's objects at their stage-local seconds: judged notes (long notes as `#LNTYPE 1` pairs on `5x` /
 * `6x`), shadowed duplicates as BGM, invisible notes, mines (their value is the damage, kept as is), BGM and BGA.
 * Returns false when the stitched key space runs out.
 */
function addStageObjects(
  chart: ResolvedChart,
  push: (
    seconds: number,
    channel: string,
    value: string | undefined,
    bmson?: BeMusicEvent['bmson'],
    endSeconds?: number,
    lrx?: LRXEventExtensions,
  ) => boolean,
  wav: (key: string) => string | undefined,
  bmp: (key: string) => string | undefined,
  asBmson: boolean,
): boolean {
  let ok = true;
  if (chart.sourceFormat === 'lrx') return addLRXStageObjects(chart, push, wav, bmp);
  const triggers = asBmson ? new Map(chart.sampleTriggers.map((trigger) => [trigger.event, trigger])) : undefined;
  const add = (
    seconds: number,
    channel: string,
    value: string | undefined,
    event?: BeMusicEvent,
    endSeconds?: number,
    lnMode?: number,
  ): void => {
    const trigger = event !== undefined ? triggers?.get(event) : undefined;
    const bmson =
      asBmson && event !== undefined
        ? {
            ...event.bmson,
            c: event.bmson?.c === true,
            sampleOffsetSeconds: trigger?.sampleOffsetSeconds ?? 0,
            ...(trigger?.sampleDurationSeconds !== undefined
              ? { sampleDurationSeconds: trigger.sampleDurationSeconds }
              : {}),
            ...(lnMode !== undefined ? { t: lnMode } : {}),
          }
        : undefined;
    if (!push(seconds, channel, value, bmson, endSeconds)) ok = false;
  };
  for (const note of chart.notes) {
    Iif (note.freeZone === true) continue;
    const key = wav(note.sampleKey);
    if (asBmson) {
      for (const event of note.soundEvents ?? [note.event])
        add(note.seconds, note.channel, wav(event.value), event, note.endSeconds, note.lnMode);
      if (note.endSoundEvent && note.endSeconds !== undefined)
        add(note.endSeconds, note.channel, wav(note.endSoundEvent.value), note.endSoundEvent);
    } else if (note.kind === 'ln' && note.endSeconds !== undefined) {
      const lane = `${note.channel[0] === '2' ? '6' : '5'}${note.channel[1]}`;
      add(note.seconds, lane, key);
      add(note.endSeconds, lane, key);
    } else {
      add(note.seconds, note.channel, key);
    }
  }
  if (chart.sourceFormat !== 'bmson')
    for (const note of chart.shadowedNotes) add(note.seconds, '01', wav(note.sampleKey), note.event);
  for (const note of chart.invisibleNotes)
    add(note.seconds, normalizeChannel(note.event.channel), wav(note.sampleKey), note.event);
  for (const mine of chart.mines) {
    if (asBmson) {
      Iif (
        !push(
          mine.seconds,
          normalizeChannel(mine.event.channel),
          wav(chart.sourceFormat === 'bmson' ? mine.sampleKey : '00'),
          { damage: mine.damage },
        )
      )
        ok = false;
    } else add(mine.seconds, normalizeChannel(mine.event.channel), mine.event.value.toUpperCase());
  }
  for (const event of chart.sortedEvents) {
    const channel = normalizeChannel(event.channel);
    const value = normalizeObjectKey(event.value, chart.idBase, chart.sourceFormat === 'bmson');
    if (channel === '01') add(chart.timing.eventToSeconds(event), '01', wav(value), event);
    else if (!asBmson && BGA_CHANNELS.has(channel)) add(chart.timing.eventToSeconds(event), channel, bmp(value));
  }
  if (asBmson) {
    for (const [layer, channel] of [
      ['base', '04'],
      ['layer', '07'],
      ['layer2', '0A'],
      ['poor', '06'],
    ] as const) {
      for (const cue of chart.bga[layer]) {
        // An explicit zero clears the layer without consuming a resource key.
        add(cue.seconds, channel, cue.key === undefined ? '00' : bmp(cue.key));
      }
    }
  }
  return ok;
}
 
/**
 * {@link addStageObjects} for an LRX stage stitched into an LRX course: judged notes on their lanes (a long note keeps
 * its end, and gets its tick `length` on the grid), every background sound with its LRX values (chain and hidden notes
 * keep their lane, so chart-model ties them again), and BGA. Its hidden notes are background sounds already, so their
 * invisible-note copies add nothing.
 */
function addLRXStageObjects(
  chart: ResolvedChart,
  push: (
    seconds: number,
    channel: string,
    value: string | undefined,
    bmson?: BeMusicEvent['bmson'],
    endSeconds?: number,
    lrx?: LRXEventExtensions,
  ) => boolean,
  wav: (key: string) => string | undefined,
  bmp: (key: string) => string | undefined,
): boolean {
  let ok = true;
  const values = (event: BeMusicEvent): LRXEventExtensions | undefined => {
    if (event.lrx === undefined) return undefined;
    const { length: _length, ...rest } = event.lrx;
    return Object.keys(rest).length > 0 ? rest : undefined;
  };
  for (const note of chart.notes) {
    const endSeconds = note.kind === 'ln' ? note.endSeconds : undefined;
    // A long note always carries an LRX block, for the grid to give it its length.
    const lrx = endSeconds !== undefined ? (values(note.event) ?? {}) : values(note.event);
    Iif (!push(note.seconds, note.channel, wav(note.sampleKey), undefined, endSeconds, lrx)) ok = false;
  }
  for (const event of chart.sortedEvents) {
    const channel = normalizeChannel(event.channel);
    const value = normalizeObjectKey(event.value, chart.idBase, false);
    const seconds = chart.timing.eventToSeconds(event);
    if (channel === '01') {
      Iif (!push(seconds, '01', wav(value), undefined, undefined, values(event))) ok = false;
    } else Iif (BGA_CHANNELS.has(channel) && !push(seconds, channel, bmp(value))) ok = false;
  }
  return ok;
}
 
/**
 * A stage's 97 / 98 volume changes (rule version 4), at stitched seconds: inside its window as they are; at its start
 * the volume in force there (its own last change before, or full volume when an earlier stage changed it), so a stage
 * plays at the volumes it would alone. Changes past the window are dropped, as they would set the next stage's volume.
 */
function placeNonstopVolumeChanges(
  chart: ResolvedChart,
  window: { start: number; end: number },
  stitchedSeconds: (seconds: number) => number,
  stage: number,
  changedChannels: Set<string>,
): StitchedObject[] {
  const own = chart.volumeChanges.map((change) => ({
    seconds: stitchedSeconds(change.seconds),
    channel: normalizeChannel(change.event.channel),
    value: change.event.value.toUpperCase(),
    stage,
  }));
  const placed: StitchedObject[] = [];
  for (const channel of ['97', '98']) {
    const before = own.filter((change) => change.channel === channel && change.seconds <= window.start).at(-1);
    Iif (before !== undefined) placed.push({ ...before, seconds: window.start });
    else if (changedChannels.has(channel)) placed.push({ seconds: window.start, channel, value: 'FF', stage });
  }
  placed.push(...own.filter((change) => change.seconds > window.start && change.seconds < window.end));
  for (const object of placed) changedChannels.add(object.channel);
  return placed;
}
 
/** The judged lanes a seam note is compared on: a tap or long-note head on `1x` / `2x`, or `5x` / `6x` heads. */
function laneOf(object: StitchedObject): string | undefined {
  const bank = object.channel[0];
  if (bank === '1' || bank === '2') return object.channel;
  if (bank === '5') return `1${object.channel[1]}`;
  Iif (bank === '6') return `2${object.channel[1]}`;
  return undefined;
}
 
/**
 * LR2's seam rule (OpenLR2 L26988-L27010): a later stage's note before the previous stage's last note (by more than
 * 0.1 s), or within 0.1 s of it on a lane the earlier stages also used within that time, becomes background sound. A
 * long note so converted keeps only its head's sound.
 */
function convertSeamNotes(objects: StitchedObject[], stageCount: number): void {
  for (let stage = 1; stage < stageCount; stage += 1) {
    const previous = noteHeads(objects, stage - 1);
    if (previous.size === 0) continue;
    // LR2 measures from the previous stage's last note head (ops 10-29), not a long-note tail.
    const previousLast = Math.max(...[...previous.keys()].map((head) => head.seconds));
    const earlier = [...objects].filter((object) => object.stage < stage && laneOf(object) !== undefined);
    const converts = (object: StitchedObject): boolean => {
      if (object.seconds > previousLast + OVERLAP_SECONDS) return false;
      if (Math.abs(object.seconds - previousLast) >= OVERLAP_SECONDS) return object.seconds < previousLast;
      const lane = laneOf(object);
      return earlier.some((other) => laneOf(other) === lane && other.seconds >= previousLast - OVERLAP_SECONDS);
    };
    const dropped = new Set<StitchedObject>();
    for (const [head, tail] of noteHeads(objects, stage)) {
      if (!converts(head)) continue;
      head.channel = '01';
      Iif (tail !== undefined) dropped.add(tail);
    }
    for (let index = objects.length - 1; index >= 0; index -= 1) {
      Iif (dropped.has(objects[index]!)) objects.splice(index, 1);
    }
  }
}
 
/** Stitched seconds of a stage's first and last judged note heads (after the seam rule), when it has any. */
function stageNoteHeads(
  objects: readonly StitchedObject[],
  stage: number,
): { noteHeads?: { first: number; last: number } } {
  const heads = [...noteHeads(objects, stage).keys()].map((head) => head.seconds);
  return heads.length > 0 ? { noteHeads: { first: Math.min(...heads), last: Math.max(...heads) } } : {};
}
 
/** A stage's judged note heads (taps and long-note heads), each with its long-note tail, in time order. */
function noteHeads(objects: readonly StitchedObject[], stage: number): Map<StitchedObject, StitchedObject | undefined> {
  const heads = new Map<StitchedObject, StitchedObject | undefined>();
  const open = new Map<string, StitchedObject>();
  const own = objects
    .filter((object) => object.stage === stage && laneOf(object) !== undefined)
    .sort((left, right) => left.seconds - right.seconds);
  for (const object of own) {
    const long = object.channel[0] === '5' || object.channel[0] === '6';
    const head = long ? open.get(object.channel) : undefined;
    if (head !== undefined) {
      heads.set(head, object);
      open.delete(object.channel);
      continue;
    }
    heads.set(object, undefined);
    if (long) open.set(object.channel, object);
  }
  return heads;
}
 
/** Seconds of scroll at stitched `seconds`: the time with the STOPs before it (and the part of one it is in) removed. */
function scrollSeconds(seconds: number, stops: readonly StitchedStop[]): number {
  let frozen = 0;
  for (const stop of stops) {
    if (stop.seconds >= seconds) break;
    frozen += Math.min(stop.duration, seconds - stop.seconds);
  }
  return seconds - frozen;
}
 
/**
 * Lays the stitched objects on a 150-BPM grid: measures run between the kept bar lines, each object goes to the
 * position its scroll time gives, and each STOP becomes a `#STOP` of its exact length (in 1/192 of a 150-BPM measure).
 */
function layOnGrid(
  chart: BeMusicJSON,
  objects: readonly StitchedObject[],
  stops: StitchedStop[],
  barLineSeconds: readonly number[],
  stopKeys: NonstopKeyAllocator,
): void {
  stops.sort((left, right) => left.seconds - right.seconds);
  const toMeasures = (seconds: number): number => Math.max(0, scrollSeconds(seconds, stops)) / MEASURE_SECONDS;
  const lines = [0];
  for (const seconds of [...barLineSeconds].sort((left, right) => left - right)) {
    const at = toMeasures(seconds);
    if (at - lines.at(-1)! > 1e-6) lines.push(at);
  }
  const lastObject = Math.max(0, ...objects.map((object) => toMeasures(object.seconds)));
  while (lines.at(-1)! <= lastObject) lines.push(lines.at(-1)! + 1);
  for (let index = 0; index < lines.length - 1; index += 1) {
    const length = lines[index + 1]! - lines[index]!;
    if (Math.abs(length - 1) > 1e-9) chart.measures.push({ index, length });
  }
  const place = (seconds: number): Pick<BeMusicEvent, 'measure' | 'position'> => {
    const at = toMeasures(seconds);
    let measure = 0;
    while (measure < lines.length - 2 && lines[measure + 1]! <= at) measure += 1;
    const length = lines[measure + 1]! - lines[measure]!;
    const grid = Math.max(1, Math.round(length * GRID_PER_MEASURE));
    const step = Math.min(grid - 1, Math.round(((at - lines[measure]!) / length) * grid));
    return { measure, position: reduce(Math.max(0, step), grid) };
  };
  for (const object of objects) {
    const bmson = object.bmson !== undefined ? { ...object.bmson } : undefined;
    if (bmson !== undefined && object.endSeconds !== undefined && laneOf(object) !== undefined) {
      bmson.l = Math.max(
        0,
        (toMeasures(object.endSeconds) - toMeasures(object.seconds)) * 4 * (chart.bmson.info.resolution ?? 240),
      );
    } else if (bmson !== undefined) delete bmson.l;
    // An LRX long note's end is its length in LRX ticks, 480 to a quarter of the 150-BPM measure grid.
    const lrx =
      object.lrx !== undefined
        ? {
            ...object.lrx,
            ...(object.endSeconds !== undefined && laneOf(object) !== undefined
              ? {
                  length: Math.max(
                    1,
                    Math.round((toMeasures(object.endSeconds) - toMeasures(object.seconds)) * 4 * LRX_TICKS_PER_BEAT),
                  ),
                }
              : {}),
          }
        : undefined;
    chart.events.push({
      ...place(object.seconds),
      channel: object.channel,
      value: object.value,
      ...(bmson !== undefined ? { bmson } : {}),
      ...(lrx !== undefined ? { lrx } : {}),
    });
  }
  for (const stop of stops) {
    const key = stopKeys.fresh();
    Iif (key === undefined) {
      chart.events.length = 0;
      return;
    }
    chart.resources.stop[key] = (stop.duration / MEASURE_SECONDS) * 192;
    chart.events.push({ ...place(stop.seconds), channel: '09', value: key });
  }
  chart.events.sort(
    (left, right) =>
      left.measure - right.measure ||
      left.position[0] / left.position[1] - right.position[0] / right.position[1] ||
      left.channel.localeCompare(right.channel),
  );
}
 
function reduce(numerator: number, denominator: number): [number, number] {
  let a = numerator;
  let b = denominator;
  while (b !== 0) [a, b] = [b, a % b];
  return numerator === 0 ? [0, 1] : [numerator / a, denominator / a];
}
 
function withoutBmsonUp(event: BeMusicEvent): BeMusicEvent {
  if (event.bmson?.up === undefined) return event;
  const { up: _up, ...bmson } = event.bmson;
  return { ...event, bmson };
}