All files / audio-sample/src sample-path.ts

99.1% Statements 111/112
97.22% Branches 35/36
100% Functions 5/5
99.08% Lines 108/109

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        25x                                         109x 109x 109x         52x                         121x 121x   121x 1590x 1590x 125x   1465x 1465x     121x 121x       121x 121x 4x 4x 4x       121x 121x 1x     121x 126x     121x       121x 7x 7x       5x 5x 5x 121x 1x   4x       126x   126x 126x   126x   7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x     119x   109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x     10x 5x 5x 5x 5x 5x 5x 5x 5x 5x     5x 3x 3x 3x 3x 3x 3x 3x 3x 3x     2x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x    
import { extname } from '@be-music/shared-utils/core';
import { resolveFirstExistingPath } from '@be-music/shared-utils/path';
 
// Filesystem lookups for alternate extensions can share libuv's default four filesystem threads.
const SAMPLE_PATH_LOOKUP = { fallbackConcurrency: 4 };
 
export interface ResolveSamplePathOptions {
  /**
   * BMS spec — `#PATH_WAV <prefix>` declares a directory the chart's WAVs live under, e.g. `wav/` so that `#WAV01
   * kick.wav` resolves to `wav/kick.wav` on disk. The resolver tries the `pathPrefix`-joined form first and falls back
   * to the bare path so charts that omit `#PATH_WAV` (or mix conventions) keep working.
   */
  pathPrefix?: string;
}
 
/**
 * The file a chart's sample resolves to under `baseDir` (the chart's folder): the {@link createSamplePathCandidates}
 * walk there, then the same walk one folder up. Absolute path, or `undefined` when nothing matches.
 */
export async function resolveSamplePath(
  baseDir: string,
  samplePath: string,
  signal?: AbortSignal,
  options: ResolveSamplePathOptions = {},
): Promise<string | undefined> {
  const candidates = createSamplePathCandidates(samplePath, options);
  const found = await resolveFirstExistingPath(baseDir, candidates, signal, SAMPLE_PATH_LOOKUP);
  if (found !== undefined) return found;
  // As LR2: every candidate once more one folder up, so a 差分 (alternate difficulty) chart shipped in a sub-folder finds
  // the keysounds beside its parent.
  // `..` rather than a string `dirname`: `baseDir` is a file-system path (absolute, maybe Windows), which the resolver
  // normalises with Node's `path.resolve`.
  return resolveFirstExistingPath(`${baseDir.replace(/[\\/]+$/u, '')}/..`, candidates, signal, SAMPLE_PATH_LOOKUP);
}
 
/**
 * Builds the codec-fallback candidate list for a chart-declared sample path. Exported so callers (and tests) can
 * inspect the walk order — the bmson 1.0.0 spec mandates that `.m4a` is part of the chain, and lock-in tests pin the
 * sequencing to prevent regressions.
 *
 * When `options.pathPrefix` is set (typically `chart.bms.pathWAV`), the prefixed candidates are tried *before* the bare
 * ones so a chart that authors `#PATH_WAV wav/` with `#WAV01 kick.wav` resolves to `wav/kick.wav` first, falling
 * through to `kick.wav` when the chart's path-wav layout doesn't match.
 */
export function createSamplePathCandidates(samplePath: string, options: ResolveSamplePathOptions = {}): string[] {
  const seen = new Set<string>();
  const candidates: string[] = [];
 
  const push = (value: string): void => {
    const normalized = value.trim();
    if (normalized.length === 0 || seen.has(normalized)) {
      return;
    }
    seen.add(normalized);
    candidates.push(normalized);
  };
 
  const basePaths: string[] = [];
  const slashNormalizedSample = samplePath.replaceAll('\\', '/');
  // `#PATH_WAV` prefix-joined variants come first so a chart with `wav/` layout resolves through its declared directory
  // before the bare-name fallback. Skip the prefix entirely when blank / null-safe — empty `#PATH_WAV` is treated as
  // "no prefix" by hitkey BMS Memo.
  const prefixed = joinPathWAVPrefix(options.pathPrefix, samplePath);
  if (prefixed !== undefined) {
    basePaths.push(prefixed);
    const slashNormalized = prefixed.replaceAll('\\', '/');
    Iif (slashNormalized !== prefixed) {
      basePaths.push(slashNormalized);
    }
  }
  basePaths.push(samplePath);
  if (slashNormalizedSample !== samplePath) {
    basePaths.push(slashNormalizedSample);
  }
 
  for (const basePath of basePaths) {
    appendSampleCandidatesByRule(basePath, push);
  }
 
  return candidates;
}
 
