All files / chart-model/src timing.ts

96.81% Statements 152/157
90.74% Branches 98/108
100% Functions 25/25
96.68% Lines 146/151

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                                                                                                        1974x 76x   1898x                 597x     597x                       92449x 91929x   520x 331x   189x 167x   22x                                                 61609x             420x       6456x 6456x 6456x   6456x 491184x 11328x   763303x 479856x 479856x 479856x     6456x 1776x     1880x 1776x     6456x 60x     67x 60x 60x     6456x 491184x 491184x 449808x   289791x 41376x 6657x   34719x           6456x 170x 170x 140x 140x     6456x     12355x                           13953x                             6456x   6456x 6456x 6456x 6456x 13740x     13740x 170x         13740x   6456x                                 44951x 44951x 44951x 334761x 334761x 305766x   28995x 4210x 4210x 4210x   4210x   24785x 24785x 334761x 24639x   44951x                                   597x                       44371x 44371x 44371x 44371x 44371x 330709x 307213x   23496x 23496x 330709x   3x       23493x 330709x 330709x 330709x 41x 41x   23452x 4004x   23452x   44371x                         597x       3661x 3661x 241x   3420x 3420x 3661x 3661x 3x   3417x                 6456x 6456x   6456x 130x 130x 123x   7x       7x       6456x 12350x 12350x         12350x     6456x 12030x 12024x   6x     6456x 6456x   6456x 12357x 12357x             6456x             130x 130x           12350x     140040x 12350x       13740x 13740x     13740x 540x 540x 540x       540x     13200x 13200x 13200x 172x   13200x    
import { findLastIndexAtOrBefore, findLastIndexBefore } from '@be-music/shared-utils/core';
import {
  DEFAULT_BPM,
  normalizeChannel,
  normalizeObjectKey,
  resolveBMSBase,
  type BeMusicEvent,
  type BeMusicJSON,
} from '@be-music/chart-source';
import { createBeatResolver, isStopChannel, parseBPMFrom03Token, sortEvents, type BeatResolver } from './index.ts';
 
export interface TempoPoint {
  beat: number;
  bpm: number;
  seconds: number;
  /**
   * BPM the readouts show when it differs from `bpm`. Set for negative `#BPMxx` events: timing integrates the full
   * |BPM|, but LR2 converts the value to int first (LR2body.exe 0x42b960 `__ftol`), so NOWBPM shows |trunc(BPM)|.
   */
  displayBPM?: number;
}
 
export interface StopPoint {
  beat: number;
  seconds: number;
  cumulativeSeconds: number;
}
 
/**
 * Position of the first negative `#BPMxx` event (channel 08) — LR2's reverse-scroll gimmick anchor. LR2 integrates
 * note times at |BPM| (so the timeline stays monotonic) and, from this point on, mirrors the DISPLAY and JUDGE
 * clocks around it while its event pump freezes: nothing behind the reversal ever sounds or gets judged, and the
 * chart visually scrolls backwards forever. See docs/bms-spec.md "Negative BPM" and issue #134.
 */
export interface TempoReversalPoint {
  beat: number;
  seconds: number;
}
 
/**
 * Display beat past an LR2 negative-BPM reversal. LR2 mirrors the chart POSITION, not the clock:
 * `songtimer = 2 * bpmChangedBmstime - songtimer` on the forward position (OpenLR2 `LR2f.cpp:2185-2188`, LR2body.exe
 * 0x406d81), so the chart recedes exactly as fast as the forward beat advances through the post-reversal tempo map —
 * at the |BPM| of the negative value, following later tempo changes, and pausing during post-reversal STOPs.
 *
 * Returns `beat` unchanged at or before the reversal. Past it the mirrored beat can recede into negative chart positions.
 */
export function mirrorBeatAtTempoReversal(
  reversal: TempoReversalPoint | undefined,
  seconds: number,
  beat: number,
): number {
  if (reversal === undefined || seconds <= reversal.seconds) {
    return beat;
  }
  return reversal.beat * 2 - beat;
}
 
