All files / player-browser/src/session/play play-media.ts

67.52% Statements 79/117
56.45% Branches 70/124
70% Functions 14/20
69.23% Lines 72/104

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                                                                                                                                                                                                                              221x     221x         5x               28x 23x                 5x 28x   28x       28x         28x 28x 5x 5x 5x 5x 5x                 5x                 5x 5x 5x     5x   5x   5x                                       3x       3x             5x 5x 5x           5x                                       3x 3x 3x                                                         33x                 23x 23x 23x 23x           23x                                                     23x                                                       30x 30x 30x 30x   30x 30x 30x                                           30x 30x   30x                         30x 30x 30x 30x 30x 30x                           30x 30x 30x 30x 30x 30x 30x                                     31x 31x 31x                     7x 7x 2x   4x 4x 4x     2x    
import type { WebAudioSessionSlicePlayback } from '../../runtime/web-audio-session.ts';
/**
 * Media preparation for a play on the built-in and LR2 play screens (`PlaySession`): the play's AudioContext,
 * audio bus and analyser, the decoded (and, for keep pitch, stretched) samples, the NONSTOP stage mixer and the
 * `WebAudioSession` the engine plays through; the BGA textures and videos; and the audio graph's teardown, which a
 * play that ended naturally delays so its last samples ring out.
 *
 * The functions read and write the play's state through {@link PlayMediaContext}; the play session passes itself.
 */
 
import { resolveLRXBGAProgram, type TimedSampleTrigger, type TimingResolver } from '@be-music/chart-model';
import type { BeMusicEvent, BeMusicJSON } from '@be-music/chart-source';
import { resolveJudgeTimingAutoAdjust } from '@be-music/player-engine/display';
import type { TimedPlayableNote } from '@be-music/player-engine/display';
import type { Texture } from 'pixi.js';
import { loadPlaySamples, type PlaySampleWindow } from '../../chart/play-audio.ts';
import type { PreparedPlaybackChartData } from '@be-music/player-engine';
import { loadPlayBGA, releaseVideo } from '../../chart/play-bga.ts';
import { LRX_POOR_SECONDS, LRXBGACompositor } from '../../media/lrx-bga-compositor.ts';
import type { PlayerUIFramePayload } from '@be-music/player-engine/signals';
import type { LibraryChart } from '@be-music/player-scene-model';
import type { BrowserAssetSource } from '../../collection/types.ts';
import { AudioAnalyzer } from '../../runtime/audio-analysis.ts';
import type {
  AudioBusChannel,
  AudioBusHandle,
  CompressorMode,
  CompressorParams,
  TunableCompressor,
} from '../../runtime/audio-bus.ts';
import type { AudioService, PlayAudioHandle } from '../../runtime/audio-service.ts';
import type { GuideSound } from '@be-music/player-engine';
import type { SystemSound } from '@be-music/player-scene-model';
import { createNonstopStageMixer, type NonstopStageMixer } from '../../runtime/nonstop-audio.ts';
import { createPlayAudioGraph } from '../../runtime/play-audio-graph.ts';
import { chartToElapsedSeconds, resolveSamplePlaybackRate, stretchSlicePlayback } from '../../runtime/play-tempo.ts';
import { createWebAudioSession, type WebAudioSession } from '../../runtime/web-audio-session.ts';
import { clipBGACuesToWindow, type BGACue } from '../../chart/bga-timeline.ts';
import type { PlayDisposeOptions, PlaySessionOptions } from './play-options.ts';
import { resolveGameplayAudioTailCleanupDelayMs } from './result-delay.ts';
 
