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 | 48x 40x 40x 212x 2x 2x 2x 10x 8x 4x 4x 2x 48x 4x 4x 4x 13x 4x 3x 6x 6x 6x 3x 3x 3x 3x 3x 3x 35x 198x 35x 35x 35x 3x 35x 35x 55x 35x 35x 35x 35x 35x 35x 14x 25x 25x 35x 35x 35x 35x 53x 51x 53x 53x 53x 5x 5x 5x 46x 46x 56x 56x 54x 54x 54x 53x 53x 52x 1x 51x 42x 1x 1x 1x 42x 20x 42x 42x 42x 10x 9x 35x 35x 53x 53x 35x 35x 58x 58x 58x 58x 58x 3x 35x 35x 2x 2x 1x 1x 35x 3x 3x 4x 4x 3x 35x 1x 1x 1x 1x 1x 4x 4x 4x 4x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x | // Chart audio preparation for the play session (`session/play/play-media.ts`), which every gameplay family plays
// through. One place decodes the chart's `#WAV` samples under the key the audio session looks them up by, into the
// play's audio graph (`runtime/play-audio-graph.ts`), stretches them for a keep-pitch tempo and folds the `#WAVCMD` /
// `#EXWAV` volumes.
import { runWithConcurrency } from '@be-music/shared-utils/core';
import {
collectBmsWAVVolumeMultipliers,
resolveBmsWAVResources,
resolveReferencedBmsWAVResources,
collectBmsWAVPlaybackModifiers,
type TimedSampleTrigger,
} from '@be-music/chart-model';
import { normalizeObjectKey, resolveBMSBase, type BeMusicJSON } from '@be-music/chart-source';
import type { NonstopStitchMap } from '@be-music/player-engine/course';
import { loadAssetBytes, resolveChartAudioAsset } from '../collection/collection.ts';
import type { BrowserAssetEntry, BrowserAssetSource } from '../collection/types.ts';
import {
resolveSampleStretchRates,
stretchDecodedSamples,
type TempoPitchMode,
type TimeStretchAlgorithm,
} from '../runtime/play-tempo.ts';
import type { ChartSampleCache, ChartSampleLease } from '../runtime/chart-sample-cache.ts';
import { decodedSampleKey } from '../runtime/web-audio-session.ts';
import { prepareWAVPlaybackBuffer, readNativeAudioSampleRate } from '../runtime/wav-playback.ts';
import { logger } from '../logger.ts';
import { applyChartPeakGain } from './peak-gain.ts';
const log = logger('play-audio');
/**
* Samples decoded at once: one per core, as the browser decodes them in parallel and the wall time stops falling there
* (a 1,300-sample chart on 10 cores: 1.45 s at 4, 0.99 s at 8, 0.86 s at 16, 0.88 s at 32). At least 4, and at most 16
* so hundreds of decoders don't allocate PCM together.
*/
export function resolveAudioDecodeConcurrency(hardwareConcurrency: number | undefined): number {
const cores = hardwareConcurrency !== undefined && Number.isFinite(hardwareConcurrency) ? hardwareConcurrency : 8;
return Math.min(16, Math.max(4, Math.floor(cores)));
}
/**
* Per-slot volume multipliers of a chart: `#WAVCMD 01 xx vv` and the volume of `#EXWAVxx`, multiplied together when a
* slot has both. Pitch, balance, frequency and sounding time are prepared separately.
*/
export function collectChartVolumeMultipliers(chart: BeMusicJSON): Map<string, number> {
return collectBmsWAVVolumeMultipliers(chart);
}
export interface LoadPlaySamplesOptions {
audioContext: BaseAudioContext;
/** The resolved chart (after `#RANDOM` / `#IF`), so `#IF`-gated `#WAV`s match the chosen branches. */
chart: BeMusicJSON;
source: BrowserAssetSource;
chartPath: string;
/** The map the samples land in, keyed by {@link decodedSampleKey} of the chart's `#WAV` path. */
samples: Map<string, AudioBuffer>;
/** The play tempo (`clampPlayTempo`). */
tempo: number;
tempoPitchMode: TempoPitchMode;
tempoStretchAlgorithm: TimeStretchAlgorithm;
/** A stitched NONSTOP chart's stages: keep pitch stretches each stage's samples by its FIT rate too. */
nonstop?: NonstopStitchMap;
/** True once the play was abandoned: the remaining decodes and stretches are skipped. */
isCancelled?: () => boolean;
/** Fraction of sample paths processed, including cached and unavailable samples. */
onDecodeProgress?: (fraction: number) => void;
/** Fraction of keep-pitch time stretching completed. */
onStretchProgress?: (fraction: number) => void;
/**
* Scale every decoded sample by one gain so the loudest peak sits near −3 dBFS. Off unless the host asks: charts
* keep the level they were authored at.
*/
peakGain?: boolean;
/**
* The part of the chart the play sounds, as a PRACTICE play of picked bars has it: only the samples it can sound are
* decoded ({@link resolvePlayWindowSamples}). Absent decodes every sample the chart plays.
*/
window?: PlaySampleWindow;
/**
* The decoded samples of the chart played last (`AudioService.chartSamples`). A play takes the decodes of the files
* its `#WAV` paths resolve to from there and decodes only what is missing; the cache lets go of the rest first.
* Without it, every sample decodes.
*/
sampleCache?: ChartSampleCache;
}
/** The chart seconds a play sounds, and the sample triggers of its chart ({@link LoadPlaySamplesOptions.window}). */
export interface PlaySampleWindow {
readonly startSeconds: number;
readonly endSeconds: number;
readonly triggers: readonly Pick<TimedSampleTrigger, 'seconds' | 'sampleKey'>[];
}
/**
* Pure helper: the samples a play of `window` can sound, by sample key: those triggered in it (`inWindow`), and for
* each other sample triggered before it, when it was triggered last (`before`): it sounds only if it rings past the
* window's start, which its length decides.
*/
export function resolvePlayWindowSamples(window: PlaySampleWindow): {
inWindow: Set<string>;
before: Map<string, number>;
} {
const inWindow = new Set<string>();
const before = new Map<string, number>();
for (const trigger of window.triggers) {
if (trigger.seconds > window.endSeconds) continue;
if (trigger.seconds >= window.startSeconds) inWindow.add(trigger.sampleKey);
else before.set(trigger.sampleKey, Math.max(before.get(trigger.sampleKey) ?? 0, trigger.seconds));
}
for (const key of inWindow) before.delete(key);
return { inWindow, before };
}
/** The lowest bitrate {@link estimateMaxAudioSeconds} assumes of a compressed file, in bytes a second (32 kbps). */
const MIN_COMPRESSED_BYTES_PER_SECOND = 4000;
/**
* Pure helper: how long the audio file `bytes` plays at most, in seconds, read without decoding it: a RIFF WAVE's
* length from its header, and any other file's at {@link MIN_COMPRESSED_BYTES_PER_SECOND}, longer than it can be.
*/
export function estimateMaxAudioSeconds(bytes: Uint8Array): number {
const compressed = bytes.length / MIN_COMPRESSED_BYTES_PER_SECOND;
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const tag = (offset: number): string =>
offset + 4 <= bytes.length ? String.fromCharCode(...bytes.subarray(offset, offset + 4)) : '';
if (tag(0) !== 'RIFF' || tag(8) !== 'WAVE') return compressed;
let byteRate: number | undefined;
for (let offset = 12; offset + 8 <= bytes.length;) {
const id = tag(offset);
const size = view.getUint32(offset + 4, true);
if (id === 'fmt ' && offset + 16 <= bytes.length) {
// PCM's byte rate; a compressed WAVE (an ADPCM one) plays longer than its bytes at it, so it falls back.
const format = view.getUint16(offset + 8, true);
byteRate = format === 1 || format === 3 || format === 0xfffe ? view.getUint32(offset + 16, true) : undefined;
Iif (byteRate === undefined) return compressed;
} else Eif (id === 'data') {
return byteRate !== undefined && byteRate > 0 ? Math.min(size, bytes.length - offset - 8) / byteRate : compressed;
}
offset += 8 + size + (size % 2);
}
return compressed;
}
/**
* Decodes every `#WAVxx` sample the chart plays into `samples` (codec fallbacks via `resolveChartAudioAsset`, honouring
* `#PATH_WAV`) and, for keep pitch, stretches them to the play tempo once so they then play at their own pitch.
* Decode or read failures advance to the next distinct asset; a sample with no playable candidate is skipped. Resolves `true` when the samples were stretched.
*/
export async function loadPlaySamples(options: LoadPlaySamplesOptions): Promise<boolean> {
const { audioContext, chart, source, chartPath, samples } = options;
const isCancelled = options.isCancelled ?? (() => false);
// Every declared slot: a `#WAVxx` slot is base-36, so a dense chart can use well over 256 samples.
const wavResources = resolveBmsWAVResources(chart);
const playbackModifiers = collectBmsWAVPlaybackModifiers(chart);
const nativeRatePaths = new Set(
[...playbackModifiers].filter(([, value]) => value.frequencyHz !== undefined).map(([key]) => wavResources[key]),
);
const nativeRates = new Map<string, number>();
// Only what some sample event names: a chart can declare hundreds of slots it never plays (a short cut of a long
// track), and each decoded sample costs its whole PCM. One path behind several slots decodes once.
const wavPaths = [
...new Set(
Object.values(resolveReferencedBmsWAVResources(chart)).filter((path): path is string => typeof path === 'string'),
),
];
// A play of part of the chart (`window`) decodes what that part sounds: the samples triggered in it, and those
// triggered before it that ring into it, which their files' lengths tell before they decode.
const windowSamples = options.window === undefined ? undefined : resolvePlayWindowSamples(options.window);
const windowPaths = windowSamples === undefined ? undefined : resolveWindowSamplePaths(chart, windowSamples);
// `#PATH_WAV <prefix>`: the chart's samples live under that directory; the resolver tries the prefixed path first.
const pathPrefix = typeof chart.bms.pathWAV === 'string' ? chart.bms.pathWAV : undefined;
const concurrency = resolveAudioDecodeConcurrency(
typeof navigator === 'undefined' ? undefined : navigator.hardwareConcurrency,
);
// The file each path resolves to first: what the cache keeps a decode under, so another chart of the track that
// resolves a path to the same file takes its decode, and one that resolves it elsewhere does not.
const firstFiles = new Map<string, BrowserAssetEntry>();
if (options.sampleCache !== undefined) {
for (const path of wavPaths) {
const entry = resolveChartAudioAsset(source, chartPath, path, { pathPrefix });
Eif (entry !== undefined) firstFiles.set(path, entry);
}
}
const lease = options.sampleCache?.claim(
{ source, chartPath, sampleRate: audioContext.sampleRate },
firstFiles.values(),
);
if (lease !== undefined) log.debug('cached samples', { reused: lease.reused, files: firstFiles.size });
const decodePaths = windowPaths === undefined ? wavPaths : wavPaths.filter((path) => windowPaths.has(path));
const decodePath = async (path: string): Promise<void> => {
if (isCancelled()) return;
const ringsFrom = windowPaths?.get(path);
const file = firstFiles.get(path);
const cached = file === undefined ? undefined : lease?.get(file);
// A path that needs its native rate decodes again when the cached decode has none (its `#EXWAV` changed branch).
if (cached !== undefined && (!nativeRatePaths.has(path) || cached.nativeSampleRate !== undefined)) {
Iif (cached.nativeSampleRate !== undefined) nativeRates.set(path, cached.nativeSampleRate);
samples.set(decodedSampleKey(path), cached.buffer);
return;
}
const attempted = new Set<BrowserAssetEntry>();
while (!isCancelled()) {
const entry = resolveChartAudioAsset(source, chartPath, path, {
pathPrefix,
...(attempted.size ? { excludedEntries: attempted } : {}),
});
if (entry === undefined || attempted.has(entry)) return;
attempted.add(entry);
try {
// Lazy audio files are read only when their codec candidate is attempted.
const bytes = await loadAssetBytes(entry);
Iif (isCancelled()) return;
if (!bytes) continue;
// Triggered only before the window: decoded when it may still ring at its start.
if (ringsFrom !== undefined && ringsFrom + estimateMaxAudioSeconds(bytes) <= options.window!.startSeconds)
return;
const decoded = await audioContext.decodeAudioData(bytes.slice().buffer);
let nativeSampleRate: number | undefined;
if (nativeRatePaths.has(path)) {
// The PCM decoded; an unreadable container header only loses the EXWAV native-rate reference.
try {
nativeSampleRate = await readNativeAudioSampleRate(bytes);
nativeRates.set(path, nativeSampleRate);
} catch (error) {
log.debug('native sample rate unavailable', { path, error });
}
}
// Kept even when the play was abandoned meanwhile: an F5 during loading picks up from here.
if (file !== undefined)
lease?.set(
file,
nativeSampleRate !== undefined ? { buffer: decoded, nativeSampleRate } : { buffer: decoded },
);
Iif (isCancelled()) return;
// Keep the declared WAV name as the key even when an alternate codec supplied the PCM.
samples.set(decodedSampleKey(path), decoded);
return;
} catch (error) {
if (isCancelled()) return;
log.debug('decode candidate skipped', { path, error });
}
}
};
let processed = 0;
await runWithConcurrency(decodePaths, concurrency, async (path) => {
await decodePath(path);
if (!isCancelled()) options.onDecodeProgress?.(++processed / decodePaths.length);
});
const stretchResources: Record<string, string> = {};
for (const [key, path] of Object.entries(wavResources)) {
const modifiers = playbackModifiers.get(key);
const cacheKey = decodedSampleKey(path, modifiers ? key : undefined);
stretchResources[key] = cacheKey;
const buffer = samples.get(decodedSampleKey(path));
if (modifiers && buffer && !isCancelled()) {
samples.set(cacheKey, prepareWAVPlaybackBuffer(audioContext, buffer, modifiers, nativeRates.get(path)));
}
}
let stretched = false;
if (options.tempoPitchMode === 'keep-pitch' && !isCancelled()) {
const rates = resolveSampleStretchRates(stretchResources, (key) => key, options.tempo, options.nonstop);
if (rates.size > 0) {
await stretchDecodedSamples(
audioContext,
samples,
rates,
options.tempoStretchAlgorithm,
isCancelled,
options.onStretchProgress,
);
stretched = true;
}
}
// After stretch, so a keep-pitch resample's new peak is what the gain sees. `#VOLWAV` still applies at playback.
if (options.peakGain === true && !isCancelled()) {
// The gain scales in place, so a cached decode the play would scale is copied first.
if (lease !== undefined) copyCachedBuffers(audioContext, samples, new Set(Object.values(stretchResources)), lease);
const audibleBuffers = new Set(
Object.values(stretchResources)
.map((key) => samples.get(key))
.filter((buffer): buffer is AudioBuffer => buffer !== undefined),
);
applyChartPeakGain(audibleBuffers);
}
return stretched;
}
/**
* The paths a play of part of the chart decodes: each path behind a sample triggered in it (`undefined`: always), and
* each one behind a sample triggered only before it, with when it was triggered last.
*/
function resolveWindowSamplePaths(
chart: BeMusicJSON,
samples: ReturnType<typeof resolvePlayWindowSamples>,
): Map<string, number | undefined> {
const base = resolveBMSBase(chart);
const longKeys = chart.sourceFormat === 'bmson';
const always = new Set<string>();
const before = new Map<string, number>();
for (const [key, path] of Object.entries(resolveBmsWAVResources(chart))) {
const sampleKey = normalizeObjectKey(key, base, longKeys);
if (samples.inWindow.has(sampleKey)) always.add(path);
const last = samples.before.get(sampleKey);
if (last !== undefined) before.set(path, Math.max(before.get(path) ?? last, last));
}
const paths = new Map<string, number | undefined>(before);
for (const path of always) paths.set(path, undefined);
return paths;
}
/** Replaces each of `keys`' buffers that `lease` holds with a copy of it in `samples`, one copy per buffer. */
function copyCachedBuffers(
context: BaseAudioContext,
samples: Map<string, AudioBuffer>,
keys: ReadonlySet<string>,
lease: ChartSampleLease,
): void {
const copies = new Map<AudioBuffer, AudioBuffer>();
for (const key of keys) {
const buffer = samples.get(key);
Iif (buffer === undefined || !lease.holds(buffer)) continue;
let copy = copies.get(buffer);
Eif (copy === undefined) {
copy = context.createBuffer(buffer.numberOfChannels, buffer.length, buffer.sampleRate);
for (let channel = 0; channel < buffer.numberOfChannels; channel += 1) {
copy.copyToChannel(buffer.getChannelData(channel), channel);
}
copies.set(buffer, copy);
}
samples.set(key, copy);
}
}
|