feat(audio): passing sounds decoded once and played through WebAudio, no lag with several cars at once (1.89.27)

This commit is contained in:
larssand committed 2026-11-14 15:40:49 +01:00
1 parent 5241cced77
commit ae829123cc
6 files changed
+112 -5

No files matched your search

+6
View File
@@ -8,6 +8,12 @@ The application version is maintained in `package.json` and displayed in the adm
No changes recorded yet.
## 1.89.27 - 2026-11-14
### Changed
- **Passing sound without lag:** the passing sound (and a car's or driver's own) is loaded and decoded once and played through WebAudio, so several cars crossing at once each get their beep straight away (about 1 ms instead of starting a new audio file per passing). Before the page has been clicked, or without WebAudio, it plays as before.
## 1.89.26 - 2026-11-14
### Added
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "rc-racecore",
"version": "1.89.26",
"version": "1.89.27",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "rc-racecore",
"version": "1.89.26",
"version": "1.89.27",
"hasInstallScript": true,
"dependencies": {
"better-sqlite3": "^12.11.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "rc-racecore",
"version": "1.89.26",
"version": "1.89.27",
"private": true,
"description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence",
"engines": {
+2
View File
@@ -6219,6 +6219,8 @@ let audioCtx = null;
let lastFinishAnnouncementSessionId = null;
const raceAudioEngine = createRaceAudioEngine({
getSettings: () => state.settings.raceAudio,
// Passing sounds through WebAudio (decoded once, low latency); overlay windows stay silent anyway.
getAudioContext: () => (overlayMode ? null : ensureAudioContext()),
speak: (text, options = {}) => new Promise((resolve) => {
let settled = false;
const done = (value) => { if (!settled) { settled = true; resolve(value); } };
+43 -2
View File
@@ -234,6 +234,10 @@ export function createRaceAudioEngine(options = {}) {
const random = options.random || Math.random;
const now = options.now || Date.now;
const log = options.log || (() => {});
// WebAudio for passing sounds: each file is fetched and decoded once, then every passing plays
// its own copy at once (overlapping, no <audio> start-up lag). No context: the <audio> path.
const getAudioContext = options.getAudioContext || (() => null);
const decodedBuffers = new Map(); // url -> Promise<AudioBuffer | null>
let manifestPromise = null;
let manifest = null;
let currentVoice = null;
@@ -279,6 +283,43 @@ export function createRaceAudioEngine(options = {}) {
}
}
function loadBuffer(context, url) {
if (!decodedBuffers.has(url)) decodedBuffers.set(url, (async () => {
try {
const response = await fetchImpl(url);
if (!response?.ok) return null;
const data = await response.arrayBuffer();
return await new Promise((resolve, reject) => {
const result = context.decodeAudioData(data, resolve, reject);
if (result?.then) result.then(resolve, reject);
});
} catch { return null; }
})());
return decodedBuffers.get(url);
}
// true = played through WebAudio, null = not possible here (use <audio>).
async function attemptBufferedEffect(effectPath, volume, playbackRate) {
if (!effectPath || missingEffects.has(effectPath) || !fetchImpl) return null;
let context = null;
try { context = getAudioContext(); } catch { context = null; }
// Not allowed to sound yet (no click on the page since load): <audio> as before.
if (!context?.createBufferSource || context.state === "suspended" || context.state === "closed") return null;
const buffer = await loadBuffer(context, joinUrl(baseUrl, effectPath));
if (!buffer) return null;
try {
const source = context.createBufferSource();
source.buffer = buffer;
if (playbackRate) source.playbackRate.value = playbackRate;
const gain = context.createGain();
gain.gain.value = clamp(volume, 0.8);
source.connect(gain);
gain.connect(context.destination);
source.start();
return true;
} catch { return null; }
}
async function playEffect(key, eventOptions = {}) {
const { settings, definition, configured } = configFor(key);
if (!settings.enabled || settings.muted || !configured.effect || !definition?.effect) return false;
@@ -289,9 +330,9 @@ export function createRaceAudioEngine(options = {}) {
const isPassing = key === "transponder_pass" || key === "transponder_detected";
const volume = settings.masterVolume * (isPassing ? settings.passingVolume : settings.effectsVolume);
const rate = settings.perCompetitorPassingTone && isPassing && eventOptions.variant ? variantPlaybackRate(eventOptions.variant) : undefined;
const played = await attemptEffect(effectPath, volume, rate);
const played = (isPassing && await attemptBufferedEffect(effectPath, volume, rate)) || await attemptEffect(effectPath, volume, rate);
const fallbackRate = rate || (customPath && isPassing ? variantPlaybackRate(customPath) : undefined);
if (!played && customPath && isPassing) return attemptEffect(DEFAULT_PASSING_SOUND, volume, fallbackRate);
if (!played && customPath && isPassing) return (await attemptBufferedEffect(DEFAULT_PASSING_SOUND, volume, fallbackRate)) || attemptEffect(DEFAULT_PASSING_SOUND, volume, fallbackRate);
return played;
}
+58
View File
@@ -30,6 +30,64 @@ test("missing custom passing sound never rejects and falls back safely", async (
assert.deepEqual(played, ["/race-sounds/sounds/effects/pass_01.wav", "/race-sounds/sounds/effects/transponder_pass.wav"]);
});
// A fake AudioContext: decodeAudioData and every started buffer source are recorded.
function fakeAudioContext(state = "running") {
const log = { decoded: 0, started: [] };
const context = {
state,
destination: {},
decodeAudioData: (data, ok) => { log.decoded += 1; ok({ duration: 0.1, data }); },
createGain: () => ({ gain: { value: 1 }, connect: () => {} }),
createBufferSource: () => {
const source = { buffer: null, playbackRate: { value: 1 }, connect: () => {}, start: () => log.started.push({ buffer: source.buffer, rate: source.playbackRate.value }) };
return source;
},
};
return { context, log };
}
test("passings play from a sound decoded once through WebAudio, several at once", async () => {
const fetched = [];
const elements = [];
const { context, log } = fakeAudioContext();
const engine = createRaceAudioEngine({
fetchImpl: async (url) => { fetched.push(url); return url.endsWith(".json") ? { ok: true, json: async () => manifest } : { ok: true, arrayBuffer: async () => new ArrayBuffer(8) }; },
audioFactory: (src) => ({ play: () => { elements.push(src); return Promise.resolve(); }, volume: 1 }),
getAudioContext: () => context,
getSettings: () => normalizeRaceAudioSettings(),
});
const results = await Promise.all([engine.playEffect("transponder_pass"), engine.playEffect("transponder_pass"), engine.playEffect("transponder_pass")]);
assert.deepEqual(results, [true, true, true]);
assert.equal(log.started.length, 3, "three passings, three sounds");
assert.equal(log.decoded, 1, "decoded once");
assert.equal(fetched.filter((url) => url.endsWith(".wav")).length, 1, "fetched once");
assert.deepEqual(elements, [], "no <audio> element for passings");
// Other effects (start tone, warnings) keep the <audio> path.
await engine.playEffect("start_tone");
assert.equal(elements.length, 1);
});
test("passing sound falls back to <audio> without a running AudioContext or when the file can't be decoded", async () => {
const run = async (contextFactory, fetchWav) => {
const elements = [];
const engine = createRaceAudioEngine({
fetchImpl: async (url) => (url.endsWith(".json") ? { ok: true, json: async () => manifest } : fetchWav()),
audioFactory: (src) => ({ play: () => { elements.push(src); return Promise.resolve(); }, volume: 1 }),
getAudioContext: contextFactory,
getSettings: () => normalizeRaceAudioSettings(),
});
assert.equal(await engine.playEffect("transponder_pass"), true);
return elements.length;
};
const okWav = () => ({ ok: true, arrayBuffer: async () => new ArrayBuffer(8) });
assert.equal(await run(() => fakeAudioContext("suspended").context, okWav), 1, "page not clicked yet: <audio>");
assert.equal(await run(() => null, okWav), 1, "no WebAudio: <audio>");
assert.equal(await run(() => fakeAudioContext().context, () => ({ ok: false })), 1, "file not found for WebAudio: <audio>");
const broken = fakeAudioContext();
broken.context.decodeAudioData = (data, ok, fail) => fail(new Error("bad wav"));
assert.equal(await run(() => broken.context, okWav), 1, "can't decode: <audio>");
});
test("critical control voice is prioritized over queued low-priority voice", async () => {
const resolvers = [];
const spoken = [];