/**
 * Channels LR2 fires BEFORE the negative-BPM event when they share its tick. LR2 sorts same-tick events by op
 * (`CMP_NotesByRealTimingOp`, OpenLR2 `LR2f.cpp:24013`): BGM (op 1), BPM (op 3), and the BGA layers (ops 4 / 6 / 7)
 * precede the exBPM (op 8) that arms the reversal, while STOP (op 9), lane sounds (10–29), and invisible objects
 * (30+) come after it and freeze with the pump. `0A` (BGA layer 2) is grouped with the other BGA layers.
 */
const CHANNELS_FIRING_BEFORE_REVERSAL: ReadonlySet<string> = new Set(['01', '03', '04', '06', '07', '0A']);
 
/** Same-tick tolerance: both sides come from the same `beatToSeconds`, so equal positions agree to the last bit. */
const REVERSAL_TICK_EPSILON_SECONDS = 1e-9;
 
/**
 * Whether an event at `seconds` on `channel` still fires under LR2's negative-BPM reversal. LR2's event pump freezes
 * at the reversal: everything strictly before it fires, everything after it never does, and on the reversal tick
 * itself only the channels LR2 orders before the negative BPM (BGM, BPM, BGA) fire. Always `true` without a reversal.
 */
export function firesBeforeTempoReversal(
  reversal: TempoReversalPoint | undefined,
  seconds: number,
  channel: string,
): boolean {
  if (reversal === undefined) {
    return true;
  }
  if (seconds < reversal.seconds - REVERSAL_TICK_EPSILON_SECONDS) {
    return true;
  }
  if (seconds > reversal.seconds + REVERSAL_TICK_EPSILON_SECONDS) {
    return false;
  }
  return CHANNELS_FIRING_BEFORE_REVERSAL.has(normalizeChannel(channel));
}
 
export interface TimingResolver {
  tempoPoints: TempoPoint[];
  stopPoints: StopPoint[];
  /** Last position of an LR2 timing table whose entries can run backwards in time. */
  nonMonotonicEndBeat?: number;
  /** NOWBPM latched by the first reversing event in playback order. */
  reversalDisplayBPM?: number;
  /** Set when the chart contains a negative `#BPMxx` reference — the LR2 reverse-scroll anchor. */
  reversal?: TempoReversalPoint;
  beatToSeconds: (beat: number) => number;
  eventToSeconds: (event: BeMusicEvent) => number;
  bpmAtBeat: (beat: number) => number;
  /** BPM the readouts show at `beat` — `bpmAtBeat` except where a {@link TempoPoint.displayBPM} overrides it. */
  displayBPMAtBeat: (beat: number) => number;
}
 
export interface TimingBuildContext {
  sortedEvents: BeMusicEvent[];
  beatResolver: BeatResolver;
}
 
export function createTimingBuildContext(json: BeMusicJSON): TimingBuildContext {
  return {
    sortedEvents: sortEvents(json.events),
    beatResolver: createBeatResolver(json),
  };
}
 
export function createTimingResolver(json: BeMusicJSON): TimingResolver {
  return createTimingResolverWithContext(json, createTimingBuildContext(json));
}
 
