All files / audio-sample/src index.ts

97.46% Statements 77/79
92.3% Branches 36/39
100% Functions 6/6
97.4% Lines 75/77

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 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247                                                                                        24x 24x             32x 32x 32x 32x     32x 32x 32x               32x 32x 32x                       105x 105x 105x 105x         135x   135x 135x 20x         20x     115x 115x                   135x 5x 5x         5x     110x         135x     104x   104x 50x 50x         50x     60x 60x 60x           135x 60x 59x 59x 59x 59x 135x                         135x 135x           135x   1x 1x                 1x           115x 115x 115x 86x   29x 29x 29x       32x 32x 29x                 3x 3x 3x 39977x 39977x   3x                   104x 104x 4647311x 4647311x 4647311x 5050x   4647311x 24x     104x    
import { resolveBmsWAVPlayback, type BmsWAVPlaybackModifiers } from '@be-music/chart-model';
import { normalizeObjectKey } from '@be-music/chart-source';
import { isAbortError, throwIfAborted, transformStereoPCM } from '@be-music/shared-utils/core';
import { createFallbackTone, decodeAudioSample, resampleLinear } from './decode.ts';
import { resolveSamplePath } from './sample-path.ts';
 
export interface RenderSampleLoadProgress {
  stage: 'resolving' | 'reading' | 'decoded' | 'cached' | 'fallback';
  sampleKey: string;
  samplePath?: string;
  resolvedPath?: string;
}
 
export interface RenderResult {
  sampleRate: number;
  left: Float32Array;
  right: Float32Array;
  durationSeconds: number;
  peak: number;
}
 
export interface RenderSingleSampleOptions {
  /** Authored pitch, pan, frequency and sounding-time limit, applied before host tempo controls. */
  playbackModifiers?: BmsWAVPlaybackModifiers;
  sampleRate?: number;
  gain?: number;
  baseDir?: string;
  fallbackToneSeconds?: number;
  signal?: AbortSignal;
  onSampleLoadProgress?: (progress: RenderSampleLoadProgress) => void;
  /**
   * Object-ID radix the supplied `sampleKey` was authored under. Defaults to base 36 (case-folded). Pass `62` for
   * charts that declared `#BASE 62` so a lowercase `0a` key isn't re-folded back to `0A` during validation.
   */
  base?: 36 | 62;
  /** The chart's `#PATH_WAV` directory, tried before the bare sample path. */
  pathPrefix?: string;
}
 
export interface StereoSample {
  left: Float32Array;
  right: Float32Array;
}
 
const DEFAULT_SAMPLE_RATE = 44_100;
const FALLBACK_SAMPLE_CACHE = new Map<string, StereoSample>();
 
export async function renderSingleSample(
  sampleKey: string,
  samplePath: string | undefined,
  options: RenderSingleSampleOptions = {},
): Promise<RenderResult> {
  const normalizedKey = normalizeObjectKey(sampleKey, options.base ?? 36);
  const sampleRate = options.sampleRate ?? DEFAULT_SAMPLE_RATE;
  const gain = typeof options.gain === 'number' && Number.isFinite(options.gain) ? options.gain : 1;
  const baseDir = options.baseDir ?? process.cwd();
  // Spec-compliant default: missing / undecodable samples are silent. Pass a positive value to opt into the
  // debugging sine tone.
  const fallbackToneSeconds = options.fallbackToneSeconds ?? 0;
  throwIfAborted(options.signal);
  const load = createSampleLoader({
    sampleRate,
    baseDir,
    fallbackToneSeconds,
    signal: options.signal,
    pathPrefix: options.pathPrefix,
    onSampleLoadProgress: options.onSampleLoadProgress,
  });
  const sample = await load(normalizedKey, samplePath, options.playbackModifiers);
  throwIfAborted(options.signal);
  return toRenderResult(sample, sampleRate, gain);
}
 
