All files / player-browser/src/chart preview.ts

83.99% Statements 404/481
70.37% Branches 209/297
88.7% Functions 55/62
89.51% Lines 367/410

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 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065                                            24x                   24x               24x           24x           24x           24x                                                                                                                                               13x 13x 10x 13x 9x                                                                                 16x             16x           16x 16x   16x                         16x 16x 16x 16x       16x 16x 16x                   10x 10x     10x 10x 10x 10x 10x 10x 10x 1x   9x 7x 7x   2x                           10x 10x 10x 10x 10x 10x 10x 10x                                                                                                 2x 2x     2x 2x 2x 2x 2x 2x       22x 1x 1x         22x 22x 8x 6x   2x             27x 27x 27x 27x 27x                 27x 27x 27x       6x 6x 6x 6x 6x 6x 6x 6x 6x         6x   4x 4x                 26x 26x 26x 26x 26x             2x 2x 2x         2x       1x 1x 1x 1x             1x           6x 6x 6x       6x 6x       6x 2x         17x 17x 17x       24x 5x 5x       71x       7x 7x 7x 1x 1x   6x               9x 9x 11x       11x 11x 11x 11x 11x 11x 11x 9x                 1x 1x           1x   1x 1x 1x 1x 1x             1x 1x 1x     1x 1x         1x       10x 10x 2x 8x 10x 10x 10x                 10x 10x               19x 19x   15x 15x   19x             15x 15x 15x 15x       15x 15x 15x 15x 15x 15x                                                       10x 10x 14x   10x 10x 10x 10x 10x 27x 19x 19x 19x 19x     10x 4x 4x 10x 10x 3x   4x 7x 10x   7x 6x 6x   4x       10x 10x     10x 10x 10x 17x 10x 10x   10x 12x   4x   4x 4x 4x 6x 6x       6x 6x     10x 10x 10x 10x         10x 10x 10x 10x                 17x 17x 17x       17x     17x 17x 17x 17x 17x 17x       17x 17x 17x       17x 17x 17x 17x 17x 17x 17x 17x         10x 12x 12x   11x 12x 12x   10x 15x 15x 15x 15x 15x 15x   10x       6x 6x 6x       6x 6x 6x 9x 9x     6x 6x   8x 8x 8x 8x 8x     6x           6x 6x 6x 6x 6x     6x 6x         6x 6x 6x 6x 9x 9x     9x     9x 9x   9x 9x 9x 9x 9x       9x 9x 9x 9x 9x           9x 9x 1x   9x     9x   9x 9x 9x             6x 6x                           22x 19x       19x 19x     58x       45x                     12x 11x 11x 48x                           14x 63x 14x 13x 14x 14x 14x 23x 3x   13x                       16x 16x 15x 16x   16x 4x 4x                                               11x 11x 14x   14x 14x 14x 14x         24x     24x                       12x 6x 6x 5x 5x 5x 3x                 22x                         20x 20x 20x 20x       12x 9x 1x                                                             9x 9x 8x 8x     7x 7x 9x   7x 286x 337x 6x       1x         26x    
import {
  firesBeforeTempoReversal,
  isInvisibleNoteChannel,
  resolveBmsWAVResources,
  resolveChart,
  usesMonophonicWAVPlayback,
  volWAVToLinearGain,
  type TimedSampleTrigger,
} from '@be-music/chart-model';
import type { BeMusicJSON } from '@be-music/chart-source';
import { loadAssetBytes, resolveChartAudioAsset } from '../collection/collection.ts';
import type { LibraryChart } from '@be-music/player-scene-model';
import type { BrowserAssetEntry, BrowserAssetSource } from '../collection/types.ts';
import { MIXER_HEADROOM_GAIN_LINEAR } from '../runtime/audio-bus.ts';
import type { TimeStretchAlgorithm } from '../runtime/time-stretch.ts';
import { PreviewStretchStore } from './preview-stretch.ts';
 
/**
 * Sample-amplitude threshold below which we treat audio as silent for the leading-silence trim. Mirrors
 * `PREVIEW_SILENCE_THRESHOLD` in `packages/player-engine`'s CLI preview module — the rendered float waveform there uses the
 * same cut-off — so the web and CLI behave identically when given the same source file.
 */
const PREVIEW_SILENCE_THRESHOLD = 0.0001;
 
/**
 * Focus → preview-start delay, in milliseconds. Mirrors LR2's default song-select wait — the player has to leave the
 * cursor on a bar for ~1 second before the preview kicks in, which keeps a fast scroll through the list quiet rather
 * than machine-gunning every chart's intro for 50 ms each.
 *
 * Exported as a constant rather than baked into the engine so tests / hosts can reach for the "official" value without
 * hard-coding a magic number themselves.
 */
export const LR2_PREVIEW_FOCUS_DELAY_MS = 1000;
 
/**
 * Hard cap on the in-place chart-playback fallback (the "no `#PREVIEW` declared" branch). LR2 itself doesn't ship this
 * fallback — it just stays silent for charts without a preview audio file — but we want the user to hear *something* so
 * they can audition the chart. 30 s gives the typical chart intro + first verse without scheduling thousands of sample
 * triggers up-front.
 */
export const DEFAULT_CHART_PREVIEW_FALLBACK_DURATION_SECONDS = 30;
 
/**
 * Short fade used when the focused song changes or the select scene hides. Long enough to avoid an audible hard cut,
 * short enough that rapid cursor movement still feels responsive.
 */
export const CHART_PREVIEW_STOP_FADE_OUT_SECONDS: number = 0.25;
 
/**
 * How long the in-place fallback (no `#PREVIEW`) fades out at the end of its window, so the preview closes like a
 * preview file instead of the chart stopping mid-phrase while its long samples ring on.
 */
export const CHART_PREVIEW_FALLBACK_FADE_OUT_SECONDS: number = 3;
 
/**
 * How long a window preview ({@link ChartPreviewEngine.playWindow}) rings on past its end while it fades out, so a bar
 * closes without a click but the next bar's first hit stays out.
 */
export const CHART_PREVIEW_WINDOW_FADE_OUT_SECONDS: number = 0.12;
 
/** A stretch of a chart to sound, in chart seconds: `[startSeconds, endSeconds)`. */
export interface ChartPreviewWindow {
  readonly startSeconds: number;
  readonly endSeconds: number;
  /**
   * The play tempo the window sounds at (default 1): a play at that tempo's speed, the chart's seconds `tempo` times as
   * fast. With `keepPitch` the samples are stretched to it at their own pitch (`stretchAlgorithm`, WSOLA by default),
   * as a keep-pitch play does; otherwise they play `tempo` times as fast, the pitch following, as LR2 does.
   */
  readonly tempo?: number;
  readonly keepPitch?: boolean;
  readonly stretchAlgorithm?: TimeStretchAlgorithm;
}
 
