All files / player-terminal/src/cli args.ts

88.03% Statements 184/209
86.27% Branches 132/153
100% Functions 16/16
87.86% Lines 181/206

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 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492                                                                                                                                          2x 2x     80x 80x   80x 168x 168x 30x   138x 138x 33x 33x   88x 3x 2x   3x   80x     58x 58x       2x     4x 13x 4x 2x   2x       6x 6x 6x   3x 3x 1x       2x   3x 13x 3x 1x   2x       80x                                         168x   4x 4x 4x   5x 5x 5x   3x 3x   2x 2x   1x 1x         1x 1x   1x 1x         1x 1x   1x 1x   1x 1x         1x 1x         3x 3x   1x 1x   2x 2x   1x 1x   2x 2x   138x         138x 138x   138x         6x 6x   4x 4x   3x 3x   6x 6x   2x 2x   2x 2x   1x 1x   1x 1x   1x 1x   1x 1x   1x 1x   1x 1x   1x 1x   1x 1x   4x 4x   3x 1x 2x 2x   6x 6x                     1x 1x     1x 1x         1x 1x   1x 1x   1x 1x   1x 1x   88x         88x 1x   87x 1x   86x 2x   84x     84x 1x   83x 1x   82x 2x   80x     80x     80x     80x     80x     80x       2x 1x   1x       6x 6x     6x 2x   4x 4x 4x 1x   3x       4x 4x 1x   3x 1x   2x       3x 3x 1x   2x 1x   1x       6x 1x   5x 1x   4x 6x           1x   3x       2x 1x   1x       1x                                                                                                                        
import {
  DEFAULT_IMAGE_RESIZE_ALGORITHM,
  DEFAULT_TUI_NOTE_HEIGHT,
  isImageResizeAlgorithm,
  MAX_TUI_NOTE_HEIGHT,
  MIN_TUI_NOTE_HEIGHT,
  TUI_NOTE_HEIGHT_HALF,
  type ImageResizeAlgorithm,
  type TUINoteHeight,
} from '@be-music/player-engine/display';
import {
  isGaugePick,
  RULESET_IDS,
  type GaugePick,
  type GaugeType,
  type RulesetId,
} from '@be-music/player-engine/ruleset';
import { HIGH_SPEED_STEP, MAX_HIGH_SPEED, MIN_HIGH_SPEED } from './config.ts';
 
export interface CLIArgs {
  input?: string;
  logFile?: string;
  auto: boolean;
  autoScratch: boolean;
  kittyGraphics: boolean;
  videoBGAStreaming: boolean;
  inferBmsLNTypeWhenMissing: boolean;
  showInvisibleNotes: boolean;
  compressor: boolean;
  compressorThresholdDb?: number;
  compressorRatio?: number;
  compressorAttackMs?: number;
  compressorReleaseMs?: number;
  compressorMakeupDb?: number;
  limiter: boolean;
  limiterCeilingDb?: number;
  limiterReleaseMs?: number;
  speed?: number;
  uiFPS: number;
  tuiVisibleNotesLimit: number;
  tuiNoteHeight: TUINoteHeight;
  imageResizeAlgorithm: ImageResizeAlgorithm;
  highSpeed?: number;
  judgeWindowMs?: number;
  /** Compat ruleset the engine judges under (`PlayerOptions.judgeRuleset`). Defaults to LR2. */
  judgeRuleset?: RulesetId;
  bmsonTotalMode?: import('@be-music/player-engine/ruleset').BmsonTotalMode;
  /**
   * Gauge pick, in LR2's names; each ruleset maps it onto its own line-up. Defaults to `GROOVE`. Qualified with a source
   * (`lr2:HARD`), it runs that source's gauge under whichever ruleset judges.
   */
  gauge?: GaugePick;
  /** `false` keeps judging after a survival gauge empties (`PlayerOptions.endOnFailure`); omitted ends the play there. */
  endOnFailure?: boolean;
  debugActiveAudio: boolean;
  renderAudioPath?: string;
  audio: boolean;
  volume?: number;
  bgmVolume?: number;
  playVolume?: number;
  audioTailSeconds?: number;
  audioHeadPaddingMs?: number;
  audioLeadMs?: number;
  audioLeadMaxMs?: number;
  audioLeadStepUpMs?: number;
  audioLeadStepDownMs?: number;
  tui: boolean;
}
 
const DEFAULT_TUI_FPS = 60;
const DEFAULT_TUI_VISIBLE_NOTES_LIMIT = 8192;
 