/** The play state the media preparation reads and fills: the play session's fields of these names. */
export interface PlayMediaContext {
  readonly options: Readonly<
    Pick<
      PlaySessionOptions,
      | 'audioCompressor'
      | 'audioCompressorMode'
      | 'audioCompressorStages'
      | 'peakGain'
      | 'tempoPitchMode'
      | 'tempoStretchAlgorithm'
      | 'nonstop'
      | 'bgaTranscodeMaxLongEdgePx'
      | 'bgaTranscodeUseWebCodecs'
      | 'bgaTranscodeQuality'
      | 'audio'
      | 'judgeTimingAutoAdjust'
      | 'replay'
      | 'guideSounds'
      | 'practiceRange'
    >
  >;
  readonly chart: LibraryChart | undefined;
  readonly source: BrowserAssetSource | undefined;
  readonly resolvedChart: BeMusicJSON | undefined;
  /** The chart the engine plays (`prepareChart`), prepared before the samples decode. */
  readonly preparedChart:
    | Pick<PreparedPlaybackChartData, 'resolvedChart' | 'practicePlayStartSeconds' | 'totalSeconds'>
    | undefined;
  readonly disposed: boolean;
  readonly tempo: number;
  readonly playbackTempo?: number;
  audioContext: AudioContext | undefined;
  audioBus: AudioBusHandle | undefined;
  audioAnalyzer: AudioAnalyzer | undefined;
  /** The play's graph as the host's audio service opened it (`options.audio`); undefined when the play made its own. */
  playAudio: PlayAudioHandle | undefined;
  audioCompressorMode: CompressorMode;
  readonly audioCompressorParams: Partial<Record<TunableCompressor, Partial<CompressorParams>>>;
  readonly audioVolumes: Record<AudioBusChannel, number>;
  webAudioSession: WebAudioSession | undefined;
  nonstopMixer: NonstopStageMixer | undefined;
  readonly decodedSamples: Map<string, AudioBuffer>;
  readonly wavCmdVolumeMultipliers: Map<string, number>;
  bmsonSlicePlayback: Map<BeMusicEvent, WebAudioSessionSlicePlayback> | undefined;
  readonly hasBGA: boolean;
  readonly bgaTimeline: { base: BGACue[]; layer: BGACue[]; layer2?: BGACue[]; poor: BGACue[] };
  readonly poorBGAFallbackKey: string | undefined;
  readonly bgaTextures: Map<string, Texture>;
  readonly bgaLayerTextures: Map<string, Texture>;
  readonly bgaVideos: Map<string, { video: HTMLVideoElement; objectURL: string; dispose?: () => void }>;
  readonly bgaSubRegionOrigins: Map<string, { x: number; y: number }>;
  readonly timingResolver: TimingResolver | undefined;
  readonly engineFrame: Readonly<PlayerUIFramePayload> | undefined;
  readonly lastPoorAt: number;
  playClock(): number;
  /** Set once the BGA images are loaded, for an LRX chart whose BGA only the compositor can draw. */
  lrxBGA: LRXBGACompositor | undefined;
  /** Uploads `textures` to the GPU now (Pixi's `PrepareSystem`), so the first frame that draws them does not stall. */
  preparePixiUpload(textures: Iterable<Texture | undefined>): Promise<void>;
}
 
/**
 * Whether a play runs LR2's SILENT automatic judge timing, which loads no chart keysounds, BGM or BGA (OpenLR2
 * `LR2f.cpp` 24346-24349): the selected mode, or the mode a replay recorded.
 */
export function isSilentJudgeTimingPlay(
  options: Readonly<Pick<PlaySessionOptions, 'judgeTimingAutoAdjust' | 'replay'>>,
): boolean {
  const mode =
    options.replay !== undefined
      ? resolveJudgeTimingAutoAdjust(options.replay.play.options?.judgeTimingAutoAdjust)
      : options.judgeTimingAutoAdjust;
  return mode === 'LR2-SILENT';
}
 
/** Opens the play's audio graph ({@link openPlayAudio}) and decodes its samples into it ({@link decodePlayAudio}). */
export async function prepareAudio(ctx: PlayMediaContext): Promise<void> {
  Eif (openPlayAudio(ctx)) await decodePlayAudio(ctx);
}
 
/**
 * Opens the play's AudioContext and bus, synchronously, so the play has them before its samples decode. False when
 * the play has no chart or source to sound.
 */