export interface ChartPreviewTarget {
  chart: LibraryChart;
  source: BrowserAssetSource;
}
 
interface PreviewSourceHandle {
  source: AudioBufferSourceNode;
  gain: GainNode;
  /** The source's resting level ({@link resolveChartPreviewLevel}), which the window-end fade starts from. */
  level: number;
  stopping: boolean;
}
 
export interface ChartPreviewEngineOptions {
  /**
   * Override for the focus-to-start delay. Defaults to {@link LR2_PREVIEW_FOCUS_DELAY_MS}. Lower values are useful for
   * tests / debugging; production hosts should leave this at the default to match LR2.
   */
  focusDelayMs?: number;
  /**
   * Maximum duration of the in-place chart-playback fallback used when the chart has no `#PREVIEW`. Defaults to {@link
   * DEFAULT_CHART_PREVIEW_FALLBACK_DURATION_SECONDS}.
   */
  fallbackDurationSeconds?: number;
  /**
   * Whether the `#PREVIEW`-file playback should loop. Defaults to `true` so a 5-second preview wav doesn't go silent
   * after the first pass — LR2 also loops these.
   */
  loopPreviewFile?: boolean;
  /**
   * Optional callback fired when the engine actually begins audible playback for a target (after the focus delay AND
   * the asset decode). Hosts can use this to duck the select-screen BGM, log telemetry, etc. Receives the target
   * identity that started.
   */
  onPlaybackStart?: (target: ChartPreviewTarget) => void;
  /**
   * Optional callback fired when active preview playback stops — either because the engine was asked to stop, the
   * target changed, or the looped buffer was last-source-replaced. Symmetric with {@link onPlaybackStart}.
   */
  onPlaybackStop?: () => void;
}
 
/**
 * Returns the chart-relative path to the preview audio that should play on song-select focus, or `undefined` when the
 * chart didn't declare one.
 *
 * Resolution priority:
 *
 * 1. `#PREVIEW <path>` (BMS) — stored in `chart.bms.preview` by the parser.
 * 2. `info.preview_music` (bmson) — stored in `chart.bmson.info.previewMusic`.
 *
 * Both are chart-relative paths handed to `resolveChartAudioAsset` unchanged; the audio loader walks the codec-fallback
 * chain (`.opus` / `.ogg` / `.mp3` / `.wav`) and case-insensitive lookup so a chart that says `preview.wav` still
 * resolves to a shipped `preview.ogg`.
 */
export function resolveChartPreviewPath(chart: BeMusicJSON): string | undefined {
  const bms = chart.bms?.preview;
  if (typeof bms === 'string' && bms.length > 0) return bms;
  const bmson = chart.bmson?.info?.previewMusic;
  if (typeof bmson === 'string' && bmson.length > 0) return bmson;
  return undefined;
}
 
/**
 * Drives the song-select preview audio: a single AudioContext client that schedules playback shortly after the user's
 * cursor settles on a song, and tears it back down when the cursor moves on or the scene goes away.
 *
 * Two playback modes (mirrors the user-facing requirement):
 *
 * 1. **`#PREVIEW` present** — the chart shipped a preview audio file. We resolve it through {@link
 *    resolveChartAudioAsset} (case-insensitive + codec fallback), decode once, and play it on a looped `BufferSource`.
 *
 * 2. **`#PREVIEW` absent** — fall back to playing the chart "in place": collect every AUTO PLAY-audible
 *    `TimedSampleTrigger` whose `seconds` fall inside the fallback duration window, decode just those WAVs (a small
 *    subset of the chart's full `#WAVxx` table), and schedule each as a one-shot at `audioContext.currentTime +
 *    trigger.seconds`. Stops scheduling further triggers once the user moves cursor.
 *
 * Lifecycle:
 *
 * - `focus(target)` cancels any pending / active playback, then schedules the next start on a `setTimeout` so a fast
 *   scroll past dozens of bars doesn't actually start anything.
 * - `focus(undefined)` is the explicit "stop and forget".
 * - `dispose()` is permanent; further `focus()` calls no-op.
 *
 * Race-safety is handled via a monotonic `activeSequence`: every `focus()` increments it, and every async callback
 * re-checks before mutating state. A WAV decode that returns AFTER the user moved cursor never schedules its source.
 */
export class ChartPreviewEngine {
  private readonly audioContext: AudioContext;
  private readonly output: AudioNode;
  private readonly focusDelayMs: number;
  private readonly fallbackDurationSeconds: number;
  private readonly loopPreviewFile: boolean;
  private readonly onPlaybackStart: ((target: ChartPreviewTarget) => void) | undefined;
  private readonly onPlaybackStop: (() => void) | undefined;
  private currentTarget: ChartPreviewTarget | undefined;
  /**
   * Increments on every `focus` (including `focus(undefined)` and `stop`). Async work captures the value at the moment
   * it was scheduled and bails if the field has moved on by the time it can act — that's how we keep stale decodes from
   * silently scheduling sources after the user has moved on.
   */
  private activeSequence = 0;
  private pendingFocusTimer: ReturnType<typeof setTimeout> | undefined;
  /**
   * Live preview sources, including short fade-out tails from the previous focus. Tracked so a subsequent `stop()` can
   * disconnect them all in one pass — necessary because the in-place fallback typically schedules many sources at once
   * and the loopable preview-file branch keeps a single source alive across the entire focus.
   */
  private activeSources = new Set<PreviewSourceHandle>();
  /**
   * `true` once the engine has emitted `onPlaybackStart` for the current sequence and not yet emitted the matching
   * `onPlaybackStop`. Keeps the start / stop callbacks paired even when the in-place fallback's first audible sample is
   * delayed by a slow decode.
   */
  private playbackActive = false;
  private disposed = false;
  /** A window preview ({@link playWindow}) was started since the last focus, so even no focus has something to stop. */
  private windowStarted = false;
  /** The chart a window preview last sounded, with its triggers and decodes, kept for the next window of it. */
  private windowCache:
    | {
        readonly target: ChartPreviewTarget;
        readonly triggers: readonly TimedSampleTrigger[];
        readonly buffers: Map<string, Promise<AudioBuffer | undefined>>;
        /** Samples stretched for a keep-pitch window, the bar first and the rest of the chart in the background. */
        readonly stretcher: PreviewStretchStore;
      }
    | undefined;
 
