All files / player-browser/src/runtime play-tempo.ts

93.84% Statements 61/65
87.67% Branches 64/73
93.75% Functions 15/16
98.11% Lines 52/53

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                                      53x 53x                       344x 46x         1x         13x               37x               356x                                   33x 2x   31x 1x   33x         1x 1x 1x                             5x 5x 4x 6x   5x 5x 11x 11x 11x   5x                       4x 2x 2x 3x               2x                               2x 2x 4x   2x 2x 2x 3x 2x   2x         2x 2x     2x 2x 2x 2x 2x                       2x 3x                 3x 1x   2x    
import { clamp } from '@be-music/shared-utils/core';
import type { NonstopStitchMap } from '@be-music/player-engine/course';
import {
  DEFAULT_REPLAY_PLAYBACK_OPTIONS,
  type ReplayPlay,
  type ReplayTempoChange,
} from '@be-music/player-engine/replay';
import type { TimedSampleTrigger } from '@be-music/chart-model';
import type { BeMusicEvent } from '@be-music/chart-source';
import { stretchAudioBuffers, type TimeStretchAlgorithm } from './time-stretch.ts';
import type { WebAudioSessionSlicePlayback } from './web-audio-session.ts';
 
/**
 * The play tempo: a play runs `tempo` times as fast (the engine's `PlayerOptions.speed`), its clock, audio, scroll and
 * BGA alike, while judging stays in chart time. A stitched NONSTOP chart's FIT stages change the tempo the same way, per
 * stage, and the two multiply.
 */
 
/** The slowest and fastest play tempo the web player offers (-50 % .. +50 %). */
export const PLAY_TEMPO_MIN = 0.5;
export const PLAY_TEMPO_MAX = 1.5;
 
/**
 * How a tempo change sounds: `pitch` plays the samples faster or slower, so the pitch moves with the tempo (LR2, a
 * turntable); `keep-pitch` stretches the samples in time when they load and keeps their pitch.
 */
export type TempoPitchMode = 'pitch' | 'keep-pitch';
 
export type { TimeStretchAlgorithm };
 
/** `value` as a play tempo: clamped to {@link PLAY_TEMPO_MIN}..{@link PLAY_TEMPO_MAX} on a 1 % grid; 1 when unusable. */
export function clampPlayTempo(value: number | undefined): number {
  if (value === undefined || !Number.isFinite(value) || value <= 0) return 1;
  return Math.round(clamp(value, PLAY_TEMPO_MIN, PLAY_TEMPO_MAX) * 100) / 100;
}
 
/** Chart seconds `elapsedSeconds` of the play clock cover at `tempo`. */
export function elapsedToChartSeconds(elapsedSeconds: number, tempo: number): number {
  return elapsedSeconds * tempo;
}
 
/** Play-clock seconds `chartSeconds` of the chart take at `tempo`. */
export function chartToElapsedSeconds(chartSeconds: number, tempo: number): number {
  return chartSeconds / tempo;
}
 
/**
 * The playback rate of a sample: in `pitch` mode the tempo times its NONSTOP stage's FIT rate (`stageRate`), in
 * `keep-pitch` mode 1, since the sample was stretched to that rate when it loaded ({@link resolveSampleStretchRates}).
 */
export function resolveSamplePlaybackRate(mode: TempoPitchMode, tempo: number, stageRate = 1): number {
  return mode === 'keep-pitch' ? 1 : tempo * stageRate;
}
 
/**
 * Whether the tempo can change during a play: in `pitch` mode the samples follow the tempo through their playback rate;
 * in `keep-pitch` mode they were stretched to the tempo they loaded at, so it stays.
 */
export function supportsLiveTempoChange(mode: TempoPitchMode): boolean {
  return mode === 'pitch';
}
 
/** The tempo a replay plays at: the one it starts at and the changes it follows (chart time, the log's clock). */
export interface ReplayTempo {
  tempo: number;
  changes: ReplayTempoChange[];
}
 
/**
 * The tempo a replay plays at. When the viewer reproduces the recorded tempo (`reproduce`, by default as
 * `DEFAULT_REPLAY_PLAYBACK_OPTIONS`), it starts at `play.tempo` and, when the tempo can change live
 * ({@link supportsLiveTempoChange}), follows `play.tempoChanges`; otherwise it plays at the viewer's own tempo.
 */
export function resolveReplayTempo(
  play: Pick<ReplayPlay, 'tempo' | 'tempoChanges'>,
  options: { ownTempo?: number; pitchMode: TempoPitchMode; reproduce?: boolean },
): ReplayTempo {
  if (!(options.reproduce ?? DEFAULT_REPLAY_PLAYBACK_OPTIONS.tempo)) {
    return { tempo: clampPlayTempo(options.ownTempo), changes: [] };
  }
  const changes = supportsLiveTempoChange(options.pitchMode)
    ? (play.tempoChanges ?? []).map((change) => ({ timeUs: change.timeUs, tempo: clampPlayTempo(change.tempo) }))
    : [];
  return { tempo: clampPlayTempo(play.tempo ?? 1), changes };
}
 
/** Runs BGA videos at `tempo`, so their time stays the chart time since their cue. */
export function setVideoPlaybackTempo(videos: Iterable<HTMLVideoElement>, tempo: number): void {
  for (const video of videos) {
    video.defaultPlaybackRate = tempo;
    video.playbackRate = tempo;
  }
}
 