export function openPlayAudio(ctx: PlayMediaContext): boolean {
  if (!ctx.source || !ctx.chart) {
    return false;
  }
  // Build the audio bus. See `audio-bus.ts` for the full architecture; in short:
  //
  // key sources → keyMixer → keyComp ↘ masterComp → makeup → destination ('split') BGM sources → bgmMixer → bgmComp ↗
  //
  // 'legacy' collapses both buses onto a single compressor; 'off' bypasses every compressor stage. Sample sources
  // always feed `keyMixer` / `bgmMixer`, never directly to the destination, so a mode switch never has to reconnect
  // in-flight `BufferSourceNode`s — important because hundreds of one-shots come and go per second on dense charts.
  ctx.audioCompressorMode = ctx.options.audioCompressorMode ?? 'split';
  const initialMode: CompressorMode = ctx.options.audioCompressor === false ? 'off' : ctx.audioCompressorMode;
  // Use the control-flow-resolved chart so #IF-gated #WAVxx declarations match the chosen #RANDOM branch.
  const chart = ctx.resolvedChart ?? ctx.chart.chart;
  // The AudioContext, the bus and `#VOLWAV` are built by the audio layer (`runtime/play-audio-graph.ts`), and the
  // samples decoded into them (`chart/play-audio.ts`). With the host's audio service the play opens them through it
  // (`openPlayGraph`, ADR 0007), which taps the bus for the analyser and owns the context's teardown.
  const busOptions = {
    initialStages: ctx.options.audioCompressorStages,
    initialVolumes: ctx.audioVolumes,
    initialCompressorParams: ctx.audioCompressorParams,
  };
  const audio = ctx.options.audio;
  if (audio !== undefined) {
    const handle = audio.openPlayGraph(chart, initialMode, busOptions, { owner: ctx });
    ctx.playAudio = handle;
    ctx.audioContext = handle.audioContext;
    ctx.audioBus = handle.audioBus;
    ctx.audioAnalyzer = handle.analyzer;
  } else E{
    const graph = createPlayAudioGraph(chart, initialMode, busOptions);
    ctx.audioContext = graph.audioContext;
    ctx.audioBus = graph.audioBus;
    // Audio-reactive skins read the post-mix signal from the bus's analysis tap.
    ctx.audioAnalyzer = new AudioAnalyzer(ctx.audioContext);
    ctx.audioBus.outputNode.connect(ctx.audioAnalyzer.input);
  }
  return true;
}
 
/** Decodes the chart's samples into the graph {@link openPlayAudio} opened, then builds the play's audio session. */
export async function decodePlayAudio(
  ctx: PlayMediaContext,
  onDecodeProgress?: (fraction: number) => void,
  onStretchProgress?: (fraction: number) => void,
): Promise<void> {
  Iif (!ctx.source || !ctx.chart || !ctx.audioContext) return;
  const chart = ctx.resolvedChart ?? ctx.chart.chart;
  const pitchMode = ctx.options.tempoPitchMode ?? 'pitch';
  // Keep pitch: the samples are stretched to the play tempo (times a NONSTOP FIT stage's rate) once, here, and then
  // play at their own pitch. LR2's SILENT loads none: the play runs without its keysounds and BGM.
  const silent = isSilentJudgeTimingPlay(ctx.options);
  // A SILENT play decodes nothing, so it keeps no other chart's samples either.
  if (silent) ctx.options.audio?.chartSamples.release();
  const stretched =
    !silent &&
    (await loadPlaySamples({
      audioContext: ctx.audioContext,
      chart,
      source: ctx.source,
      chartPath: ctx.chart.chartPath,
      samples: ctx.decodedSamples,
      tempo: ctx.playbackTempo ?? ctx.tempo,
      tempoPitchMode: pitchMode,
      tempoStretchAlgorithm: ctx.options.tempoStretchAlgorithm ?? 'signalsmith',
      ...(ctx.options.nonstop !== undefined ? { nonstop: ctx.options.nonstop } : {}),
      ...practiceSampleWindow(ctx),
      isCancelled: () => ctx.disposed,
      onDecodeProgress,
      onStretchProgress,
      ...(ctx.options.peakGain === true ? { peakGain: true } : {}),
      // The chart played last keeps its decodes in the audio service, so a quick retry skips decoding them.
      ...(ctx.options.audio !== undefined ? { sampleCache: ctx.options.audio.chartSamples } : {}),
    }));
  // GUIDE SE: the sound set's judgment sounds. A SILENT play has no sound of its own, so none of these either.
  const guideSounds = silent
    ? new Map<GuideSound, AudioBuffer>()
    : await decodeGuideSounds(ctx.options.audio, ctx.options.guideSounds);
  // bmson slices index into the stretched samples (a bmson chart has no NONSTOP stages: one rate).
  Iif (stretched && ctx.bmsonSlicePlayback !== undefined) {
    ctx.bmsonSlicePlayback = stretchSlicePlayback(ctx.bmsonSlicePlayback, ctx.playbackTempo ?? ctx.tempo);
  }
  // Build the WebAudioSession now that the sample cache is populated. The session captures the maps by reference
  // (the underlying entries can still grow if asset loading races onto a later tick), and owns every sample
  // playback path from this point on — `playSample` / `playSampleByKey` / `scheduleAutoSamples` all delegate to
  // it. See the field doc for why this beats keeping the audio plumbing inline on the view.
  Eif (!ctx.disposed && ctx.audioContext && ctx.audioBus) {
    ctx.nonstopMixer?.dispose();
    ctx.nonstopMixer =
      ctx.options.nonstop !== undefined
        ? createNonstopStageMixer(ctx.audioContext, ctx.audioBus.bgmMixer, ctx.options.nonstop, {
            keepPitch: pitchMode === 'keep-pitch',
          })
        : undefined;
    ctx.webAudioSession = createWebAudioSession({
      audioContext: ctx.audioContext,
      audioBus: ctx.audioBus,
      chart: ctx.resolvedChart ?? ctx.chart!.chart,
      decodedSamples: ctx.decodedSamples,
      wavCmdVolumeMultipliers: ctx.wavCmdVolumeMultipliers,
      bmsonSlicePlayback: ctx.bmsonSlicePlayback,
      ...(ctx.nonstopMixer !== undefined ? { stageMixer: ctx.nonstopMixer } : {}),
      ...(guideSounds.size > 0 ? { guideSounds } : {}),
      playbackRate: samplePlaybackRate(ctx),
    });
  }
}
 
