All files / player-browser/src/runtime web-audio-session.ts

90.22% Statements 360/399
85.9% Branches 262/305
92.3% Functions 48/52
94.28% Lines 330/350

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                                                                                      51x                   51x                                                                                                                                                                                                                                     1x         14x               8x 8x 8x                                                                                                           32x 32x 32x     32x               32x 4x   32x 24x 24x 24x   32x 32x 32x 32x 32x 118x 118x 118x 109x 109x 109x 1x         1x           118x 118x     32x 32x     32x 32x 32x 32x 32x       32x 32x   32x   32x 60x 1x 1x         32x 55x 55x 2x 1x   55x     32x           32x 2x 2x 8x 8x 8x 4x 4x   8x   2x               32x 1x 1x 1x 1x 1x 4x   2x 1x 1x   1x 4x 4x                               32x 12x     32x 67x 67x       32x 12x   32x 62x 62x     32x 59x 59x 59x 59x               32x                 55x 55x 55x 55x 55x 55x 55x   5x     55x 5x 4x   55x 55x 55x   55x   55x 55x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     55x 55x 18x 18x 18x 18x   37x   55x     32x 42x 42x       42x 10x 10x         42x                 32x 42x 42x 32x   42x 7x   42x 22x       32x   23x 23x 23x 13x   10x           23x 17x 17x       32x 59x 59x 59x 59x 59x   57x   59x       59x     59x 59x 56x   56x 56x 55x 59x 59x 59x           59x               59x   59x 59x 59x 59x                 59x 55x   55x 25x 25x             55x 101x 12x 2x 2x   10x 10x   55x 55x 59x 13x     55x             59x 59x 59x 55x 55x 55x       32x 7x 7x 7x 7x 7x 7x           7x     32x 4x 4x 4x 4x 4x 4x   4x 1x 1x 1x 1x 1x 1x             3x 2x 1x 1x       32x 32x       3x 3x     2x 2x 2x 2x                 14x 14x   14x 14x 14x     1x 1x 1x     1x 1x 1x                     1x 1x           1x                     2x 2x       2x 3x   2x 2x 2x 2x 2x 2x             2x         48x 3x 3x   45x     7x       7x           3x       3x       5x 5x 1x 1x   4x     4x   4x 4x 4x 4x 3x 3x 3x 2x       6x     6x 1x 1x 5x 6x 6x 6x 6x   6x 6x 6x 6x     2x 2x 1x                   2x 2x 2x                             13x 13x 11x 11x   13x 7x 7x 7x                       64x 51x   13x 1x   12x                         64x 54x   10x 10x     10x                                 55x 55x 55x 55x 7x 48x 6x   42x   55x                                 401x 401x    
import {
  isBmsBGMVolumeChangeChannel,
  isBMSKeyVolumeChangeChannel,
  playsAtKeysoundVolume,
  parseBMSDynamicVolumeGain,
  resolveBmsWAVResources,
  collectBmsWAVPlaybackModifiers,
  usesMonophonicWAVPlayback,
} from '@be-music/chart-model';
import type { WebAudioStageMixer } from './nonstop-audio.ts';
import {
  normalizeChannel,
  normalizeObjectKey,
  resolveBMSBase,
  type BeMusicEvent,
  type BeMusicJSON,
} from '@be-music/chart-source';
import type { AudioSession, GuideSound } from '@be-music/player-engine';
import {
  normalizePath,
  resolveSampleVoiceEnvelope,
  resolveStereoBalance,
  SAMPLE_SLICE_FADE_SECONDS,
  type SampleSliceEnvelope,
} from '@be-music/shared-utils/core';
import { type AudioBusHandle } from './audio-bus.ts';
import { prepareWAVPlaybackBuffer } from './wav-playback.ts';
 
interface WebAudioSourceHandle {
  node: AudioBufferSourceNode;
  buffer: AudioBuffer;
  gain: GainNode | undefined;
  /**
   * The rate the sample plays at on top of the session's base rate: its NONSTOP stage's rate (1 outside a stage) times
   * its trigger's own (an LRX note's `frq`).
   */
  stageRate: number;
  /** The nodes of a stereo balance (an LRX note's `pan`) between the source and its bus, disconnected with it. */
  balance?: readonly AudioNode[];
  startContextSeconds?: number;
}
 
/** How long a live tempo change glides the playback rate of the samples already playing, in seconds. */
export const LIVE_TEMPO_RAMP_SECONDS = 0.03;
 
/**
 * How far ahead of the audio clock the session reports its write head (`AudioSinkClockState.scheduledSeconds`), so the
 * engine queues the chart's background sounds, volume changes and AUTO keysounds that long before they are due, and
 * {@link WebAudioSession.scheduleEventAt} starts each one at its due time with `start(when)`. Without it, a sound
 * starts when the engine's ~60 Hz tick reaches it: up to a tick (and the main thread's timer slip) late, a different
 * amount for each sound. 50 ms covers a tick and a stalled one after it. Nothing a player does waits on it: a press's
 * keysound still starts at once, and judging reads the output clock.
 */
export const WEB_AUDIO_SCHEDULE_AHEAD_SECONDS = 0.05;
 
/**
 * Per-event playback override produced by the bmson 1.0.0 slicing pipeline. Each entry carries the seek `offset` into
 * the source `sound_channels[]` WAV plus an optional `duration` cap that bounds how long this slice plays before the
 * next note's slice takes over. BMS / json paths leave this map unset and play the whole WAV from `t = 0`.
 */
export interface WebAudioSessionSlicePlayback {
  offsetSeconds: number;
  durationSeconds?: number;
  sliceId?: string;
  /** An LRX note's own gain, on top of the slot's. */
  gain?: number;
  /** An LRX note's stereo balance, −1 (left) to 1 (right). */
  pan?: number;
  /** An LRX note's own playback rate. */
  rate?: number;
  /** An LRX note's fade-in, in seconds of the sample. */
  attackSeconds?: number;
  /** An LRX note's fade-out past the end of `durationSeconds`, in seconds of the sample. */
  releaseSeconds?: number;
}
 