export function parseArgs(rawArgs: string[]): CLIArgs {
  const args = createDefaultCLIArgs();
  const positional: string[] = [];
 
  for (let index = 0; index < rawArgs.length; index += 1) {
    const token = rawArgs[index];
    if (applyCLIToggleArg(args, token)) {
      continue;
    }
    const nextIndex = consumeCLIValueArg(args, rawArgs, index);
    if (nextIndex !== undefined) {
      index = nextIndex;
      continue;
    }
    if (consumeDeprecatedCLIArg(token)) {
      if ((token === '--judge-window' || token === '--audio-offset-ms') && index + 1 < rawArgs.length) {
        index += 1;
      }
      continue;
    }
    positional.push(token);
  }
 
  args.input = positional[0];
  return args;
}
 
/** The gauge types, in the order the CLI lists them. */
const CLI_GAUGES: readonly GaugeType[] = ['GROOVE', 'EASY', 'HARD', 'DEATH', 'DEATH-CORRECTED'];
 
function parseCLIRuleset(rawValue: string): RulesetId {
  const value = rawValue.trim().toLowerCase();
  const match = RULESET_IDS.find((ruleset) => ruleset === value);
  if (!match) {
    throw new Error(`Unknown --ruleset "${rawValue}". Expected one of: ${RULESET_IDS.join(', ')}.`);
  }
  return match;
}
 
function parseCLIGauge(rawValue: string): GaugePick {
  const trimmed = rawValue.trim();
  const colon = trimmed.indexOf(':');
  if (colon >= 0) {
    // `<source>:<NAME>`: that source's gauge, whatever ruleset judges (`lr2:HARD`, `beatoraja:EX-HARD`).
    const qualified = `${trimmed.slice(0, colon).toLowerCase()}:${trimmed.slice(colon + 1).toUpperCase()}`;
    if (!isGaugePick(qualified)) {
      throw new Error(
        `Unknown --gauge "${rawValue}". A qualified gauge is <source>:<NAME>, a gauge the source defines (lr2:HARD).`,
      );
    }
    return qualified;
  }
  const value = trimmed.toUpperCase();
  const match = CLI_GAUGES.find((gauge) => gauge === value);
  if (!match) {
    throw new Error(`Unknown --gauge "${rawValue}". Expected one of: ${CLI_GAUGES.join(', ')}.`);
  }
  return match;
}
 
function createDefaultCLIArgs(): CLIArgs {
  return {
    auto: false,
    autoScratch: false,
    kittyGraphics: true,
    videoBGAStreaming: true,
    imageResizeAlgorithm: DEFAULT_IMAGE_RESIZE_ALGORITHM,
    inferBmsLNTypeWhenMissing: false,
    showInvisibleNotes: false,
    compressor: true,
    limiter: true,
    audio: true,
    volume: undefined,
    tui: true,
    uiFPS: DEFAULT_TUI_FPS,
    tuiVisibleNotesLimit: DEFAULT_TUI_VISIBLE_NOTES_LIMIT,
    tuiNoteHeight: DEFAULT_TUI_NOTE_HEIGHT,
    debugActiveAudio: false,
  };
}
 
function applyCLIToggleArg(args: CLIArgs, token: string): boolean {
  switch (token) {
    case '--auto':
      args.auto = true;
      args.autoScratch = false;
      return true;
    case '--auto-scratch':
      args.auto = false;
      args.autoScratch = true;
      return true;
    case '--ln-type-auto':
      args.inferBmsLNTypeWhenMissing = true;
      return true;
    case '--no-ln-type-auto':
      args.inferBmsLNTypeWhenMissing = false;
      return true;
    case '--show-invisible-notes':
      args.showInvisibleNotes = true;
      return true;
    case '--no-show-invisible-notes':
      args.showInvisibleNotes = false;
      return true;
    case '--compressor':
      args.compressor = true;
      return true;
    case '--no-compressor':
      args.compressor = false;
      return true;
    case '--limiter':
      args.limiter = true;
      return true;
    case '--no-limiter':
      args.limiter = false;
      return true;
    case '--debug-active-audio':
      args.debugActiveAudio = true;
      return true;
    case '--no-audio':
      args.audio = false;
      return true;
    case '--audio':
      args.audio = true;
      return true;
    case '--no-end-on-failure':
      args.endOnFailure = false;
      return true;
    case '--tui':
      args.tui = true;
      return true;
    case '--no-tui':
      args.tui = false;
      return true;
    case '--kitty-graphics':
      args.kittyGraphics = true;
      return true;
    case '--no-kitty-graphics':
      args.kittyGraphics = false;
      return true;
    case '--video-bga-streaming':
      args.videoBGAStreaming = true;
      return true;
    case '--no-video-bga-streaming':
      args.videoBGAStreaming = false;
      return true;
    default:
      return false;
  }
}
 
