All files / chart-model/src resolved-notes.ts

99.53% Statements 213/214
97.39% Branches 187/192
100% Functions 23/23
99.48% Lines 195/196

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                                                                                                                                                                                                                                  597x     597x                                                       5020x 5020x 174579x   1662x                         52163x             57183x 57183x 57183x 57183x 57183x 57183x   57183x 894756x 894756x 135697x   759059x 758917x 758917x 758917x 470x 470x 470x 758447x 542x 542x 757905x 11x 11x   758917x 1023x   1023x     758917x     57183x 57183x 57183x 57183x 57183x 57183x 57183x 860x 860x   860x 46509x 144x   860x 33696x     57183x 57183x                 28x 49x 28x 28x 90x 90x 49x 49x     41x 90x 90x 12x 12x           7238x 7238x 224977x 224977x 224977x 207839x   17138x 17138x                   7238x                 4348x 4348x 213449x 213449x 4x 4x               4x   213445x 213445x 213445x 212669x   776x 776x                 4348x                     75828x               4x               7400x               72x 72x 72x                 1333250x     1333250x 1333250x       176241x 176241x 146619x                         29622x                           176241x 459x   29622x                                   57183x 57183x 57183x 57183x 656859x 656859x 656859x         21683x   656859x 637397x 637397x 637397x 637397x   19462x   19462x 38662x 10591x 10591x     19462x 19462x     41x 41x 86x 86x 76x   41x   19462x 19462x 41145x 41145x 29931x   11214x 11214x   19462x 19462x 19462x   57183x 57183x       758263x 503577x   254686x 232132x   22554x 11838x   10716x         599115x 30707x 30707x 30707x 136874x 136874x 136874x 136874x 150755x 150755x 44588x 44588x   136874x 45320x   30707x                   57183x 888x   56295x 56295x 42531x   13764x 13764x 464106x 91603x   372503x 448x 448x   372055x 372055x 372055x 91603x 91603x 91603x 91603x   372055x   13764x         57183x 57183x 888x   56295x 56295x   55816x     55816x                                   57183x                     5051x 5051x 384x   4667x    
import {
  LRX_TICKS_PER_BEAT,
  normalizeChannel,
  normalizeObjectKey,
  type BeMusicEvent,
  type BeMusicJSON,
} from '@be-music/chart-source';
import { resolveBMSLongNotes, resolveLNOBJLongNotes, type BeatResolver, type ChartPlayVariant } from './index.ts';
import {
  DEFAULT_LONG_NOTE_MODE,
  resolveChartLongNoteMode,
  resolveLandmineDamage,
  type LongNoteMode,
} from './note-rules.ts';
import type { TimingResolver } from './timing.ts';
 
/** What a resolved note is: a judged tap, a judged long note, a landmine, or an invisible (keysound-only) object. */
export type ResolvedNoteKind = 'tap' | 'ln' | 'mine' | 'invisible';
 
/**
 * One note of a resolved chart, with every format rule already applied: the lane is the playable `1x` / `2x` channel
 * (invisible `3x` / `4x`, `#LNTYPE` `5x` / `6x` and mine `Dx` / `Ex` objects are mapped onto it), times are in beats and
 * seconds after BPM / STOP / `#STP`, and a long note carries its end and its LN / CN / HCN mode.
 */
export interface ResolvedNote {
  readonly kind: ResolvedNoteKind;
  /** The playable lane channel (`11`..`1Z`, `21`..`2Z`), normalized. */
  readonly channel: string;
  readonly beat: number;
  readonly seconds: number;
  /** `ln` only: where the long note ends. */
  readonly endBeat?: number;
  readonly endSeconds?: number;
  /** `ln` only: the long-note mode (bmson per-note `t` > `info.ln_type` > `#LNMODE` > LN). */
  readonly lnMode?: LongNoteMode;
  /** `ln` only: the note sits on a FREE ZONE column (`17` / `27` in the That-Which-Must-Not-Be-Named families), which has a fixed one-beat tail. */
  readonly freeZone?: true;
  /** The keysound slot (the object value normalized under the chart's `#BASE`). For a mine, its object value. */
  readonly sampleKey: string;
  /** `mine` only: the gauge damage in percent (`resolveLandmineDamage`). */
  readonly damage?: number;
  /** The source event the note was resolved from, for keysound lookup and diagnostics. */
  readonly event: BeMusicEvent;
  /** bmson layered note: every constituent source event, including `event`, triggered by one press. */
  readonly soundEvents?: readonly BeMusicEvent[];
  /** bmson `up`: source slice played when this long note's tail is resolved. */
  readonly endSoundEvent?: BeMusicEvent;
  /** LRX chain notes that follow this note: played after a press that sounds it (see {@link ResolvedChainSound}). */
  readonly chainSounds?: readonly ResolvedChainSound[];
}
 