  public constructor(audioContext: AudioContext, output: AudioNode, options: ChartPreviewEngineOptions = {}) {
    this.audioContext = audioContext;
    this.output = output;
    this.focusDelayMs = Math.max(0, options.focusDelayMs ?? LR2_PREVIEW_FOCUS_DELAY_MS);
    this.fallbackDurationSeconds = Math.max(
      0,
      options.fallbackDurationSeconds ?? DEFAULT_CHART_PREVIEW_FALLBACK_DURATION_SECONDS,
    );
    this.loopPreviewFile = options.loopPreviewFile ?? true;
    this.onPlaybackStart = options.onPlaybackStart;
    this.onPlaybackStop = options.onPlaybackStop;
  }
 
  /**
   * Sets the focused song (or clears it). The actual audio playback won't start until the focus-settle delay elapses; a
   * fast scroll past the song therefore doesn't trigger any decode work. Pass `undefined` to stop without re-arming.
   *
   * Idempotent: focusing the same target twice in a row only arms one timer.
   */
  public focus(target: ChartPreviewTarget | undefined): void {
    Iif (this.disposed) return;
    Iif (sameTarget(this.currentTarget, target) && !this.windowStarted) {
      return;
    }
    this.windowStarted = false;
    const sequence = ++this.activeSequence;
    this.cancelPending();
    this.stopAllSources({ fade: true });
    this.emitPlaybackStop();
    this.currentTarget = target;
    if (!target) {
      return;
    }
    if (this.focusDelayMs <= 0) {
      void this.startPreview(target, sequence);
      return;
    }
    this.pendingFocusTimer = setTimeout(() => {
      this.pendingFocusTimer = undefined;
      void this.startPreview(target, sequence);
    }, this.focusDelayMs);
  }
 
  /**
   * Sounds `window` of `target`'s chart at once, as AUTO PLAY would play it there (a PRACTICE bar's audition): every
   * sample that starts inside the window, and every sample started before it that still sounds at its start (a long
   * BGM, a long note's keysound) from where it is there, fading out just past the window's end. Whatever was playing
   * (the focus preview, or the previous window) fades out first, and the focus is forgotten, so focusing the chart
   * again re-arms its preview. The chart's triggers and decoded samples are kept for the next window of the same chart.
   */
  public playWindow(target: ChartPreviewTarget, window: ChartPreviewWindow): void {
    Iif (this.disposed) return;
    const sequence = ++this.activeSequence;
    this.cancelPending();
    this.stopAllSources({ fade: true });
    this.emitPlaybackStop();
    this.currentTarget = undefined;
    this.windowStarted = true;
    void this.playWindowNow(target, window, sequence);
  }
 
  /**
   * Gets the window previews of `target` ready to sound at `settings`' tempo with the pitch kept: in the background,
   * what each of `bars` sounds is stretched, nearest `aroundSeconds` first and a sample at a time, while a window that
   * plays always goes ahead of it. A new tempo or stretcher starts over; `undefined` settings (or a tempo that keeps the
   * pitch at 1, or a pitch that follows the tempo) stop the background and keep what was stretched.
   */
  public prepareWindows(
    target: ChartPreviewTarget,
    settings: Omit<ChartPreviewWindow, 'startSeconds' | 'endSeconds'> | undefined,
    bars?: readonly Pick<ChartPreviewWindow, 'startSeconds' | 'endSeconds'>[],
    aroundSeconds?: number,
  ): void {
    if (this.disposed) return;
    const rate =
      settings?.tempo !== undefined && Number.isFinite(settings.tempo) && settings.tempo > 0 ? settings.tempo : 1;
    const stretching = settings !== undefined && rate !== 1 && settings.keepPitch === true;
    if (!stretching) {
      if (this.windowCache !== undefined && sameTarget(this.windowCache.target, target))
        this.windowCache.stretcher.prepare(undefined);
      return;
    }
    this.windowCacheFor(target).stretcher.prepare(
      { rate, algorithm: settings.stretchAlgorithm ?? 'wsola' },
      bars,
      aroundSeconds,
    );
  }
 
  /**
   * Force-stops any pending / active preview without changing the focused-target field. Use this when the host wants
   * the preview to go silent (scene hidden, song picked, etc.) but is about to call `focus(...)` again with new state.
   */
  public stop(): void {
    if (this.disposed) return;
    // Bump first so async loads/decodes already in flight cannot schedule new sources while we fade the old ones out.
    this.activeSequence += 1;
    this.cancelPending();
    this.stopAllSources({ fade: true });
    this.emitPlaybackStop();
  }
 
  /**
   * Permanent teardown. Stops everything, drops references, and makes subsequent `focus` / `stop` calls no-ops. Doesn't
   * close the AudioContext — the host owns that.
   */
  public dispose(): void {
    Iif (this.disposed) return;
    this.disposed = true;
    // Bump the sequence just like `stop()` so async loads/decodes already in flight cannot resurrect playback after
    // permanent teardown.
    this.activeSequence += 1;
    this.cancelPending();
    this.stopAllSources({ fade: false });
    this.emitPlaybackStop();
    this.currentTarget = undefined;
    this.windowCache?.stretcher.dispose();
  }
 
  private cancelPending(): void {
    if (this.pendingFocusTimer !== undefined) {
      clearTimeout(this.pendingFocusTimer);
      this.pendingFocusTimer = undefined;
    }
  }
 
  private stopAllSources(options: { fade: boolean }): void {
    const now = this.audioContext.currentTime;
    for (const handle of Array.from(this.activeSources)) {
      if (options.fade) {
        this.fadeOutSource(handle, now);
      } else {
        this.stopSourceImmediately(handle);
      }
    }
  }
 
  private attachSource(source: AudioBufferSourceNode, level: number): PreviewSourceHandle | undefined {
    let gain: GainNode;
    try {
      gain = this.audioContext.createGain();
      gain.gain.value = level;
      source.connect(gain);
      gain.connect(this.output);
    } catch {
      try {
        source.disconnect();
      } catch {
        // Disconnect is best-effort — failure just means there is nothing useful to tear down.
      }
      return undefined;
    }
    const handle: PreviewSourceHandle = { source, gain, level, stopping: false };
    this.activeSources.add(handle);
    return handle;
  }
 
  private fadeOutSource(handle: PreviewSourceHandle, now: number): void {
    Iif (handle.stopping) return;
    handle.stopping = true;
    const fadeEnd = now + CHART_PREVIEW_STOP_FADE_OUT_SECONDS;
    try {
      const gain = handle.gain.gain;
      gain.cancelScheduledValues(now);
      gain.setValueAtTime(gain.value, now);
      gain.linearRampToValueAtTime(0, fadeEnd);
      handle.source.stop(fadeEnd);
    } catch {
      this.finishSource(handle);
      return;
    }
    setTimeout(
      () => {
        Eif (handle.stopping) {
          this.finishSource(handle);
        }
      },
      CHART_PREVIEW_STOP_FADE_OUT_SECONDS * 1000 + 50,
    );
  }
 
