All files / player-engine/src/core playback-support.ts

92.3% Statements 72/78
89.65% Branches 52/58
91.66% Functions 11/12
92% Lines 69/75

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                                                                                                                  923x 6241x 5569x 1664x                                                                                                             3023x 3023x 271693x 36878x   234815x 234815x   271693x 271693x                                                               22x 22x     22x 11x     11x 11x 11x 11x     11x     11x 22x 22x                   5x 5x     5x 5x 5x 5x   5x 5x                               108x 108x 20x 20x 108x 108x 108x                                                           268969x 268969x 268969x 6138x     6138x 69x 69x 69x   6069x 22x 22x   6047x 6x 6x   6041x 1x 1x   6040x 4x 4x   6036x 5x 5x   6031x 150x 150x   5881x                                   3021x 4x 4x      
import type { ReplayOptionState } from '../replay/options.ts';
import type { ReplayViewState } from '../replay/view.ts';
import { mirrorBeatAtTempoReversal, type TempoReversalPoint } from '@be-music/chart-model';
import { type PlayerStateSignals } from '../state-signals.ts';
import { applyHighSpeedControlAction, type HighSpeedControlAction } from './high-speed-control.ts';
import { type PlayerInputCommand, type PlayerInputSignalBus } from './input-signal-bus.ts';
import { type PlayerUIFramePayload, type PlayerUISignalBus } from './ui-signal-bus.ts';
import { type TempoClock } from './tempo-clock.ts';
import type { PlayerTempoChange } from './engine-types.ts';
 
type PauseablePlaybackClock = {
  nowMs: () => number;
  isPaused: () => boolean;
  pause: () => boolean;
  resume: () => boolean;
};
 
type PauseableAudioSession = {
  pause: () => void;
  resume: () => void;
};
 
type InterruptCommand = Extract<PlayerInputCommand, { kind: 'interrupt' }>;
 
export interface PlaybackStateLogger {
  logGaugeChange: (
    seconds: number,
    params: {
      reason: string;
      judge?: string;
      delta?: number;
    },
  ) => void;
  logComboChange: (
    seconds: number,
    params: {
      value: number;
      reason: string;
      judge?: string;
      channel?: string;
    },
  ) => void;
  logLongNoteState: (
    seconds: number,
    params: {
      channel: string;
      state: 'start' | 'release' | 'break' | 'complete';
      mode: 1 | 2 | 3;
      event: { value: string; channel: string };
      resources: Readonly<Record<string, string>>;
      endSeconds?: number;
    },
  ) => void;
  logResult: (seconds: number, params: { reason: string; summary: PlayerUIFramePayload['summary'] }) => void;
}
 
export function createNoopPlaybackStateLogger(): PlaybackStateLogger {
  return {
    logGaugeChange: () => undefined,
    logComboChange: () => undefined,
    logLongNoteState: () => undefined,
    logResult: () => undefined,
  };
}
 