/**
 * An LRX chain note (`cn="1"`) tied to the judged note before it on its lane. plugout plays it whenever a press sounds
 * that note, `delaySeconds` after the press: as far after the note as it is in the chart (`plugout4.exe` 0x43bbb0 links
 * the notes, 0x43bcd0 plays them). Its event stays in the background channel for players that do not judge.
 */
export interface ResolvedChainSound {
  readonly event: BeMusicEvent;
  /** Chart seconds from the note it follows to the chain note, ≥ 0. */
  readonly delaySeconds: number;
}
 
export interface ResolvedNoteLists {
  /** Judged notes (`tap` / `ln`): at most one per lane and position, sorted by beat, then lane, then object value. */
  notes: ResolvedNote[];
  /**
   * Notes that lost their lane and position to a note in `notes` and carry a different keysound: not judged or drawn,
   * but their keysound still belongs to the chart. BMS hosts sound them as background audio; bmson keeps
   * them on the judged note in `soundEvents`.
   */
  shadowedNotes: ResolvedNote[];
}
 
export interface ResolvedNoteContext {
  json: BeMusicJSON;
  timing: TimingResolver;
  beatResolver: BeatResolver;
  sortedEvents: ReadonlyArray<BeMusicEvent>;
  idBase: 36 | 62;
  /** The play variant (only judged notes need it, for FREE ZONE), resolved on demand. */
  resolvePlayVariant: () => ChartPlayVariant;
  inferBmsLNTypeWhenMissing: boolean;
  /**
   * Overrides whether `17` / `27` are FREE ZONE instead of reading it from the play variant. The chart fingerprint
   * resolves with `false` and applies FREE ZONE itself once an outcome's lane mode is known.
   */
  freeZone?: boolean;
}
 
/**
 * Where a judged long note's tail comes from, exactly: the `#LNOBJ` end object or the closing `#LNTYPE 1` object
 * (`event`), one cell after the last object of an `#LNTYPE 2` run (`after-event`), a bmson length in pulses or an LRX
 * length in ticks (`pulses`), or the fixed one-beat FREE ZONE tail (`free-zone`).
 */
export type JudgedNoteTail =
  | { readonly kind: 'event'; readonly event: BeMusicEvent }
  | { readonly kind: 'after-event'; readonly event: BeMusicEvent }
  | { readonly kind: 'pulses'; readonly pulses: number }
  | { readonly kind: 'free-zone' };
 
/** A judged note before freezing: what {@link resolveJudgedNotes} keeps, plus the exact source of its tail. */
export interface JudgedNoteEntry {
  readonly event: BeMusicEvent;
  readonly channel: string;
  readonly beat: number;
  readonly lnMode?: LongNoteMode;
  /** A FREE ZONE note (`17` / `27` under a variant that has FREE ZONE): judged by nobody, so not scored. */
  readonly freeZone?: true;
  /** Set exactly when the note is a long note. */
  readonly tail?: JudgedNoteTail;
}
 
/** plugout counts and judges an LRX long note's end, which Be-Music calls a CN. */
const LRX_LONG_NOTE_MODE: LongNoteMode = 2;
 
/** A FREE ZONE note's fixed tail, in beats. */
const FREE_ZONE_BEAT_LENGTH = 1;
 
interface MutableNote {
  event: BeMusicEvent;
  channel: string;
  beat: number;
  seconds: number;
  endBeat?: number;
  endSeconds?: number;
  lnMode?: LongNoteMode;
  freeZone?: true;
  tail?: JudgedNoteTail;
  soundEvents?: BeMusicEvent[];
  endSoundEvent?: BeMusicEvent;
  chainSounds?: ResolvedChainSound[];
}
 