/**
 * Construction-time inputs for {@link createWebAudioSession}. Decoupled from `BeMusicJSON` resolution so the player's
 * existing prepare path can decode every `#WAVxx` to an `AudioBuffer` once and reuse the same buffer cache across
 * pause / restart / replay cycles without re-decoding.
 */
export interface WebAudioSessionContext {
  /** Live `AudioContext` shared with the rest of the player. The session never closes the context — that's the host's
   *  responsibility, since `AudioContext.close()` is irreversible and would brick the select / decide BGM paths. */
  audioContext: AudioContext;
  /** Pre-built audio bus from {@link createAudioBus} — sample sources land at `keyMixer` (player input) or `bgmMixer`
   *  (auto-triggered BGM) per the BMS channel routing rules below. */
  audioBus: AudioBusHandle;
  /** Resolved chart used to look up `event.value` → `#WAVxx` slot path and to read the `#BASE` radix for slot lookups
   *  on `#BASE 62` charts. */
  chart: BeMusicJSON;
  /** Decoded WAV cache, keyed by lower-cased `normalizePath(resourceWAVPath)`. The session reads from this map but
   *  never mutates it; the host keeps decoding ownership so cross-session caches stay possible. */
  decodedSamples: ReadonlyMap<string, AudioBuffer>;
  /** Native encoded rates for externally decoded/resampled buffers with EXWAV frequency, keyed by decodedSampleKey(path). */
  nativeSampleRates?: ReadonlyMap<string, number>;
  /** Per-`#WAVxx` slot gain multiplier produced by `collectBmsWAVCmdVolumeMultipliers` /
   *  `collectBMSExWAVVolumeMultipliers`. Slots without an entry play at unity gain. */
  wavCmdVolumeMultipliers: ReadonlyMap<string, number>;
  /** Optional per-event slice overrides for bmson sound-channel splitting — see
   *  {@link WebAudioSessionSlicePlayback}. */
  bmsonSlicePlayback?: ReadonlyMap<BeMusicEvent, WebAudioSessionSlicePlayback>;
  /** Lead-in (ms) the engine should wait between {@link AudioSession.start} and chart's note-zero timing. The web
   *  backend doesn't fill an output buffer before playback starts (Web Audio handles its own ring), so the default
   *  `0` is fine; exposed for parity with the engine's contract. */
  chartStartDelayMs?: number;
  /** Human-readable label surfaced on the engine's "Audio backend: ..." log line. Defaults to `'web-audio'`. */
  backendLabel?: string;
  /**
   * Closure that returns the chart's t=0 on the audio-context clock — i.e. the value the host's renderer treats
   * as `audioContextStartTime`. Used by {@link AudioSession.getClockState} to keep the engine's playback clock in
   * lock-step with the renderer's `currentSeconds()` calculation, so judges fire exactly when the note hits the
   * judgment line. Returning `0` (the default when omitted) makes the session report the absolute audio-context
   * time, which matches the legacy "engine owns its own playback clock" flow but causes a per-chart drift between
   * renderer and judge if the host's renderer references a different anchor.
   */
  getChartStartContextTime?: () => number;
  /**
   * A stitched NONSTOP chart's stages (`createNonstopStageMixer`): each sample plays at its stage's rate (FIT changes
   * the pitch), and a stage's background voices go through its fade instead of straight to the BGM bus.
   */
  stageMixer?: WebAudioStageMixer;
  /**
   * The playback rate of every sample (`resolveSamplePlaybackRate`): the play tempo when a tempo change moves the pitch,
   * 1 when the samples were stretched to it. A NONSTOP stage's rate multiplies with it. Defaults to 1.
   */
  playbackRate?: number;
  /**
   * {@link playbackRate} is the play tempo (`pitch` mode), so a live tempo change ({@link AudioSession.setTempo}) sets it:
   * samples started afterwards play at the new tempo, and the ones still playing glide to it. Without it (keep pitch,
   * where the samples were stretched to the tempo they load at) the samples' rate ignores tempo changes.
   */
  playbackRateFollowsTempo?: boolean;
  /**
   * The play tempo the chart starts at (chart seconds per second): how far into a sample a sound started partway begins
   * (`triggerEventAt`), and when a NONSTOP stage's fades fall on the audio clock. Defaults to {@link playbackRate} when
   * it follows the tempo, else 1.
   */
  tempo?: number;
  /**
   * Crossfades each seek over this many seconds: the sounds of the old position that already started fade out, while
   * the ones the new position starts partway (still ringing there) fade in, instead of stopping or starting at once.
   * The sounds the new position starts on time play at full volume from the first, and the old position's sounds that
   * were queued but had not started yet do not play. A PRACTICE play's loop (#949) goes back to its start with a seek,
   * so its range comes round again smoothly with its first beat whole. Absent or 0: no fades.
   */
  seekCrossfadeSeconds?: number;
  /**
   * beatoraja's GUIDE SE: the decoded sound of each judgment. With any, the session plays the judgment's on the key
   * bus as the engine judges ({@link AudioSession.playGuideSound}), at the key volume like a keysound; without, the
   * session has no `playGuideSound`.
   */
  guideSounds?: ReadonlyMap<GuideSound, AudioBuffer>;
}
 
/**
 * A crossfade's gains, before each bus mixer, so one position's voices fade together: `key` / `bgm` for the voices it
 * starts on time, open from the first, and `partwayKey` / `partwayBGM` for those it starts partway, which fade in.
 */
interface CrossfadeGeneration {
  readonly key: GainNode;
  readonly bgm: GainNode;
  readonly partwayKey: GainNode;
  readonly partwayBGM: GainNode;
}
 
/** Every gain of a crossfade generation. */
function crossfadeGains(generation: CrossfadeGeneration): GainNode[] {
  return [generation.key, generation.bgm, generation.partwayKey, generation.partwayBGM];
}
 
/** Whether `handle` was queued to start after `now` on the audio clock and has not started yet. */
function isQueued(handle: { readonly startContextSeconds?: number }, now: number): boolean {
  return handle.startContextSeconds !== undefined && handle.startContextSeconds > now + 1e-6;
}
 
