All files / player-engine/src/core play-replay.ts

98% Statements 49/50
75% Branches 15/20
93.33% Functions 14/15
97.82% Lines 45/46

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                                    2198x 2198x 2198x 2198x 2198x 24914x 82287x 2184x   90x 90x 90x 90x   90x 90x 90x 2959x 2959x 216x 216x 216x 2743x 2741x   90x 209x 214x     90x 1x 2x 2x 1x     90x           73x 73x                           19x 19x 19x 19x   19x         82762x   82762x   82435x   2198x   2183x       1631x             127x            
import { advanceJudgeCoreReplay, createJudgeCoreReplay, type JudgeCoreEffect } from './judge-core.ts';
import type { PlaySession } from './play-session.ts';
import type { JudgeStrategy, PlayJudge } from './play-strategy.ts';
import { createPlayJudgeCore, judgeCoreJudge, writeManualIntro } from './play-manual.ts';
import { createSeekRebuildSink } from './play-seek.ts';
import { resolveRulesetLongNoteMode, toUILongNoteMode } from './judge-rules.ts';
 
/**
 * The replay judge strategy: the manual judge core re-driven by a recorded replay input stream
 * (`PlayerOptions.replayInputs`). It steps the core from one judgment instant to the next (`advanceJudgeCoreReplay`)
 * up to each tick's chart time, so the replayed judgments depend on neither tick timing nor `speed`. Live lane and key
 * input is ignored; pause, HIGH-SPEED, tempo, view and interrupt commands still work.
 *
 * The recorded inputs are replayed as they are. A log recorded before the engine inferred releases for input that
 * reports none (a terminal without the kitty keyboard protocol) has only presses, so each key stays down from its press
 * to the end of the play and every key repeat is a press of its own, as the replay simulators read it.
 */
function createReplayJudge(session: PlaySession): PlayJudge {
  const { applyJudgeEffect } = session;
  let judgeCore = createPlayJudgeCore(session, 1000);
  let replay = createJudgeCoreReplay(session.options.replayInputs ?? [], session.options.replayInputSources);
  let coreJudge = judgeCoreJudge(session, judgeCore);
  return {
    isSettled: () => coreJudge.isSettled(),
    isClosed: () => coreJudge.isClosed(),
    finish: () => coreJudge.finish(),
    seek: (seconds) => {
      judgeCore = createPlayJudgeCore(session, 1000);
      coreJudge = judgeCoreJudge(session, judgeCore);
      replay = createJudgeCoreReplay(session.options.replayInputs ?? [], session.options.replayInputSources);
      const rebuilt = createSeekRebuildSink(session.summary);
      // Rebuild silently, retaining keysounds not cut by a later stop on their lane.
      const sounds = new Map<string, Array<Extract<JudgeCoreEffect, { kind: 'sound' }>>>();
      const chains: Array<Extract<JudgeCoreEffect, { kind: 'chain-sounds' }>> = [];
      advanceJudgeCoreReplay(judgeCore, replay, seconds, (effect) => {
        rebuilt.emit(effect);
        if (effect.kind === 'sound') {
          const lane = sounds.get(effect.channel) ?? [];
          lane.push(effect);
          sounds.set(effect.channel, lane);
        } else if (effect.kind === 'stop-sound') sounds.delete(effect.channel);
        else if (effect.kind === 'chain-sounds') chains.push(effect);
      });
      for (const lane of sounds.values()) {
        for (const sound of lane)
          session.audioSession?.triggerEventAt?.(sound.event, Math.max(0, seconds - sound.seconds));
      }
      // The LRX chain notes those presses queued: the ones already due start partway, the rest wait for their moment.
      for (const chain of chains) {
        for (const sound of chain.sounds) {
          const due = chain.seconds + sound.delaySeconds;
          if (due < seconds) session.audioSession?.triggerEventAt?.(sound.event, seconds - due);
          else session.chainSounds.schedule(seconds, [{ event: sound.event, delaySeconds: due - seconds }]);
        }
      }
      return {
        judgments: rebuilt.judgments,
        bmsonBGAInputs: rebuilt.bmsonBGAInputs,
        chartTextInputs: rebuilt.chartTextInputs,
        heldLongNotes: [
          ...[...judgeCore.activeLongNotes.values()]
            .filter(({ note }) => judgeCore.heldChannels.has(note.channel))
            .map(({ note, mode }) => ({
              channel: note.channel,
              beat: note.beat,
              endBeat: note.endBeat,
              mode: toUILongNoteMode(mode),
            })),
          ...judgeCore.pendingAutoScratchLongNotes.map(({ note }) => ({
            channel: note.channel,
            beat: note.beat,
            endBeat: note.endBeat,
            mode: toUILongNoteMode(resolveRulesetLongNoteMode(session.ruleset.longNoteStyle, note) ?? 2),
          })),
        ],
        hellChargeNotes: [...judgeCore.hcnPassing.values()].flatMap((first) => {
          const notes: Array<{ channel: string; beat: number; state: 'gaining' | 'draining' }> = [];
          for (let passing: typeof first | undefined = first; passing !== undefined; passing = passing.next) {
            Eif (passing.reported !== undefined)
              notes.push({ channel: passing.note.channel, beat: passing.note.beat, state: passing.reported });
          }
          return notes;
        }),
      };
    },
    beforeAudio: (tick) => {
      advanceJudgeCoreReplay(judgeCore, replay, tick.nowSec, applyJudgeEffect);
    },
    judge: () => undefined,
    // A replay has only judged up to its last chart-time step, which can trail the tick by up to one step.
    judgedThroughSeconds: () => replay.judgedThroughSeconds,
    // Everything due by the last step's chart time has been judged, whether or not a judgment fell on it.
    settledThroughSeconds: () => Math.max(0, replay.judgedThroughSeconds),
    beforeFinish: () => {
      if (replay.events.length > 0) {
        // The loop can end once every note is judged while inputs are still queued — typically the release that
        // follows the last note. Drain them so the re-recorded replay carries the whole input stream no matter how
        // far the final tick overshot.
        advanceJudgeCoreReplay(judgeCore, replay, replay.events.at(-1)!.timeUs / 1_000_000, applyJudgeEffect);
      }
    },
  };
}
 
/** A replay: a recorded play's inputs, re-driven at their recorded chart times. */
export const replayStrategy: JudgeStrategy = {
  mode: 'manual',
  estimatesActiveAudio: false,
  writeIntro: writeManualIntro,
  createJudge: createReplayJudge,
};