/**
 * Resolves the judged notes.
 *
 * Each lane and position holds at most one judged note, as in beatoraja, whose timeline keeps one note per lane: a
 * later BMS normal-channel object replaces an earlier one before long-note pairing. Dedicated long notes take
 * precedence over taps at their start. bmson layers notes from different sound channels.
 */
export function resolveJudgedNotes(
  context: ResolvedNoteContext,
  droppedStackedNotes?: BeMusicEvent[],
): ResolvedNoteLists {
  const { notes, shadowed } = resolveMutableJudgedNotes(context, droppedStackedNotes);
  return {
    notes: notes.map((note) => freezeJudgedNote(note, context.idBase, context.json.sourceFormat === 'bmson')),
    shadowedNotes: shadowed.map((note) =>
      freezeJudgedNote(note, context.idBase, context.json.sourceFormat === 'bmson'),
    ),
  };
}
 
/**
 * {@link resolveJudgedNotes} before freezing: the judged and shadowed notes with the exact source of each long note's
 * tail. Not part of the package API; the chart fingerprint reads exact positions from it.
 */
export function resolveJudgedNoteEntries(context: ResolvedNoteContext): {
  notes: JudgedNoteEntry[];
  shadowed: JudgedNoteEntry[];
} {
  return resolveMutableJudgedNotes(context);
}
 
function resolveMutableJudgedNotes(
  context: ResolvedNoteContext,
  droppedStackedNotes?: BeMusicEvent[],
): { notes: MutableNote[]; shadowed: MutableNote[] } {
  const { json, timing, beatResolver } = context;
  const freeZoneActive = context.freeZone ?? variantUsesFreeZone(context.resolvePlayVariant());
  const bmsonResolution = json.sourceFormat === 'bmson' ? Math.max(1, json.bmson.info.resolution || 240) : undefined;
  const lnType = json.bmson.info.lnType;
  const chartLongNoteType: LongNoteMode | undefined = lnType === 1 || lnType === 2 || lnType === 3 ? lnType : undefined;
  const notes: MutableNote[] = [];
 
  for (const event of context.sortedEvents) {
    const channel = normalizeChannel(event.channel);
    if (!isLaneChannel(channel) || (channel.charCodeAt(0) !== 0x31 && channel.charCodeAt(0) !== 0x32)) {
      continue;
    }
    if (json.sourceFormat === 'bmson' && event.bmson?.up === true) continue;
    const beat = beatResolver.eventToBeat(event);
    const note: MutableNote = { event, channel, beat, seconds: timing.beatToSeconds(beat) };
    if (freeZoneActive && (channel === '17' || channel === '27')) {
      note.endBeat = beat + FREE_ZONE_BEAT_LENGTH;
      note.freeZone = true;
      note.tail = { kind: 'free-zone' };
    } else if (event.bmson?.l && event.bmson.l > 0 && bmsonResolution !== undefined) {
      note.endBeat = beat + event.bmson.l / bmsonResolution;
      note.tail = { kind: 'pulses', pulses: event.bmson.l };
    } else if (json.sourceFormat === 'lrx' && event.lrx?.length && event.lrx.length > 0) {
      note.endBeat = beat + event.lrx.length / LRX_TICKS_PER_BEAT;
      note.tail = { kind: 'pulses', pulses: event.lrx.length };
    }
    if (note.endBeat !== undefined) {
      note.endSeconds = timing.beatToSeconds(note.endBeat);
      // plugout judges an LRX long note's end as a note of its own: a CN.
      note.lnMode =
        json.sourceFormat === 'lrx' ? LRX_LONG_NOTE_MODE : resolveBmsonLongNoteMode(event, chartLongNoteType);
    }
    notes.push(note);
  }
 
  const bmsLongNoteMode = resolveBMSLongNoteMode(json);
  const normalObjects = json.sourceFormat === 'bms' ? selectBMSNormalObjects(notes) : notes;
  const withLNOBJ = applyLNOBJLongNotes(json, normalObjects, timing, bmsLongNoteMode);
  appendLNTypeLongNotes(context, withLNOBJ, bmsLongNoteMode);
  withLNOBJ.sort(compareNotes);
  const shadowed = collapseSamePositionNotes(withLNOBJ, json.sourceFormat === 'bmson', droppedStackedNotes);
  if (json.sourceFormat === 'bmson') {
    const endSounds = new Map<string, BeMusicEvent>();
    const endKey = (channel: string, beat: number): string => `${channel}:${Math.round(beat * bmsonResolution!)}`;
    // Source-channel order is retained by the parser's slot keys: later definitions replace earlier ones.
    for (const event of context.sortedEvents) {
      if (event.bmson?.up === true)
        endSounds.set(endKey(normalizeChannel(event.channel), beatResolver.eventToBeat(event)), event);
    }
    for (const note of withLNOBJ) {
      if (note.endBeat !== undefined) note.endSoundEvent = endSounds.get(endKey(note.channel, note.endBeat));
    }
  }
  if (json.sourceFormat === 'lrx') linkLRXChainSounds(context, withLNOBJ);
  return { notes: withLNOBJ, shadowed };
}
 