function joinPathWAVPrefix(prefix: string | undefined, samplePath: string): string | undefined {
  if (typeof prefix !== 'string') return undefined;
  const trimmedPrefix = prefix.trim();
  if (trimmedPrefix.length === 0) return undefined;
  // Skip when the chart already includes the prefix in the sample path — common when a chart pulls samples from a
  // sub-folder explicitly via `#WAV01 wav/kick.wav` AND sets `#PATH_WAV wav/`. Returning `undefined` here keeps the
  // regular candidate list (without the second prefix application) and the bare path still resolves correctly.
  const normalizedPrefix = trimmedPrefix.replaceAll('\\', '/');
  const normalizedSample = samplePath.replaceAll('\\', '/');
  const prefixWithSep = normalizedPrefix.endsWith('/') ? normalizedPrefix : `${normalizedPrefix}/`;
  if (normalizedSample.startsWith(prefixWithSep)) {
    return undefined;
  }
  return `${prefixWithSep}${samplePath}`;
}
 
function appendSampleCandidatesByRule(samplePath: string, push: (candidatePath: string) => void): void {
  push(samplePath);
 
  const extension = extname(samplePath).toLowerCase();
  const withoutExtension = extension.length > 0 ? samplePath.slice(0, -extension.length) : samplePath;
 
  if (extension === '.mp3') {
    // If .mp3 is explicitly specified, try mp3 first and then fallback to ogg/opus/m4a.
    push(`${withoutExtension}.mp3`);
    push(`${withoutExtension}.MP3`);
    push(`${withoutExtension}.ogg`);
    push(`${withoutExtension}.OGG`);
    push(`${withoutExtension}.oga`);
    push(`${withoutExtension}.OGA`);
    push(`${withoutExtension}.opus`);
    push(`${withoutExtension}.OPUS`);
    push(`${withoutExtension}.m4a`);
    push(`${withoutExtension}.M4A`);
    return;
  }
 
  if (extension === '.wav') {
    // If .wav is specified but not found, fallback to mp3 -> ogg -> opus -> m4a.
    push(`${withoutExtension}.wav`);
    push(`${withoutExtension}.WAV`);
    push(`${withoutExtension}.mp3`);
    push(`${withoutExtension}.MP3`);
    push(`${withoutExtension}.ogg`);
    push(`${withoutExtension}.OGG`);
    push(`${withoutExtension}.oga`);
    push(`${withoutExtension}.OGA`);
    push(`${withoutExtension}.opus`);
    push(`${withoutExtension}.OPUS`);
    push(`${withoutExtension}.m4a`);
    push(`${withoutExtension}.M4A`);
    return;
  }
 
  if (extension === '.ogg' || extension === '.oga') {
    push(`${withoutExtension}.ogg`);
    push(`${withoutExtension}.OGG`);
    push(`${withoutExtension}.oga`);
    push(`${withoutExtension}.OGA`);
    push(`${withoutExtension}.opus`);
    push(`${withoutExtension}.OPUS`);
    push(`${withoutExtension}.m4a`);
    push(`${withoutExtension}.M4A`);
    return;
  }
 
  if (extension === '.opus') {
    push(`${withoutExtension}.opus`);
    push(`${withoutExtension}.OPUS`);
    push(`${withoutExtension}.ogg`);
    push(`${withoutExtension}.OGG`);
    push(`${withoutExtension}.oga`);
    push(`${withoutExtension}.OGA`);
    push(`${withoutExtension}.m4a`);
    push(`${withoutExtension}.M4A`);
    return;
  }
 
  if (extension === '.m4a') {
    // bmson 1.0.0 spec example explicitly lists `.m4a` (AAC) as a fallback codec, so treat it as a first-class entry:
    // try m4a, then walk the rest of the codec list for the case where the chart authors `.m4a` but the disk only has a
    // re-encoded variant.
    push(`${withoutExtension}.m4a`);
    push(`${withoutExtension}.M4A`);
    push(`${withoutExtension}.ogg`);
    push(`${withoutExtension}.OGG`);
    push(`${withoutExtension}.oga`);
    push(`${withoutExtension}.OGA`);
    push(`${withoutExtension}.opus`);
    push(`${withoutExtension}.OPUS`);
    push(`${withoutExtension}.mp3`);
    push(`${withoutExtension}.MP3`);
    return;
  }
 
  // Extension omitted or unknown: wav -> mp3 -> ogg -> opus -> m4a. The bmson 1.0.0 spec calls out `.m4a` (AAC)
  // explicitly in its extensionless-name example ("Try piano.wav, piano.ogg, piano.m4a, …"), so we include it here and
  // in the with- extension branches above.
  push(`${withoutExtension}.wav`);
  push(`${withoutExtension}.WAV`);
  push(`${withoutExtension}.mp3`);
  push(`${withoutExtension}.MP3`);
  push(`${withoutExtension}.ogg`);
  push(`${withoutExtension}.OGG`);
  push(`${withoutExtension}.oga`);
  push(`${withoutExtension}.OGA`);
  push(`${withoutExtension}.opus`);
  push(`${withoutExtension}.OPUS`);
  push(`${withoutExtension}.m4a`);
  push(`${withoutExtension}.M4A`);
}