function consumeCLIValueArg(args: CLIArgs, rawArgs: string[], index: number): number | undefined {
  const token = rawArgs[index];
  const rawValue = rawArgs[index + 1];
 
  switch (token) {
    case '--speed':
      args.speed = Number.parseFloat(rawValue);
      return index + 1;
    case '--high-speed':
      args.highSpeed = parseHighSpeedArg(rawValue);
      return index + 1;
    case '--tui-fps':
      args.uiFPS = parseTuiFPSArg(rawValue);
      return index + 1;
    case '--tui-visible-notes-limit':
      args.tuiVisibleNotesLimit = parseTUIVisibleNotesLimitArg(rawValue);
      return index + 1;
    case '--tui-note-height':
      args.tuiNoteHeight = parseTUINoteHeightArg(rawValue);
      return index + 1;
    case '--image-resize-algorithm':
      args.imageResizeAlgorithm = parseImageResizeAlgorithmArg(rawValue);
      return index + 1;
    case '--log-file':
      args.logFile = readRequiredCLIPathArg(rawValue, '--log-file');
      return index + 1;
    case '--compressor-threshold-db':
      args.compressorThresholdDb = Number.parseFloat(rawValue);
      return index + 1;
    case '--compressor-ratio':
      args.compressorRatio = Number.parseFloat(rawValue);
      return index + 1;
    case '--compressor-attack-ms':
      args.compressorAttackMs = Number.parseFloat(rawValue);
      return index + 1;
    case '--compressor-release-ms':
      args.compressorReleaseMs = Number.parseFloat(rawValue);
      return index + 1;
    case '--compressor-makeup-db':
      args.compressorMakeupDb = Number.parseFloat(rawValue);
      return index + 1;
    case '--limiter-ceiling-db':
      args.limiterCeilingDb = Number.parseFloat(rawValue);
      return index + 1;
    case '--limiter-release-ms':
      args.limiterReleaseMs = Number.parseFloat(rawValue);
      return index + 1;
    case '--debug-judge-window':
      args.judgeWindowMs = Number.parseInt(rawValue, 10);
      return index + 1;
    case '--ruleset':
      args.judgeRuleset = parseCLIRuleset(rawValue);
      return index + 1;
    case '--bmson-total-mode':
      if (rawValue !== 'beatoraja' && rawValue !== 'spec')
        throw new Error('Expected --bmson-total-mode beatoraja or spec.');
      args.bmsonTotalMode = rawValue;
      return index + 1;
    case '--gauge':
      args.gauge = parseCLIGauge(rawValue);
      return index + 1;
    case '--render-audio':
      args.renderAudioPath = rawValue;
      return index + 1;
    case '--audio-tail':
      args.audioTailSeconds = Number.parseFloat(rawValue);
      return index + 1;
    case '--bgm-volume':
      args.bgmVolume = Number.parseFloat(rawValue);
      return index + 1;
    case '--volume':
      args.volume = Number.parseFloat(rawValue);
      return index + 1;
    case '--play-volume':
    case '--key-volume':
      args.playVolume = Number.parseFloat(rawValue);
      return index + 1;
    case '--audio-head-padding-ms':
      args.audioHeadPaddingMs = Number.parseInt(rawValue, 10);
      return index + 1;
    case '--audio-lead-ms':
      args.audioLeadMs = Number.parseFloat(rawValue);
      return index + 1;
    case '--audio-lead-max-ms':
      args.audioLeadMaxMs = Number.parseFloat(rawValue);
      return index + 1;
    case '--audio-lead-step-up-ms':
      args.audioLeadStepUpMs = Number.parseFloat(rawValue);
      return index + 1;
    case '--audio-lead-step-down-ms':
      args.audioLeadStepDownMs = Number.parseFloat(rawValue);
      return index + 1;
    default:
      return undefined;
  }
}
 