/**
 * Ties each LRX chain note to the judged note before it on its lane, in chart order, as plugout links a lane's notes
 * (0x43bbb0): a chain note follows the last note of its lane that is not one, together with the chain notes between
 * them. A chain note with no such note stays a background sound.
 */
function linkLRXChainSounds(context: ResolvedNoteContext, notes: MutableNote[]): void {
  const judged = new Map<BeMusicEvent, MutableNote>();
  for (const note of notes) judged.set(note.event, note);
  const previous = new Map<string, MutableNote>();
  for (const event of context.sortedEvents) {
    const note = judged.get(event);
    if (note !== undefined) {
      previous.set(note.channel, note);
      continue;
    }
    // A hidden chain note is in no lane list in plugout, so it follows nothing.
    const lane = event.lrx?.chain === true && event.lrx.damage !== 0 ? event.lrx.lane : undefined;
    const base = lane === undefined ? undefined : previous.get(lane);
    if (base === undefined) continue;
    const seconds = context.timing.beatToSeconds(context.beatResolver.eventToBeat(event));
    (base.chainSounds ??= []).push({ event, delaySeconds: Math.max(0, seconds - base.seconds) });
  }
}
 
/** Resolves the landmines (`Dx` / `Ex`), on the lane they sit on, with their gauge damage. */
export function resolveMineNotes(context: ResolvedNoteContext): ResolvedNote[] {
  const mines: ResolvedNote[] = [];
  for (const event of context.sortedEvents) {
    const channel = normalizeChannel(event.channel);
    const side = channel.charCodeAt(0);
    if (!isLaneChannel(channel) || (side !== 0x44 && side !== 0x45)) {
      continue;
    }
    const beat = context.beatResolver.eventToBeat(event);
    mines.push({
      kind: 'mine',
      channel: `${side === 0x44 ? '1' : '2'}${channel[1]!}`,
      beat,
      seconds: context.timing.beatToSeconds(beat),
      sampleKey: normalizeObjectKey(event.value, context.idBase, context.json.sourceFormat === 'bmson'),
      damage: resolveLandmineDamage(event, context.idBase, context.json.sourceFormat),
      event,
    });
  }
  return mines;
}
 
/**
 * Resolves the invisible objects (`3x` / `4x`): not judged, but they set the lane's keysound in manual play. An LRX
 * hidden (`dmg="0"`) lane note is one too, on its lane, besides the background sound it plays: plugout makes it the
 * lane's keysound once it plays (`plugout4.exe` 0x43f430), and reads BMS invisible objects as such notes (0x44b00c).
 */