export function createTimingResolverWithContext(json: BeMusicJSON, context: TimingBuildContext): TimingResolver {
  const { sortedEvents, beatResolver } = context;
  const { points: tempoPoints, reversingChanges } = createTempoPoints(json, sortedEvents, beatResolver);
  const stopPoints = createStopPoints(json, tempoPoints, sortedEvents, beatResolver);
 
  const beatToSecondsWithoutStops = (beat: number): number => {
    if (beat <= 0 || tempoPoints.length === 0) {
      return 0;
    }
    const index = findLastIndexAtOrBefore(tempoPoints, beat, (point) => point.beat);
    const point = tempoPoints[Math.max(0, index)]!;
    const deltaBeat = beat - point.beat;
    return point.seconds + (deltaBeat * 60) / point.bpm;
  };
 
  const bpmAtBeat = (beat: number): number => {
    Iif (tempoPoints.length === 0) {
      return json.metadata.bpm > 0 ? json.metadata.bpm : DEFAULT_BPM;
    }
    const index = findLastIndexAtOrBefore(tempoPoints, beat, (point) => point.beat);
    return tempoPoints[Math.max(0, index)]!.bpm;
  };
 
  const displayBPMAtBeat = (beat: number): number => {
    Iif (tempoPoints.length === 0) {
      return json.metadata.bpm > 0 ? json.metadata.bpm : DEFAULT_BPM;
    }
    const index = findLastIndexAtOrBefore(tempoPoints, beat, (point) => point.beat);
    const point = tempoPoints[Math.max(0, index)]!;
    return point.displayBPM ?? point.bpm;
  };
 
  const beatToSeconds = (beat: number): number => {
    const base = beatToSecondsWithoutStops(beat);
    if (stopPoints.length === 0) {
      return base;
    }
    const index = findLastIndexBefore(stopPoints, beat, (point) => point.beat);
    if (index < 0) {
      return base;
    }
    return base + stopPoints[index]!.cumulativeSeconds;
  };
 
  // A negative STOP can move the next event before the preceding event in real time.
  let reversal: TempoReversalPoint | undefined;
  let reversalDisplayBPM: number | undefined;
  for (const change of reversingChanges) {
    const seconds = beatToSeconds(change.beat);
    if (!reversal || seconds < reversal.seconds) {
      reversal = { beat: change.beat, seconds };
      reversalDisplayBPM = change.displayBPM;
    }
  }
  return {
    tempoPoints,
    stopPoints,
    ...(tempoPoints[0]!.bpm < 0 || stopPoints.some((stop) => stop.seconds < 0)
      ? {
          nonMonotonicEndBeat: Math.max(
            beatResolver.measureToBeat(999),
            tempoPoints.at(-1)!.beat,
            stopPoints.at(-1)?.beat ?? 0,
          ),
        }
      : {}),
    reversal,
    reversalDisplayBPM,
    bpmAtBeat,
    displayBPMAtBeat,
    beatToSeconds,
    eventToSeconds: (event) => beatToSeconds(beatResolver.eventToBeat(event)),
  };
}
 
interface TempoIntegration {
  points: TempoPoint[];
  /** Beat of the first negative `#BPMxx` event, if any — the LR2 reverse-scroll anchor. */
  reversingChanges: Array<{ beat: number; displayBPM: number }>;
}
 
function createTempoPoints(
  json: BeMusicJSON,
  sortedEvents: BeMusicEvent[],
  beatResolver: BeatResolver,
): TempoIntegration {
  const header = json.metadata.bpm;
  const baseBPM =
    header > 0 || (json.sourceFormat === 'bms' && Number.isFinite(header) && header < 0) ? header : DEFAULT_BPM;
  const points: TempoPoint[] = [{ beat: 0, bpm: baseBPM, seconds: 0 }];
  const reversingChanges: TempoIntegration['reversingChanges'] = [];
  for (const { event, bpm } of collectTempoChanges(json, sortedEvents)) {
    const beat = beatResolver.eventToBeat(event);
    // LR2 truncates the BPM to int before its `< 0` check (LR2body.exe 0x42b960 `__ftol`), so -1 < BPM < 0 never
    // reverses — it only crawls at |BPM|.
    if (Math.trunc(bpm) < 0) {
      reversingChanges.push({ beat, displayBPM: Math.abs(Math.trunc(bpm)) });
    }
    // LR2 integrates negative exBPM at |BPM| (LR2_bmsload.cpp:2841-2843) — the timeline never runs backwards; the
    // reversal is a presentation/judging gimmick anchored at the first negative event. Of several changes at one beat
    // the last in chart order wins.
    integrateTempoPoint(points, beat, Math.abs(bpm), bpm < 0 ? Math.abs(Math.trunc(bpm)) : undefined);
  }
  return { points, reversingChanges };
}
 
/** A BPM change object (`03`, or `08` with `#BPMxx`) that sets a non-zero BPM. */
export interface TempoChange {
  readonly event: BeMusicEvent;
  /** The BPM as written; negative for a `#BPMxx` that triggers LR2's reverse scroll. */
  readonly bpm: number;
}
 