  /** Fades `handle` out over the fallback window's last seconds and stops it at the window's end. */
  private fadeOutAtWindowEnd(handle: PreviewSourceHandle, fadeStartAt: number, endAt: number): void {
    try {
      const gain = handle.gain.gain;
      gain.setValueAtTime(handle.level, fadeStartAt);
      gain.linearRampToValueAtTime(0, endAt);
      handle.source.stop(endAt);
    } catch {
      // A context that refuses the automation keeps the source as it was: it ends with its sample.
    }
  }
 
  private stopSourceImmediately(handle: PreviewSourceHandle): void {
    handle.stopping = true;
    try {
      handle.source.stop();
    } catch {
      // `stop()` throws when the source hasn't started yet (a future-scheduled trigger we never reached) or has already
      // ended. Both are fine — we just want it gone.
    }
    this.finishSource(handle);
  }
 
  private stopSourceAt(handle: PreviewSourceHandle, stopAt: number): void {
    const scheduledStopAt = Number.isFinite(stopAt) ? Math.max(this.audioContext.currentTime, stopAt) : undefined;
    try {
      if (scheduledStopAt !== undefined) {
        handle.source.stop(scheduledStopAt);
      } else E{
        handle.source.stop();
      }
    } catch {
      // Already stopped, never started, or context closed.
    }
    Iif (scheduledStopAt === undefined || scheduledStopAt <= this.audioContext.currentTime + 1e-6) {
      this.finishSource(handle);
    }
  }
 
  private finishSource(handle: PreviewSourceHandle): void {
    const wasActive = this.activeSources.delete(handle);
    try {
      handle.source.disconnect();
    } catch {
      // Disconnect is idempotent + safe to silence.
    }
    try {
      handle.gain.disconnect();
    } catch {
      // Same.
    }
    if (wasActive && this.activeSources.size === 0) {
      this.emitPlaybackStop();
    }
  }
 
  private emitPlaybackStart(target: ChartPreviewTarget): void {
    Iif (this.playbackActive) return;
    this.playbackActive = true;
    this.onPlaybackStart?.(target);
  }
 
  private emitPlaybackStop(): void {
    if (!this.playbackActive) return;
    this.playbackActive = false;
    this.onPlaybackStop?.();
  }
 
  private isStale(sequence: number): boolean {
    return this.disposed || sequence !== this.activeSequence;
  }
 
  private async startPreview(target: ChartPreviewTarget, sequence: number): Promise<void> {
    Iif (this.isStale(sequence)) return;
    const previewPath = resolveChartPreviewPath(target.chart.chart);
    if (previewPath !== undefined) {
      await this.playPreviewFile(target, previewPath, sequence);
      return;
    }
    await this.playInPlace(target, sequence);
  }
 
  private async decodeChartAudio(
    target: ChartPreviewTarget,
    path: string,
    sequence: number,
  ): Promise<AudioBuffer | undefined> {
    const attempted = new Set<BrowserAssetEntry>();
    while (!this.isStale(sequence)) {
      const entry = resolveChartAudioAsset(target.source, target.chart.chartPath, path, {
        pathPrefix: target.chart.chart.bms.pathWAV,
        ...(attempted.size ? { excludedEntries: attempted } : {}),
      });
      Iif (entry === undefined || attempted.has(entry)) return undefined;
      attempted.add(entry);
      try {
        const bytes = await loadAssetBytes(entry);
        Iif (this.isStale(sequence)) return undefined;
        Iif (!bytes) continue;
        const buffer = await this.audioContext.decodeAudioData(bytes.slice().buffer);
        return this.isStale(sequence) ? undefined : buffer;
      } catch {
        // A missing or unsupported candidate may still have a playable alternate codec.
      }
    }
    return undefined;
  }
 
  private async playPreviewFile(target: ChartPreviewTarget, previewPath: string, sequence: number): Promise<void> {
    const buffer = await this.decodeChartAudio(target, previewPath, sequence);
    Iif (!buffer) return;
    // LR2 / packages/player-engine both trim leading silence from the preview rendering so the user hears the first audible
    // sample the moment the focus delay elapses, not several hundred milliseconds of "did anything happen?" silence
    // baked into the source file. Web Audio's `start(when, offset)` is exactly the right tool: skip past the silent
    // prefix on first play, and pin the loop boundary to the same offset so every subsequent loop iteration also starts
    // at the first audible sample.
    const audibleOffsetSeconds = findFirstAudibleOffsetSeconds(buffer);
    let source: AudioBufferSourceNode;
    try {
      source = this.audioContext.createBufferSource();
      source.buffer = buffer;
      source.loop = this.loopPreviewFile;
      Iif (this.loopPreviewFile && audibleOffsetSeconds > 0) {
        source.loopStart = audibleOffsetSeconds;
        // `loopEnd = 0` means "end of buffer", which is what we want.
      }
    } catch {
      return;
    }
    const handle = this.attachSource(source, resolveChartPreviewLevel(target.chart.chart));
    Iif (!handle) return;
    source.onended = (): void => {
      this.finishSource(handle);
    };
    try {
      source.start(0, audibleOffsetSeconds);
    } catch {
      this.finishSource(handle);
      return;
    }
    this.emitPlaybackStart(target);
  }
 
  private windowCacheFor(target: ChartPreviewTarget): NonNullable<ChartPreviewEngine['windowCache']> {
    const cached = this.windowCache;
    if (cached !== undefined && sameTarget(cached.target, target) && cached.target.chart.chart === target.chart.chart)
      return cached;
    cached?.stretcher.dispose();
    const triggers = collectChartPreviewTriggers(target.chart.chart, Number.MAX_VALUE);
    const buffers = new Map<string, Promise<AudioBuffer | undefined>>();
    const fresh: NonNullable<ChartPreviewEngine['windowCache']> = {
      target,
      triggers,
      buffers,
      stretcher: new PreviewStretchStore(
        this.audioContext,
        async (bar, spec) => (await this.planWindow(fresh, bar, spec.rate, true)).requests,
      ),
    };
    this.windowCache = fresh;
    return fresh;
  }
 
