All files / player-browser/src/session/play live-tempo.ts

100% Statements 14/14
100% Branches 9/9
100% Functions 3/3
100% Lines 11/11

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                                      327x 327x         5x 4x 4x 1x 4x         62x 62x 1x 1x      
import type { PlayerInputCommand } from '@be-music/player-engine/signals';
import { clampPlayTempo } from '../../runtime/play-tempo.ts';
 
type TempoCommandSink = { pushCommand: (command: PlayerInputCommand) => void };
 
/**
 * A gameplay scene's live play tempo: the tempo in force (the play's starting one, then each change the engine
 * reports) and the changes the host asks for, pushed to the engine as its `{ kind: 'tempo' }` input command. A change
 * asked for before the engine's input bus is up waits for it. With `enabled` false (keep pitch, or a replay) it takes
 * none.
 */
export class LiveTempo {
  public tempo: number;
  private readonly enabled: boolean;
  private pending: number | undefined;
  private signals: TempoCommandSink | undefined;
 
  // Plain fields, not parameter properties: Node's type stripping (which `pnpm bench` runs on) rejects those.
  public constructor(tempo: number, enabled = true) {
    this.tempo = tempo;
    this.enabled = enabled;
  }
 
  /** Asks the engine for `tempo` (clamped by `clampPlayTempo`). Returns whether the change was taken. */
  public request(tempo: number): boolean {
    if (!this.enabled) return false;
    const next = clampPlayTempo(tempo);
    if (this.signals === undefined) this.pending = next;
    else this.signals.pushCommand({ kind: 'tempo', tempo: next });
    return true;
  }
 
  /** The engine's input bus is up (or gone, `undefined`): a change asked for before goes out now. */
  public attach(signals: TempoCommandSink | undefined): void {
    this.signals = signals;
    if (signals === undefined || this.pending === undefined) return;
    signals.pushCommand({ kind: 'tempo', tempo: this.pending });
    this.pending = undefined;
  }
}