/**
 * Moves `param` from where it is now to `target` over `seconds` from `now` in a straight line, cancelling what was
 * scheduled after now so a fade that starts mid-fade does not jump.
 */
export function rampGainTo(param: AudioParam, target: number, now: number, seconds: number): void {
  param.cancelScheduledValues?.(now);
  param.setValueAtTime(param.value, now);
  param.linearRampToValueAtTime(target, now + Math.max(0, seconds));
}
 
/**
 * Extension of the engine's {@link AudioSession} contract that exposes the web-only "schedule a sample at a precise
 * audio-context time" affordance. Web Audio's `BufferSource.start(when)` lets us pre-schedule BGM cues sample-
 * accurately up to ~0.5s ahead, which is dramatically tighter than the per-frame `triggerEvent` cadence the engine
 * uses on the TUI side. Hosts that drive their own per-frame BGM look-ahead call {@link scheduleEvent} instead of
 * `triggerEvent` so the buffer is queued at the right audio-context timestamp rather than firing immediately.
 */
export interface WebAudioSession extends AudioSession {
  /**
   * Schedules `event`'s associated `#WAVxx` slot to start at `audioContextStartSeconds` (the absolute time on the
   * `AudioContext.currentTime` clock — usually computed by the host as `chartStartContextTime + chartSeconds`).
   *
   * Routing rules and `#WAVCMD` gain handling are identical to {@link AudioSession.triggerEvent}; only the start
   * timing differs. When `audioContextStartSeconds` is in the past the buffer fires immediately (Web Audio's
   * `start(when)` semantics), so a host that polls on a slightly-late tick won't drop the cue.
   */
  scheduleEvent: (event: BeMusicEvent, audioContextStartSeconds: number) => void;
  /**
   * Starts `event`'s sound (or applies its `#xxx97` / `#xxx98` volume) at `outputSeconds` on the clock `getClockState`
   * reports, the context's from the chart's start: the engine queues the chart's realtime sounds
   * {@link WEB_AUDIO_SCHEDULE_AHEAD_SECONDS} ahead and this places each at its due time.
   */
  scheduleEventAt: NonNullable<AudioSession['scheduleEventAt']>;
}
 
/**
 * Web Audio API implementation of the engine's {@link AudioSession} contract. Sole purpose is to plug a browser
 * runtime into the same judge / fallback / LN logic the TUI uses, so the web (Pixi) view doesn't need to keep its
 * own copy of the BMS sample triggering rules.
 *
 * Routing rules (mirror what the engine's TUI session does on Node):
 *
 * - **Player input lanes (`#xxx11..#xxx29` minus volume channels)** — route through `audioBus.keyMixer` so the
 *   key-bus compressor sees the input transient stream.
 * - **Auto-triggered lane sounds (`#xxx01`, `#xxx51..#xxx69` LN-start, `#xxx07` POOR BGA, etc.)** — route through
 *   `audioBus.bgmMixer` so the BGM bed shares the BGM compressor.
 * - **`#xxx97` / `#xxx98` dynamic volume events** — update the session's current BGM / key dynamic gain. Per
 *   docs/bms-spec.md「#xxx97 / #xxx98」, the new level applies as the initial gain of voices triggered from that
 *   point on; already-playing voices keep the gain they started with (mirrors the engine's Node mixer behavior).
 * - **`#xxxD0` / `#xxxE0` (landmine explosions)** — route through `bgmMixer` (the engine fires these via
 *   `triggerEvent` on landmine hit; the explosion is BGM-style, not the player's keysound).
 *
 * **bmson slices** — each pulse plays its own source window. Different slices of one stem may overlap; simultaneous
 * uses of one slice share a voice. `c` selects the window's offset and never suppresses a later slice's trigger.
 *
 * **Channel-targeted stop** (`stopChannel`) — when the engine retires an LN early (LNMODE 1 grace expired, LNMODE 2/3
 * mid-hold release), it expects the session to silence the keysound on that lane. The session keeps a per-channel map
 * of the most recent `BufferSourceNode` triggered for that channel and calls `node.stop()` when asked.
 */