/** Creates a loader for one chart render. Each sample key identifies one file and set of playback modifiers. */
export function createSampleLoader(options: {
  sampleRate: number;
  baseDir: string;
  fallbackToneSeconds: number;
  signal?: AbortSignal;
  onSampleLoadProgress?: (progress: RenderSampleLoadProgress) => void;
  pathPrefix?: string;
}): (sampleKey: string, samplePath?: string, playbackModifiers?: BmsWAVPlaybackModifiers) => Promise<StereoSample> {
  const { sampleRate, baseDir, fallbackToneSeconds, signal, onSampleLoadProgress, pathPrefix } = options;
  const loadedSamples = new Map<string, StereoSample>();
  const resolvedPathCache = new Map<string, string | undefined>();
  return async (
    sampleKey: string,
    samplePath?: string,
    playbackModifiers?: BmsWAVPlaybackModifiers,
  ): Promise<StereoSample> => {
    throwIfAborted(signal);
 
    const cached = loadedSamples.get(sampleKey);
    if (cached) {
      onSampleLoadProgress?.({
        stage: 'cached',
        sampleKey,
        samplePath,
      });
      return cached;
    }
 
    const originalFallback = getFallbackSample(sampleKey, sampleRate, fallbackToneSeconds);
    const fallback = playbackModifiers
      ? transformStereoPCM(
          originalFallback.left,
          originalFallback.right,
          sampleRate,
          sampleRate,
          resolveBmsWAVPlayback(playbackModifiers, sampleRate),
          signal,
        )
      : originalFallback;
    if (!samplePath) {
      loadedSamples.set(sampleKey, fallback);
      onSampleLoadProgress?.({
        stage: 'fallback',
        sampleKey,
        samplePath,
      });
      return fallback;
    }
 
    onSampleLoadProgress?.({
      stage: 'resolving',
      sampleKey,
      samplePath,
    });
    const resolvedPath = resolvedPathCache.has(samplePath)
      ? resolvedPathCache.get(samplePath)
      : await resolveSamplePath(baseDir, samplePath, signal, { pathPrefix });
    resolvedPathCache.set(samplePath, resolvedPath);
 
    if (!resolvedPath) {
      loadedSamples.set(sampleKey, fallback);
      onSampleLoadProgress?.({
        stage: 'fallback',
        sampleKey,
        samplePath,
      });
      return fallback;
    }
 
    try {
      throwIfAborted(signal);
      onSampleLoadProgress?.({
        stage: 'reading',
        sampleKey,
        samplePath,
        resolvedPath,
      });
      const { readFile } = await import('node:fs/promises');
      const buffer = await readFile(resolvedPath, { signal });
      throwIfAborted(signal);
      const decoded = await decodeAudioSample(buffer, resolvedPath, signal);
      throwIfAborted(signal);
      const rightSource = decoded.right ?? decoded.left;
      const sample = playbackModifiers
        ? transformStereoPCM(
            decoded.left,
            rightSource,
            decoded.sampleRate,
            sampleRate,
            resolveBmsWAVPlayback(playbackModifiers, decoded.sampleRate),
            signal,
          )
        : {
            left: resampleLinear(decoded.left, decoded.sampleRate, sampleRate, signal),
            right: resampleLinear(rightSource, decoded.sampleRate, sampleRate, signal),
          };
      loadedSamples.set(sampleKey, sample);
      onSampleLoadProgress?.({
        stage: 'decoded',
        sampleKey,
        samplePath,
        resolvedPath,
      });
      return sample;
    } catch (error) {
      Eif (isAbortError(error)) {
        throw error;
      }
      loadedSamples.set(sampleKey, fallback);
      onSampleLoadProgress?.({
        stage: 'fallback',
        sampleKey,
        samplePath,
        resolvedPath,
      });
      return fallback;
    }
  };
}
 
function getFallbackSample(sampleKey: string, sampleRate: number, fallbackToneSeconds: number): StereoSample {
  const cacheKey = `${sampleKey}:${sampleRate}:${fallbackToneSeconds}`;
  const cached = FALLBACK_SAMPLE_CACHE.get(cacheKey);
  if (cached) {
    return cached;
  }
  const created = createFallbackTone(sampleKey, sampleRate, fallbackToneSeconds);
  FALLBACK_SAMPLE_CACHE.set(cacheKey, created);
  return created;
}
 
function toRenderResult(sample: StereoSample, sampleRate: number, gain: number): RenderResult {
  const safeGain = Number.isFinite(gain) ? gain : 1;
  if (safeGain === 1) {
    return {
      sampleRate,
      left: sample.left,
      right: sample.right,
      durationSeconds: sample.left.length / sampleRate,
      peak: measurePeak(sample.left, sample.right),
    };
  }
 
  const left = new Float32Array(sample.left.length);
  const right = new Float32Array(sample.right.length);
  for (let index = 0; index < sample.left.length; index += 1) {
    left[index] = sample.left[index] * safeGain;
    right[index] = sample.right[index] * safeGain;
  }
  return {
    sampleRate,
    left,
    right,
    durationSeconds: left.length / sampleRate,
    peak: measurePeak(left, right),
  };
}
 
export function measurePeak(left: Float32Array, right: Float32Array): number {
  let peak = 0;
  for (let index = 0; index < left.length; index += 1) {
    const absLeft = Math.abs(left[index]);
    const absRight = Math.abs(right[index]);
    if (absLeft > peak) {
      peak = absLeft;
    }
    if (absRight > peak) {
      peak = absRight;
    }
  }
  return peak;
}