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 | 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 33x 33x 165x 165x 150x 150x 33x 58x 739x 737x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 160x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 67x 67x 67x 67x 67x 67x 67x 67x 67x 9x 9x 9x 58x 10x 10x 10x 10x 10x 10x 48x 48x 48x 67x 67x 48x 48x 45x 45x 45x 3x 3x 40x 21x 20x 20x 6x 9x 7x 7x 7x 8x 4x 4x 5x 1x 1x 7x 6x 2x 4x 1x 3x 6x 9x 9x 9x 9x 9x 9x 9x 9x 3x 3x 6x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 160x 160x 160x 161x 161x 161x 161x 161x 13x 10x 10x 7x 3x | import { masterOutput } from './master-volume.ts';
/**
* Audio routing for the gameplay scene.
*
* Three modes are supported:
*
* - **`'split'`** (default) — separate compressors on the key-sound and BGM buses, plus a master compressor that
* catches the summed peaks. Each compressed mode trims the signal before compression, then restores most of that
* level after the compressor stack, so hot source files do not drive the compressors as hard. Each bus is tuned for
* its content: key bus is transient-aware (jacks / dense input bursts), BGM bus is gentler / more musical, master is
* a final clip-protection limiter. This pattern matches the standard mastering bus layout and prevents the BGM from
* ducking under dense input bursts (the classic single-bus failure mode).
*
* - **`'legacy'`** — the original single-compressor bus, kept for A/B comparison via the player's `?compressor=legacy`
* URL flag. Sample sources still connect to the same `keyMixer` / `bgmMixer` nodes so the gameplay code stays
* mode-agnostic; the builder just collapses both into a single compressor stage.
*
* - **`'off'`** — bypass every compressor, compressed-mode input trim, and makeup gain. The two bus mixers still pass
* through the chart-level `#VOLWAV` gain and output tap. Used by the player checkbox to compare against an unprocessed
* signal path.
*
* The graph topology stays stable across mode switches: the `keyMixer` / `bgmMixer` `GainNode`s are always the
* connection point for sample sources, so flipping the mode is a `disconnect()` + reconnect of the downstream wiring
* rather than a full rebuild. That matters because hundreds of one-shot `BufferSourceNode`s come and go per second on
* dense charts; rebuilding their connection point would be a real performance hazard.
*
* Compressor parameter values are exported as plain readonly objects so they're easy to unit-test (no `AudioContext`
* required) and easy to tweak in one place. See `audio-bus.test.ts` for sanity-range coverage.
*/
export type CompressorMode = 'split' | 'legacy' | 'off';
/**
* `DynamicsCompressorNode` parameter set (in spec units — same names as the Web Audio properties). Exported so the player
* / debug tooling can introspect the active values without reading them off a live `AudioContext`.
*/
export interface CompressorParams {
/** Threshold in dB. Compression starts above this input level. */
threshold: number;
/**
* Compression ratio (`x:1`). 1 = no compression, ∞ = limiter. We stick to `1..20` per the Web Audio spec's clamp.
*/
ratio: number;
/** Attack time in seconds. Web Audio range: 0..1. */
attack: number;
/** Release time in seconds. Web Audio range: 0..1. */
release: number;
/**
* Knee width in dB. Larger values = softer onset. Web Audio range: 0..40.
*/
knee: number;
}
/**
* Key-sound bus compressor. Tuned for punch: each hit's attack transient passes before the gain comes down, so
* keysounds keep their snap, while dense jacks and 16th-note bursts still get their summed body caught.
*
* Rationale per parameter: - `threshold = -6`: high enough that hot-but-normal hits are not constantly compressed after
* the compressor input trim, while dense same-lane bursts still cross it. - `ratio = 3`: controls bursts gently, so a
* hit's body is evened out rather than flattened. - `attack = 0.012`: slow enough that the first ~10 ms of each hit —
* the click / snap that reads as attack — passes uncompressed (the master limiter still guards the absolute peak). -
* `release = 0.08`: recovers before the next 16th at typical tempos, so one hit's gain reduction doesn't dull the next
* hit's transient. - `knee = 3`: a firmer knee keeps the onset defined instead of easing compression in early.
*/
export const KEY_BUS_COMPRESSOR_PARAMS: Readonly<CompressorParams> = {
threshold: -6,
ratio: 3,
attack: 0.012,
release: 0.08,
knee: 3,
};
/**
* BGM bus compressor. Tuned as gentle glue: it evens out the auto-triggered background bed so it sits under the
* keysounds, without the per-hit pumping of the key bus compressor.
*
* Rationale per parameter: - `threshold = -10`: works on the bed's body a little more consistently than before, so its
* level stays steady under the keysounds, while already-mastered samples see only light reduction after the input trim.
* - `ratio = 2`: glue, not squash. - `attack = 0.025`: slow enough that drum-loop kicks and snares in the BGM keep their
* own attack. - `release = 0.25`: long enough to avoid pumping on the beat grid. - `knee = 12`: soft, so the compressor
* doesn't introduce a detectable threshold artefact.
*/
export const BGM_BUS_COMPRESSOR_PARAMS: Readonly<CompressorParams> = {
threshold: -10,
ratio: 2,
attack: 0.025,
release: 0.25,
knee: 12,
};
/**
* Master bus compressor. Final clip-protection limiter. With the key / BGM compressors already shaping their respective
* buses, the master only needs to catch the summed peaks, so it's tuned as a ceiling that stays out of the way until a
* peak actually threatens to clip.
*
* Rationale per parameter: - `threshold = -1.5`: leaves explicit headroom below 0 dBFS while touching less of the
* keysound transients the key bus now lets through. - `ratio = 20`: the Web Audio maximum — a firm ceiling, so the
* limiter does its work in a few dB of peaks instead of compressing the mix. - `attack = 0.002`: still catches peaks
* within a couple of milliseconds, but no longer shaves the very front of every hit. - `release = 0.15`: slower than
* the key bus so the limiter doesn't pump or distort on sustained bass. - `knee = 1`: hard knee so it activates
* decisively at the threshold.
*/
export const MASTER_BUS_COMPRESSOR_PARAMS: Readonly<CompressorParams> = {
threshold: -1.5,
ratio: 20,
attack: 0.002,
release: 0.15,
knee: 1,
};
/**
* Legacy (pre-split) single-compressor params. Preserved verbatim from the original `prepareAudio` block so the
* `'legacy'` mode is a true byte-for-byte revert that the player can flip to via the `?compressor=legacy` URL flag.
*/
export const LEGACY_COMPRESSOR_PARAMS: Readonly<CompressorParams> = {
threshold: -8,
ratio: 4,
attack: 0.003,
release: 0.12,
knee: 6,
};
/**
* Compressor input trim (linear, not dB) applied only in compressed modes (`'split'` / `'legacy'`). This gives hot
* source files extra headroom before they hit the compressor thresholds, so normal playback stays more transparent and
* the compressors spend most of their work on real overloads.
*/
export const COMPRESSOR_INPUT_TRIM_GAIN_LINEAR: number = 10 ** (-3 / 20);
/**
* Makeup gain (linear, not dB) applied after the compressor stack. It broadly offsets
* `COMPRESSOR_INPUT_TRIM_GAIN_LINEAR`, but remains inside the master limiter path so peaks are still caught before the
* chart-level `#VOLWAV` gain and output tap.
*/
export const MASTER_MAKEUP_GAIN_LINEAR: number = 10 ** (3 / 20);
/**
* Per-mixer summing-headroom gain (linear). Each `BufferSourceNode` connects to `keyMixer` / `bgmMixer` at unity, so N
* simultaneous samples sum to amplitude N at the mixer output. With BMS charts routinely overlapping 4–6 samples (chord
* notes + scratch + BGM layers), the un-attenuated sum digital-clips at the destination (16-bit DAC clamp). Setting the
* mixer gain below unity buys `1/MIXER_HEADROOM_GAIN_LINEAR` clean voices before the compressor stack has to do
* anything; remaining peaks are caught by the master limiter.
*
* `0.5` ≈ −6 dB → ~2 simultaneous unity-amplitude samples sum to full scale. Combined with compressed-mode input trim
* and the split-bus master limiter (threshold = −2 dB, ratio 10), the perceived headroom is generous enough that
* sustained clipping is essentially impossible on typical BMS charts. Single-source playback is quieter than with unity
* mixers, but compressed modes restore a measured amount after the compressor stack; this is preferable to having the
* player surreptitiously clip.
*/
export const MIXER_HEADROOM_GAIN_LINEAR = 0.5;
/**
* Per-compressor-stage identifier used by {@link AudioBusHandle.setStageEnabled}.
*
* - `'key'` — key bus compressor (between `keyMixer` and master).
* - `'bgm'` — BGM bus compressor (between `bgmMixer` and master).
* - `'master'` — final master bus compressor.
*
* Stage toggles only have an effect in `'split'` mode. `'legacy'` has just a single compressor (toggling individual
* stages there is meaningless — use mode `'off'` to bypass it) and `'off'` is already a complete bypass.
*/
export type CompressorStage = 'key' | 'bgm' | 'master';
/** Compressor whose parameters can be tuned: the three split-mode stages, or the single `'legacy'` compressor. */
export type TunableCompressor = CompressorStage | 'legacy';
/** Factory parameters of every tunable compressor. */
export const DEFAULT_COMPRESSOR_PARAMS: Readonly<Record<TunableCompressor, Readonly<CompressorParams>>> = {
key: KEY_BUS_COMPRESSOR_PARAMS,
bgm: BGM_BUS_COMPRESSOR_PARAMS,
master: MASTER_BUS_COMPRESSOR_PARAMS,
legacy: LEGACY_COMPRESSOR_PARAMS,
};
/** Web Audio `DynamicsCompressorNode` ranges each parameter is clamped to. */
export const COMPRESSOR_PARAM_RANGES: Readonly<Record<keyof CompressorParams, { min: number; max: number }>> = {
threshold: { min: -100, max: 0 },
ratio: { min: 1, max: 20 },
attack: { min: 0, max: 1 },
release: { min: 0, max: 1 },
knee: { min: 0, max: 40 },
};
const COMPRESSOR_PARAM_KEYS: ReadonlyArray<keyof CompressorParams> = [
'threshold',
'ratio',
'attack',
'release',
'knee',
];
/**
* Merges `patch` over `base`, clamping each value into its {@link COMPRESSOR_PARAM_RANGES} range; non-finite values
* keep the base value.
*/
export function mergeCompressorParams(base: CompressorParams, patch: Partial<CompressorParams> = {}): CompressorParams {
const merged = { ...base };
for (const key of COMPRESSOR_PARAM_KEYS) {
const value = patch[key];
if (value === undefined || !Number.isFinite(value)) continue;
const { min, max } = COMPRESSOR_PARAM_RANGES[key];
merged[key] = Math.min(max, Math.max(min, value));
}
return merged;
}
/** Source bus a user volume applies to: `'key'` (player keysounds) or `'bgm'` (auto-triggered BGM). */
export type AudioBusChannel = 'key' | 'bgm';
/** Upper bound for a user bus volume (2 = +6 dB). */
export const MAX_BUS_VOLUME = 2;
/**
* Sanitizes a user bus volume (linear, 1 = unity): non-finite → unity, negative → 0, and clamped to
* {@link MAX_BUS_VOLUME} so a stray value can't blow the mix past the compressor stack's headroom.
*/
export function sanitizeBusVolume(value: number): number {
if (!Number.isFinite(value)) return 1;
return Math.min(MAX_BUS_VOLUME, Math.max(0, value));
}
/** Per-stage on/off state. Defaults to all `true` (every stage engaged). */
export interface CompressorStages {
key: boolean;
bgm: boolean;
master: boolean;
}
/**
* Single bus-mode handle. The keys are stable references that sample sources connect to (their own connections never
* need to be touched after creation). `setMode(next)` re-routes the downstream stages without disturbing the
* source-side wiring.
*
* `dispose()` tears down every node we created. The caller is responsible for stopping any in-flight `BufferSourceNode`
* before disposing — those connect to `keyMixer` / `bgmMixer` so they'd otherwise survive into the next chart's bus and
* play through.
*/
export interface AudioBusHandle {
readonly keyMixer: GainNode;
readonly bgmMixer: GainNode;
/**
* Final node before `audioContext.destination` — i.e. the stage the playback actually reaches the speakers from.
* Exposed so external taps (recording, analyzers, level meters) can `connect` to their own destinations without
* disrupting the main path.
*
* Internally a unity-gain `GainNode` that every mode (`'off'` / `'legacy'` / `'split'`) routes through. Unity gain
* means the tap is acoustically transparent — even `'off'` mode's "raw signal" goes through it without level / phase
* change. Recording therefore captures whatever the user is hearing regardless of the active compressor
* configuration.
*/
readonly outputNode: AudioNode;
readonly mode: CompressorMode;
setMode(next: CompressorMode): void;
getMode(): CompressorMode;
/**
* Toggle one compressor stage in `'split'` mode. With every stage off the split bus collapses to
* `keyMixer → input trim → makeup → destination` and `bgmMixer → input trim → makeup → destination` (the per-bus /
* master compressors are all bypassed but compressed-mode gain staging still applies, distinct from the global
* `'off'` mode that bypasses everything).
*
* No-op in `'legacy'` / `'off'` modes — but the state is still remembered, so a later `setMode('split')` picks it up.
*/
setStageEnabled(stage: CompressorStage, enabled: boolean): void;
/**
* Returns the cached stage flag. Reflects the **requested** state even when the active mode isn't `'split'` (so a UI
* checkbox can round-trip its value through the bus without losing it on a temporary mode change).
*/
getStageEnabled(stage: CompressorStage): boolean;
/**
* Sets the user volume of one source bus (linear, 1 = unity; see {@link sanitizeBusVolume}). Applied at the bus's
* mixer on top of the headroom trim, ahead of every compressor stage, so it balances keysounds against BGM in every
* routing mode and the recording tap captures the balance the user hears.
*/
setBusVolume(channel: AudioBusChannel, value: number): void;
/** Returns the current user volume of one source bus (default `1`). */
getBusVolume(channel: AudioBusChannel): number;
/**
* Retunes one compressor live (see {@link mergeCompressorParams}); unspecified fields keep their current value. Works
* whether or not the compressor is currently routed, so a later mode / stage switch picks the tuning up.
*/
setCompressorParams(compressor: TunableCompressor, params: Partial<CompressorParams>): void;
/** Returns the current parameters of one compressor. */
getCompressorParams(compressor: TunableCompressor): CompressorParams;
/**
* Sets the chart-level master gain (BMS `#VOLWAV`). The value is a linear multiplier applied at a dedicated stage
* that sits BEFORE the recording tap, so a chart authored with `#VOLWAV 80` runs at 80 % through every routing mode
* and the recorder captures the same attenuated signal the user hears. Passing `1.0` (or omitting the field on the
* chart) leaves the bus at unity. Negative / non-finite inputs are clamped to `0`.
*/
setMasterGain(value: number): void;
/** Returns the currently-applied chart master gain (default `1.0`). */
getMasterGain(): number;
/**
* Fades the **audible** signal path (post-tap, just before `audioContext.destination`) toward `targetGain` over
* `durationMs`. Used by the gameplay scene's exit transition so the audio dies in lock-step with the screen's
* `#FADEOUT` alpha animation.
*
* Crucially, this stage sits AFTER the recording tap — so a recording in progress keeps capturing the unattenuated
* mix while the speaker output dips to silence. That matches the user expectation that "saved WAV ≈ what the chart
* sounds like in full", not "what the user heard during a partial play / abort".
*
* Idempotent re-calls re-anchor the ramp at the current value, so a frantic second ESC press just continues the
* existing fade rather than producing a stair-step.
*/
fadeOutAudibleTo(targetGain: number, durationMs: number): void;
/**
* Restores the post-tap fade gain to unity immediately. The gameplay scene calls this when it cancels an in-flight
* fade (e.g. a pause that the user then unpauses by mashing keys instead of letting the exit timeline complete) so
* subsequent audio plays at full level again.
*/
resetFadeGain(): void;
dispose(): void;
}
export interface BuildAudioBusOptions {
/**
* Initial per-stage flags (only relevant in `'split'` mode). Missing fields default to `true`. Used by hosts that
* surface a UI for per-stage bypass and want the bus's state to come up matching the pre-mount UI selection.
*/
initialStages?: Partial<CompressorStages>;
/** Initial user volume per source bus (linear, 1 = unity). Missing fields default to `1`. */
initialVolumes?: Partial<Record<AudioBusChannel, number>>;
/** Initial parameter overrides per compressor, merged over {@link DEFAULT_COMPRESSOR_PARAMS}. */
initialCompressorParams?: Partial<Record<TunableCompressor, Partial<CompressorParams>>>;
}
/**
* Builds the audio bus and connects it to `audioContext.destination`. Sample sources should connect to `keyMixer`
* (player input keysounds) or `bgmMixer` (auto-triggered BGM) and never directly to the destination — that bypasses
* every compressor stage and the `setMode` toggle won't reach those samples.
*
* `initialMode` is the starting mode. Most callers pass `'split'`; the player's `?compressor=...` flag can pass
* `'legacy'` or `'off'` for A/B comparison.
*/
export function buildAudioBus(
audioContext: AudioContext,
initialMode: CompressorMode = 'split',
options: BuildAudioBusOptions = {},
): AudioBusHandle {
const keyMixer = audioContext.createGain();
const bgmMixer = audioContext.createGain();
// Sub-unity mixer gain so multiple simultaneous samples don't sum past full scale before the compressor stack has a
// chance to react. See `MIXER_HEADROOM_GAIN_LINEAR` for why ~−6 dB.
// The user's per-bus volume rides on the same gain, so it sits ahead of every compressor stage.
const volumes: Record<AudioBusChannel, number> = {
key: sanitizeBusVolume(options.initialVolumes?.key ?? 1),
bgm: sanitizeBusVolume(options.initialVolumes?.bgm ?? 1),
};
keyMixer.gain.value = MIXER_HEADROOM_GAIN_LINEAR * volumes.key;
bgmMixer.gain.value = MIXER_HEADROOM_GAIN_LINEAR * volumes.bgm;
const keyCompressorInput = audioContext.createGain();
const bgmCompressorInput = audioContext.createGain();
keyCompressorInput.gain.value = COMPRESSOR_INPUT_TRIM_GAIN_LINEAR;
bgmCompressorInput.gain.value = COMPRESSOR_INPUT_TRIM_GAIN_LINEAR;
// Per-bus compressors plus the master — created up front, wired in/out by `applyMode`. Held even when the active mode
// doesn't use them so the next `setMode` call can splice them back in without re-creating Web Audio nodes (cheap, but
// recreating would also reset their internal envelope state which wastes any "warm" gain reduction the mode switch
// could otherwise preserve).
// Without overrides each compressor just starts from a copy of its factory tuning (no merge pass).
const overrides = options.initialCompressorParams;
const initialParams = (base: CompressorParams, patch: Partial<CompressorParams> | undefined): CompressorParams =>
patch ? mergeCompressorParams(base, patch) : { ...base };
const compressorParams: Record<TunableCompressor, CompressorParams> = {
key: initialParams(KEY_BUS_COMPRESSOR_PARAMS, overrides?.key),
bgm: initialParams(BGM_BUS_COMPRESSOR_PARAMS, overrides?.bgm),
master: initialParams(MASTER_BUS_COMPRESSOR_PARAMS, overrides?.master),
legacy: initialParams(LEGACY_COMPRESSOR_PARAMS, overrides?.legacy),
};
const keyComp = createCompressor(audioContext, compressorParams.key);
const bgmComp = createCompressor(audioContext, compressorParams.bgm);
const masterComp = createCompressor(audioContext, compressorParams.master);
// Legacy mode reuses a single compressor with the original pre-split params. Distinct node from the master so
// swapping modes doesn't have to mutate AudioParam values mid-chart.
const legacyComp = createCompressor(audioContext, compressorParams.legacy);
const compressorNodes: Record<TunableCompressor, DynamicsCompressorNode> = {
key: keyComp,
bgm: bgmComp,
master: masterComp,
legacy: legacyComp,
};
const makeup = audioContext.createGain();
makeup.gain.value = MASTER_MAKEUP_GAIN_LINEAR;
// BMS spec — `#VOLWAV <0..ZZ>` declares the chart's master volume scaling (100 = unity). Implemented as a dedicated
// gain node placed BEFORE the universal tap so every routing mode (`'off'` / `'legacy'` / `'split'`) feels the
// attenuation, and the recording tap captures the post-`#VOLWAV` signal — i.e. what the user actually hears.
// Initialized to unity so charts that omit `#VOLWAV` (or run outside a chart context) are unaffected.
const masterGain = audioContext.createGain();
masterGain.gain.value = 1.0;
// Universal output tap. Every mode routes through this unity- gain node before reaching `audioContext.destination`,
// so external consumers (the recorder, future analyzers, level meters) can `connect` to a single stable point and
// capture whatever the user is hearing — including `'off'` mode where the makeup gain is bypassed for the audible
// path. Unity gain means the tap is acoustically transparent: it sums its inputs with no level / phase change, so the
// "raw signal" intent of `'off'` is preserved.
const tap = audioContext.createGain();
tap.gain.value = 1.0;
// Post-tap fade gain. Splits the "audible" path (which goes to the destination) from the "recording" path (taps off
// `tap`), so an exit-sequence fade-out can dip the speakers to silence without also pulling the recording mix down.
// Initialized to unity so steady-state playback is acoustically transparent.
const exitFadeGain = audioContext.createGain();
exitFadeGain.gain.value = 1.0;
masterGain.connect(tap);
tap.connect(exitFadeGain);
exitFadeGain.connect(masterOutput(audioContext));
// `makeup → masterGain → tap` is wired once and never re-disconnected; modes that use makeup (legacy / split) just
// connect their last compressor to makeup and let the rest of the chain ride.
makeup.connect(masterGain);
let activeMode: CompressorMode = initialMode;
// Stage on/off state. Persisted across mode changes so a UI checkbox can flip the architecture mid-play without
// forgetting which stages the user had disabled. `initialStages` lets the host seed this from a pre-mount UI
// selection.
const stages: CompressorStages = {
key: options.initialStages?.key ?? true,
bgm: options.initialStages?.bgm ?? true,
master: options.initialStages?.master ?? true,
};
applyRouting();
/**
* Rebuilds every downstream edge based on the current `activeMode` + `stages`. Source-side connections (TO `keyMixer`
* / `bgmMixer`) stay untouched because `disconnect()` only removes a node's **outgoing** edges, and we never
* disconnect on the source-side mixers' inputs.
*/
function applyRouting(): void {
keyMixer.disconnect();
bgmMixer.disconnect();
keyCompressorInput.disconnect();
bgmCompressorInput.disconnect();
keyComp.disconnect();
bgmComp.disconnect();
masterComp.disconnect();
legacyComp.disconnect();
if (activeMode === 'off') {
// Bypass every compressor + makeup — but route through the master-gain (#VOLWAV) and shared `tap` nodes anyway so
// the recorder (and any other tap-side consumer) sees the signal. `tap.gain = 1.0` keeps this transparent for the
// audible path; only `#VOLWAV` modulates volume here.
keyMixer.connect(masterGain);
bgmMixer.connect(masterGain);
return;
}
if (activeMode === 'legacy') {
// keyMixer + bgmMixer → input trim → legacyComp → makeup → destination. Stage toggles are intentionally ignored
// here — legacy is a single-comp architecture, "disable key only" doesn't map onto its topology. The flags
// persist so toggling back to split mode picks them up.
keyMixer.connect(keyCompressorInput);
bgmMixer.connect(bgmCompressorInput);
keyCompressorInput.connect(legacyComp);
bgmCompressorInput.connect(legacyComp);
legacyComp.connect(makeup);
return;
}
// 'split' — 3-stage architecture with per-stage bypass.
//
// `stages.key` — engage `keyComp` (else key input-trim skips ahead) `stages.bgm` — engage `bgmComp` (else BGM
// input-trim skips ahead) `stages.master` — engage `masterComp` (else key/BGM tails meet at `makeup`)
//
// The branch graph stays the same shape; only which intermediate node each path threads through changes.
// Sample-source mixers never see the difference.
keyMixer.connect(keyCompressorInput);
bgmMixer.connect(bgmCompressorInput);
const keyTail: AudioNode = stages.key ? keyComp : keyCompressorInput;
const bgmTail: AudioNode = stages.bgm ? bgmComp : bgmCompressorInput;
if (stages.key) keyCompressorInput.connect(keyComp);
if (stages.bgm) bgmCompressorInput.connect(bgmComp);
if (stages.master) {
keyTail.connect(masterComp);
bgmTail.connect(masterComp);
masterComp.connect(makeup);
} else {
keyTail.connect(makeup);
bgmTail.connect(makeup);
}
}
return {
keyMixer,
bgmMixer,
outputNode: tap,
get mode(): CompressorMode {
return activeMode;
},
setMode(next: CompressorMode): void {
if (activeMode === next) return;
activeMode = next;
applyRouting();
},
getMode(): CompressorMode {
return activeMode;
},
setStageEnabled(stage: CompressorStage, enabled: boolean): void {
if (stages[stage] === enabled) return;
stages[stage] = enabled;
// Only re-route when the active mode is one that uses stage flags. Persisting the flag for legacy/off is the
// right thing — see the doc comment on `setStageEnabled`.
Eif (activeMode === 'split') {
applyRouting();
}
},
getStageEnabled(stage: CompressorStage): boolean {
return stages[stage];
},
setBusVolume(channel: AudioBusChannel, value: number): void {
volumes[channel] = sanitizeBusVolume(value);
(channel === 'key' ? keyMixer : bgmMixer).gain.value = MIXER_HEADROOM_GAIN_LINEAR * volumes[channel];
},
getBusVolume(channel: AudioBusChannel): number {
return volumes[channel];
},
setCompressorParams(compressor: TunableCompressor, params: Partial<CompressorParams>): void {
compressorParams[compressor] = mergeCompressorParams(compressorParams[compressor], params);
applyCompressorParams(compressorNodes[compressor], compressorParams[compressor]);
},
getCompressorParams(compressor: TunableCompressor): CompressorParams {
return { ...compressorParams[compressor] };
},
setMasterGain(value: number): void {
// Sanitize pathological inputs — `#VOLWAV` is documented as `0..ZZ` (linear-scale BMS units, 100 = unity, > 100
// boosts the chart above unity), but a malformed chart could emit NaN / Infinity / negative numbers that would
// otherwise propagate into a Web Audio AudioParam and produce silent failure or a runtime exception. Non-finite →
// unity (no surprise scaling); negative-finite → 0 (silence is the safer interpretation of a negative gain).
let sanitized: number;
if (!Number.isFinite(value)) {
sanitized = 1.0;
} else if (value < 0) {
sanitized = 0;
} else {
sanitized = value;
}
masterGain.gain.value = sanitized;
},
getMasterGain(): number {
return masterGain.gain.value;
},
fadeOutAudibleTo(targetGain: number, durationMs: number): void {
// Re-anchor the ramp at the current value so chained fade-out calls don't snap back to the previous setpoint.
// `cancelScheduledValues` discards any in-flight ramp, then `setValueAtTime(currentValue, now)` pins the curve to
// the present audible level before linearly tweening to the target — chosen `linearRampToValueAtTime` over
// `exponentialRampToValueAtTime` because the screen overlay animates linearly, and we want the visible / audible
// fades to feel synchronized rather than the audio dying off ahead of the screen.
const now = audioContext.currentTime;
const param = exitFadeGain.gain;
const safeTarget = Number.isFinite(targetGain) ? Math.max(0, targetGain) : 0;
const safeDurationSeconds = Number.isFinite(durationMs) ? Math.max(0, durationMs) / 1000 : 0;
param.cancelScheduledValues(now);
param.setValueAtTime(param.value, now);
if (safeDurationSeconds <= 0) {
// Zero / negative duration → snap immediately. Avoids `linearRampToValueAtTime` being called with `endTime ===
// now` which the spec leaves implementation-defined.
param.setValueAtTime(safeTarget, now);
return;
}
param.linearRampToValueAtTime(safeTarget, now + safeDurationSeconds);
},
resetFadeGain(): void {
const now = audioContext.currentTime;
const param = exitFadeGain.gain;
param.cancelScheduledValues(now);
param.setValueAtTime(1, now);
},
dispose(): void {
try {
keyMixer.disconnect();
bgmMixer.disconnect();
keyCompressorInput.disconnect();
bgmCompressorInput.disconnect();
keyComp.disconnect();
bgmComp.disconnect();
masterComp.disconnect();
legacyComp.disconnect();
makeup.disconnect();
masterGain.disconnect();
tap.disconnect();
exitFadeGain.disconnect();
} catch {
// `disconnect()` throws when called on an already-disposed node. Swallowing is safe — `dispose()` is idempotent
// and the only thing the caller cares about is "no future outputs from this bus".
}
},
};
}
function createCompressor(audioContext: AudioContext, params: CompressorParams): DynamicsCompressorNode {
const node = audioContext.createDynamicsCompressor();
applyCompressorParams(node, params);
return node;
}
function applyCompressorParams(node: DynamicsCompressorNode, params: CompressorParams): void {
node.threshold.value = params.threshold;
node.ratio.value = params.ratio;
node.attack.value = params.attack;
node.release.value = params.release;
node.knee.value = params.knee;
}
/**
* Parses a `?compressor=...` URL search-param value into a valid {@link CompressorMode}, or `undefined` when the value
* is missing / unrecognized so callers can fall through to their default. The player passes the URL's
* `searchParams.get('compressor')` here at mount time.
*/
export function parseCompressorMode(raw: string | null | undefined): CompressorMode | undefined {
if (raw === null || raw === undefined) return undefined;
const lower = raw.trim().toLowerCase();
if (lower === 'split' || lower === 'legacy' || lower === 'off') {
return lower;
}
return undefined;
}
|