export function createUIFramePublisher(params: {
  uiEnabled: boolean;
  uiSignals: PlayerUISignalBus;
  totalSeconds: number;
  summary: PlayerUIFramePayload['summary'];
  /** The 2P player's summary of a two-player play. */
  summary2P?: PlayerUIFramePayload['summary'];
  notes: PlayerUIFramePayload['notes'];
  landmineNotes?: PlayerUIFramePayload['landmineNotes'];
  invisibleNotes?: PlayerUIFramePayload['invisibleNotes'];
  audioBackend: string;
  resolveDebugActiveAudioState: (
    seconds: number,
  ) => Pick<PlayerUIFramePayload, 'activeAudioFiles' | 'activeAudioVoiceCount'>;
  /**
   * LR2 negative-BPM reversal anchor. Past `seconds`, frames carry a display beat mirrored in chart-POSITION space —
   * `displayBeat = 2 * beat - currentBeat` — exactly like LR2's `songtimer = 2 * bpmChangedBmstime - songtimer`
   * (LR2body.exe 0x406d81). The forward beat keeps following the tempo map past the reversal, so the reverse scroll
   * runs at the post-reversal |BPM| and a post-reversal STOP pauses it.
   */
  reversal?: TempoReversalPoint;
  reversalAnchor?: TempoReversalPoint;
  /** The seek generation and the clock a frame at `seconds` holds at (`PlayerUIFramePayload.generation` / `clock`). */
  resolveClock?: (seconds: number) => Pick<PlayerUIFramePayload, 'generation' | 'clock'>;
  resolveHCNLanes?: (seconds: number) => PlayerUIFramePayload['hcnLanes'];
  resolveKeyBoundBGA?: (seconds: number) => PlayerUIFramePayload['keyBoundBGA'];
  resolveBmsonBGA?: (seconds: number) => PlayerUIFramePayload['bmsonBGA'];
  resolveChartText?: (seconds: number) => string;
  resolveChartOptions?: (seconds: number) => PlayerUIFramePayload['chartOptions'];
  resolveJudgedNoteCount?: () => number;
}): (seconds: number, beat: number) => void {
  const {
    uiEnabled,
    uiSignals,
    totalSeconds,
    summary,
    summary2P,
    notes,
    landmineNotes,
    invisibleNotes,
    audioBackend,
    resolveDebugActiveAudioState,
    reversal,
    resolveClock,
    resolveHCNLanes,
    resolveKeyBoundBGA,
    resolveBmsonBGA,
    resolveChartText,
    resolveChartOptions,
    resolveJudgedNoteCount,
  } = params;
  return (seconds: number, beat: number): void => {
    if (!uiEnabled) {
      return;
    }
    const debugState = resolveDebugActiveAudioState(seconds);
    const anchor = params.reversalAnchor ?? reversal;
    const displayBeat =
      anchor !== undefined && seconds > anchor.seconds ? mirrorBeatAtTempoReversal(anchor, seconds, beat) : undefined;
    uiSignals.publishFrame({
      currentBeat: beat,
      ...(resolveChartOptions ? { chartOptions: resolveChartOptions(seconds) } : {}),
      currentSeconds: seconds,
      displayBeat,
      reversalSeconds: reversal?.seconds,
      reversalActivation: Number.isFinite(anchor?.seconds) ? anchor : undefined,
      totalSeconds,
      summary,
      ...(summary2P !== undefined ? { summary2P } : {}),
      notes,
      hcnLanes: resolveHCNLanes?.(seconds),
      ...(resolveKeyBoundBGA ? { keyBoundBGA: resolveKeyBoundBGA(seconds) } : {}),
      ...(resolveBmsonBGA ? { bmsonBGA: resolveBmsonBGA(seconds) } : {}),
      ...(resolveChartText ? { chartText: resolveChartText(seconds) } : {}),
      judgedNoteCount: resolveJudgedNoteCount?.(),
      landmineNotes,
      invisibleNotes,
      audioBackend,
      activeAudioFiles: debugState.activeAudioFiles,
      activeAudioVoiceCount: debugState.activeAudioVoiceCount,
      ...resolveClock?.(seconds),
    });
  };
}
 
export function togglePlaybackPause(params: {
  playbackClock?: PauseablePlaybackClock;
  audioSession?: PauseableAudioSession;
  activeStateSignals?: PlayerStateSignals;
  onStateChange?: (state: 'pause' | 'resume', nowMs: number) => void;
}): void {
  const { playbackClock, audioSession, activeStateSignals, onStateChange } = params;
  Iif (!playbackClock) {
    return;
  }
  if (playbackClock.isPaused()) {
    Iif (!playbackClock.resume()) {
      return;
    }
    audioSession?.resume();
    activeStateSignals?.setPaused(false);
    onStateChange?.('resume', playbackClock.nowMs());
    return;
  }
 
  Iif (!playbackClock.pause()) {
    return;
  }
  audioSession?.pause();
  activeStateSignals?.setPaused(true);
  onStateChange?.('pause', playbackClock.nowMs());
}
 
export function applyPlaybackHighSpeedAction(params: {
  action: HighSpeedControlAction | undefined;
  currentHighSpeed: number;
  activeStateSignals?: PlayerStateSignals;
  onHighSpeedChange?: (highSpeed: number) => void;
  logHighSpeedChange?: (highSpeed: number) => void;
}): number {
  const { action, currentHighSpeed, activeStateSignals, onHighSpeedChange, logHighSpeedChange } = params;
  Iif (!action) {
    return currentHighSpeed;
  }
  const nextHighSpeed = applyHighSpeedControlAction(currentHighSpeed, action);
  Eif (nextHighSpeed !== currentHighSpeed) {
    activeStateSignals?.setHighSpeed(nextHighSpeed);
    onHighSpeedChange?.(nextHighSpeed);
  }
  logHighSpeedChange?.(nextHighSpeed);
  return nextHighSpeed;
}
 