export function createWebAudioSession(context: WebAudioSessionContext): WebAudioSession {
  const { audioContext, audioBus, chart, decodedSamples, wavCmdVolumeMultipliers, bmsonSlicePlayback, stageMixer } =
    context;
  const resolveChartStartContextTime = context.getChartStartContextTime ?? (() => 0);
  let basePlaybackRate = context.playbackRate !== undefined && context.playbackRate > 0 ? context.playbackRate : 1;
  /** The play tempo in force: chart seconds per second of the audio clock. */
  let tempo =
    context.tempo !== undefined && Number.isFinite(context.tempo) && context.tempo > 0
      ? context.tempo
      : context.playbackRateFollowsTempo === true
        ? basePlaybackRate
        : 1;
  /** Where the chart was on the audio clock at the last start, seek or tempo change: chart second `chart` at `context`. */
  let anchor: { context: number; chart: number } | undefined;
  /** The chart second the audio clock reads now, from the last anchor at the tempo in force (paused: the context holds). */
  const chartSecondsNow = (): number | undefined =>
    anchor === undefined ? undefined : anchor.chart + (audioContext.currentTime - anchor.context) * tempo;
  /** Re-anchors the chart at `chartSeconds` now and moves a NONSTOP chart's fades to fall where the chart now runs. */
  const anchorChartAt = (chartSeconds: number): void => {
    const now = audioContext.currentTime;
    anchor = { context: now, chart: chartSeconds };
    stageMixer?.retime?.(chartSeconds, (seconds) => now + (seconds - chartSeconds) / tempo);
  };
  const sampleIdBase = resolveBMSBase(chart);
  const wavResources = resolveBmsWAVResources(chart);
  const playbackModifiers = collectBmsWAVPlaybackModifiers(chart);
  const preparedBuffers = new Map<string, AudioBuffer>();
  const sampleBuffer = (path: string, key: string): AudioBuffer | undefined => {
    const cacheKey = decodedSampleKey(path, key);
    const prepared = decodedSamples.get(cacheKey) ?? preparedBuffers.get(cacheKey);
    if (prepared) return prepared;
    const raw = decodedSamples.get(decodedSampleKey(path));
    const modifiers = playbackModifiers.get(key);
    if (!raw || !modifiers) return raw;
    Iif (modifiers.frequencyHz !== undefined && !context.nativeSampleRates?.has(decodedSampleKey(path))) {
      throw new Error(
        'EXWAV frequency requires a prepared slot buffer or nativeSampleRates for externally decoded audio',
      );
    }
    const buffer = prepareWAVPlaybackBuffer(
      audioContext,
      raw,
      modifiers,
      context.nativeSampleRates?.get(decodedSampleKey(path)),
    );
    preparedBuffers.set(cacheKey, buffer);
    return buffer;
  };
  /** The most recent source per WAV slot, for BMS monophonic retriggers. */
  const activeBySlot = new Map<string, WebAudioSourceHandle>();
  const activeBySlice = new Map<string, WebAudioSourceHandle>();
  /** Active BufferSource per BMS channel (lane). Populated for player-input lanes so `stopChannel` can silence the
   *  most recent keysound when the engine releases an LN early. */
  const activeByChannel = new Map<string, WebAudioSourceHandle>();
  const activeSources = new Set<WebAudioSourceHandle>();
  let paused = false;
  let disposed = false;
  let started = false;
  // `#xxx97` / `#xxx98` current dynamic gains. Spec (docs/bms-spec.md「#xxx97 / #xxx98」): a volume change applies to
  // voices triggered from that point on; already-playing voices are untouched. The gain is therefore captured
  // per-voice at build time instead of being written onto the shared bus mixers.
  let currentBGMDynamicGain = 1;
  let currentKeyDynamicGain = 1;
  /** Volume changes queued ahead of the audio clock, by time: each applies to the voices that start from its time on. */
  let pendingGainChanges: Array<{ at: number; bgm: boolean; gain: number }> = [];
  /** Applies the queued volume changes that are due by `now`. */
  const settleGainChanges = (now: number): void => {
    while (pendingGainChanges.length > 0 && pendingGainChanges[0]!.at <= now + 1e-6) {
      const change = pendingGainChanges.shift()!;
      if (change.bgm) currentBGMDynamicGain = change.gain;
      else EcurrentKeyDynamicGain = change.gain;
    }
  };
  /** The dynamic gain of a voice starting at `at`: the volume in force then, queued changes included. */
  const dynamicGainAt = (bgm: boolean, at: number): number => {
    let gain = bgm ? currentBGMDynamicGain : currentKeyDynamicGain;
    for (const change of pendingGainChanges) {
      if (change.at > at + 1e-6) break;
      Eif (change.bgm === bgm) gain = change.gain;
    }
    return gain;
  };
  const crossfadeSeconds =
    context.seekCrossfadeSeconds !== undefined && Number.isFinite(context.seekCrossfadeSeconds)
      ? Math.max(0, context.seekCrossfadeSeconds)
      : 0;
  /** The gains the voices of the position now playing go through, while crossfades are on. */
  let generation: CrossfadeGeneration | undefined;
  /** Opens the gains for a new position: those of its on-time voices at once, those of its partway ones fading in. */
  const openGeneration = (): void => {
    const now = audioContext.currentTime;
    const open = (mixer: GainNode, fadeIn: boolean): GainNode => {
      const gain = audioContext.createGain();
      gain.connect(mixer);
      if (fadeIn) {
        gain.gain.value = 0;
        rampGainTo(gain.gain, 1, now, crossfadeSeconds);
      }
      return gain;
    };
    generation = {
      key: open(audioBus.keyMixer, false),
      bgm: open(audioBus.bgmMixer, false),
      partwayKey: open(audioBus.keyMixer, true),
      partwayBGM: open(audioBus.bgmMixer, true),
    };
  };
  /** Fades the position playing out over the crossfade, stopping its voices and dropping its gains at the end. */
  const closeGeneration = (voices: readonly WebAudioSourceHandle[]): void => {
    const closing = generation;
    generation = undefined;
    const now = audioContext.currentTime;
    const endAt = now + crossfadeSeconds;
    const gains = closing === undefined ? [] : crossfadeGains(closing);
    for (const gain of gains) rampGainTo(gain.gain, 0, now, crossfadeSeconds);
    // A voice queued ahead of the audio clock that has not started belongs past the old position: it never plays.
    for (const handle of voices) stopSource(handle, isQueued(handle, now) ? undefined : endAt);
    Iif (closing === undefined) return;
    setTimeout(
      () => {
        for (const gain of gains) {
          try {
            gain.disconnect();
          } catch {
            // Already disconnected, or the context closed first.
          }
        }
      },
      crossfadeSeconds * 1000 + 50,
    );
  };
 
  /**
   * How far into its sample a sound that started `elapsedSeconds` of chart time ago is: the time it has played, at the
   * rate it plays (the session's rate times its NONSTOP stage's), over the tempo the chart runs at. With pitch the rate
   * is the tempo, so a chart second is a stage-rate second of the sample; with kept pitch the samples were stretched to
   * the tempo and play at rate 1, so it is `1 / tempo` of one.
   */
  const elapsedInBuffer = (sampleKey: string, elapsedSeconds: number): number =>
    (elapsedSeconds * basePlaybackRate * stageRateOf(sampleKey)) / tempo;
 
  /** How fast a sample plays for its NONSTOP stage (FIT); 1 outside a stitched chart. */
  const stageRateOf = (sampleKey: string): number => {
    const stage = stageMixer?.stageOf(sampleKey);
    return stage === undefined ? 1 : stageMixer!.rate(stage);
  };
 
  /** A trigger's own rate (an LRX note's `frq`); 1 for any other. */
  const voiceRateOf = (slice: WebAudioSessionSlicePlayback | undefined): number =>
    slice?.rate !== undefined && slice.rate > 0 ? slice.rate : 1;
 
  const sliceRateOf = (sampleKey: string): number => {
    const stage = stageMixer?.stageOf(sampleKey);
    return stage === undefined ? 1 : (stageMixer?.sliceRate?.(stage) ?? 1);
  };
 
  const resolveSamplePath = (event: BeMusicEvent): { sampleKey: string; path: string } | undefined => {
    const sampleKey = normalizeObjectKey(event.value, sampleIdBase, chart.sourceFormat === 'bmson');
    const path = wavResources[sampleKey];
    Iif (typeof path !== 'string') return undefined;
    return { sampleKey, path };
  };
 
  /**
   * Builds + parents a `BufferSourceNode` to the appropriate mixer with the `#WAVCMD` per-slot gain and the current
   * `#xxx97` / `#xxx98` dynamic gain spliced in. Returns `undefined` when the slot has no decoded buffer (chart
   * referenced an asset we never loaded, e.g. a missing file).
   */
  const buildSourceNode = (
    sampleKey: string,
    path: string,
    bus: AudioNode,
    dynamicGain: number,
    withGainNode: boolean,
    partway = false,
    voice?: WebAudioSessionSlicePlayback,
  ): WebAudioSourceHandle | undefined => {
    const buffer = sampleBuffer(path, sampleKey);
    Iif (!buffer) return undefined;
    const node = audioContext.createBufferSource();
    node.buffer = buffer;
    const stage = stageMixer?.stageOf(sampleKey);
    const stageRate = stageRateOf(sampleKey);
    if (stage !== undefined) {
      // A stage's background voices go through its fade; the player's keysounds stay on the key bus.
      if (bus === audioBus.bgmMixer) bus = stageMixer!.bgmInput(stage) ?? bus;
    }
    // While crossfades are on, a voice goes through its position's gains.
    if (generation !== undefined) {
      if (bus === audioBus.keyMixer) bus = partway ? generation.partwayKey : generation.key;
      else Eif (bus === audioBus.bgmMixer) bus = partway ? generation.partwayBGM : generation.bgm;
    }
    const voiceRate = voice?.rate !== undefined && voice.rate > 0 ? voice.rate : 1;
    const rate = basePlaybackRate * stageRate * voiceRate;
    if (rate !== 1) node.playbackRate.value = rate;
    // An LRX note's balance: the far channel attenuated, the near one left alone.
    const { left, right } = resolveStereoBalance(voice?.pan ?? 0);
    let balance: AudioNode[] | undefined;
    let output: AudioNode = bus;
    if (left !== 1 || right !== 1) {
      const splitter = audioContext.createChannelSplitter(2);
      const merger = audioContext.createChannelMerger(2);
      const leftGain = audioContext.createGain();
      const rightGain = audioContext.createGain();
      leftGain.gain.value = left;
      rightGain.gain.value = right;
      splitter.connect(leftGain, 0);
      splitter.connect(rightGain, 1);
      leftGain.connect(merger, 0, 0);
      rightGain.connect(merger, 0, 1);
      merger.connect(bus);
      balance = [splitter, leftGain, rightGain, merger];
      output = splitter;
    }
    let gain: GainNode | undefined;
    const combinedGain = (wavCmdVolumeMultipliers.get(sampleKey) ?? 1) * dynamicGain * (voice?.gain ?? 1);
    if (combinedGain !== 1 || withGainNode) {
      gain = audioContext.createGain();
      gain.gain.value = combinedGain;
      node.connect(gain);
      gain.connect(output);
    } else {
      node.connect(output);
    }
    return { node, buffer, gain, stageRate: stageRate * voiceRate, ...(balance ? { balance } : {}) };
  };
 
  const disconnectSource = (handle: WebAudioSourceHandle): void => {
    try {
      handle.node.disconnect();
    } catch {
      // Already disconnected / context closed — both terminal states.
    }
    if (handle.gain !== undefined) {
      try {
        handle.gain.disconnect();
      } catch {
        // Same as above; source cleanup is best-effort.
      }
    }
    for (const node of handle.balance ?? []) {
      try {
        node.disconnect();
      } catch {
        // Same as above.
      }
    }
  };
 
  const forgetSource = (handle: WebAudioSourceHandle): void => {
    activeSources.delete(handle);
    for (const [slot, active] of activeBySlot) {
      if (active === handle) activeBySlot.delete(slot);
    }
    for (const [slice, active] of activeBySlice) {
      if (active === handle) activeBySlice.delete(slice);
    }
    for (const [channel, active] of activeByChannel) {
      if (active === handle) activeByChannel.delete(channel);
    }
  };
 
  const stopSource = (handle: WebAudioSourceHandle, stopAt?: number): void => {
    const scheduledStopAt =
      typeof stopAt === 'number' && Number.isFinite(stopAt) ? Math.max(audioContext.currentTime, stopAt) : undefined;
    try {
      if (scheduledStopAt !== undefined) {
        handle.node.stop(scheduledStopAt);
      } else {
        handle.node.stop();
      }
    } catch {
      // Already stopped, never started, or context closed.
    }
 
    if (scheduledStopAt === undefined || scheduledStopAt <= audioContext.currentTime + 1e-6) {
      forgetSource(handle);
      disconnectSource(handle);
    }
  };
 
  const playSampleEvent = (event: BeMusicEvent, audioContextStartSeconds?: number, elapsedSeconds = 0): void => {
    Iif (disposed) return;
    const resolved = resolveSamplePath(event);
    Iif (!resolved) return;
    const { sampleKey, path } = resolved;
    if (elapsedSeconds > 0 && !isStillRinging(event, sampleKey, path, elapsedSeconds)) return;
 
    const slice = bmsonSlicePlayback?.get(event);
    const sliceId =
      chart.sourceFormat === 'bmson'
        ? (slice?.sliceId ?? `${sampleKey}:${event.measure}:${event.position[0] / event.position[1]}`)
        : undefined;
    const startAt =
      audioContextStartSeconds !== undefined
        ? Math.max(audioContext.currentTime, audioContextStartSeconds)
        : audioContext.currentTime;
    const previousSlice = sliceId === undefined ? undefined : activeBySlice.get(sliceId);
    if (previousSlice?.startContextSeconds === startAt) return;
    settleGainChanges(audioContext.currentTime);
 
    const buffer = sampleBuffer(path, sampleKey);
    if (!buffer) return;
    const elapsed = elapsedSeconds > 0 ? elapsedInBuffer(sampleKey, elapsedSeconds) * voiceRateOf(slice) : 0;
    const sliceRate = sliceRateOf(sampleKey);
    const offsetSeconds = clampSampleOffset((slice?.offsetSeconds ?? 0) / sliceRate + elapsed, buffer.duration);
    const durationSeconds = clampSampleDuration(
      slice?.durationSeconds !== undefined ? slice.durationSeconds / sliceRate - elapsed : undefined,
      buffer.duration,
      offsetSeconds,
    );
    // An LRX note's attack only applies from its start; a seek past it plays on at full level.
    const envelope = resolveSampleVoiceEnvelope(
      offsetSeconds,
      durationSeconds,
      buffer.duration,
      SAMPLE_SLICE_FADE_SECONDS,
      elapsed > 0 ? 0 : (slice?.attackSeconds ?? 0),
      slice?.releaseSeconds ?? 0,
    );
    const hasEnvelope = envelope.fadeIn > 0 || envelope.fadeOut > 0;
 
    const channel = normalizeChannel(event.channel);
    const isPlayerLane = playsAtKeysoundVolume(channel, event);
    const bus = isPlayerLane ? audioBus.keyMixer : audioBus.bgmMixer;
    const built = buildSourceNode(
      sampleKey,
      path,
      bus,
      dynamicGainAt(!isPlayerLane, startAt),
      hasEnvelope,
      elapsedSeconds > 0,
      slice,
    );
    Iif (!built) return;
    const { node } = built;
 
    node.onended = (): void => {
      forgetSource(built);
      disconnectSource(built);
    };
    // Scheduled BGM cues clamp to "now" so a slightly-late polling tick still fires immediately rather than
    // throwing for a past timestamp; player-input keysounds and immediate triggers go through the no-`when` path.
    // A voice queued to start after this one (a sound scheduled ahead, then a press) cuts this one when it starts and
    // stays the latest: the voices of a slot or slice cut each other in the order they sound, not the order queued.
    let cutAt: number | undefined;
    const retrigger = (previous: WebAudioSourceHandle | undefined): boolean => {
      if (previous === undefined) return true;
      if (isQueued(previous, startAt)) {
        cutAt = Math.min(cutAt ?? Infinity, previous.startContextSeconds!);
        return false;
      }
      stopSource(previous, startAt);
      return true;
    };
    const latestOfSlice = retrigger(previousSlice);
    const latestOfSlot = !usesMonophonicWAVPlayback(chart, sampleKey) || retrigger(activeBySlot.get(sampleKey));
    if (hasEnvelope && built.gain) {
      scheduleSliceEnvelope(built.gain.gain, startAt, durationSeconds, envelope, basePlaybackRate * built.stageRate);
    }
    // A cut slice rings on past its end while it fades out.
    startSampleNode(
      node,
      startAt,
      offsetSeconds,
      durationSeconds === undefined ? undefined : durationSeconds + envelope.fadeOut,
    );
 
    activeSources.add(built);
    built.startContextSeconds = startAt;
    if (cutAt !== undefined) stopSource(built, cutAt);
    if (latestOfSlot) activeBySlot.set(sampleKey, built);
    if (sliceId !== undefined && latestOfSlice) activeBySlice.set(sliceId, built);
    if (isPlayerLane) activeByChannel.set(channel, built);
  };
 
  /** Whether `event`'s sound, started `elapsedSeconds` ago, still has something left to play. */
  const isStillRinging = (event: BeMusicEvent, sampleKey: string, path: string, elapsedSeconds: number): boolean => {
    const buffer = sampleBuffer(path, sampleKey);
    Iif (!buffer) return false;
    const slice = bmsonSlicePlayback?.get(event);
    const sliceRate = sliceRateOf(sampleKey);
    const start = (slice?.offsetSeconds ?? 0) / sliceRate;
    const end = Math.min(
      slice?.durationSeconds !== undefined
        ? start + slice.durationSeconds / sliceRate + (slice.releaseSeconds ?? 0)
        : buffer.duration,
      buffer.duration,
    );
    return start + elapsedInBuffer(sampleKey, elapsedSeconds) * voiceRateOf(slice) < end;
  };
 
  const applyDynamicVolumeEvent = (event: BeMusicEvent, audioContextSeconds?: number): void => {
    Iif (disposed) return;
    const gain = parseBMSDynamicVolumeGain(event.value);
    Iif (gain === undefined) return;
    const clamped = Math.max(0, Math.min(1, gain));
    const now = audioContext.currentTime;
    settleGainChanges(now);
    // Due ahead of the audio clock: it applies to the voices that start from then (`dynamicGainAt`).
    if (audioContextSeconds !== undefined && audioContextSeconds > now + 1e-6) {
      const bgm = isBmsBGMVolumeChangeChannel(event.channel);
      Iif (!bgm && !isBMSKeyVolumeChangeChannel(event.channel)) return;
      const at = audioContextSeconds;
      const index = pendingGainChanges.findIndex((change) => change.at > at);
      pendingGainChanges.splice(index < 0 ? pendingGainChanges.length : index, 0, { at, bgm, gain: clamped });
      return;
    }
    // BGM channel = `97`, key channel = `98`. The dispatcher already gated on
    // `isBMSDynamicVolumeChangeChannel(event.channel)` so one of the two predicates must match — but we still branch
    // explicitly so an unrecognized future channel doesn't accidentally retarget the wrong side. The stored gain is
    // consumed by `buildSourceNode` for subsequently triggered voices only — never written to the live bus mixers,
    // so in-flight voices keep the level they started with (docs/bms-spec.md「#xxx97 / #xxx98」).
    if (isBmsBGMVolumeChangeChannel(event.channel)) {
      currentBGMDynamicGain = clamped;
    } else Eif (isBMSKeyVolumeChangeChannel(event.channel)) {
      currentKeyDynamicGain = clamped;
    }
  };
 
  const guideSounds = context.guideSounds;
  return {
    ...(guideSounds !== undefined && guideSounds.size > 0
      ? {
          playGuideSound: (sound: GuideSound): void => {
            const buffer = guideSounds.get(sound);
            if (buffer === undefined) return;
            // Straight to the key bus, at once: a guide sound is no chart sample, so it has no lane to stop it, no
            // `#WAVCMD` gain and no tempo rate.
            const node = audioContext.createBufferSource();
            node.buffer = buffer;
            node.connect(audioBus.keyMixer);
            node.start();
          },
        }
      : {}),
    backendLabel: context.backendLabel ?? 'web-audio',
    chartStartDelayMs: context.chartStartDelayMs ?? 0,
    start: (): void => {
      // Defensive — repeat starts are a no-op so a host that re-invokes `start()` after pause / resume doesn't reset
      // the active-source tracking (which would lose `stopChannel` reach to in-flight LN samples).
      Iif (started) return;
      started = true;
      // Chart second 0 is now (after the backend's own start delay): a NONSTOP chart's fades fall from here.
      const delaySeconds = (context.chartStartDelayMs ?? 0) / 1000;
      anchorChartAt(delaySeconds > 0 ? -delaySeconds * tempo : 0);
      if (crossfadeSeconds > 0) openGeneration();
    },
    pause: (): void => {
      Iif (paused) return;
      paused = true;
      void audioContext.suspend?.().catch(() => undefined);
    },
    resume: (): void => {
      Iif (!paused) return;
      paused = false;
      void audioContext.resume?.().catch(() => undefined);
    },
    /**
     * Reports the chart's elapsed audio-context time so the engine's playback clock locks to the same reference
     * the renderer's `currentSeconds()` is using. Without this, the engine's default
     * `createPerformancePlaybackClockSource` would tick on `performance.now()` minus its own internal start
     * stamp — which drifts from the audio-context clock by however long the engine took to set up between the
     * host setting its `audioContextStartTime` and the engine entering its tick loop. The drift is small (tens
     * of ms) but enough to push judges off the visual judgment line by a couple of frames.
     */
    getClockState: () => {
      const chartStart = resolveChartStartContextTime();
      const outputSeconds = Math.max(0, audioContext.currentTime - chartStart);
      // We don't actually buffer ahead on the web (Web Audio's BufferSource handles its own scheduling), so the
      // scheduled head matches the output head. Reporting the same value lets the engine's
      // `createAudioPlaybackClockSource` short-circuit its `Math.max` between the two.
      // The write head runs ahead: the engine queues the chart's realtime sounds that early and `scheduleEventAt`
      // starts each at its due time (`WEB_AUDIO_SCHEDULE_AHEAD_SECONDS`).
      return { outputSeconds, scheduledSeconds: outputSeconds + WEB_AUDIO_SCHEDULE_AHEAD_SECONDS };
    },
    finish: async (): Promise<void> => {
      // Engine finished playback gracefully — let any tail samples ring out naturally. Drop our tracking so a
      // post-finish `stopChannel` (defensive) doesn't try to silence an already-cleaned source.
      activeBySlot.clear();
      activeBySlice.clear();
      activeByChannel.clear();
      activeSources.clear();
    },
    dispose: async (): Promise<void> => {
      Iif (disposed) return;
      disposed = true;
      // Hard-stop every still-playing source so they don't survive into the next chart's bus and bleed audio. The
      // engine's dispose path runs after `finish` (the abort variant) — the source set is empty in the graceful
      // path so this loop is a no-op there.
      for (const handle of Array.from(activeSources)) {
        stopSource(handle);
      }
      activeBySlot.clear();
      activeBySlice.clear();
      activeByChannel.clear();
      activeSources.clear();
      preparedBuffers.clear();
      for (const gain of generation === undefined ? [] : crossfadeGains(generation)) {
        try {
          gain.disconnect();
        } catch {
          // Already disconnected, or the context closed first.
        }
      }
      generation = undefined;
    },
    triggerEvent: (event: BeMusicEvent): void => {
      // Dynamic volume changes (`#xxx97` / `#xxx98`) reach the session through the same `triggerEvent` channel as
      // sample plays — the engine batches all realtime audio into one stream — so we branch on the channel here.
      if (isBmsBGMVolumeChangeChannel(event.channel) || isBMSKeyVolumeChangeChannel(event.channel)) {
        applyDynamicVolumeEvent(event);
        return;
      }
      playSampleEvent(event);
    },
    triggerEventAt: (event: BeMusicEvent, offsetSeconds: number): void => {
      Iif (isBmsBGMVolumeChangeChannel(event.channel) || isBMSKeyVolumeChangeChannel(event.channel)) {
        applyDynamicVolumeEvent(event);
        return;
      }
      playSampleEvent(event, undefined, offsetSeconds);
    },
    scheduleEvent: (event: BeMusicEvent, audioContextStartSeconds: number): void => {
      // Scheduled cues are exclusively BGM-style triggers (player input is by definition immediate), so we don't
      // expect dynamic volume events to arrive here — but route them through the same handler if they ever do so a
      // misuse doesn't silently drop the event.
      Iif (isBmsBGMVolumeChangeChannel(event.channel) || isBMSKeyVolumeChangeChannel(event.channel)) {
        applyDynamicVolumeEvent(event);
        return;
      }
      playSampleEvent(event, audioContextStartSeconds);
    },
    scheduleEventAt: (event: BeMusicEvent, outputSeconds: number): void => {
      // The output clock `getClockState` reports is the context's, from the chart's start.
      const at = resolveChartStartContextTime() + outputSeconds;
      if (isBmsBGMVolumeChangeChannel(event.channel) || isBMSKeyVolumeChangeChannel(event.channel)) {
        applyDynamicVolumeEvent(event, at);
        return;
      }
      playSampleEvent(event, at);
    },
    setTempo: (next: number): void => {
      Iif (disposed || !(Number.isFinite(next) && next > 0)) return;
      // The chart runs on at the new tempo from where it is now: a NONSTOP chart's fades move with it.
      const chartNow = chartSecondsNow();
      tempo = next;
      Eif (chartNow !== undefined) anchorChartAt(chartNow);
      if (context.playbackRateFollowsTempo !== true) return;
      basePlaybackRate = next;
      const now = audioContext.currentTime;
      for (const handle of activeSources) {
        glidePlaybackRate(handle.node.playbackRate, next * handle.stageRate, now);
      }
    },
    seek: (seconds: number): void => {
      Iif (disposed) return;
      // What plays belongs to the old position; the engine starts what still rings at `seconds` partway. With
      // crossfades on, the old position fades out under the new one instead of stopping at once.
      if (crossfadeSeconds > 0 && started) {
        closeGeneration(Array.from(activeSources));
        openGeneration();
      } else for (const handle of Array.from(activeSources)) stopSource(handle);
      activeBySlot.clear();
      activeBySlice.clear();
      activeByChannel.clear();
      activeSources.clear();
      // The engine applies the volume changes before `seconds` again, from the chart's start values.
      currentBGMDynamicGain = 1;
      currentKeyDynamicGain = 1;
      pendingGainChanges = [];
      anchorChartAt(seconds);
    },
    stopChannel: (channel: string): void => {
      const handle = activeByChannel.get(normalizeChannel(channel));
      if (!handle) return;
      stopSource(handle);
    },
  };
}
 
