All files / chart-model/src timelines.ts

98.57% Statements 138/140
94.11% Branches 80/85
100% Functions 25/25
98.47% Lines 129/131

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                                                                                      1x 1x 1x 6x 6x     6x     1x       2101x 2101x 2101x   2101x 3131x 3131x 1x       3130x     3131x 1x   3129x       3129x 3129x     2101x 2x 2x     2101x       2761x 2620x   141x       2702x 2666x   36x                           38096x                             38233x       5770x                           76329x 76329x 46098x 21693x   24405x 24405x 6387x   18018x 18018x 2x   18016x   76329x       177x 177x 7700x 7700x 7699x     177x       6x 6x       3301x 3301x     4x 4x 6x 6x   4x 10x 10x 10x                 4x 4x 4x 8x 8x 4x 4x     4x 370x 374x 369x 127x 127x     3297x 3297x 3297x   3297x 270641x 1015x   269626x     269626x 840x 840x   269626x   269626x 464x 464x   269626x 269626x 495x     269131x 269131x         5398x 5398x 900x 900x     5398x 657x   899x 899x                               270x 270x 270x 270x   270x 693x 693x     693x 2x   691x 691x     270x             269131x 1x   280850x   269130x 269130x 269130x       242x 242x 1895x 360x     242x 24x 6x     242x    
import { findFirstIndexAtOrAfter, findLastIndexAtOrBefore } from '@be-music/shared-utils/core';
import {
  normalizeChannel,
  normalizeObjectKey,
  resolveBMSBase,
  type BeMusicEvent,
  type BeMusicJSON,
} from '@be-music/chart-source';
import { isScrollChannel, sortEvents, type BeatResolver } from './index.ts';
import { createTimingResolver, type TimingResolver } from './timing.ts';
 
export interface MeasureTimelinePoint {
  measure: number;
  seconds: number;
}
 
export interface BPMTimelinePoint {
  bpm: number;
  seconds: number;
}
 
export interface ScrollTimelinePoint {
  beat: number;
  speed: number;
}
 
export interface SpeedTimelinePoint {
  beat: number;
  speed: number;
}
 
export interface StopBeatWindow {
  beat: number;
  startSeconds: number;
  endSeconds: number;
  durationSeconds: number;
}
 
export function createMeasureTimeline(
  json: BeMusicJSON,
  resolver: TimingResolver,
  beatResolver: BeatResolver,
): MeasureTimelinePoint[] {
  const maxMeasure = resolveMaxMeasureIndex(json);
  const timeline: MeasureTimelinePoint[] = [];
  for (let measure = 0; measure <= maxMeasure + 1; measure += 1) {
    const seconds = resolver.beatToSeconds(beatResolver.measureToBeat(measure, 0));
    Iif (!Number.isFinite(seconds)) {
      continue;
    }
    timeline.push({ measure, seconds });
  }
 
  return timeline;
}
 
export function createBPMTimeline(json: BeMusicJSON, resolver: TimingResolver): BPMTimelinePoint[] {
  const timeline: BPMTimelinePoint[] = [];
  let previousSeconds = Number.NaN;
  let previousBPM = Number.NaN;
 
  for (const point of resolver.tempoPoints) {
    const seconds = resolver.beatToSeconds(point.beat);
    if (!Number.isFinite(seconds) || !Number.isFinite(point.bpm) || point.bpm === 0) {
      continue;
    }
    // The readout value: a negative `#BPMxx` shows as |trunc(BPM)| the way LR2's NOWBPM does.
    const bpm =
      seconds === resolver.reversal?.seconds
        ? (resolver.reversalDisplayBPM ?? point.displayBPM ?? point.bpm)
        : (point.displayBPM ?? point.bpm);
    if (Math.abs(seconds - previousSeconds) < 1e-6 && Math.abs(bpm - previousBPM) < 1e-6) {
      continue;
    }
    timeline.push({
      bpm,
      seconds,
    });
    previousSeconds = seconds;
    previousBPM = bpm;
  }
 
  if (timeline.length === 0) {
    const fallbackBPM = Number.isFinite(json.metadata.bpm) && json.metadata.bpm > 0 ? json.metadata.bpm : 130;
    timeline.push({ bpm: fallbackBPM, seconds: 0 });
  }
 
  return timeline;
}
 
export function createScrollTimeline(json: BeMusicJSON, beatResolver: BeatResolver): ScrollTimelinePoint[] {
  if (Object.keys(json.bms.scroll).length === 0) {
    return [];
  }
  return toBeatTimeline(collectScrollChanges(json, sortEvents(json.events)), beatResolver);
}
 