  /** Decodes a sample once per chart for the window previews; a failed decode is kept as `undefined`. */
  private decodeWindowSample(
    cache: NonNullable<ChartPreviewEngine['windowCache']>,
    path: string,
  ): Promise<AudioBuffer | undefined> {
    let decoded = cache.buffers.get(path);
    if (decoded === undefined) {
      // The decode outlives the window that asked for it: the next window of the chart reuses it.
      decoded = this.decodeChartAudioUnsequenced(cache.target, path);
      cache.buffers.set(path, decoded);
    }
    return decoded;
  }
 
  private async decodeChartAudioUnsequenced(
    target: ChartPreviewTarget,
    path: string,
  ): Promise<AudioBuffer | undefined> {
    Iif (this.disposed) return undefined;
    const attempted = new Set<BrowserAssetEntry>();
    for (;;) {
      const entry = resolveChartAudioAsset(target.source, target.chart.chartPath, path, {
        pathPrefix: target.chart.chart.bms.pathWAV,
        ...(attempted.size ? { excludedEntries: attempted } : {}),
      });
      Iif (entry === undefined || attempted.has(entry)) return undefined;
      attempted.add(entry);
      try {
        const bytes = await loadAssetBytes(entry);
        Iif (!bytes) continue;
        return await this.audioContext.decodeAudioData(bytes.slice().buffer);
      } catch {
        // A missing or unsupported candidate may still have a playable alternate codec.
      }
    }
  }
 
  /**
   * What a window of the chart sounds: the triggers in it, those carried into it, their decoded samples by sample key,
   * and with `rate` stretching the pitch kept, what of each to stretch (a sample that has finished before the window
   * sounds nothing in it and is left out; of a long one, only the part the window sounds).
   */
  private async planWindow(
    cache: NonNullable<ChartPreviewEngine['windowCache']>,
    window: Pick<ChartPreviewWindow, 'startSeconds' | 'endSeconds'>,
    rate: number,
    stretching: boolean,
  ): Promise<{
    triggers: TimedSampleTrigger[];
    carried: TimedSampleTrigger[];
    sources: Map<string, { readonly path: string; readonly buffer: AudioBuffer }>;
    requests: {
      readonly key: string;
      readonly path: string;
      readonly source: AudioBuffer;
      readonly segment?: WindowStretchSegment;
    }[];
  }> {
    const chart = cache.target.chart.chart;
    const triggers = selectChartWindowTriggers(cache.triggers, window);
    const monophonic = (sampleKey: string): boolean => usesMonophonicWAVPlayback(chart, sampleKey);
    // What started before the window and may still sound at its start, as a play that seeks there starts it partway.
    const carried = selectChartWindowCarryOvers(cache.triggers, window, monophonic);
    const sources = new Map<string, { readonly path: string; readonly buffer: AudioBuffer }>();
    Iif (triggers.length === 0 && carried.length === 0) return { triggers, carried, sources, requests: [] };
    const wavResources = resolveBmsWAVResources(chart);
    await Promise.all(
      [...new Set([...carried, ...triggers].map((trigger) => trigger.sampleKey))].map(async (key) => {
        const path = wavResources[key];
        Iif (typeof path !== 'string') return;
        const buffer = await this.decodeWindowSample(cache, path);
        Eif (buffer !== undefined) sources.set(key, { path, buffer });
      }),
    );
    if (!stretching) return { triggers, carried, sources, requests: [] };
    const byKey = new Map<string, TimedSampleTrigger[]>();
    for (const trigger of [...carried, ...triggers]) {
      const list = byKey.get(trigger.sampleKey);
      if (list === undefined) byKey.set(trigger.sampleKey, [trigger]);
      else list.push(trigger);
    }
    const requests = [...sources].flatMap(([key, { path, buffer }]) => {
      const needs = windowSampleNeeds(byKey.get(key) ?? [], window, rate, buffer.duration).filter(
        (need) => need.endSeconds > need.startSeconds,
      );
      if (needs.length === 0) return [];
      const segment = resolveWindowStretchSegment(needs, buffer.duration);
      return [{ key, path, source: buffer, ...(segment !== undefined ? { segment } : {}) }];
    });
    return { triggers, carried, sources, requests };
  }
 