function consumeDeprecatedCLIArg(token: string): boolean {
  if (token === '--audio-io-buffer-ms' || token === '--audio-io-high-water-ms' || token === '--audio-io-low-water-ms') {
    throw new Error(`${token} is no longer supported; audio-io backend has been removed`);
  }
  if (token === '--audio-backend') {
    throw new Error('--audio-backend is no longer supported; node-web-audio-api is always used');
  }
  if (token === '--audify-high-water-ms' || token === '--audify-low-water-ms') {
    throw new Error(`${token} is no longer supported; audify backend has been removed`);
  }
  Iif (token === '--speaker-buffer-size' || token === '--speaker-samples-per-frame') {
    throw new Error(`${token} is no longer supported; speaker backend has been removed`);
  }
  if (token === '--preview' || token === '--preview-audio') {
    return true;
  }
  if (token === '--no-preview' || token === '--no-preview-audio') {
    throw new Error(`${token} is no longer supported; music preview is always enabled`);
  }
  if (token === '--judge-window' || token === '--audio-offset-ms') {
    return true;
  }
  Iif (token.startsWith('--audio-backend=')) {
    throw new Error('--audio-backend is no longer supported; node-web-audio-api is always used');
  }
  Iif (token.startsWith('--judge-window=')) {
    return true;
  }
  Iif (token.startsWith('--audio-offset-ms=')) {
    return true;
  }
  Iif (token.startsWith('--audify-')) {
    throw new Error(`${token.split('=')[0]} is no longer supported; audify backend has been removed`);
  }
  Iif (token.startsWith('--speaker-')) {
    throw new Error(`${token.split('=')[0]} is no longer supported; speaker backend has been removed`);
  }
  return false;
}
 
function readRequiredCLIPathArg(raw: string | undefined, option: string): string {
  if (typeof raw === 'string' && raw.length > 0) {
    return raw;
  }
  throw new Error(`${option} expects a path`);
}
 
function parseHighSpeedArg(raw: string | undefined): number {
  const parsed = Number.parseFloat(raw ?? '');
  Iif (!Number.isFinite(parsed)) {
    throw new Error('--high-speed expects a numeric value');
  }
  if (parsed < MIN_HIGH_SPEED || parsed > MAX_HIGH_SPEED) {
    throw new Error(`--high-speed must be between ${MIN_HIGH_SPEED} and ${MAX_HIGH_SPEED}`);
  }
  const steps = parsed / HIGH_SPEED_STEP;
  const roundedSteps = Math.round(steps);
  if (Math.abs(steps - roundedSteps) > 1e-9) {
    throw new Error(`--high-speed must be in ${HIGH_SPEED_STEP} increments`);
  }
  return roundedSteps * HIGH_SPEED_STEP;
}
 
function parseTuiFPSArg(raw: string | undefined): number {
  const parsed = Number.parseFloat(raw ?? '');
  if (!Number.isFinite(parsed)) {
    throw new Error('--tui-fps expects a numeric value');
  }
  if (parsed <= 0) {
    throw new Error('--tui-fps must be greater than 0');
  }
  return parsed;
}
 
function parseTUIVisibleNotesLimitArg(raw: string | undefined): number {
  const parsed = Number.parseInt(raw ?? '', 10);
  if (!Number.isFinite(parsed)) {
    throw new Error('--tui-visible-notes-limit expects an integer value');
  }
  if (parsed <= 0) {
    throw new Error('--tui-visible-notes-limit must be greater than 0');
  }
  return parsed;
}
 
function parseTUINoteHeightArg(raw: string | undefined): TUINoteHeight {
  if (raw === 'full') {
    return MAX_TUI_NOTE_HEIGHT;
  }
  if (raw === 'half') {
    return TUI_NOTE_HEIGHT_HALF;
  }
  const parsed = Number.parseInt(raw ?? '', 10);
  if (
    Number.isFinite(parsed) &&
    parsed >= MIN_TUI_NOTE_HEIGHT &&
    parsed <= MAX_TUI_NOTE_HEIGHT &&
    Number.isInteger(parsed)
  ) {
    return parsed as TUINoteHeight;
  }
  throw new Error('--tui-note-height must be an integer from 1 to 8, or the alias full or half');
}
 
function parseImageResizeAlgorithmArg(raw: string | undefined): ImageResizeAlgorithm {
  if (typeof raw === 'string' && isImageResizeAlgorithm(raw)) {
    return raw;
  }
  throw new Error('--image-resize-algorithm must be one of: nearest, lanczos');
}
 