export function createSpeedTimeline(json: BeMusicJSON, beatResolver: BeatResolver): SpeedTimelinePoint[] {
  if (Object.keys(json.bms.speed).length === 0) {
    return [];
  }
  return toBeatTimeline(collectSpeedChanges(json, sortEvents(json.events)), beatResolver);
}
 
/** A SCROLL (`SC` + `#SCROLLxx`) or SPEED (`SP` + `#SPEEDxx`) keyframe object and the value it sets. */
export interface KeyframeChange {
  readonly event: BeMusicEvent;
  readonly value: number;
}
 
/**
 * The SCROLL keyframes of a chart, in chart order: `SC` objects whose `#SCROLLxx` is a finite number (negative values
 * included). Not part of the package API (the chart fingerprint reads exact positions from the events).
 */
export function collectScrollChanges(json: BeMusicJSON, sortedEvents: ReadonlyArray<BeMusicEvent>): KeyframeChange[] {
  return collectKeyframeChanges(
    json.bms.scroll,
    resolveBMSBase(json),
    sortedEvents,
    isScrollChannel,
    true,
    json.sourceFormat === 'bmson',
  );
}
 
/**
 * The SPEED keyframes of a chart, in chart order: `SP` objects whose `#SPEEDxx` is a finite number of at least 0. Not
 * part of the package API (the chart fingerprint reads exact positions from the events).
 */
export function collectSpeedChanges(json: BeMusicJSON, sortedEvents: ReadonlyArray<BeMusicEvent>): KeyframeChange[] {
  return collectKeyframeChanges(
    json.bms.speed,
    resolveBMSBase(json),
    sortedEvents,
    (channel) => normalizeChannel(channel) === 'SP',
    false,
    json.sourceFormat === 'bmson',
  );
}
 
function collectKeyframeChanges(
  values: Readonly<Record<string, number>>,
  idBase: 36 | 62,
  sortedEvents: ReadonlyArray<BeMusicEvent>,
  isChannel: (channel: string) => boolean,
  allowNegative: boolean,
  allowLongKeys: boolean,
): KeyframeChange[] {
  const changes: KeyframeChange[] = [];
  for (const event of sortedEvents) {
    if (!isChannel(event.channel)) {
      continue;
    }
    const key = normalizeObjectKey(event.value, idBase, allowLongKeys);
    if (!Object.hasOwn(values, key)) {
      continue;
    }
    const value = values[key];
    if (typeof value !== 'number' || !Number.isFinite(value) || (!allowNegative && value < 0)) {
      continue;
    }
    changes.push({ event, value });
  }
  return changes;
}
 
function toBeatTimeline(changes: ReadonlyArray<KeyframeChange>, beatResolver: BeatResolver): ScrollTimelinePoint[] {
  const timeline: ScrollTimelinePoint[] = [];
  for (const change of changes) {
    const beat = beatResolver.eventToBeat(change.event);
    if (Number.isFinite(beat) && beat >= 0) {
      timeline.push({ beat, speed: change.value });
    }
  }
  return timeline;
}
 
export function createBeatAtSecondsResolver(json: BeMusicJSON): (seconds: number) => number {
  const resolver = createTimingResolver(json);
  return createBeatAtSecondsResolverFromTimingResolver(resolver);
}
 