/**
 * The BPM changes of a chart, in chart order: channel `03` read as hex (always positive), channel `08` through
 * `#BPMxx`. Zero `#BPMxx` references are ignored. Undefined BMS slots use -1, and negative values keep their sign, since the
 * engine plays it as LR2's reverse scroll. Several at one position all appear; the last one wins. Not part of the
 * package API (the chart fingerprint reads exact positions from the events).
 */
export function collectTempoChanges(json: BeMusicJSON, sortedEvents: ReadonlyArray<BeMusicEvent>): TempoChange[] {
  const changes: TempoChange[] = [];
  const idBase = resolveBMSBase(json);
  for (const event of sortedEvents) {
    const channel = normalizeChannel(event.channel);
    if (channel !== '03' && channel !== '08') {
      continue;
    }
    if (channel === '03') {
      const bpm = parseBPMFrom03Token(event.value);
      Eif (bpm > 0) {
        changes.push({ event, bpm });
      }
      continue;
    }
    const key = normalizeObjectKey(event.value, idBase, json.sourceFormat === 'bmson');
    const bpm = json.resources.bpm[key] ?? (json.sourceFormat === 'bms' ? -1 : undefined);
    if (typeof bpm !== 'number' || !Number.isFinite(bpm) || bpm === 0) continue;
    changes.push({ event, bpm });
  }
  return changes;
}
 
/**
 * A `#STOPxx` object (BMS) or bmson stop, in 1/192 of a 4/4 measure. Positive, except for a BMS STOP whose `#STOPxx`
 * is zero, negative or undefined, which LR2 plays as {@link LR2_UNSET_STOP_UNITS}.
 */
export interface StopChange {
  readonly event: BeMusicEvent;
  readonly beat: number;
  readonly duration: number;
}
 
/**
 * What LR2 plays for a STOP whose `#STOPxx` is zero, negative or undefined: it stores only `#STOPxx` values above 0
 * (OpenLR2 L26324-26331), so the slot keeps its initial `-1.0` (L25773) and the STOP adds `-1/192` of a measure at the
 * tempo in force (L26666-26669), moving everything after it that much earlier.
 */
const LR2_UNSET_STOP_UNITS = -1;
 
/**
 * The STOP objects that take effect, in chart order. BMS keeps one `#STOPxx` per position and the last one wins, as LR2
 * (OpenLR2 L26666-26670) and beatoraja (one STOP per timeline) read it; bmson stops on one pulse all stay and add up,
 * as its spec says. Not part of the package API (the chart fingerprint reads exact positions from the events).
 */
export function collectStopChanges(
  json: BeMusicJSON,
  sortedEvents: ReadonlyArray<BeMusicEvent>,
  beatResolver: BeatResolver,
): StopChange[] {
  const idBase = resolveBMSBase(json);
  const lastStopWins = json.sourceFormat === 'bms';
  const changes: StopChange[] = [];
  const indexByBeat = new Map<number, number>();
  for (const event of sortedEvents) {
    if (!isStopChannel(normalizeChannel(event.channel))) {
      continue;
    }
    const value = json.resources.stop[normalizeObjectKey(event.value, idBase, json.sourceFormat === 'bmson')];
    const positive = typeof value === 'number' && Number.isFinite(value) && value > 0;
    if (!positive && !lastStopWins) {
      // A non-positive or missing bmson stop is skipped, as its spec says.
      continue;
    }
    // A BMS STOP without a positive `#STOPxx` (zero, negative or undefined) plays as LR2 plays it, and takes part in
    // the last-one-wins rule as any STOP does.
    const duration = positive ? value : LR2_UNSET_STOP_UNITS;
    const beat = beatResolver.eventToBeat(event);
    const replaced = lastStopWins ? indexByBeat.get(beat) : undefined;
    if (replaced !== undefined) {
      changes[replaced] = { event, beat, duration };
      continue;
    }
    if (lastStopWins) {
      indexByBeat.set(beat, changes.length);
    }
    changes.push({ event, beat, duration });
  }
  return changes;
}
 