export function printUsage(): void {
  process.stdout.write(
    [
      'Usage: bms-player <input.(bms|bme|bml|pms|bmson|n2s|lrs|json)|directory> [options]',
      '',
      'Essential options:',
      '  --auto                    Enable auto play mode (default: off)',
      '  --auto-scratch            Enable scratch auto mode (16ch/26ch only)',
      '  --speed <rate>            Playback speed multiplier (default: 1)',
      `  --tui-fps <value>        Target TUI refresh rate while playing (default: ${DEFAULT_TUI_FPS})`,
      `  --tui-visible-notes-limit <count>  Max notes considered in the visible render window (default: ${DEFAULT_TUI_VISIBLE_NOTES_LIMIT})`,
      `  --tui-note-height <level> Height of regular notes and judge line: 1-8, or full/half aliases (default: ${DEFAULT_TUI_NOTE_HEIGHT})`,
      '  --high-speed <rate>       TUI note fall speed multiplier, 0.5-10.0 in 0.5 steps (default: 1.0)',
      '  --audio / --no-audio      Enable or disable in-game audio playback (default: on)',
      '                           Audio backend: node-web-audio-api (fixed)',
      '  --tui / --no-tui          Enable or disable TUI play screen (default: on in TTY)',
      '                           When disabled, playback runs in AUTO mode and prints realtime trigger logs',
      '  --kitty-graphics          Enable Kitty graphics protocol BGA rendering when supported (default: on)',
      '  --no-kitty-graphics       Disable Kitty graphics protocol BGA rendering',
      '  --video-bga-streaming     Stream video BGA frames progressively (default: on)',
      '  --no-video-bga-streaming  Decode full video BGA before playback (legacy behavior)',
      `  --image-resize-algorithm <nearest|lanczos>  Resize algorithm for BGA/BANNER/STAGEFILE images (default: ${DEFAULT_IMAGE_RESIZE_ALGORITHM})`,
      '  --log-file <path>         Write structured NDJSON logs to a file',
      '                           Default: ~/.be-music/logs/player.ndjson',
      '',
      'Advanced tuning:',
      '  --show-invisible-notes    Show invisible channels (31-39/41-49) in TUI as green notes',
      '  --ln-type-auto            Auto-detect omitted BMS #LNTYPE (default: Type 1)',
      '  --no-ln-type-auto         Disable BMS #LNTYPE auto-detection when omitted',
      '  --render-audio <path>     Render audio preview before playing',
      '  --volume <value>          Global volume multiplier applied before bus-specific volumes (default: 1)',
      '  --bgm-volume <value>      Volume multiplier for non-play lanes (default: 1, 0 disables BGM)',
      '  --key-volume <value>      Volume multiplier for playable/key sounds (alias: --play-volume, default: 1)',
      '  --audio-tail <seconds>    Audio tail length when rendering playback buffer (default: 1.5)',
      '  --compressor / --no-compressor',
      '                            Enable or disable output compressor (default: on)',
      '  --compressor-threshold-db Compressor threshold in dBFS (default: -12)',
      '  --compressor-ratio        Compressor ratio (default: 2.5)',
      '  --compressor-attack-ms    Compressor attack time in ms (default: 8)',
      '  --compressor-release-ms   Compressor release time in ms (default: 120)',
      '  --compressor-makeup-db    Compressor makeup gain in dB (default: 0)',
      '  --limiter / --no-limiter  Enable or disable output limiter (default: on)',
      '  --limiter-ceiling-db      Limiter ceiling in dBFS (default: -0.3)',
      '  --limiter-release-ms      Limiter release time in ms (default: 80)',
      '  --audio-head-padding-ms   Silent head padding before chart start (default: 0)',
      '  --audio-lead-ms <ms>      Base lead time for real-time mixer scheduling (default: 10)',
      '  --audio-lead-max-ms <ms>  Maximum adaptive lead time under heavy load (default: 32)',
      '  --audio-lead-step-up-ms   Adaptive lead increment step (default: 1.5)',
      '  --audio-lead-step-down-ms Adaptive lead decrement step (default: 0.5)',
      '',
      'Developer/debug:',
      '  --debug-active-audio      Show currently sounding key-sound filenames on play screen (default: off)',
      '  --bmson-total-mode <mode>  bmson TOTAL 0: beatoraja (default) | spec (no recovery)',
      '  --ruleset <name>       Compat ruleset: lr2 (default) | beatoraja | ____ | plugout',
      `  --gauge <name>         Gauge: GROOVE (default) | ${CLI_GAUGES.slice(1).join(' | ')},`,
      "                         or <source>:<NAME> for a source's gauge under any ruleset (lr2:HARD, beatoraja:EX-HARD)",
      '  --no-end-on-failure    Keep playing after a survival gauge empties (default: the play ends there)',
      '  --debug-judge-window <ms> Override BAD window for debugging',
    ].join('\n') + '\n',
  );
}