/**
 * Moves a sample's playback rate to `rate` over {@link LIVE_TEMPO_RAMP_SECONDS} from `now`, so a long sample already
 * playing changes speed without a click. A bmson slice keeps its length in buffer time, so it still ends on its note.
 */
export function glidePlaybackRate(param: AudioParam, rate: number, now: number): void {
  param.cancelScheduledValues(now);
  param.setValueAtTime(param.value, now);
  param.linearRampToValueAtTime(rate, now + LIVE_TEMPO_RAMP_SECONDS);
}
 
/**
 * Schedules the ramps of a bmson slice that cuts its source file (see `resolveSampleSliceEnvelope`) on the voice's
 * gain, from its level now. `lengthSeconds` and the envelope are buffer time; `rate` turns them into context time.
 * A live tempo change later glides the rate, which moves the end of a slice by a fraction of the ramp at most.
 */
export function scheduleSliceEnvelope(
  param: AudioParam,
  startAt: number,
  lengthSeconds: number | undefined,
  envelope: SampleSliceEnvelope,
  rate: number,
): void {
  const level = param.value;
  if (envelope.fadeIn > 0) {
    param.setValueAtTime(0, startAt);
    param.linearRampToValueAtTime(level, startAt + envelope.fadeIn / rate);
  }
  if (envelope.fadeOut > 0 && lengthSeconds !== undefined) {
    const endAt = startAt + lengthSeconds / rate;
    param.setValueAtTime(level, endAt);
    param.linearRampToValueAtTime(0, endAt + envelope.fadeOut / rate);
  }
}
 