/**
 * The samples a keep-pitch play stretches: every sample path of the chart's `#WAV` table (as `normalize` keys the
 * decoded-sample cache) with the rate it plays at, the tempo times its NONSTOP stage's FIT rate (`map`). Samples played
 * at rate 1 are left out.
 */
export function resolveSampleStretchRates(
  wav: Readonly<Record<string, string | undefined>>,
  normalize: (path: string) => string,
  tempo: number,
  map?: NonstopStitchMap,
): Map<string, number> {
  const stageRateOfKey = new Map<string, number>();
  for (const stage of map?.stages ?? []) {
    const rate = stage.placement.rate > 0 ? stage.placement.rate : 1;
    for (const key of stage.wavKeys) stageRateOfKey.set(key, rate);
  }
  const rates = new Map<string, number>();
  for (const [key, path] of Object.entries(wav)) {
    Iif (path === undefined) continue;
    const rate = tempo * (stageRateOfKey.get(key) ?? 1);
    if (rate !== 1 && rate > 0) rates.set(normalize(path), rate);
  }
  return rates;
}
 
/**
 * bmson slices (and LRX note windows) of samples stretched by `rate` (played `rate` times as fast): each slice's
 * offset, length and ramps shrink by `rate`, so it still starts and ends on the same note. Other fields are kept; at
 * rate 1 it is a plain copy.
 */
export function stretchSlicePlayback<T extends WebAudioSessionSlicePlayback>(
  slices: ReadonlyMap<BeMusicEvent, T>,
  rate: number,
): Map<BeMusicEvent, T> {
  if (rate === 1 || !(rate > 0)) return new Map(slices);
  const stretched = new Map<BeMusicEvent, T>();
  for (const [event, slice] of slices) {
    stretched.set(event, {
      ...slice,
      offsetSeconds: slice.offsetSeconds / rate,
      ...(slice.durationSeconds !== undefined ? { durationSeconds: slice.durationSeconds / rate } : {}),
      ...(slice.attackSeconds !== undefined ? { attackSeconds: slice.attackSeconds / rate } : {}),
      ...(slice.releaseSeconds !== undefined ? { releaseSeconds: slice.releaseSeconds / rate } : {}),
    });
  }
  return stretched;
}
 
/**
 * Keep pitch: replaces each decoded sample in `samples` with itself stretched to its rate in `rates` (keyed as
 * `samples` is), keeping its pitch. The samples of one rate are stretched together (one Signalsmith Stretch render per
 * rate). Stops early once `cancelled` returns true.
 */
export async function stretchDecodedSamples(
  context: BaseAudioContext,
  samples: Map<string, AudioBuffer>,
  rates: ReadonlyMap<string, number>,
  algorithm: TimeStretchAlgorithm,
  cancelled: () => boolean = () => false,
  onProgress?: (fraction: number) => void,
): Promise<void> {
  const byRate = new Map<number, string[]>();
  for (const [path, rate] of rates) {
    if (samples.has(path)) byRate.set(rate, [...(byRate.get(rate) ?? []), path]);
  }
  let completedGroups = 0;
  let reported = 0;
  for (const [rate, paths] of byRate) {
    if (cancelled()) return;
    const stretched = await stretchAudioBuffers(
      context,
      paths.map((path) => samples.get(path)!),
      rate,
      algorithm,
      onProgress &&
        ((fraction) => {
          const progress = (completedGroups + fraction) / byRate.size;
          Eif (!cancelled() && progress > reported) onProgress((reported = progress));
        }),
    );
    Iif (cancelled()) return;
    paths.forEach((path, index) => samples.set(path, stretched[index]!));
    completedGroups++;
    const progress = completedGroups / byRate.size;
    Iif (progress > reported) onProgress?.((reported = progress));
  }
}
 
/**
 * The per-event playback of the triggers that carry their own (an LRX note's slice, gain, balance, rate and ramps), or
 * `undefined` when none does.
 */
export function collectTriggerVoicePlayback(
  triggers: readonly TimedSampleTrigger[],
): Map<BeMusicEvent, WebAudioSessionSlicePlayback> | undefined {
  let playback: Map<BeMusicEvent, WebAudioSessionSlicePlayback> | undefined;
  for (const trigger of triggers) {
    const voice: WebAudioSessionSlicePlayback = {
      offsetSeconds: trigger.sampleOffsetSeconds,
      ...(trigger.sampleDurationSeconds !== undefined ? { durationSeconds: trigger.sampleDurationSeconds } : {}),
      ...(trigger.sampleGain !== undefined ? { gain: trigger.sampleGain } : {}),
      ...(trigger.samplePan !== undefined ? { pan: trigger.samplePan } : {}),
      ...(trigger.samplePlaybackRate !== undefined ? { rate: trigger.samplePlaybackRate } : {}),
      ...(trigger.sampleAttackSeconds !== undefined ? { attackSeconds: trigger.sampleAttackSeconds } : {}),
      ...(trigger.sampleReleaseSeconds !== undefined ? { releaseSeconds: trigger.sampleReleaseSeconds } : {}),
    };
    if (voice.offsetSeconds === 0 && Object.keys(voice).length === 1) continue;
    (playback ??= new Map()).set(trigger.event, voice);
  }
  return playback;
}