export function resolveInvisibleNotes(context: ResolvedNoteContext): ResolvedNote[] {
  const invisible: ResolvedNote[] = [];
  for (const event of context.sortedEvents) {
    const hiddenLane = event.lrx?.damage === 0 ? event.lrx.lane : undefined;
    if (hiddenLane !== undefined && context.json.sourceFormat === 'lrx') {
      const beat = context.beatResolver.eventToBeat(event);
      invisible.push({
        kind: 'invisible',
        channel: hiddenLane,
        beat,
        seconds: context.timing.beatToSeconds(beat),
        sampleKey: normalizeObjectKey(event.value, context.idBase, false),
        event,
      });
      continue;
    }
    const channel = normalizeChannel(event.channel);
    const side = channel.charCodeAt(0);
    if (!isLaneChannel(channel) || (side !== 0x33 && side !== 0x34)) {
      continue;
    }
    const beat = context.beatResolver.eventToBeat(event);
    invisible.push({
      kind: 'invisible',
      channel: `${side === 0x33 ? '1' : '2'}${channel[1]!}`,
      beat,
      seconds: context.timing.beatToSeconds(beat),
      sampleKey: normalizeObjectKey(event.value, context.idBase, context.json.sourceFormat === 'bmson'),
      event,
    });
  }
  return invisible;
}
 
/**
 * Are channels `17` / `27` FREE ZONE under this variant?
 *
 * They're real key columns in POPN-9 (lane 7 of the nine-column bank) and in the 24-key keyboard modes (lane 7 of the
 * 24-column bank), where stamping the FREE ZONE one-beat tail would turn an ordinary tap into a phantom long note — and
 * would shadow a genuine `#LNOBJ` tail authored on the same channel. Every That-Which-Must-Not-Be-Named family keeps them as FREE ZONE.
 */
export function variantUsesFreeZone(variant: ChartPlayVariant): boolean {
  return ['5', '7', '10', '14'].includes(variant);
}
 
/**
 * Whether `channel` is a FREE ZONE column under `variant` (`17` / `27`, see {@link variantUsesFreeZone}): its notes have
 * a fixed one-beat tail but are judged by nobody, so they are not long notes.
 */
export function isFreeZoneChannel(channel: string, variant: ChartPlayVariant): boolean {
  return (channel === '17' || channel === '27') && variantUsesFreeZone(variant);
}
 
/**
 * Whether a resolved note is a long note a player holds: an `ln` note with a tail, not a FREE ZONE note, whose fixed
 * tail only marks the zone. What a chart lists as its long notes (the LN tag, the LN feature) counts these.
 */
export function isHeldLongNote(note: Pick<ResolvedNote, 'kind' | 'endBeat' | 'freeZone'>): boolean {
  return note.kind === 'ln' && note.endBeat !== undefined && note.freeZone !== true;
}
 
/**
 * Whether `channel` places an invisible object (`3x` / `4x`) on a lane: one that sets the lane's keysound in manual
 * play but is neither judged nor sounded by auto play.
 */
export function isInvisibleNoteChannel(channel: string): boolean {
  const normalized = normalizeChannel(channel);
  const side = normalized.charCodeAt(0);
  return isLaneChannel(normalized) && (side === 0x33 || side === 0x34);
}
 
/**
 * Lane codes span the classic `1`-`9` columns plus the extended `A`-`Z` columns the 24-key (Keyboardmania) modes author
 * lanes 10..24 on — `1A..1O` / `2A..2O` for playable notes, and the matching `3X` / `4X`, `DX` / `EX` families for
 * invisible objects and landmines.
 */
function isLaneChannel(normalizedChannel: string): boolean {
  Iif (normalizedChannel.length !== 2) {
    return false;
  }
  const laneCode = normalizedChannel.charCodeAt(1);
  return (laneCode >= 0x31 && laneCode <= 0x39) || (laneCode >= 0x41 && laneCode <= 0x5a);
}
 
function freezeJudgedNote(note: MutableNote, idBase: 36 | 62, allowLongKeys: boolean): ResolvedNote {
  const sampleKey = normalizeObjectKey(note.event.value, idBase, allowLongKeys);
  if (note.endBeat === undefined) {
    return {
      kind: 'tap',
      channel: note.channel,
      beat: note.beat,
      seconds: note.seconds,
      sampleKey,
      event: note.event,
      ...(note.soundEvents ? { soundEvents: note.soundEvents } : {}),
      ...(note.chainSounds ? { chainSounds: note.chainSounds } : {}),
    };
  }
  const resolved: {
    -readonly [K in keyof ResolvedNote]: ResolvedNote[K];
  } = {
    kind: 'ln',
    channel: note.channel,
    beat: note.beat,
    seconds: note.seconds,
    endBeat: note.endBeat,
    endSeconds: note.endSeconds,
    lnMode: note.lnMode,
    ...(note.endSoundEvent ? { endSoundEvent: note.endSoundEvent } : {}),
    sampleKey,
    event: note.event,
    ...(note.soundEvents ? { soundEvents: note.soundEvents } : {}),
    ...(note.chainSounds ? { chainSounds: note.chainSounds } : {}),
  };
  if (note.freeZone) {
    resolved.freeZone = true;
  }
  return resolved;
}
 