/**
 * Clamps a bmson slice offset against the loaded buffer's duration so a misauthored offset (or one that came from a
 * trimmed take) doesn't produce a `start()` call past EOF — Web Audio would silently emit nothing in that case. Any
 * non-finite / negative input collapses to 0 so the historical "play from t=0" behavior stays the default fallback.
 *
 * Exported for test parity with the inlined version that {@link createWebAudioSession} uses internally.
 */
export function clampSampleOffset(offsetSeconds: number | undefined, bufferDuration: number): number {
  if (typeof offsetSeconds !== 'number' || !Number.isFinite(offsetSeconds) || offsetSeconds <= 0) {
    return 0;
  }
  if (offsetSeconds >= bufferDuration) {
    return Math.max(0, bufferDuration - 1e-3);
  }
  return offsetSeconds;
}
 
/**
 * Caps a bmson slice duration against the loaded buffer's tail so the slice playback doesn't overshoot the file.
 * Returns `undefined` when no duration was authored — the caller then lets the buffer source play to its natural end
 * (matching BMS-style "trigger plays the whole sample" semantics).
 */
export function clampSampleDuration(
  durationSeconds: number | undefined,
  bufferDuration: number,
  offsetSeconds: number,
): number | undefined {
  if (typeof durationSeconds !== 'number' || !Number.isFinite(durationSeconds) || durationSeconds <= 0) {
    return undefined;
  }
  const remaining = Math.max(0, bufferDuration - offsetSeconds);
  Iif (remaining <= 0) {
    return undefined;
  }
  return Math.min(durationSeconds, remaining);
}
 
