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 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 | 9x 7598x 9x 38x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 23x 23x 23x 23x 23x 22x 23x 23x 23x 23x 23x 23x 23x 23x 23x 31x 31x 22x 22x 22x 23x 23x 23x 23x 23x 23x 22x 22x 8x 8x 8x 14x 14x 23x 23x 23x 23x 23x 23x 23x 23x 23x 7x 7x 7x 7x 23x 14x 14x 14x 14x 14x 14x 12x 23x 12x 12x 22326x 7364x 7364x 3099x 5x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 5x 11x 11x 6x 2x 4x 9x 9x 11x 2x 7x 11x 2x 2x 3x 18x 18x 18x 18x 18x 18x 18x 10x 8x 7357x 19x 19x 1x 1x 18x 18x 18x 18x 18x 18x 18x 18x 4x 29x 29x 29x 29x 14x 14x 2652x 2652x 2652x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 6x 6x 6x 6x 6x 6x 11x 9x 5x 5x 5x 9x 9x 9x 5x 11x 11x 6x 6x 3x 3x 3x 11x 7352x 7352x 13x 13x 13x 3x 10x 10x 7352x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 7364x 7364x 7364x 7364x 7364x 12x 7352x 1882112x 1882112x 1882112x 1882112x 7352x 7352x 1882112x 1882112x 1882112x 1882112x 964096x 964096x 964096x 964096x 964096x 964096x 964096x 964096x 964096x 964096x 964096x 964096x 964096x 1882112x 1882112x 7352x 7352x 7352x 7352x 7352x 7352x 12x 5x 7x 7364x 7364x 7364x 14945x 14945x 14945x 14945x 7359x 7586x 7586x 7586x 7352x 7352x 7352x 7352x 7352x 7352x 7352x 7352x 7352x 7352x 6700x 652x 623x 7352x 7352x 7352x 67x 7352x 22x 22x 22x 22x 22x 22x 22x 22x 22x 5x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 51x 51x 51x 51x 51x 51x 51x 51x 156x 156x 3x 22x 22x 22x 22x 22x 1x 22x 22x 22x 22x 22x 30x 30x 30x 30x 30x 30x 22x 14x 14x 15x 14x 22x 22x 22x 22x 37x 22x 5x 22x 22x 22x 22x 22x 22x 22x 22x 66x 64x 2x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 1x 4x 4x 4x 2x 2x 22x 22x 22x | import {
collectBmsWAVVolumeMultipliers,
collectBmsWAVPlaybackModifiers,
collectLNOBJEndEvents,
isBmsBGMVolumeChangeChannel,
isBMSDynamicVolumeChangeChannel,
isBMSKeyVolumeChangeChannel,
playsAtKeysoundVolume,
parseBMSDynamicVolumeGain,
resolveBmsWAVResources,
usesMonophonicWAVPlayback,
volWAVToLinearGain,
type ResolvedChart,
type TimedSampleTrigger,
} from '@be-music/chart-model';
import {
floatToInt16,
readSampleFrame,
resolveSampleVoiceEnvelope,
resolveStereoBalance,
sampleSliceEnvelopeGain,
SAMPLE_SLICE_FADE_SECONDS,
throwIfAborted,
type SampleSliceEnvelope,
} from '@be-music/shared-utils/core';
import { type BeMusicEvent, normalizeChannel, normalizeObjectKey, resolveBMSBase } from '@be-music/chart-source';
import { type RenderResult, renderSingleSample } from '@be-music/audio-sample';
import { createNodeAudioSink, type AudioSink } from './audio-sink.ts';
import type { AudioSession, CreateAudioSessionContext, PlayerOptions } from '@be-music/player-engine';
const LANDMINE_EXPLOSION_SAMPLE_KEY = '00';
const delay = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
const PAUSE_POLL_INTERVAL_MS = 16;
const resolveDefaultBaseDir = (): string => process.cwd();
interface AudioLeadTuning {
baseLeadMs: number;
maxLeadMs: number;
stepUpMs: number;
stepDownMs: number;
}
interface OutputDynamicsConfig {
compressorEnabled: boolean;
compressorThresholdLinear: number;
compressorInvRatioMinusOne: number;
compressorAttackCoef: number;
compressorReleaseCoef: number;
compressorMakeupGain: number;
limiterEnabled: boolean;
limiterCeilingLinear: number;
limiterReleaseCoef: number;
}
interface PlayableNotePlayback {
offsetSeconds: number;
durationSeconds?: number;
sliceId?: string;
/** A trigger's own gain, balance, rate and ramps (an LRX note's); see `TimedSampleTrigger`. */
gain?: number;
pan?: number;
rate?: number;
attackSeconds?: number;
releaseSeconds?: number;
}
const AUTO_AUDIO_CHUNK_FRAMES = 256;
const MANUAL_AUDIO_CHUNK_FRAMES = 256;
const MANUAL_AUDIO_TARGET_LEAD_MS = 10;
const AUTO_AUDIO_TARGET_LEAD_MS = MANUAL_AUDIO_TARGET_LEAD_MS;
const AUDIO_TARGET_LEAD_MAX_MS = 32;
const AUDIO_TARGET_LEAD_STEP_UP_MS = 1.5;
const AUDIO_TARGET_LEAD_STEP_DOWN_MS = 0.5;
const DEBUG_ACTIVE_AUDIO_FALLBACK_SECONDS = 0.18;
const DEBUG_ACTIVE_AUDIO_SAMPLE_RATE = 44_100;
const RUNTIME_AUDIO_SAMPLE_RATE = 44_100;
const DEFAULT_COMPRESSOR_THRESHOLD_DB = -12;
const DEFAULT_COMPRESSOR_RATIO = 2.5;
const DEFAULT_COMPRESSOR_ATTACK_MS = 8;
const DEFAULT_COMPRESSOR_RELEASE_MS = 120;
const DEFAULT_COMPRESSOR_MAKEUP_DB = 0;
const DEFAULT_LIMITER_CEILING_DB = -0.3;
const DEFAULT_LIMITER_RELEASE_MS = 80;
/** Load the resolved chart's samples and open a Node realtime playback session. */
export async function createNodeAudioSession({
resolvedChart: resolved,
options,
mode,
onLoadProgress,
}: CreateAudioSessionContext): Promise<AudioSession | undefined> {
const json = resolved.source;
const wavResources = resolveBmsWAVResources(json);
throwIfAborted(options.signal);
const writeOutput =
options.writeOutput ??
((text: string): void => {
process.stdout.write(text);
});
if (options.audio === false) return undefined;
const headPaddingMs = options.audioHeadPaddingMs ?? 0;
const masterVolume = normalizeMasterVolume(options.volume);
const bgmVolume = normalizeBGMVolume(options.bgmVolume, masterVolume);
const playVolume = normalizePlayVolume(options.playVolume, masterVolume);
const chartWAVGain = volWAVToLinearGain(json.bms.volWAV);
const lnobjEndEvents = collectLNOBJEndEvents(json);
const runtimeSampleRate = RUNTIME_AUDIO_SAMPLE_RATE;
onLoadProgress?.({
ratio: 0.05,
message: 'Preparing real-time key sounds...',
});
throwIfAborted(options.signal);
const samplesByKey = await buildRuntimeSampleMap(
resolved,
options,
runtimeSampleRate,
(progress) => {
const ratio = progress.total <= 0 ? 1 : progress.loaded / progress.total;
onLoadProgress?.({
ratio: 0.08 + Math.max(0, Math.min(1, ratio)) * 0.72,
message: `Loading key sounds... (${progress.loaded}/${progress.total})`,
detail: progress.samplePath ?? progress.sampleKey,
});
},
chartWAVGain,
options.signal,
);
// Cache the chart's object-ID radix so the per-event runtime lookup below uses the same case-sensitivity as the keys
// in `samplesByKey` (which were extracted from `json.resources.wav` and therefore mirror the chart's authored case).
const runtimeSampleIdBase = resolveBMSBase(json);
throwIfAborted(options.signal);
onLoadProgress?.({
ratio: 0.82,
message: 'Initializing audio backend...',
});
const background = createSilentRenderResult(runtimeSampleRate);
const sampleRate = toPlaybackSampleRate(background.sampleRate, options.speed ?? 1);
const samplesPerFrame = mode === 'manual' ? MANUAL_AUDIO_CHUNK_FRAMES : AUTO_AUDIO_CHUNK_FRAMES;
const leadTuning = createAudioLeadTuning(options, mode);
const outputDynamics = createOutputDynamicsConfig(options, sampleRate);
const output = await createNodeAudioSink({
sampleRate,
channels: 2,
samplesPerFrame,
mode,
signal: options.signal,
});
throwIfAborted(options.signal);
if (!output) {
writeOutput('Audio playback disabled: node-web-audio-api is unavailable.\n');
onLoadProgress?.({
ratio: 1,
message: 'Audio unavailable.',
});
return undefined;
}
const eventPlaybackMap = buildEventPlaybackMap(resolved);
onLoadProgress?.({
ratio: 1,
message: 'Audio ready.',
});
let closed = false;
let abortRequested = false;
let draining = false;
let paused = false;
let playbackTask: Promise<void> | undefined;
const activeVoices: ActiveVoice[] = [];
let currentBGMDynamicGain = 1;
let currentPlayDynamicGain = 1;
output.onError(() => {
writeOutput(`Audio playback stream error (${output.label}).\n`);
});
const finish = async (): Promise<void> => {
Iif (closed) {
return;
}
draining = true;
Iif (!playbackTask) {
return;
}
await playbackTask.catch(() => undefined);
};
const dispose = async (): Promise<void> => {
Iif (closed) {
return;
}
closed = true;
abortRequested = true;
draining = true;
output.destroy();
if (playbackTask) {
await Promise.race([playbackTask.catch(() => undefined), delay(300)]);
}
};
return {
backendLabel: output.label,
start: () => {
Iif (closed || playbackTask) {
return;
}
playbackTask = playMixedPCMThroughOutput({
output,
background,
activeVoices,
shouldStop: () => abortRequested,
isDraining: () => draining,
isPaused: () => paused,
mode,
leadTuning,
outputDynamics,
playbackSampleRate: sampleRate,
}).catch(() => undefined);
},
finish,
dispose,
chartStartDelayMs: headPaddingMs,
getClockState: () => output.getClockState(),
pause: () => {
if (closed) {
return;
}
paused = true;
void output.suspend();
},
resume: () => {
if (closed) {
return;
}
paused = false;
void output.resume();
},
getActiveAudioFiles: () => collectActiveAudioFileNames(activeVoices),
getActiveAudioVoiceCount: () => activeVoices.length,
triggerEvent: (event: BeMusicEvent) => {
Iif (draining || abortRequested || paused) {
return;
}
const normalizedChannel = normalizeChannel(event.channel);
Iif (isBMSDynamicVolumeChangeChannel(normalizedChannel)) {
const dynamicGain = parseBMSDynamicVolumeGain(event.value);
if (dynamicGain === undefined) {
return;
}
if (isBMSKeyVolumeChangeChannel(normalizedChannel)) {
currentPlayDynamicGain = dynamicGain;
} else if (isBmsBGMVolumeChangeChannel(normalizedChannel)) {
currentBGMDynamicGain = dynamicGain;
}
return;
}
Iif (lnobjEndEvents.has(event)) {
return;
}
const normalized = normalizeObjectKey(event.value, runtimeSampleIdBase, json.sourceFormat === 'bmson');
const sample = samplesByKey.get(normalized);
Iif (!sample) {
return;
}
const playback = eventPlaybackMap.get(event);
const window = resolveVoiceFrameWindow(sample.left.length, sample.sampleRate, playback);
Iif (!window) {
return;
}
if (usesMonophonicWAVPlayback(json, normalized)) {
removeActiveVoicesInPlace(activeVoices, (voice) => voice.sampleKey === normalized);
}
const startSeconds = output.getClockState().outputSeconds;
if (playback?.sliceId) {
if (activeVoices.some((voice) => voice.sliceId === playback.sliceId && voice.startSeconds === startSeconds)) {
return;
}
removeActiveVoicesInPlace(activeVoices, (voice) => voice.sliceId === playback.sliceId);
}
const isPlayLaneSound = playsAtKeysoundVolume(normalizedChannel, event);
const voiceGain =
(isPlayLaneSound ? playVolume : bgmVolume) *
(isPlayLaneSound ? currentPlayDynamicGain : currentBGMDynamicGain) *
(playback?.gain ?? 1);
if (voiceGain <= 0) {
return;
}
const balance = resolveStereoBalance(playback?.pan ?? 0);
activeVoices.push({
sample,
...window,
channel: normalizeChannel(event.channel),
sampleKey: normalized,
samplePath: wavResources[normalized],
sliceId: playback?.sliceId,
startSeconds,
gain: voiceGain,
...(playback?.rate !== undefined && playback.rate > 0 && playback.rate !== 1 ? { rate: playback.rate } : {}),
...(balance.left !== 1 || balance.right !== 1 ? { leftGain: balance.left, rightGain: balance.right } : {}),
});
},
stopChannel:
mode === 'manual'
? (channel: string) => {
Iif (paused) {
return;
}
const normalizedChannel = normalizeChannel(channel);
removeActiveVoicesInPlace(activeVoices, (voice) => voice.channel === normalizedChannel);
}
: undefined,
};
}
export interface ActiveVoice {
sample: RenderResult;
/** Source frame the voice started at, which a slice envelope is measured from. */
startPosition: number;
position: number;
endPosition: number;
slice?: VoiceSlice;
channel?: string;
sampleKey?: string;
samplePath?: string;
sliceId?: string;
startSeconds?: number;
gain: number;
/** Source frames the voice moves on per output frame (an LRX note's `frq`); 1 when absent. */
rate?: number;
/** Per-channel gains of the voice's stereo balance (an LRX note's `pan`); 1 when absent. */
leftGain?: number;
rightGain?: number;
}
/** A slice window that cuts its source file, with the ramps that keep the cut from clicking. */
interface VoiceSlice {
lengthFrames: number;
envelope: SampleSliceEnvelope;
}
/**
* The source frames a triggered sample plays. A bmson slice that cuts its file fades in where it starts inside the
* file and rings on past its end while it fades out, so the window grows by the fade-out.
*/
export function resolveVoiceFrameWindow(
sampleLength: number,
sampleRate: number,
playback: PlayableNotePlayback | undefined,
): Pick<ActiveVoice, 'startPosition' | 'position' | 'endPosition' | 'slice'> | undefined {
const offsetFrames = Math.max(0, Math.round((playback?.offsetSeconds ?? 0) * sampleRate));
const requestedFrames =
typeof playback?.durationSeconds === 'number' && Number.isFinite(playback.durationSeconds)
? Math.max(1, Math.round(playback.durationSeconds * sampleRate))
: undefined;
const lengthFrames = Math.min(sampleLength - offsetFrames, requestedFrames ?? sampleLength);
Iif (lengthFrames <= 0) {
return undefined;
}
const window = { startPosition: offsetFrames, position: offsetFrames, endPosition: offsetFrames + lengthFrames };
const envelope = resolveSampleVoiceEnvelope(
offsetFrames,
requestedFrames,
sampleLength,
Math.round(SAMPLE_SLICE_FADE_SECONDS * sampleRate),
Math.round((playback?.attackSeconds ?? 0) * sampleRate),
Math.round((playback?.releaseSeconds ?? 0) * sampleRate),
);
if (envelope.fadeIn === 0 && envelope.fadeOut === 0) {
return window;
}
return { ...window, endPosition: window.endPosition + envelope.fadeOut, slice: { lengthFrames, envelope } };
}
/** Adds up to `chunkFrames` of every active voice, from its current position, onto the mix. */
export function mixActiveVoices(
mixedLeft: Float32Array,
mixedRight: Float32Array,
activeVoices: readonly ActiveVoice[],
chunkFrames: number,
): void {
// Voice-major accumulation removes a per-sample boundary branch from the hot path.
for (let voiceIndex = 0; voiceIndex < activeVoices.length; voiceIndex += 1) {
const voice = activeVoices[voiceIndex]!;
if (voice.rate !== undefined || voice.leftGain !== undefined) {
mixShapedVoice(mixedLeft, mixedRight, voice, chunkFrames);
continue;
}
const voiceFrames = Math.min(chunkFrames, voice.endPosition - voice.position);
Iif (voiceFrames <= 0) {
continue;
}
const voiceLeft = voice.sample.left;
const voiceRight = voice.sample.right;
const voiceGain = voice.gain;
let sourceFrame = voice.position;
const slice = voice.slice;
if (slice) {
for (let frame = 0; frame < voiceFrames; frame += 1) {
const frameGain =
voiceGain * sampleSliceEnvelopeGain(sourceFrame - voice.startPosition, slice.lengthFrames, slice.envelope);
mixedLeft[frame] += voiceLeft[sourceFrame] * frameGain;
mixedRight[frame] += voiceRight[sourceFrame] * frameGain;
sourceFrame += 1;
}
} else if (Math.abs(voiceGain - 1) <= 1e-9) {
for (let frame = 0; frame < voiceFrames; frame += 1) {
mixedLeft[frame] += voiceLeft[sourceFrame];
mixedRight[frame] += voiceRight[sourceFrame];
sourceFrame += 1;
}
} else E{
for (let frame = 0; frame < voiceFrames; frame += 1) {
mixedLeft[frame] += voiceLeft[sourceFrame] * voiceGain;
mixedRight[frame] += voiceRight[sourceFrame] * voiceGain;
sourceFrame += 1;
}
}
}
}
/** {@link mixActiveVoices} for a voice with its own rate or balance: it reads its source `rate` frames per output frame. */
function mixShapedVoice(
mixedLeft: Float32Array,
mixedRight: Float32Array,
voice: ActiveVoice,
chunkFrames: number,
): void {
const rate = voice.rate ?? 1;
const leftGain = voice.gain * (voice.leftGain ?? 1);
const rightGain = voice.gain * (voice.rightGain ?? 1);
const slice = voice.slice;
let sourceFrame = voice.position;
for (let frame = 0; frame < chunkFrames && sourceFrame < voice.endPosition; frame += 1) {
const envelope = slice
? sampleSliceEnvelopeGain(sourceFrame - voice.startPosition, slice.lengthFrames, slice.envelope)
: 1;
mixedLeft[frame] += readSampleFrame(voice.sample.left, sourceFrame) * leftGain * envelope;
mixedRight[frame] += readSampleFrame(voice.sample.right, sourceFrame) * rightGain * envelope;
sourceFrame += rate;
}
}
function collectActiveAudioFileNames(activeVoices: ActiveVoice[]): string[] {
const unique = new Set<string>();
for (const voice of activeVoices) {
const label = voice.samplePath ?? voice.sampleKey;
if (typeof label !== 'string' || label.length === 0) {
continue;
}
unique.add(label);
}
return [...unique];
}
/** Decode each referenced sample once to supply lengths for active-audio diagnostics. */
export async function loadNodeAudioSampleDurations(
resolved: ResolvedChart,
options: { baseDir?: string; signal?: AbortSignal } = {},
): Promise<Map<string, number>> {
const { baseDir, signal } = options;
const triggers = resolved.sampleTriggers;
const base = resolveBMSBase(resolved.source);
throwIfAborted(signal);
const uniqueTriggers = new Map<string, TimedSampleTrigger>();
for (const trigger of triggers) {
if (!uniqueTriggers.has(trigger.sampleKey)) {
uniqueTriggers.set(trigger.sampleKey, trigger);
}
}
const durations = new Map<string, number>();
const playbackModifiers = collectBmsWAVPlaybackModifiers(resolved.source);
for (const trigger of uniqueTriggers.values()) {
throwIfAborted(signal);
const rendered = await renderSingleSample(trigger.sampleKey, trigger.samplePath, {
baseDir: baseDir ?? resolveDefaultBaseDir(),
pathPrefix: resolved.source.bms.pathWAV,
sampleRate: DEBUG_ACTIVE_AUDIO_SAMPLE_RATE,
gain: 1,
fallbackToneSeconds: DEBUG_ACTIVE_AUDIO_FALLBACK_SECONDS,
signal,
base,
playbackModifiers: playbackModifiers.get(trigger.sampleKey),
});
durations.set(trigger.sampleKey, rendered.durationSeconds);
}
return durations;
}
function removeActiveVoicesInPlace(activeVoices: ActiveVoice[], shouldRemove: (voice: ActiveVoice) => boolean): void {
let writeIndex = 0;
for (let readIndex = 0; readIndex < activeVoices.length; readIndex += 1) {
const voice = activeVoices[readIndex]!;
if (shouldRemove(voice)) {
continue;
}
Iif (writeIndex !== readIndex) {
activeVoices[writeIndex] = voice;
}
writeIndex += 1;
}
activeVoices.length = writeIndex;
}
function advanceAndPruneActiveVoices(activeVoices: ActiveVoice[], chunkFrames: number): void {
let writeIndex = 0;
for (let readIndex = 0; readIndex < activeVoices.length; readIndex += 1) {
const voice = activeVoices[readIndex]!;
voice.position += chunkFrames * (voice.rate ?? 1);
if (voice.position >= voice.endPosition) {
continue;
}
Iif (writeIndex !== readIndex) {
activeVoices[writeIndex] = voice;
}
writeIndex += 1;
}
activeVoices.length = writeIndex;
}
async function playMixedPCMThroughOutput(params: {
output: AudioSink;
background: RenderResult;
activeVoices: ActiveVoice[];
shouldStop: () => boolean;
isDraining: () => boolean;
isPaused: () => boolean;
mode: 'auto' | 'manual';
leadTuning: AudioLeadTuning;
outputDynamics?: OutputDynamicsConfig;
playbackSampleRate: number;
}): Promise<void> {
const { output, background, activeVoices, shouldStop, isDraining, isPaused, mode, leadTuning, playbackSampleRate } =
params;
const chunkFrames = mode === 'manual' ? MANUAL_AUDIO_CHUNK_FRAMES : AUTO_AUDIO_CHUNK_FRAMES;
// Keep one reusable PCM buffer and fill through Int16Array to minimize per-sample write overhead.
const chunkSamples = new Int16Array(chunkFrames * 2);
const chunk = new Uint8Array(chunkSamples.buffer);
const mixedLeft = new Float32Array(chunkFrames);
const mixedRight = new Float32Array(chunkFrames);
const backgroundLeft = background.left;
const backgroundRight = background.right;
const backgroundLength = backgroundLeft.length;
let playhead = 0;
const outputStartSeconds = output.getClockState().outputSeconds;
let adaptiveLeadMs = leadTuning.baseLeadMs;
const chunkDurationMs = (chunkFrames / playbackSampleRate) * 1000;
const outputDynamics = params.outputDynamics;
let compressorGain = 1;
let limiterGain = 1;
while (!shouldStop()) {
Iif (isPaused()) {
await delay(PAUSE_POLL_INTERVAL_MS);
continue;
}
const mixStartedAtMs = performance.now();
await waitForPlaybackRealtime(output, playhead, playbackSampleRate, outputStartSeconds, shouldStop, adaptiveLeadMs);
const backgroundEnded = playhead >= background.left.length;
if (isDraining() && backgroundEnded && activeVoices.length === 0) {
break;
}
for (let frame = 0; frame < chunkFrames; frame += 1) {
const sourceFrame = playhead + frame;
Iif (sourceFrame < backgroundLength) {
mixedLeft[frame] = backgroundLeft[sourceFrame];
mixedRight[frame] = backgroundRight[sourceFrame];
} else {
mixedLeft[frame] = 0;
mixedRight[frame] = 0;
}
}
mixActiveVoices(mixedLeft, mixedRight, activeVoices, chunkFrames);
for (let frame = 0; frame < chunkFrames; frame += 1) {
const sampleOffset = frame * 2;
let leftSample = mixedLeft[frame];
let rightSample = mixedRight[frame];
if (outputDynamics) {
const level = Math.max(Math.abs(leftSample), Math.abs(rightSample));
Iif (outputDynamics.compressorEnabled) {
const desiredCompressorGain =
level > outputDynamics.compressorThresholdLinear
? Math.pow(level / outputDynamics.compressorThresholdLinear, outputDynamics.compressorInvRatioMinusOne)
: 1;
const compressorCoef =
desiredCompressorGain < compressorGain
? outputDynamics.compressorAttackCoef
: outputDynamics.compressorReleaseCoef;
compressorGain = desiredCompressorGain + compressorCoef * (compressorGain - desiredCompressorGain);
} else {
compressorGain = 1;
}
const compressorAppliedGain = compressorGain * outputDynamics.compressorMakeupGain;
leftSample *= compressorAppliedGain;
rightSample *= compressorAppliedGain;
if (outputDynamics.limiterEnabled) {
const limitedLevel = Math.max(Math.abs(leftSample), Math.abs(rightSample));
const desiredLimiterGain =
limitedLevel > outputDynamics.limiterCeilingLinear && limitedLevel > 1e-9
? outputDynamics.limiterCeilingLinear / limitedLevel
: 1;
Iif (desiredLimiterGain < limiterGain) {
// Limiter attack is immediate to avoid transient clipping.
limiterGain = desiredLimiterGain;
} else {
limiterGain = desiredLimiterGain + outputDynamics.limiterReleaseCoef * (limiterGain - desiredLimiterGain);
}
leftSample *= limiterGain;
rightSample *= limiterGain;
} else E{
limiterGain = 1;
}
}
chunkSamples[sampleOffset] = floatToInt16(leftSample);
chunkSamples[sampleOffset + 1] = floatToInt16(rightSample);
}
advanceAndPruneActiveVoices(activeVoices, chunkFrames);
playhead += chunkFrames;
const writable = output.write(chunk);
Iif (!writable) {
await output.waitWritable(shouldStop);
}
const mixDurationMs = Math.max(0, performance.now() - mixStartedAtMs);
adaptiveLeadMs = resolveAdaptiveLeadMs(
adaptiveLeadMs,
leadTuning,
chunkDurationMs,
mixDurationMs,
activeVoices.length,
);
}
if (shouldStop()) {
return;
}
await output.end();
}
async function waitForPlaybackRealtime(
output: AudioSink,
playheadFrames: number,
sampleRate: number,
startOutputSeconds: number,
shouldStop: () => boolean,
targetLeadMs: number,
): Promise<void> {
const safeTargetLeadMs = Number.isFinite(targetLeadMs) ? Math.max(0, targetLeadMs) : MANUAL_AUDIO_TARGET_LEAD_MS;
const targetLeadFrames = Math.max(0, Math.round((safeTargetLeadMs / 1000) * sampleRate));
while (!shouldStop()) {
const outputSeconds = Math.max(0, output.getClockState().outputSeconds - startOutputSeconds);
const elapsedFrames = Math.floor(outputSeconds * sampleRate);
const leadFrames = playheadFrames - elapsedFrames;
if (leadFrames <= targetLeadFrames) {
return;
}
const waitFrames = leadFrames - targetLeadFrames;
const waitMs = Math.max(1, Math.ceil((waitFrames / sampleRate) * 1000));
await delay(Math.min(waitMs, 3));
}
}
function resolveAdaptiveLeadMs(
currentLeadMs: number,
tuning: AudioLeadTuning,
chunkDurationMs: number,
mixDurationMs: number,
activeVoiceCount: number,
): number {
const safeBaseLeadMs = Number.isFinite(tuning.baseLeadMs) ? Math.max(0, tuning.baseLeadMs) : 0;
const safeMaxLeadMs = Number.isFinite(tuning.maxLeadMs)
? Math.max(safeBaseLeadMs, tuning.maxLeadMs)
: AUDIO_TARGET_LEAD_MAX_MS;
const safeStepUpMs =
Number.isFinite(tuning.stepUpMs) && tuning.stepUpMs > 0 ? tuning.stepUpMs : AUDIO_TARGET_LEAD_STEP_UP_MS;
const safeStepDownMs =
Number.isFinite(tuning.stepDownMs) && tuning.stepDownMs > 0 ? tuning.stepDownMs : AUDIO_TARGET_LEAD_STEP_DOWN_MS;
const safeCurrentLeadMs = Number.isFinite(currentLeadMs) ? Math.max(0, currentLeadMs) : safeBaseLeadMs;
const safeChunkDurationMs = Number.isFinite(chunkDurationMs) ? Math.max(1, chunkDurationMs) : 1;
const safeMixDurationMs = Number.isFinite(mixDurationMs) ? Math.max(0, mixDurationMs) : 0;
const loadRatio = safeMixDurationMs / safeChunkDurationMs;
let nextLeadMs = safeCurrentLeadMs;
if (loadRatio >= 0.7) {
nextLeadMs += safeStepUpMs;
} else if (loadRatio <= 0.45) {
nextLeadMs -= safeStepDownMs;
}
// Keep small baseline latency while granting temporary headroom for dense chord bursts.
const polyphonyFloorMs = safeBaseLeadMs + Math.max(0, activeVoiceCount - 24) * 0.2;
const minLeadMs = Math.max(safeBaseLeadMs, Math.min(safeMaxLeadMs, polyphonyFloorMs));
if (nextLeadMs < minLeadMs) {
nextLeadMs = minLeadMs;
}
return Math.min(safeMaxLeadMs, nextLeadMs);
}
function createAudioLeadTuning(options: PlayerOptions, mode: 'auto' | 'manual'): AudioLeadTuning {
const defaultBaseLeadMs = mode === 'manual' ? MANUAL_AUDIO_TARGET_LEAD_MS : AUTO_AUDIO_TARGET_LEAD_MS;
const baseLeadMs = resolvePositiveNumberOption(options.audioLeadMs, defaultBaseLeadMs);
const maxLeadMs = Math.max(baseLeadMs, resolvePositiveNumberOption(options.audioLeadMaxMs, AUDIO_TARGET_LEAD_MAX_MS));
const stepUpMs = resolvePositiveNumberOption(options.audioLeadStepUpMs, AUDIO_TARGET_LEAD_STEP_UP_MS);
const stepDownMs = resolvePositiveNumberOption(options.audioLeadStepDownMs, AUDIO_TARGET_LEAD_STEP_DOWN_MS);
return {
baseLeadMs,
maxLeadMs,
stepUpMs,
stepDownMs,
};
}
function createOutputDynamicsConfig(options: PlayerOptions, sampleRate: number): OutputDynamicsConfig | undefined {
const limiterEnabled = options.limiter !== false;
const compressorEnabled = Boolean(options.compressor);
if (!limiterEnabled && !compressorEnabled) {
return undefined;
}
const compressorThresholdDb = Math.min(
0,
resolveFiniteNumberOption(options.compressorThresholdDb, DEFAULT_COMPRESSOR_THRESHOLD_DB),
);
const compressorThresholdLinear = Math.max(1e-4, dbToLinear(compressorThresholdDb));
const compressorRatio = Math.max(
1.01,
resolvePositiveNumberOption(options.compressorRatio, DEFAULT_COMPRESSOR_RATIO),
);
const compressorInvRatioMinusOne = 1 / compressorRatio - 1;
const compressorAttackMs = resolvePositiveNumberOption(options.compressorAttackMs, DEFAULT_COMPRESSOR_ATTACK_MS);
const compressorReleaseMs = resolvePositiveNumberOption(options.compressorReleaseMs, DEFAULT_COMPRESSOR_RELEASE_MS);
const compressorMakeupDb = resolveFiniteNumberOption(options.compressorMakeupDb, DEFAULT_COMPRESSOR_MAKEUP_DB);
const compressorMakeupGain = dbToLinear(compressorMakeupDb);
const limiterCeilingDb = Math.min(0, resolveFiniteNumberOption(options.limiterCeilingDb, DEFAULT_LIMITER_CEILING_DB));
const limiterCeilingLinear = Math.max(1e-4, dbToLinear(limiterCeilingDb));
const limiterReleaseMs = resolvePositiveNumberOption(options.limiterReleaseMs, DEFAULT_LIMITER_RELEASE_MS);
return {
compressorEnabled,
compressorThresholdLinear,
compressorInvRatioMinusOne,
compressorAttackCoef: resolveTimeSmoothingCoef(compressorAttackMs, sampleRate),
compressorReleaseCoef: resolveTimeSmoothingCoef(compressorReleaseMs, sampleRate),
compressorMakeupGain,
limiterEnabled,
limiterCeilingLinear,
limiterReleaseCoef: resolveTimeSmoothingCoef(limiterReleaseMs, sampleRate),
};
}
function resolveFiniteNumberOption(value: number | undefined, fallback: number): number {
Eif (typeof value !== 'number' || !Number.isFinite(value)) {
return fallback;
}
return value;
}
function resolveTimeSmoothingCoef(timeMs: number, sampleRate: number): number {
const safeTimeMs = Number.isFinite(timeMs) ? Math.max(0, timeMs) : 0;
const safeSampleRate = Number.isFinite(sampleRate) ? Math.max(1, sampleRate) : 1;
Iif (safeTimeMs <= 0) {
return 0;
}
return Math.exp(-1 / ((safeTimeMs / 1000) * safeSampleRate));
}
function dbToLinear(db: number): number {
const safeDb = Number.isFinite(db) ? db : 0;
return 10 ** (safeDb / 20);
}
function resolvePositiveNumberOption(value: number | undefined, fallback: number): number {
Eif (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
return fallback;
}
return value;
}
export function shouldUseAutoMixBGMHeadroomControl(options: PlayerOptions): boolean {
return options.limiter === false;
}
async function buildRuntimeSampleMap(
resolved: ResolvedChart,
options: PlayerOptions,
sampleRate: number,
onProgress?: (progress: { loaded: number; total: number; sampleKey: string; samplePath?: string }) => void,
chartWAVGain = 1,
signal?: AbortSignal,
): Promise<Map<string, RenderResult>> {
throwIfAborted(signal);
const json = resolved.source;
const sampleMap = new Map<string, RenderResult>();
const keys = collectRealtimeAudioSampleKeys(resolved);
if (keys.length === 0) {
onProgress?.({
loaded: 0,
total: 0,
sampleKey: '',
samplePath: undefined,
});
}
const idBase = resolveBMSBase(json);
const wavResources = resolveBmsWAVResources(json);
const volumeMultipliers = collectBmsWAVVolumeMultipliers(json);
const playbackModifiers = collectBmsWAVPlaybackModifiers(json);
for (let index = 0; index < keys.length; index += 1) {
throwIfAborted(signal);
const key = keys[index];
const sourcePath = wavResources[key];
const rendered = await renderSingleSample(key, sourcePath, {
baseDir: options.audioBaseDir ?? resolveDefaultBaseDir(),
pathPrefix: json.bms.pathWAV,
sampleRate,
gain: chartWAVGain * (volumeMultipliers.get(key) ?? 1),
fallbackToneSeconds:
typeof options.missingSampleToneSeconds === 'number' &&
Number.isFinite(options.missingSampleToneSeconds) &&
options.missingSampleToneSeconds > 0
? options.missingSampleToneSeconds
: 0,
signal,
base: idBase,
playbackModifiers: playbackModifiers.get(key),
});
sampleMap.set(key, rendered);
onProgress?.({
loaded: index + 1,
total: keys.length,
sampleKey: key,
samplePath: sourcePath,
});
}
return sampleMap;
}
function buildEventPlaybackMap(resolved: ResolvedChart): Map<BeMusicEvent, PlayableNotePlayback> {
const playbackMap = new Map<BeMusicEvent, PlayableNotePlayback>();
for (const trigger of resolved.sampleTriggers) {
playbackMap.set(trigger.event, {
offsetSeconds: trigger.sampleOffsetSeconds,
durationSeconds: trigger.sampleDurationSeconds,
sliceId: trigger.sampleSliceId,
...(trigger.sampleGain !== undefined ? { gain: trigger.sampleGain } : {}),
...(trigger.samplePan !== undefined ? { pan: trigger.samplePan } : {}),
...(trigger.samplePlaybackRate !== undefined ? { rate: trigger.samplePlaybackRate } : {}),
...(trigger.sampleAttackSeconds !== undefined ? { attackSeconds: trigger.sampleAttackSeconds } : {}),
...(trigger.sampleReleaseSeconds !== undefined ? { releaseSeconds: trigger.sampleReleaseSeconds } : {}),
});
}
return playbackMap;
}
function collectRealtimeAudioSampleKeys(resolved: ResolvedChart): string[] {
const json = resolved.source;
const wavResources = resolveBmsWAVResources(json);
const keys = new Set<string>();
for (const trigger of resolved.sampleTriggers) {
keys.add(trigger.sampleKey);
}
// `#WAV00` sounds when a mine detonates: preload it when the chart has a mine on any lane, the extended 24 / 48 KEY
// lanes (`DA`–`DO` / `EA`–`EO`) and bmson `mine_channels` included.
if (
typeof wavResources[LANDMINE_EXPLOSION_SAMPLE_KEY] === 'string' &&
wavResources[LANDMINE_EXPLOSION_SAMPLE_KEY].length > 0 &&
resolved.mines.length > 0
) {
keys.add(LANDMINE_EXPLOSION_SAMPLE_KEY);
}
return [...keys];
}
function createSilentRenderResult(sampleRate: number): RenderResult {
const safeSampleRate = Number.isFinite(sampleRate)
? Math.max(8_000, Math.floor(sampleRate))
: RUNTIME_AUDIO_SAMPLE_RATE;
const left = new Float32Array(0);
const right = new Float32Array(0);
return {
sampleRate: safeSampleRate,
left,
right,
durationSeconds: 0,
peak: 0,
};
}
function normalizeBGMVolume(value: number | undefined, masterVolume = 1): number {
return normalizeBusVolume(value, masterVolume);
}
function normalizePlayVolume(value: number | undefined, masterVolume = 1): number {
return normalizeBusVolume(value, masterVolume);
}
function normalizeMasterVolume(value: number | undefined): number {
return normalizeBusVolume(value, 1);
}
function normalizeBusVolume(value: number | undefined, fallback: number): number {
if (typeof value !== 'number' || !Number.isFinite(value)) {
return fallback;
}
return Math.max(0, value) * fallback;
}
export function resolveBGMHeadroomGain(playableResult: RenderResult, bgmResult: RenderResult): number {
const playableLeft = playableResult.left;
const playableRight = playableResult.right;
const bgmLeft = bgmResult.left;
const bgmRight = bgmResult.right;
const frameLength = Math.max(playableLeft.length, bgmLeft.length);
let headroomGain = 1;
// Keep playable/key-sound amplitude intact by shrinking only the BGM side when summed peak would clip.
for (let frame = 0; frame < frameLength; frame += 1) {
const playableLeftAbs = Math.abs(playableLeft[frame] ?? 0);
const playableRightAbs = Math.abs(playableRight[frame] ?? 0);
const bgmLeftAbs = Math.abs(bgmLeft[frame] ?? 0);
const bgmRightAbs = Math.abs(bgmRight[frame] ?? 0);
headroomGain = Math.min(
headroomGain,
resolveBGMHeadroomGainForChannel(playableLeftAbs, bgmLeftAbs),
resolveBGMHeadroomGainForChannel(playableRightAbs, bgmRightAbs),
);
}
return Math.max(0, Math.min(1, headroomGain));
}
function resolveBGMHeadroomGainForChannel(playableAbs: number, bgmAbs: number): number {
Iif (bgmAbs <= 1e-9) {
return 1;
}
const availableHeadroom = 1 - playableAbs;
if (availableHeadroom <= 0) {
// Play-side already clips by itself: do not force BGM to complete silence here.
return 1;
}
return Math.min(1, availableHeadroom / bgmAbs);
}
function toPlaybackSampleRate(baseSampleRate: number, speed: number): number {
const safeSpeed = Number.isFinite(speed) && speed > 0 ? speed : 1;
const scaled = Math.round(baseSampleRate * safeSpeed);
return Math.max(8_000, Math.min(192_000, scaled));
}
|