/**
 * Keeps one note per lane and position in `notes` (sorted by {@link compareNotes}) and returns the dropped notes whose
 * keysound differs from every note kept or returned before them at that position.
 *
 * Long notes are resolved first, so a `5x` / `6x` or `#LNOBJ` long note and a tap on its start compete here and the
 * long note wins — beatoraja also replaces a tap at a `5x` start with the long note. bmson keeps the first sound
 * channel's note whatever its length and layers only notes of the same length onto it. Between notes of the same kind the
 * first in sort order wins. For BMS normal-channel objects with recorded line order, replacements were already
 * applied before pairing. For bmson the first sound channel is the note beatoraja judges.
 */
function collapseSamePositionNotes(
  notes: MutableNote[],
  layered: boolean,
  droppedStackedNotes?: BeMusicEvent[],
): MutableNote[] {
  const shadowed: MutableNote[] = [];
  let writeIndex = 0;
  let groupStart = 0;
  while (groupStart < notes.length) {
    const first = notes[groupStart]!;
    let groupEnd = groupStart + 1;
    while (
      groupEnd < notes.length &&
      notes[groupEnd]!.beat === first.beat &&
      notes[groupEnd]!.channel === first.channel
    ) {
      groupEnd += 1;
    }
    if (groupEnd - groupStart === 1) {
      notes[writeIndex] = first;
      writeIndex += 1;
      groupStart = groupEnd;
      continue;
    }
    let keptIndex = groupStart;
    // bmson keeps the first sound channel's note, as beatoraja does; BMS prefers a long note over a tap.
    for (let index = groupStart; !layered && index < groupEnd; index += 1) {
      if (notes[index]!.endBeat !== undefined) {
        keptIndex = index;
        break;
      }
    }
    const kept = notes[keptIndex]!;
    if (layered) {
      // Only notes of the kept length layer onto it. beatoraja warns about and drops a note of another length, sound
      // included (BMSONDecoder); it stays in `shadowed`, which bmson hosts never schedule.
      const events = new Map<string, BeMusicEvent>();
      for (let index = groupStart; index < groupEnd; index += 1) {
        const note = notes[index]!;
        if (note.endBeat !== kept.endBeat) droppedStackedNotes?.push(note.event);
        else Eif (!events.has(note.event.value)) events.set(note.event.value, note.event);
      }
      kept.soundEvents = [...events.values()];
    }
    const soundedValues = new Set<string>([kept.event.value]);
    for (let index = groupStart; index < groupEnd; index += 1) {
      const note = notes[index]!;
      if (index === keptIndex || soundedValues.has(note.event.value)) {
        continue;
      }
      soundedValues.add(note.event.value);
      shadowed.push(note);
    }
    notes[writeIndex] = kept;
    writeIndex += 1;
    groupStart = groupEnd;
  }
  notes.length = writeIndex;
  return shadowed;
}
 
function compareNotes(left: MutableNote, right: MutableNote): number {
  if (left.beat !== right.beat) {
    return left.beat - right.beat;
  }
  if (left.channel !== right.channel) {
    return left.channel < right.channel ? -1 : 1;
  }
  if (left.event.value !== right.event.value) {
    return left.event.value < right.event.value ? -1 : 1;
  }
  return 0;
}
 