/**
 * Wraps `AudioBufferSourceNode.start` so the offset / duration arguments only get supplied when meaningful — Web Audio
 * differentiates `start(when)` (whole buffer) from `start(when, offset)` (seek) from `start(when, offset, duration)`
 * (seek + cap), and we want to match the historical behavior for the two- and three-arg cases when slicing isn't in
 * play.
 *
 * `when` of `undefined` calls `start()` (immediate); a finite value calls `start(when)` (scheduled).
 */
export function startSampleNode(
  node: AudioBufferSourceNode,
  when: number | undefined,
  offsetSeconds: number,
  durationSeconds: number | undefined,
): void {
  const hasOffset = offsetSeconds > 0;
  const hasDuration = typeof durationSeconds === 'number';
  Eif (when !== undefined) {
    if (hasDuration) {
      node.start(when, offsetSeconds, durationSeconds);
    } else if (hasOffset) {
      node.start(when, offsetSeconds);
    } else {
      node.start(when);
    }
    return;
  }
  if (hasDuration) {
    node.start(0, offsetSeconds, durationSeconds);
  } else if (hasOffset) {
    node.start(0, offsetSeconds);
  } else {
    node.start();
  }
}
 
/**
 * The key a `#WAV` path's decoded sample is cached under for {@link createWebAudioSession}: the path normalized
 * (`\\` → `/`, `.` / `..` / empty segments resolved) and lower-cased. Every host that fills `decodedSamples` uses it, so
 * `./kick.wav`, `../common/kick.wav` or a differently-cased path finds its buffer.
 */
export function decodedSampleKey(path: string, slot?: string): string {
  const key = normalizePath(path).toLowerCase();
  return slot === undefined ? key : `${key}\0slot:${slot}`;
}