  private async playWindowNow(target: ChartPreviewTarget, window: ChartPreviewWindow, sequence: number): Promise<void> {
    const chart = target.chart.chart;
    const cache = this.windowCacheFor(target);
    // The play tempo: chart seconds pass `rate` times as fast. A keep-pitch window plays stretched samples at rate 1, a
    // pitch-following one plays the samples `rate` times as fast.
    const rate = window.tempo !== undefined && Number.isFinite(window.tempo) && window.tempo > 0 ? window.tempo : 1;
    const stretching = rate !== 1 && window.keepPitch === true;
    const { triggers, carried, sources, requests } = await this.planWindow(cache, window, rate, stretching);
    const monophonic = (sampleKey: string): boolean => usesMonophonicWAVPlayback(chart, sampleKey);
    Iif (triggers.length === 0 && carried.length === 0) return;
    const buffers = new Map<string, AudioBuffer>();
    /** The samples played stretched: where the part stretched starts in each, and the sample's own length. */
    const stretchedKeys = new Map<string, { readonly segmentStart: number; readonly sourceDuration: number }>();
    if (!stretching) for (const [key, { buffer }] of sources) buffers.set(key, buffer);
    else {
      const spec = { rate, algorithm: window.stretchAlgorithm ?? 'wsola' } as const;
      // The bar goes ahead of the background, which then carries on nearest this bar.
      cache.stretcher.prepare(spec, undefined, window.startSeconds);
      const stretched = await cache.stretcher.stretch(spec, requests);
      requests.forEach(({ key, source }, index) => {
        const part = stretched[index];
        Iif (part === undefined) {
          buffers.set(key, source);
          return;
        }
        buffers.set(key, part.buffer);
        stretchedKeys.set(key, { segmentStart: part.segmentStart, sourceDuration: source.duration });
      });
    }
    Iif (this.isStale(sequence)) return;
    const startAt = this.audioContext.currentTime + 0.02;
    const span = Math.max(0, window.endSeconds - window.startSeconds) / rate;
    const { fadeStartAt, endAt } = resolvePreviewFallbackFade(
      startAt,
      span + CHART_PREVIEW_WINDOW_FADE_OUT_SECONDS,
      CHART_PREVIEW_WINDOW_FADE_OUT_SECONDS,
    );
    const level = resolveChartPreviewLevel(chart);
    let scheduledCount = 0;
    const activeBySlot = new Map<string, PreviewSourceHandle>();
    const schedule = (
      trigger: TimedSampleTrigger,
      buffer: AudioBuffer,
      when: number,
      sampleOffsetSeconds: number,
      sampleDurationSeconds: number | undefined,
    ): void => {
      // A stretched sample is `rate` times shorter: its offset and slice scale with it; a sped-up one keeps them, the
      // buffer's own time.
      const stretchedPart = stretchedKeys.get(trigger.sampleKey);
      const stretched = stretchedPart !== undefined;
      const offsetSeconds = stretched
        ? Math.max(0, sampleOffsetSeconds - stretchedPart.segmentStart) / rate
        : sampleOffsetSeconds;
      const durationSeconds =
        sampleDurationSeconds === undefined || !stretched ? sampleDurationSeconds : sampleDurationSeconds / rate;
      let source: AudioBufferSourceNode;
      // An LRX note's own rate and gain; its balance and ramps are left to play.
      const voiceRate = previewVoiceRate(trigger);
      try {
        source = this.audioContext.createBufferSource();
        source.buffer = buffer;
        const sourceRate = (stretched ? 1 : rate) * voiceRate;
        if (sourceRate !== 1) source.playbackRate.value = sourceRate;
      } catch {
        return;
      }
      const handle = this.attachSource(source, level * (trigger.sampleGain ?? 1));
      Iif (!handle) return;
      source.onended = (): void => {
        if (activeBySlot.get(trigger.sampleKey) === handle) activeBySlot.delete(trigger.sampleKey);
        this.finishSource(handle);
      };
      try {
        const activeSameSlot = activeBySlot.get(trigger.sampleKey);
        Iif (monophonic(trigger.sampleKey) && activeSameSlot) this.stopSourceAt(activeSameSlot, when);
        Iif (durationSeconds !== undefined) source.start(when, offsetSeconds, durationSeconds);
        else source.start(when, offsetSeconds);
        this.fadeOutAtWindowEnd(handle, fadeStartAt, endAt);
        scheduledCount += 1;
        activeBySlot.set(trigger.sampleKey, handle);
      } catch {
        this.finishSource(handle);
      }
    };
    for (const trigger of carried) {
      const buffer = buffers.get(trigger.sampleKey);
      if (!buffer) continue;
      // In the sample's own time: a chart second of it has played per chart second, sped up or stretched alike.
      const sampleDuration = stretchedKeys.get(trigger.sampleKey)?.sourceDuration ?? buffer.duration;
      const part = resolveChartWindowCarryOver(trigger, sampleDuration, window.startSeconds);
      if (part !== undefined) schedule(trigger, buffer, startAt, part.offsetSeconds, part.durationSeconds);
    }
    for (const trigger of triggers) {
      const activeSameSlot = activeBySlot.get(trigger.sampleKey);
      Iif (chart.sourceFormat === 'bmson' && trigger.event.bmson?.c === true && activeSameSlot) continue;
      const buffer = buffers.get(trigger.sampleKey);
      Iif (!buffer) continue;
      const when = startAt + Math.max(0, trigger.seconds - window.startSeconds) / rate;
      schedule(trigger, buffer, when, trigger.sampleOffsetSeconds ?? 0, trigger.sampleDurationSeconds);
    }
    Eif (scheduledCount > 0) this.emitPlaybackStart(target);
  }
 
  private async playInPlace(target: ChartPreviewTarget, sequence: number): Promise<void> {
    const chart = target.chart.chart;
    const triggers = collectChartPreviewTriggers(chart, this.fallbackDurationSeconds);
    Iif (triggers.length === 0) return;
    // Unique #WAVxx slots referenced inside the preview window — the only WAVs we need to bother decoding for this
    // preview.
    // EXWAV can declare a slot's file without #WAVxx.
    const wavResources = resolveBmsWAVResources(chart);
    const sampleKeys = new Set<string>();
    for (const trigger of triggers) {
      Eif (typeof wavResources[trigger.sampleKey] === 'string') {
        sampleKeys.add(trigger.sampleKey);
      }
    }
    const buffers = new Map<string, AudioBuffer>();
    await Promise.all(
      [...sampleKeys].map(async (key) => {
        Iif (this.isStale(sequence)) return;
        const path = wavResources[key];
        Iif (typeof path !== 'string') return;
        const buffer = await this.decodeChartAudio(target, path, sequence);
        Eif (buffer) buffers.set(key, buffer);
      }),
    );
    Iif (this.isStale(sequence)) return;
    // Charts often have a few seconds of silent intro (no events until measure 1+). Pinning the first DECODABLE trigger
    // to `t=0` removes that lead-in so the user hears the first hit as soon as the focus delay elapses, matching how
    // `packages/player-engine`'s CLI preview trims its rendered waveform. We pick the earliest trigger whose WAV actually
    // decoded — a missing-buffer trigger contributes no audio, so leaving its `seconds` as the anchor would just
    // re-introduce the silence we're trying to remove.
    let leadOffsetSeconds = 0;
    for (const trigger of triggers) {
      Eif (buffers.has(trigger.sampleKey)) {
        leadOffsetSeconds = trigger.seconds;
        break;
      }
    }
    const startAt = this.audioContext.currentTime;
    const { fadeStartAt, endAt } = resolvePreviewFallbackFade(
      startAt,
      this.fallbackDurationSeconds - leadOffsetSeconds,
      CHART_PREVIEW_FALLBACK_FADE_OUT_SECONDS,
    );
    const level = resolveChartPreviewLevel(chart);
    let scheduledCount = 0;
    const activeBySlot = new Map<string, PreviewSourceHandle>();
    for (const trigger of triggers) {
      Iif (this.isStale(sequence)) return;
      const activeSameSlot = activeBySlot.get(trigger.sampleKey);
      // bmson `c = true` mirrors AUTO PLAY: the event continues the previous instance of this sample slot instead of
      // retriggering a fresh attack.
      Iif (chart.sourceFormat === 'bmson' && trigger.event.bmson?.c === true && activeSameSlot) {
        continue;
      }
      const buffer = buffers.get(trigger.sampleKey);
      Iif (!buffer) continue;
      let source: AudioBufferSourceNode;
      try {
        source = this.audioContext.createBufferSource();
        source.buffer = buffer;
        const voiceRate = previewVoiceRate(trigger);
        Iif (voiceRate !== 1) source.playbackRate.value = voiceRate;
      } catch {
        continue;
      }
      const handle = this.attachSource(source, level * (trigger.sampleGain ?? 1));
      Iif (!handle) continue;
      const offset = trigger.sampleOffsetSeconds ?? 0;
      const when = startAt + Math.max(0, trigger.seconds - leadOffsetSeconds);
      source.onended = (): void => {
        if (activeBySlot.get(trigger.sampleKey) === handle) {
          activeBySlot.delete(trigger.sampleKey);
        }
        this.finishSource(handle);
      };
      try {
        if (usesMonophonicWAVPlayback(chart) && activeSameSlot) {
          this.stopSourceAt(activeSameSlot, when);
        }
        Iif (typeof trigger.sampleDurationSeconds === 'number') {
          source.start(when, offset, trigger.sampleDurationSeconds);
        } else {
          source.start(when, offset);
        }
        this.fadeOutAtWindowEnd(handle, fadeStartAt, endAt);
        scheduledCount += 1;
        activeBySlot.set(trigger.sampleKey, handle);
      } catch {
        // `start` rejects on negative offsets / out-of-range values that can sneak in for malformed bmson slice
        // metadata. Keep going — one bad trigger shouldn't mute the rest of the preview.
        this.finishSource(handle);
      }
    }
    Eif (scheduledCount > 0) {
      this.emitPlaybackStart(target);
    }
  }
}
 