/**
 * The part of the chart a PRACTICE play of picked bars sounds ({@link LoadPlaySamplesOptions.window}): from where its
 * first round starts to its end, rest bars and long notes kept from before included; `undefined` for any other play,
 * which decodes every sample.
 */
function practiceSampleWindow(ctx: PlayMediaContext): { window: PlaySampleWindow } | undefined {
  const prepared = ctx.preparedChart;
  const range = ctx.options.practiceRange;
  Eif (ctx.options.replay !== undefined || range?.endMs === undefined || prepared === undefined) return undefined;
  if (prepared.practicePlayStartSeconds === undefined) return undefined;
  return {
    window: {
      startSeconds: prepared.practicePlayStartSeconds,
      endSeconds: prepared.totalSeconds,
      triggers: prepared.resolvedChart.sampleTriggers,
    },
  };
}
 
/**
 * The BGA cues a play loads the images of: for a PRACTICE play of picked bars, those its window shows
 * ({@link clipBGACuesToWindow}), else every cue.
 */
function practiceBGATimeline(ctx: PlayMediaContext): PlayMediaContext['bgaTimeline'] {
  const window = practiceSampleWindow(ctx)?.window;
  if (window === undefined) return ctx.bgaTimeline;
  const { base, layer, layer2, poor } = ctx.bgaTimeline;
  return {
    base: clipBGACuesToWindow(base, window),
    layer: clipBGACuesToWindow(layer, window),
    ...(layer2 !== undefined ? { layer2: clipBGACuesToWindow(layer2, window) } : {}),
    poor: clipBGACuesToWindow(poor, window),
  };
}
 
/** Every sample's playback rate: the play tempo when it moves the pitch, 1 when the samples were stretched to it. */
export function samplePlaybackRate(ctx: Pick<PlayMediaContext, 'options' | 'tempo' | 'playbackTempo'>): number {
  return resolveSamplePlaybackRate(ctx.options.tempoPitchMode ?? 'pitch', ctx.playbackTempo ?? ctx.tempo);
}
 
/**
 * Decodes every BMP resource referenced by the chart's BGA timelines into a Pixi `Texture`, keyed by the same string
 * the timeline cues reference. Loads run with bounded parallelism so a long preamble doesn't gate the playfield
 * without fanning browser decoders out without limit.
 */