/** A parsed `#STP xxx.yyy ms` line (BEMANIA DX STOP): measure `xxx`, position `yyy / 1000`, a positive length in ms. */
export interface StpStop {
  readonly measure: number;
  /** Thousandths of the measure, `0..999`. */
  readonly position: number;
  readonly durationMs: number;
  /** The length as written, for consumers that read it exactly. */
  readonly durationText: string;
}
 
const STP_PATTERN = /^\s*(\d{3})(?:\.(\d{3}))?(?:[ \t ]{1,6})([+-]?(?:\d+(?:\.\d+)?|\.\d+))(?:[^0-9].*)?$/u;
 
/** Parses a `#STP` value, or `undefined` when it is malformed or its length is not positive. */
export function parseStpStop(rawValue: string): StpStop | undefined {
  const match = STP_PATTERN.exec(rawValue);
  if (!match) {
    return undefined;
  }
  const measure = Number.parseInt(match[1]!, 10);
  const position = Number.parseInt(match[2] ?? '000', 10);
  const durationMs = Number.parseFloat(match[3]!);
  if (!Number.isFinite(measure) || !Number.isFinite(position) || !Number.isFinite(durationMs) || durationMs <= 0) {
    return undefined;
  }
  return { measure, position, durationMs, durationText: match[3]! };
}
 
function createStopPoints(
  json: BeMusicJSON,
  tempoPoints: TempoPoint[],
  sortedEvents: BeMusicEvent[],
  beatResolver: BeatResolver,
): StopPoint[] {
  const rawPoints: Array<{ beat: number; seconds: number; order: number }> = [];
  let order = 0;
 
  for (const stp of json.bms.stp) {
    const parsed = parseBemaniaDxStpStopPoint(stp, beatResolver);
    if (!parsed) {
      continue;
    }
    rawPoints.push({
      ...parsed,
      order,
    });
    order += 1;
  }
 
  // `#STP` lines at one position add up, as do bmson stops; of several BMS `#STOPxx` at one position the last wins.
  for (const stop of collectStopChanges(json, sortedEvents, beatResolver)) {
    const bpm = bpmAtBeatFromTempoPoints(tempoPoints, stop.beat);
    rawPoints.push({
      beat: stop.beat,
      seconds: (stop.duration / 192) * (240 / bpm),
      order,
    });
    order += 1;
  }
 
  rawPoints.sort((left, right) => {
    if (left.beat !== right.beat) {
      return left.beat - right.beat;
    }
    return left.order - right.order;
  });
 
  const points: StopPoint[] = [];
  let cumulativeSeconds = 0;
 
  for (const point of rawPoints) {
    cumulativeSeconds += point.seconds;
    points.push({
      beat: point.beat,
      seconds: point.seconds,
      cumulativeSeconds,
    });
  }
 
  return points;
}
 
function parseBemaniaDxStpStopPoint(
  rawValue: string,
  beatResolver: BeatResolver,
): { beat: number; seconds: number } | undefined {
  const stop = parseStpStop(rawValue);
  return stop === undefined
    ? undefined
    : { beat: beatResolver.measureToBeat(stop.measure, stop.position / 1000), seconds: stop.durationMs / 1000 };
}
 
function bpmAtBeatFromTempoPoints(tempoPoints: TempoPoint[], beat: number): number {
  Iif (tempoPoints.length === 0) {
    return DEFAULT_BPM;
  }
  const index = findLastIndexAtOrBefore(tempoPoints, beat, (point) => point.beat);
  return tempoPoints[Math.max(0, index)]!.bpm;
}
 
function integrateTempoPoint(points: TempoPoint[], beat: number, bpm: number, displayBPM?: number): void {
  const last = points[points.length - 1]!;
  Iif (beat < last.beat) {
    return;
  }
  if (Math.abs(beat - last.beat) < 1e-9) {
    last.bpm = bpm;
    if (displayBPM === undefined) {
      delete last.displayBPM;
    } else E{
      last.displayBPM = displayBPM;
    }
    return;
  }
 
  const seconds = last.seconds + ((beat - last.beat) * 60) / last.bpm;
  const point: TempoPoint = { beat, bpm, seconds };
  if (displayBPM !== undefined) {
    point.displayBPM = displayBPM;
  }
  points.push(point);
}