/**
 * Changes the play tempo at play-clock time `nowMs`: re-anchors `tempoClock` there (chart time stays continuous and
 * runs at `tempo` from then on), then tells the audio backend, the replay and the host, each with the chart second
 * the change took effect at. A change to an unusable tempo or the one in force does nothing. Returns whether it did.
 */
export function applyPlaybackTempoChange(params: {
  tempoClock: TempoClock;
  nowMs: number;
  tempo: number;
  setAudioTempo?: (tempo: number) => void;
  recordTempoChange?: (seconds: number, tempo: number) => void;
  onTempoChange?: (change: PlayerTempoChange) => void;
}): boolean {
  const { tempoClock, tempo } = params;
  if (!(Number.isFinite(tempo) && tempo > 0) || tempo === tempoClock.tempo) return false;
  const seconds = tempoClock.setTempoAtClockMs(params.nowMs, tempo);
  params.setAudioTempo?.(tempo);
  params.recordTempoChange?.(seconds, tempo);
  params.onTempoChange?.({ tempo, seconds });
  return true;
}
 
export function consumePlaybackInputCommands(params: {
  inputSignals: PlayerInputSignalBus;
  isInterrupted: () => boolean;
  setInterruptedReason: (reason: InterruptCommand['reason']) => void;
  onTogglePause: () => void;
  onHighSpeedAction: (action: HighSpeedControlAction | undefined) => void;
  /** A view change to record (`{ kind: 'view' }`). */
  onViewChange?: (change: ReplayViewState) => void;
  onOptionChange?: (values: ReplayOptionState) => void;
  /** A tempo change (`{ kind: 'tempo' }`). */
  onTempoChange?: (tempo: number) => void;
  /** A seek (`{ kind: 'seek' }`). */
  onSeek?: (seconds: number) => void;
  onUnhandledCommand?: (command: PlayerInputCommand) => void;
  logInterrupt?: (reason: InterruptCommand['reason']) => void;
}): void {
  const {
    inputSignals,
    isInterrupted,
    setInterruptedReason,
    onTogglePause,
    onHighSpeedAction,
    onViewChange,
    onTempoChange,
    onSeek,
    onUnhandledCommand,
    logInterrupt,
  } = params;
  const commands = inputSignals.drainCommands();
  for (const command of commands) {
    Iif (isInterrupted()) {
      continue;
    }
    if (command.kind === 'interrupt') {
      logInterrupt?.(command.reason);
      setInterruptedReason(command.reason);
      continue;
    }
    if (command.kind === 'toggle-pause') {
      onTogglePause();
      continue;
    }
    if (command.kind === 'high-speed') {
      onHighSpeedAction(command.action);
      continue;
    }
    if (command.kind === 'options') {
      params.onOptionChange?.(command.values);
      continue;
    }
    if (command.kind === 'view') {
      onViewChange?.(command.change);
      continue;
    }
    if (command.kind === 'tempo') {
      onTempoChange?.(command.tempo);
      continue;
    }
    if (command.kind === 'seek') {
      onSeek?.(command.seconds);
      continue;
    }
    onUnhandledCommand?.(command);
  }
}
 
/**
 * Records the view changes left on the input bus once a play's loop has ended (`{ kind: 'view' }`, sent by the host as
 * the play ends, after the loop's last drain), at `chartSeconds`; other commands left there no longer matter.
 */
export function recordPendingViewChanges(
  inputSignals: PlayerInputSignalBus,
  recorder:
    | {
        recordViewChange(timeSeconds: number, change: ReplayViewState): void;
        recordOptionChange?(timeSeconds: number, values: ReplayOptionState): void;
      }
    | undefined,
  chartSeconds: number,
): void {
  for (const command of inputSignals.drainCommands()) {
    if (command.kind === 'view') recorder?.recordViewChange(chartSeconds, command.change);
    if (command.kind === 'options') recorder?.recordOptionChange?.(chartSeconds, command.values);
  }
}