export async function prepareBGA(ctx: PlayMediaContext, onProgress?: (fraction: number) => void): Promise<void> {
  const chartEntry = ctx.chart;
  const source = ctx.source;
  Eif (!chartEntry || !source || !ctx.hasBGA) {
    return;
  }
  // Use the control-flow-resolved chart so #IF-gated BMP / bga header declarations match the chosen #RANDOM branch.
  const chart = ctx.resolvedChart ?? chartEntry.chart;
  // Loaded as the beatoraja prep loads them (`chart/play-bga.ts`): base + POOR textures keep their blacks, the layer
  // track's are keyed out for BMS, videos keep independent plane playheads, and `#BGAxx` aliases share source views.
  await loadPlayBGA({
    chart,
    keyBoundBGACues: ctx.options.nonstop?.keyBoundBGA,
    bmsonBGACues: ctx.options.nonstop?.bmsonBGA,
    source,
    chartPath: chartEntry.chartPath,
    timeline: practiceBGATimeline(ctx),
    poorFallbackKey: ctx.poorBGAFallbackKey,
    into: {
      textures: ctx.bgaTextures,
      layerTextures: ctx.bgaLayerTextures,
      videos: ctx.bgaVideos,
      subRegionOrigins: ctx.bgaSubRegionOrigins,
    },
    transcode: {
      maxLongEdgePx: ctx.options.bgaTranscodeMaxLongEdgePx,
      useWebCodecs: ctx.options.bgaTranscodeUseWebCodecs,
      ...(ctx.options.bgaTranscodeQuality !== undefined ? { quality: ctx.options.bgaTranscodeQuality } : {}),
    },
    tempo: ctx.playbackTempo ?? ctx.tempo,
    isCancelled: () => ctx.disposed,
    onProgress,
  });
  if (ctx.disposed) return;
  // An LRX chart that moves, crops or chains its BGA, or uses layer 203 / 204, is drawn as plugout draws it.
  const program =
    ctx.timingResolver !== undefined ? resolveLRXBGAProgram(chart, ctx.timingResolver.beatToSeconds) : undefined;
  Iif (program !== undefined) {
    ctx.lrxBGA?.dispose();
    ctx.lrxBGA = new LRXBGACompositor(
      program,
      { textures: ctx.bgaTextures, layerTextures: ctx.bgaLayerTextures, videos: ctx.bgaVideos },
      {
        seconds: () => ctx.engineFrame?.currentSeconds ?? 0,
        showsPoor: () => ctx.lastPoorAt > 0 && ctx.playClock() - ctx.lastPoorAt < LRX_POOR_SECONDS * 1000,
      },
    );
  }
  // Eager-upload every freshly loaded BGA texture (and any sub-region aliases registered above) so the first BGA
  // cue mid-chart doesn't stall on its own first sample. Mirrors the skin path in `prepare()`. This is fire-and-
  // forget from the prepareBGA callsite — `bgaReadyPromise` already gates chart start, and adding the upload to
  // its tail just lengthens that promise by the upload work, which is what we want.
  await ctx.preparePixiUpload(ctx.bgaTextures.values());
  if (ctx.disposed) return;
  await ctx.preparePixiUpload(ctx.bgaLayerTextures.values());
}
 
export function disposeGameplayAudioGraphAfterDelay(
  graph: {
    session: WebAudioSession | undefined;
    bus: AudioBusHandle | undefined;
    context: AudioContext | undefined;
  },
  delayMs: number,
): void {
  const cleanup = (): void => {
    void graph.session?.dispose();
    graph.bus?.dispose();
    void graph.context?.close();
  };
  Eif (delayMs <= 0) {
    cleanup();
    return;
  }
  window.setTimeout(cleanup, delayMs);
}
 
/** What {@link disposePlayAudio} tears down: the media state, and what the audio tail is measured against. */
export interface PlayMediaTeardownContext extends PlayMediaContext {
  readonly chartEnded: boolean;
  readonly notes: readonly TimedPlayableNote[];
  readonly autoSampleTriggers: readonly TimedSampleTrigger[];
  currentSeconds(): number;
}
 
/**
 * Releases the play's audio graph as the play is disposed (`PlaySession.dispose`); after a natural end with
 * `preserveAudioTail`, the graph is kept until the last samples have rung out.
 */