/**
 * Pure helper: pulls every AUTO PLAY-audible sample-trigger event out of `chart` whose chart-time falls inside the
 * preview window. Invisible objects update lane keysound state during gameplay, but AUTO PLAY does not directly sound
 * them, so the fallback preview skips them too. Exported for tests so the windowing math has direct coverage;
 * production callers reach this through {@link ChartPreviewEngine}.
 *
 * `cutoffSeconds <= 0` returns an empty array — the engine skips the in-place fallback entirely in that case.
 */
export function collectChartPreviewTriggers(chart: BeMusicJSON, cutoffSeconds: number): TimedSampleTrigger[] {
  if (!Number.isFinite(cutoffSeconds) || cutoffSeconds <= 0) return [];
  const resolved = resolveChart(chart, { inferBmsLNTypeWhenMissing: false });
  // LR2 negative-BPM reversal: the gameplay engine's event pump freezes at the reversal — nothing past it ever
  // sounds, and on the reversal tick only the BGM LR2 orders before the negative BPM does — so the select-scene
  // preview drops the same triggers.
  const { reversal } = resolved;
  return resolved.sampleTriggers
    .filter(
      (trigger) =>
        !isInvisibleNoteChannel(trigger.channel) &&
        trigger.seconds < cutoffSeconds &&
        firesBeforeTempoReversal(reversal, trigger.seconds, trigger.channel),
    )
    .sort((left, right) => left.seconds - right.seconds);
}
 
/**
 * Pure helper: the triggers of `triggers` (sorted by time, as {@link collectChartPreviewTriggers} returns them) that start
 * inside `window`, `[startSeconds, endSeconds)`. What started before the window is {@link selectChartWindowCarryOvers}'.
 */
export function selectChartWindowTriggers(
  triggers: readonly TimedSampleTrigger[],
  window: ChartPreviewWindow,
): TimedSampleTrigger[] {
  if (!(window.endSeconds > window.startSeconds)) return [];
  const startSeconds = window.startSeconds - 1e-6;
  const endSeconds = window.endSeconds - 1e-6;
  return triggers.filter((trigger) => trigger.seconds >= startSeconds && trigger.seconds < endSeconds);
}
 
/**
 * Pure helper: the triggers of `triggers` (sorted by time) that start before `window` and may still sound at its start,
 * to be started partway ({@link resolveChartWindowCarryOver}) as a play that seeks there does. Under monophonic WAV
 * playback (BMS) a slot's later trigger cuts its earlier ones, so only each slot's last trigger before the window counts.
 * A bmson continuation (`c`) is left out: it sounds through the instance it continues.
 */
export function selectChartWindowCarryOvers(
  triggers: readonly TimedSampleTrigger[],
  window: Pick<ChartPreviewWindow, 'startSeconds'>,
  monophonic: boolean | ((sampleKey: string) => boolean),
): TimedSampleTrigger[] {
  const startSeconds = window.startSeconds - 1e-6;
  const before = triggers.filter((trigger) => trigger.seconds < startSeconds && trigger.event.bmson?.c !== true);
  if (monophonic === false) return before;
  const isMonophonic = monophonic === true ? () => true : monophonic;
  const lastBySlot = new Map<string, TimedSampleTrigger>();
  const kept: TimedSampleTrigger[] = [];
  for (const trigger of before) {
    if (isMonophonic(trigger.sampleKey)) lastBySlot.set(trigger.sampleKey, trigger);
    else kept.push(trigger);
  }
  return [...kept, ...lastBySlot.values()].sort((left, right) => left.seconds - right.seconds);
}
 
/**
 * Pure helper: how to start `trigger`'s sample partway at `windowStartSeconds`, given the decoded sample's length: the
 * offset into the buffer and, for a bmson slice, how much of the slice is left. `undefined` once it has finished.
 */
export function resolveChartWindowCarryOver(
  trigger: Pick<TimedSampleTrigger, 'seconds' | 'sampleOffsetSeconds' | 'sampleDurationSeconds'>,
  bufferDurationSeconds: number,
  windowStartSeconds: number,
): { offsetSeconds: number; durationSeconds?: number } | undefined {
  const elapsed = windowStartSeconds - trigger.seconds;
  if (!(elapsed > 0)) return undefined;
  const sampleOffset = trigger.sampleOffsetSeconds ?? 0;
  const length = trigger.sampleDurationSeconds ?? bufferDurationSeconds - sampleOffset;
  // Less than a millisecond left is nothing to hear.
  if (!(length - elapsed > 0.001)) return undefined;
  const offsetSeconds = sampleOffset + elapsed;
  return trigger.sampleDurationSeconds !== undefined
    ? { offsetSeconds, durationSeconds: trigger.sampleDurationSeconds - elapsed }
    : { offsetSeconds };
}
 
/** A part of a sample, in its own seconds: `[startSeconds, endSeconds)`. */
export interface WindowStretchSegment {
  readonly startSeconds: number;
  readonly endSeconds: number;
}
 
/**
 * Pure helper: the parts of one sample a window sounds, in the sample's own seconds, for each of its `triggers` (those
 * in the window and those carried into it): from where it starts sounding (its slice offset, and how far it played
 * before the window for one carried in) up to the window's end and its fade-out, at the play tempo `rate`, or its
 * slice's end.
 */