export function createBeatAtSecondsResolverFromTimingResolver(resolver: TimingResolver): (seconds: number) => number {
  const stopWindows = createStopBeatWindows(resolver);
  if (resolver.nonMonotonicEndBeat !== undefined) {
    // LR2body 0x4ad7e0 scans the table in chart order for the first closed interval
    // containing the clock. Its fallback is the last converted position (bar 999).
    const endBeat = resolver.nonMonotonicEndBeat;
    const stops = new Map(stopWindows.map((window) => [window.beat, window]));
    const beats = [...new Set([0, ...resolver.tempoPoints.map((point) => point.beat), ...stops.keys(), endBeat])].sort(
      (a, b) => a - b,
    );
    const points = beats.flatMap((beat) => {
      const seconds = resolver.beatToSeconds(beat);
      const stop = stops.get(beat);
      return stop
        ? [
            { beat, seconds },
            { beat, seconds: stop.endSeconds },
          ]
        : [{ beat, seconds }];
    });
    // Only a segment extending past every preceding timestamp can be the first match.
    // Index those segments once, so long charts and seeks both resolve in logarithmic time.
    const segments: Array<{ from: (typeof points)[number]; to: (typeof points)[number] }> = [];
    let latest = points[0]!.seconds;
    for (let index = 1; index < points.length; index++) {
      const to = points[index]!;
      if (to.seconds > latest) {
        segments.push({ from: points[index - 1]!, to });
        latest = to.seconds;
      }
    }
    return (seconds) => {
      if (!Number.isFinite(seconds) || seconds <= 0) return 0;
      const segment = segments[findFirstIndexAtOrAfter(segments, seconds, (entry) => entry.to.seconds)];
      if (!segment) return endBeat;
      const { from, to } = segment;
      return from.beat + ((to.beat - from.beat) * (seconds - from.seconds)) / (to.seconds - from.seconds);
    };
  }
  let lastSeconds = Number.NEGATIVE_INFINITY;
  let stopCursor = 0;
  let endedStopSeconds = 0;
 
  return (seconds: number): number => {
    if (!Number.isFinite(seconds) || seconds <= 0) {
      return 0;
    }
    const safeSeconds = Math.max(0, seconds);
 
    // Playback time usually increases monotonically; keep a cursor to avoid re-scanning stop windows every frame.
    if (safeSeconds < lastSeconds) {
      stopCursor = 0;
      endedStopSeconds = 0;
    }
    lastSeconds = safeSeconds;
 
    while (stopCursor < stopWindows.length && safeSeconds >= stopWindows[stopCursor]!.endSeconds) {
      endedStopSeconds += stopWindows[stopCursor]!.durationSeconds;
      stopCursor += 1;
    }
    const activeWindow = stopWindows[stopCursor];
    if (activeWindow && safeSeconds >= activeWindow.startSeconds && safeSeconds < activeWindow.endSeconds) {
      return activeWindow.beat;
    }
 
    const adjustedSeconds = Math.max(0, safeSeconds - endedStopSeconds);
    return secondsToBeatWithoutStops(resolver.tempoPoints, adjustedSeconds);
  };
}
 
export function createStopBeatWindows(resolver: TimingResolver): StopBeatWindow[] {
  const durationByBeat = new Map<number, number>();
  for (const point of resolver.stopPoints) {
    const current = durationByBeat.get(point.beat) ?? 0;
    durationByBeat.set(point.beat, current + point.seconds);
  }
 
  return [...durationByBeat.entries()]
    .sort(([leftBeat], [rightBeat]) => leftBeat - rightBeat)
    .map(([beat, durationSeconds]) => {
      const startSeconds = resolver.beatToSeconds(beat);
      return {
        beat,
        startSeconds,
        endSeconds: startSeconds + durationSeconds,
        durationSeconds,
      } satisfies StopBeatWindow;
    });
}
 
/**
 * The beats bar lines sit at: the start of every measure from 0 to the last one with data, as beatoraja builds its
 * sections (jbms-parser `BMSDecoder`: sections `0..maxsec`, each opening with a bar line) — no line after the last
 * measure. A bmson chart that authors `lines` gets exactly those (one per measure start), as beatoraja's
 * `BMSONDecoder` draws them; without `lines` the spec's line every 4 beats applies over the chart's measures.
 */
export function createMeasureBoundariesBeats(json: BeMusicJSON, beatResolver: BeatResolver): number[] {
  const bmsonLines = json.sourceFormat === 'bmson' ? json.preservation.bmson.lines : [];
  const lastMeasure = bmsonLines.length > 0 ? bmsonLines.length - 1 : resolveMaxMeasureIndex(json);
  const boundaries: number[] = [];
  let previous = Number.NaN;
 
  for (let measure = 0; measure <= lastMeasure; measure += 1) {
    const beat = beatResolver.measureToBeat(measure, 0);
    Iif (!Number.isFinite(beat)) {
      continue;
    }
    if (Math.abs(beat - previous) < 1e-9) {
      continue;
    }
    boundaries.push(beat);
    previous = beat;
  }
 
  return boundaries;
}
 
function secondsToBeatWithoutStops(
  tempoPoints: ReadonlyArray<{ beat: number; bpm: number; seconds: number }>,
  seconds: number,
): number {
  if (tempoPoints.length === 0 || seconds <= 0) {
    return 0;
  }
  const index = findLastIndexAtOrBefore(tempoPoints, seconds, (point) => point.seconds);
 
  const point = tempoPoints[Math.max(0, index)]!;
  const elapsed = Math.max(0, seconds - point.seconds);
  return point.beat + (elapsed * point.bpm) / 60;
}
 
function resolveMaxMeasureIndex(json: BeMusicJSON): number {
  let maxMeasure = 0;
  for (const event of json.events) {
    if (event.measure > maxMeasure) {
      maxMeasure = event.measure;
    }
  }
  for (const measure of json.measures) {
    if (measure.index > maxMeasure) {
      maxMeasure = measure.index;
    }
  }
  return Math.max(0, maxMeasure);
}