export function disposePlayAudio(ctx: PlayMediaTeardownContext, options: PlayDisposeOptions): void {
  // WebAudioSession owns the in-flight BufferSource tracking that the bus's connected sources hang off of, so
  // dispose it BEFORE we tear the bus down — that gives the session a chance to call `node.stop()` on every
  // still-playing source so they don't survive into the next chart's bus and bleed audio through. Fire-and-
  // forget the returned promise; the session's dispose path is best-effort.
  const preserveAudioTail = options.preserveAudioTail === true && ctx.chartEnded;
  const audioTailChart = ctx.resolvedChart ?? ctx.chart?.chart;
  const audioTailCleanupDelayMs =
    preserveAudioTail && audioTailChart !== undefined
      ? chartToElapsedSeconds(
          resolveGameplayAudioTailCleanupDelayMs({
            chart: audioTailChart,
            notes: ctx.notes,
            autoSampleTriggers: ctx.autoSampleTriggers,
            decodedSamples: ctx.decodedSamples,
            bmsonSlicePlayback: ctx.bmsonSlicePlayback,
            currentSeconds: ctx.currentSeconds(),
          }),
          ctx.playbackTempo ?? ctx.tempo,
        )
      : 0;
  const webAudioSession = ctx.webAudioSession;
  ctx.webAudioSession = undefined;
  ctx.nonstopMixer?.dispose();
  ctx.nonstopMixer = undefined;
  const playAudio = ctx.playAudio;
  Iif (playAudio !== undefined) {
    // The audio service closes the graph it opened (its analyser included), the session's sources first.
    ctx.playAudio = undefined;
    ctx.audioAnalyzer = undefined;
    ctx.audioBus = undefined;
    ctx.audioContext = undefined;
    playAudio.close({
      delayMs: preserveAudioTail ? audioTailCleanupDelayMs : 0,
      beforeClose: () => webAudioSession?.dispose(),
    });
    return;
  }
  // Tear down the bus before closing the AudioContext so its `disconnect()` calls don't race with context shutdown.
  // The bus doesn't own the AudioContext itself; closing that is the next step.
  ctx.audioAnalyzer?.dispose();
  ctx.audioAnalyzer = undefined;
  const audioBus = ctx.audioBus;
  ctx.audioBus = undefined;
  const audioContext = ctx.audioContext;
  ctx.audioContext = undefined;
  disposeGameplayAudioGraphAfterDelay(
    {
      session: webAudioSession,
      bus: audioBus,
      context: audioContext,
    },
    preserveAudioTail ? audioTailCleanupDelayMs : 0,
  );
}
 
/** Stops the BGA videos and lets go of them as the play is disposed. */
export function disposeBGAVideos(ctx: {
  readonly bgaVideos: Map<string, { video: HTMLVideoElement; objectURL: string; dispose?: () => void }>;
  bgaActiveVideos: Record<string, { key: string; cueSeconds: number } | undefined>;
}): void {
  // Pause every BGA video BEFORE we touch textures. The Pixi `VideoSource` wrapping each video registers a
  // `requestVideoFrameCallback` that re-uploads frames into the GL texture as they decode — leaving those callbacks
  // in flight while we destroy the textures throws inside the GL texture system. Pausing also revokes the Blob URL so
  // the underlying buffer can be released.
  for (const handle of new Set(ctx.bgaVideos.values())) releaseVideo(handle);
  ctx.bgaVideos.clear();
  ctx.bgaActiveVideos = {};
}
 
/**
 * The guide sounds decoded through the audio service: the ones the sound set has and that decode. None without a
 * service or without sounds.
 */
export async function decodeGuideSounds(
  audio: Pick<AudioService, 'decodeSound'> | undefined,
  sounds: PlaySessionOptions['guideSounds'],
): Promise<Map<GuideSound, AudioBuffer>> {
  const decoded = new Map<GuideSound, AudioBuffer>();
  if (audio === undefined || sounds === undefined) return decoded;
  await Promise.all(
    (Object.entries(sounds) as [GuideSound, SystemSound | undefined][]).map(async ([name, sound]) => {
      Iif (sound === undefined) return;
      const buffer = await audio.decodeSound(sound).catch(() => undefined);
      if (buffer !== undefined) decoded.set(name, buffer);
    }),
  );
  return decoded;
}