/** Apply normal-channel replacement before pairing LNOBJ. Older IR without line order keeps its legacy behavior. */
function selectBMSNormalObjects(notes: MutableNote[]): MutableNote[] {
  if (!notes.some((note) => note.event.bmsLineOrder !== undefined)) return notes;
  const selected: MutableNote[] = [];
  let index = 0;
  while (index < notes.length) {
    const start = index;
    const first = notes[index++]!;
    let winner = first;
    while (index < notes.length) {
      const candidate = notes[index]!;
      if (candidate.beat !== first.beat || candidate.channel !== first.channel) break;
      if ((candidate.event.bmsLineOrder ?? -1) > (winner.event.bmsLineOrder ?? -1)) winner = candidate;
      index += 1;
    }
    if (winner.event.bmsLineOrder !== undefined) selected.push(winner);
    else for (let at = start; at < index; at += 1) selected.push(notes[at]!);
  }
  return selected;
}
 
/** Turns `#LNOBJ` starts into long notes and drops their end objects. Returns the kept notes. */
function applyLNOBJLongNotes(
  json: BeMusicJSON,
  notes: MutableNote[],
  timing: TimingResolver,
  longNoteMode: LongNoteMode,
): MutableNote[] {
  if (json.sourceFormat !== 'bms') {
    return notes;
  }
  const resolved = resolveLNOBJLongNotes(json);
  if (resolved.startToEndBeat.size === 0) {
    return notes;
  }
  const kept: MutableNote[] = [];
  for (const note of notes) {
    if (resolved.endEvents.has(note.event)) {
      continue;
    }
    if (typeof note.endBeat === 'number' && Number.isFinite(note.endBeat) && note.endBeat > note.beat) {
      kept.push(note);
      continue;
    }
    const endBeat = resolved.startToEndBeat.get(note.event);
    const endEvent = resolved.startToEndEvent.get(note.event);
    if (typeof endBeat === 'number' && Number.isFinite(endBeat) && endBeat > note.beat && endEvent !== undefined) {
      note.endBeat = endBeat;
      note.endSeconds = timing.beatToSeconds(endBeat);
      note.lnMode = longNoteMode;
      note.tail = { kind: 'event', event: endEvent };
    }
    kept.push(note);
  }
  return kept;
}
 
/** Appends the `#LNTYPE` long notes authored on `5x` / `6x`. */
function appendLNTypeLongNotes(context: ResolvedNoteContext, notes: MutableNote[], longNoteMode: LongNoteMode): void {
  const { json, timing } = context;
  if (json.sourceFormat !== 'bms') {
    return;
  }
  const resolved = resolveBMSLongNotes(json, { inferLNTypeWhenMissing: context.inferBmsLNTypeWhenMissing });
  for (const longNote of resolved.notes) {
    const endBeat =
      typeof longNote.endBeat === 'number' && longNote.endBeat > longNote.beat && longNote.endEvent !== undefined
        ? longNote.endBeat
        : undefined;
    notes.push({
      event: longNote.event,
      channel: longNote.channel,
      beat: longNote.beat,
      seconds: timing.beatToSeconds(longNote.beat),
      endBeat,
      endSeconds: endBeat !== undefined ? timing.beatToSeconds(endBeat) : undefined,
      lnMode: endBeat !== undefined ? longNoteMode : undefined,
      tail:
        endBeat !== undefined
          ? { kind: resolved.lnType === 2 ? 'after-event' : 'event', event: longNote.endEvent! }
          : undefined,
    });
  }
}
 
/** BMS #LNOBJ / #LNTYPE use the same chart-level LNMODE / HDX LONGMODE precedence. */
function resolveBMSLongNoteMode(json: BeMusicJSON): LongNoteMode {
  return json.sourceFormat === 'bms' ? resolveChartLongNoteMode(json) : DEFAULT_LONG_NOTE_MODE;
}
 
/**
 * Long-note mode for a bmson-style long note (and a FREE ZONE tail), per the beatoraja bmson extension precedence:
 * per-note `t` > chart-level `info.ln_type` > default (LN).
 */
export function resolveBmsonLongNoteMode(
  event: BeMusicEvent,
  chartLongNoteType: LongNoteMode | undefined,
): LongNoteMode {
  const noteType = event.bmson?.t;
  if (noteType === 1 || noteType === 2 || noteType === 3) {
    return noteType;
  }
  return chartLongNoteType ?? DEFAULT_LONG_NOTE_MODE;
}