All files / player-engine/src/core play-audio-cursor.ts

100% Statements 16/16
100% Branches 6/6
100% Functions 6/6
100% Lines 16/16

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                                                            6371x 6371x 602523x 602523x 602523x 93432x 93432x 89494x   3938x 3938x     6371x   602006x     517x 517x   761x       1598x        
import { REALTIME_AUDIO_TRIGGER_EPSILON_SECONDS } from './engine-clock.ts';
 
/**
 * The realtime audio of a play: time-sorted lists (volume changes, background sounds, AUTO play's note keysounds)
 * fired in order as the play reaches them.
 */
 
/** Walks a time-sorted list, firing each item once the reference time reaches it. */
export interface RealtimeAudioCursor<T = unknown> {
  /** Fires every item due by `referenceSeconds` (chart seconds), in order. */
  triggerUntil(referenceSeconds: number): void;
  /**
   * Moves the cursor to `referenceSeconds`, backwards or forwards (a seek): it starts over from the first item and passes
   * every item due by then, handing each to `passed` with how long ago it was due (to start what still sounds partway).
   * Without `passed` the items passed are fired, as {@link triggerUntil} fires them (state such as volume changes).
   */
  seek(referenceSeconds: number, passed?: (item: T, offsetSeconds: number) => void): void;
  /** Every item has fired. */
  readonly done: boolean;
}
 
/**
 * A cursor over `items` (sorted by `seconds`) that calls `fire` for each one due. `clamp` caps the reference time first
 * (AUTO play's keysounds freeze at an LR2 negative-BPM reversal, #134).
 */
export function createRealtimeAudioCursor<T extends { readonly seconds: number }>(
  items: readonly T[],
  fire: (item: T) => void,
  clamp?: (seconds: number) => number,
): RealtimeAudioCursor<T> {
  let index = 0;
  const walk = (referenceSeconds: number, visit: (item: T, reference: number) => void): void => {
    const reference = Math.max(0, clamp === undefined ? referenceSeconds : clamp(referenceSeconds));
    const safeReferenceSeconds = reference + REALTIME_AUDIO_TRIGGER_EPSILON_SECONDS;
    while (index < items.length) {
      const item = items[index]!;
      if (item.seconds > safeReferenceSeconds) {
        break;
      }
      visit(item, reference);
      index += 1;
    }
  };
  return {
    triggerUntil(referenceSeconds: number): void {
      walk(referenceSeconds, fire);
    },
    seek(referenceSeconds: number, passed?: (item: T, offsetSeconds: number) => void): void {
      index = 0;
      walk(
        referenceSeconds,
        passed === undefined ? fire : (item, reference) => passed(item, Math.max(0, reference - item.seconds)),
      );
    },
    get done(): boolean {
      return index >= items.length;
    },
  };
}