export function windowSampleNeeds(
  triggers: readonly Pick<TimedSampleTrigger, 'seconds' | 'sampleOffsetSeconds' | 'sampleDurationSeconds'>[],
  window: Pick<ChartPreviewWindow, 'startSeconds' | 'endSeconds'>,
  rate: number,
  sampleDurationSeconds: number,
): WindowStretchSegment[] {
  // The fade-out runs in context time: `rate` chart seconds, and as many of the sample's, per second.
  const tail = CHART_PREVIEW_WINDOW_FADE_OUT_SECONDS * rate;
  return triggers.map((trigger) => {
    const offset = trigger.sampleOffsetSeconds ?? 0;
    const sliceEnd =
      trigger.sampleDurationSeconds === undefined ? sampleDurationSeconds : offset + trigger.sampleDurationSeconds;
    const startSeconds = offset + Math.max(0, window.startSeconds - trigger.seconds);
    const endSeconds = Math.min(sliceEnd, offset + Math.max(0, window.endSeconds - trigger.seconds) + tail);
    return { startSeconds, endSeconds: Math.max(startSeconds, endSeconds) };
  });
}
 
/** How long a sample has to be before a window stretches only the part of it it sounds. */
export const WINDOW_STRETCH_SEGMENT_MIN_SAMPLE_SECONDS = 4;
 
/** How far past what a window sounds a stretched part reaches on either side, so the stretcher settles before it. */
export const WINDOW_STRETCH_SEGMENT_PAD_SECONDS = 0.25;
 
/**
 * Pure helper: the part of a sample of `sampleDurationSeconds` a window stretches to sound `needs`
 * ({@link windowSampleNeeds}), padded by {@link WINDOW_STRETCH_SEGMENT_PAD_SECONDS} and snapped out to whole tenths so
 * the windows of one bar share it; `undefined` stretches the whole sample, as for a short one or one the window sounds
 * most of.
 */
export function resolveWindowStretchSegment(
  needs: readonly WindowStretchSegment[],
  sampleDurationSeconds: number,
): WindowStretchSegment | undefined {
  if (!(sampleDurationSeconds > WINDOW_STRETCH_SEGMENT_MIN_SAMPLE_SECONDS) || needs.length === 0) return undefined;
  const from = Math.min(...needs.map((need) => need.startSeconds)) - WINDOW_STRETCH_SEGMENT_PAD_SECONDS;
  const to = Math.max(...needs.map((need) => need.endSeconds)) + WINDOW_STRETCH_SEGMENT_PAD_SECONDS;
  const startSeconds = Math.max(0, Math.floor(from * 10) / 10);
  const endSeconds = Math.min(sampleDurationSeconds, Math.ceil(to * 10) / 10);
  if (!(endSeconds > startSeconds) || endSeconds - startSeconds >= sampleDurationSeconds * 0.75) return undefined;
  return { startSeconds, endSeconds };
}
 
/**
 * Pure helper: the level a preview plays at, so it sounds as loud as the play. A play sums its samples into mixers at
 * {@link MIXER_HEADROOM_GAIN_LINEAR} (about −6 dB) and applies the chart's `#VOLWAV`; the preview takes both, where it
 * used to sum at unity and sound louder than the chart itself.
 */
export function resolveChartPreviewLevel(chart: Pick<BeMusicJSON, 'bms'>): number {
  return MIXER_HEADROOM_GAIN_LINEAR * volWAVToLinearGain(chart.bms.volWAV);
}
 
/**
 * Pure helper: when the in-place fallback starts fading and when it ends, in context time. The window is
 * `windowSeconds` long from `startAt` (the cutoff less the trimmed lead-in); the fade takes its last `fadeSeconds`, or
 * the whole window when that is shorter.
 */
export function resolvePreviewFallbackFade(
  startAt: number,
  windowSeconds: number,
  fadeSeconds: number,
): { fadeStartAt: number; endAt: number } {
  const span = Number.isFinite(windowSeconds) ? Math.max(0, windowSeconds) : 0;
  const fade = Number.isFinite(fadeSeconds) ? Math.min(Math.max(0, fadeSeconds), span) : 0;
  const endAt = startAt + span;
  return { fadeStartAt: endAt - fade, endAt };
}
 
function sameTarget(a: ChartPreviewTarget | undefined, b: ChartPreviewTarget | undefined): boolean {
  if (a === b) return true;
  if (!a || !b) return false;
  return a.chart.id === b.chart.id && a.source.id === b.source.id;
}
 
/**
 * Minimal contract for the parts of `AudioBuffer` the leading- silence scan reads. Defined separately so unit tests can
 * feed in a duck-typed object without summoning a real Web Audio AudioBuffer (which doesn't exist in node test envs),
 * and so the helper isn't gratuitously coupled to the DOM type's `Float32Array<ArrayBuffer>` parameterization.
 */
export interface AudibleOffsetBuffer {
  numberOfChannels: number;
  sampleRate: number;
  length: number;
  getChannelData(channel: number): Float32Array;
}
 
/**
 * Returns the time of the first audible sample in `buffer`, or `0` if the whole buffer is below {@link
 * PREVIEW_SILENCE_THRESHOLD} (in which case there's nothing to skip — sit at the start).
 *
 * Walks every channel in lock-step so a stereo file with silence on the left channel but tone on the right doesn't get
 * incorrectly trimmed. Threshold matches `trimPreviewLeadingSilence` in `packages/player-engine`'s CLI preview module — the
 * two implementations should produce identical "first audible point" answers for the same source file so the web and
 * CLI players stay in lockstep.
 *
 * Linear scan with a fast inner loop; even a 5-second 44.1 kHz stereo buffer (~440 k samples) finishes in well under 1
 * ms, dwarfed by the surrounding `decodeAudioData` cost.
 */
export function findFirstAudibleOffsetSeconds(
  buffer: AudibleOffsetBuffer,
  threshold: number = PREVIEW_SILENCE_THRESHOLD,
): number {
  const channelCount = buffer.numberOfChannels;
  if (channelCount === 0) return 0;
  const length = buffer.length;
  if (length === 0) return 0;
  // Cache `getChannelData` calls — repeated calls allocate a fresh `Float32Array` view in some implementations and
  // would dominate the inner loop's runtime.
  const channels: Float32Array[] = [];
  for (let channel = 0; channel < channelCount; channel += 1) {
    channels.push(buffer.getChannelData(channel));
  }
  for (let frame = 0; frame < length; frame += 1) {
    for (let channel = 0; channel < channelCount; channel += 1) {
      if (Math.abs(channels[channel]![frame]!) > threshold) {
        return frame / buffer.sampleRate;
      }
    }
  }
  return 0;
}
 
/** A trigger's own playback rate (an LRX note's `frq`), 1 for any other. */
function previewVoiceRate(trigger: Pick<TimedSampleTrigger, 'samplePlaybackRate'>): number {
  return trigger.samplePlaybackRate !== undefined && trigger.samplePlaybackRate > 0 ? trigger.samplePlaybackRate : 1;
}