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 | 44x | import { resolveBmsWAVResources } from '@be-music/chart-model';
import type { BeMusicEvent, BeMusicJSON } from '@be-music/chart-source';
import type { WebAudioStageMixer } from './nonstop-audio.ts';
import type { PlayerInputSignalBus } from '@be-music/player-engine/signals';
import {
autoPlay as engineAutoPlay,
manualPlay as engineManualPlay,
type AudioSession,
type CreateAudioSessionContext,
type PlayerOptions,
type PlayerSummary,
} from '@be-music/player-engine';
import { IIDX_GAMEPAD_SCRATCH } from './arcade-gamepad.ts';
import { logger } from '../logger.ts';
import { type AudioBusHandle } from './audio-bus.ts';
import { decodedSampleKey, createWebAudioSession, type WebAudioSessionSlicePlayback } from './web-audio-session.ts';
import { createWebInputRuntimeFactory } from './web-input-runtime.ts';
import { createWebUIRuntimeFactory, type WebUIRuntimeCallbacks } from './web-ui-runtime.ts';
const log = logger('engine-driver');
/**
* Shape the engine driver expects from the host's preloaded sample cache. Decoupled from `BeMusicJSON` so the host
* can decode `#WAVxx` slots once during the prepare phase and reuse the same `AudioBuffer` set across pause /
* resume / restart cycles without re-decoding.
*/
export interface EngineDriverAudioContext {
audioContext: AudioContext;
audioBus: AudioBusHandle;
decodedSamples: ReadonlyMap<string, AudioBuffer>;
wavCmdVolumeMultipliers: ReadonlyMap<string, number>;
bmsonSlicePlayback?: ReadonlyMap<BeMusicEvent, WebAudioSessionSlicePlayback>;
/** A stitched NONSTOP chart's per-stage rates and fades (`createNonstopStageMixer`). */
stageMixer?: WebAudioStageMixer;
/** Every sample's playback rate (`WebAudioSessionContext.playbackRate`): the play tempo when its pitch moves. */
playbackRate?: number;
/** {@link playbackRate} is the play tempo and follows a live tempo change (`pitch` mode). */
playbackRateFollowsTempo?: boolean;
/** The play tempo the chart starts at (`WebAudioSessionContext.tempo`). */
tempo?: number;
/** Fades the play in and crossfades its seeks (a PRACTICE play's loop), as `WebAudioSessionContext` takes it. */
seekCrossfadeSeconds?: number;
}
/**
* Tunables surfaced to the host. Mirrors the `PlayerOptions` fields the web view actually sets — full passthrough
* lets advanced callers reach the rest of the engine surface (limiter / compressor / lead-in / etc.) without
* widening this driver's API every time the engine adds an option.
*/
export interface EngineDriverOptions {
/** Reference chart already resolved via `parseChart` / `parseChartFile`. */
chart: BeMusicJSON;
/** Audio backend resources prepared by the host. The driver constructs a {@link createWebAudioSession} on top. */
audio: EngineDriverAudioContext;
/** Engine play mode. Mirrors the play session's `autoPlay` option. */
mode: 'manual' | 'auto';
/** Pixi-side rendering callbacks. The driver subscribes them to the engine's `uiSignals`. */
ui: WebUIRuntimeCallbacks;
/**
* DOM key event source (defaults to `window`). Scoped targets work too — pass a focusable canvas to keep stray
* keystrokes outside the player from reaching the engine.
*/
inputTarget?: EventTarget;
/** Optional hook for the input runtime — see {@link createWebInputRuntime}. */
shouldSkipKey?: (event: KeyboardEvent) => boolean;
/**
* Fires synchronously when the engine constructs its input runtime, handing back the engine-side
* `inputSignals` bus. Hosts that keep their own keyboard listener for select keys (Pause → toggle-pause, ESC
* fade, etc.) push commands through this reference to drive the engine alongside their own view-side state.
*/
onInputSignalsReady?: (signals: { inputSignals: PlayerInputSignalBus }) => void;
/** Forwarded to the engine. The driver supplies sensible defaults but a host can override any field. */
engineOptions?: Omit<PlayerOptions, 'createAudioSession' | 'createInputRuntime' | 'createUIRuntime' | 'auto'>;
}
/**
* Result returned to the host when the engine's playback loop finishes. Mirrors what `manualPlay` / `autoPlay`
* return so the host can route it straight into the result scene.
*/
export type EngineDriverResult = PlayerSummary;
/**
* Glue layer that wires the three runtime adapters ({@link createWebAudioSession},
* {@link createWebInputRuntimeFactory}, {@link createWebUIRuntimeFactory}) together and invokes the shared engine's
* `manualPlay` / `autoPlay`. Hosts call this once per chart play; the returned promise resolves with the final
* `PlayerSummary` when the chart ends (or rejects with `PlayerInterruptedError` when the player aborts).
*
* The driver is intentionally stateless — every per-chart cache (decoded samples, WAVCMD multipliers, BGA video
* handles) lives on the host side. That matches how the play session's `load` chain (`session/play/*`) already builds
* those caches, so adopting the driver in Phase 4b is a drop-in replacement for the gameplay view's self-judge
* loop rather than a state-ownership refactor.
*
* Engine behavior shared by both runtimes (TUI + Web):
* - Manual keysounds are emitted for the candidate note, or for the latest same-lane visible/invisible fallback whose
* early BAD window has already opened.
* - Out-of-window presses do not play the next pending lane keysound before that note's judgment window opens.
* - Free-Zone (`17` / `27`) channels stay excluded from score/gauge targets and keep their scratch aliases.
* - Key releases inferred for input that reports none (`play-key-inference.ts`): 380 ms after a long note's head,
* 120 ms after any other press or key repeat.
* - LN early-release audio cut via `AudioSession.stopChannel`.
* - Mine vs note delta-based priority (closest delta wins).
* - Multi-channel input mapping for scratch / Free-Zone aliases.
*
* Test-coverage trail for the dynamic-judge / sample-routing features the migration depends on:
* - **EXRANK dynamic judge windows** — engine end-to-end at
* `packages/player-engine/src/player-long-notes-and-windows.test.ts:'player: updates manual judge windows from dynamic
* EXRANK events'`. Frame summary propagation through `createWebUIRuntime` is covered by
* `packages/player-browser/src/runtime/web-ui-runtime.test.ts:'drainWebUISignals routes the current frame snapshot ...'`.
* - **#WAVCMD per-slot gain** — covered by
* `packages/player-browser/src/runtime/web-audio-session.test.ts:'applies #WAVCMD per-slot gain via an intermediate
* GainNode'`, which verifies the BufferSource → GainNode → mixer routing instead of BufferSource → mixer.
* - **bmson c=true continuation** — covered by
* `packages/player-browser/src/runtime/web-audio-session.test.ts:'honours bmson c=true continuation by suppressing
* retriggers of an in-flight slot'`. The engine's lane fallback path still flows through
* `WebAudioSession.triggerEvent` (which checks `activeBySlot`).
* - **#STP measure stops** — handled at the timing-resolver / timeline level inside `@be-music/chart-model`; the
* engine consumes chart-time seconds that already account for stops, so it doesn't have a separate code
* path. Covered by `packages/chart-model/src/timelines.test.ts:'SCROLL/BPM/STOP: keeps zero and negative scroll with
* LR2-style stop compensation'`.
*/
export async function runEngineDriver(options: EngineDriverOptions): Promise<EngineDriverResult> {
const { chart, audio, mode, ui, inputTarget, shouldSkipKey, onInputSignalsReady, engineOptions } = options;
const createAudioSession = async (context: CreateAudioSessionContext): Promise<AudioSession> => {
log.debug('audio session factory invoked', { mode: context.mode });
return createWebAudioSession({
audioContext: audio.audioContext,
audioBus: audio.audioBus,
chart: context.json,
decodedSamples: audio.decodedSamples,
wavCmdVolumeMultipliers: audio.wavCmdVolumeMultipliers,
bmsonSlicePlayback: audio.bmsonSlicePlayback,
...(audio.stageMixer !== undefined ? { stageMixer: audio.stageMixer } : {}),
...(audio.playbackRate !== undefined ? { playbackRate: audio.playbackRate } : {}),
...(audio.playbackRateFollowsTempo === true ? { playbackRateFollowsTempo: true } : {}),
...(audio.tempo !== undefined ? { tempo: audio.tempo } : {}),
...(audio.seekCrossfadeSeconds !== undefined ? { seekCrossfadeSeconds: audio.seekCrossfadeSeconds } : {}),
});
};
const createInputRuntime = createWebInputRuntimeFactory({
target: inputTarget,
shouldSkipKey,
onReady: onInputSignalsReady,
});
const createUIRuntime = createWebUIRuntimeFactory(ui);
const compositeOptions: PlayerOptions = {
loadAudioSampleDurations: async (resolved) => {
const durations = new Map<string, number>();
for (const [slot, path] of Object.entries(resolveBmsWAVResources(resolved.source))) {
const buffer =
audio.decodedSamples.get(decodedSampleKey(path, slot)) ?? audio.decodedSamples.get(decodedSampleKey(path));
if (buffer) durations.set(slot, buffer.duration);
}
return durations;
},
...engineOptions,
...(engineOptions?.recordReplay
? { recordReplay: { analogScratch: IIDX_GAMEPAD_SCRATCH, ...engineOptions.recordReplay } }
: {}),
auto: mode === 'auto',
tui: false,
createAudioSession,
createInputRuntime,
createUIRuntime,
};
log.info('engine driver starting', { mode, hasInputTarget: inputTarget !== undefined });
const summary =
mode === 'auto' ? await engineAutoPlay(chart, compositeOptions) : await engineManualPlay(chart, compositeOptions);
log.info('engine driver finished', {
score: summary.score,
exScore: summary.exScore,
perfect: summary.perfect,
great: summary.great,
good: summary.good,
bad: summary.bad,
poor: summary.poor,
});
return summary;
}
|