Files
Live_RC/tests/race_audio.test.js
T

387 lines
22 KiB
JavaScript

import test from "node:test";
import assert from "node:assert/strict";
import { RACE_AUDIO_EVENT_DEFINITIONS, createRaceAudioEngine, normalizeRaceAudioSettings, isSilencedDuringRace, formatSpokenLapTime, formatShortLapCall } from "../src/race_audio.js";
const manifest = {
events: { transponder_pass: { effect: "effects/transponder_pass.wav" }, start_tone: { effect: "effects/start_beep.wav" } },
voice_events: { sv: { drivers_ready: "Redo", start_sequence: "Start på signalen", track_call: "Stopp på banan", clock_running: "Klockan går." }, en: { drivers_ready: "Ready" } },
};
test("race audio settings normalize volume, delay, language and switches", () => {
const settings = normalizeRaceAudioSettings({ masterVolume: 4, effectsVolume: -1, language: "en", minStartDelay: 2, maxStartDelay: 1, events: { transponder_pass: { effect: false } } });
assert.equal(settings.masterVolume, 1);
assert.equal(settings.effectsVolume, 0);
assert.equal(settings.language, "en");
assert.equal(settings.voiceRate, 1.08);
assert.equal(settings.voicePitch, 0.9);
assert.equal(settings.minStartDelay, 2);
assert.equal(settings.maxStartDelay, 2);
assert.equal(settings.events.transponder_pass.effect, false);
});
test("missing custom passing sound never rejects and falls back safely", async () => {
const played = [];
const engine = createRaceAudioEngine({
fetchImpl: async () => ({ ok: true, json: async () => manifest }),
audioFactory: (src) => ({ play: () => { played.push(src); if (src.includes("pass_01")) throw new Error("missing"); return Promise.resolve(); }, volume: 1 }),
getSettings: () => normalizeRaceAudioSettings(),
});
assert.equal(await engine.playEffect("transponder_pass", { effectPath: "pass_01.wav" }), true);
assert.deepEqual(played, ["/race-sounds/sounds/effects/pass_01.wav", "/race-sounds/sounds/effects/transponder_pass.wav"]);
});
test("critical control voice is prioritized over queued low-priority voice", async () => {
const resolvers = [];
const spoken = [];
const engine = createRaceAudioEngine({
fetchImpl: async () => ({ ok: true, json: async () => ({ ...manifest, voice_events: { sv: { ...manifest.voice_events.sv, personal_best: "PB" } } }) }),
audioFactory: () => ({ play: () => Promise.resolve(), volume: 1 }),
speak: (text, options) => new Promise((resolve) => { spoken.push([text, options.interrupt]); resolvers.push(resolve); }),
getSettings: () => normalizeRaceAudioSettings(),
});
engine.trigger("personal_best");
while (spoken.length < 1) await new Promise((resolve) => setImmediate(resolve));
engine.trigger("track_call");
while (spoken.length < 2) await new Promise((resolve) => setImmediate(resolve));
assert.equal(spoken.at(-1)[0], "Stopp på banan");
assert.equal(spoken.at(-1)[1], true);
resolvers.forEach((resolve) => resolve(true));
});
test("start lights, random delay and tone precede the official start callback", async () => {
const calls = [];
const engine = createRaceAudioEngine({
fetchImpl: async () => ({ ok: true, json: async () => manifest }),
audioFactory: (src) => ({ play: () => { calls.push(["effect", src]); return Promise.resolve(); }, volume: 1 }),
speak: async (text) => { calls.push(["voice", text]); return true; },
wait: async (ms) => calls.push(["wait", ms]),
random: () => 0.5,
getSettings: () => normalizeRaceAudioSettings({ startCountdownSeconds: 0, lightIntervalMs: 300, minStartDelay: 1, maxStartDelay: 4 }),
});
const states = [];
engine.subscribeStartLights((state) => states.push(state));
await engine.runStartSequence({ id: "race", type: "final" }, { onTone: () => calls.push(["timing-start"]) });
assert.deepEqual(states, ["IDLE", "GRID", "READY", "LIGHT_1", "LIGHT_2", "LIGHT_3", "LIGHT_4", "LIGHT_5", "WAIT_RANDOM", "GO"]);
assert.equal(calls.at(-1)[0], "timing-start");
assert.deepEqual(calls.slice(-3), [["wait", 2500], ["effect", "/race-sounds/sounds/effects/start_tone.wav"], ["timing-start"]]);
});
test("staggered start mode calls out each car in grid order, 3s apart, after the official start", async () => {
const calls = [];
const engine = createRaceAudioEngine({
fetchImpl: async () => ({ ok: true, json: async () => ({ ...manifest, voice_events: { sv: { ...manifest.voice_events.sv, staggered_release: "Bil {tp}." } } }) }),
audioFactory: (src) => ({ play: () => { calls.push(["effect", src]); return Promise.resolve(); }, volume: 1 }),
speak: async (text) => { calls.push(["voice", text]); return true; },
wait: async (ms) => calls.push(["wait", ms]),
getSettings: () => normalizeRaceAudioSettings({ startCountdownSeconds: 0, startLights: false, minStartDelay: 0, maxStartDelay: 0 }),
});
await engine.runStartSequence(
{ id: "q1h1", type: "qualification", startMode: "staggered" },
{ onTone: () => calls.push(["timing-start"]), staggerOrder: ["111", "222", "333"] }
);
const afterStart = calls.slice(calls.findIndex((call) => call[0] === "timing-start") + 1);
assert.deepEqual(afterStart, [
["voice", "Bil 111."], ["wait", 3000],
["voice", "Bil 222."], ["wait", 3000],
["voice", "Bil 333."],
]);
});
function createRecordingEngine(calls, settings = {}) {
return createRaceAudioEngine({
fetchImpl: async () => ({ ok: true, json: async () => manifest }),
audioFactory: (src) => ({ play: () => { calls.push(["effect", src.split("/").pop()]); return Promise.resolve(); }, volume: 1 }),
speak: async (text) => { calls.push(["voice", text]); return true; },
wait: async (ms) => calls.push(["wait", ms]),
getSettings: () => normalizeRaceAudioSettings({ startCountdownSeconds: 0, startLights: false, minStartDelay: 2, maxStartDelay: 2, randomStartDelay: false, ...settings }),
});
}
test("a flying start has no start procedure: horn, then 'clock is running' (EFRA 9.2b)", async () => {
const calls = [];
const engine = createRecordingEngine(calls, { startLights: true });
const states = [];
engine.subscribeStartLights((state) => states.push(state));
await engine.runStartSequence({ id: "q1", type: "qualification", startMode: "flying" }, { onTone: () => calls.push(["timing-start"]), skipCountdown: true });
await new Promise((resolve) => setImmediate(resolve));
assert.deepEqual(states, ["IDLE", "GRID", "GO"], "no lights and no random delay");
assert.deepEqual(calls, [["effect", "start_tone.wav"], ["timing-start"], ["voice", "Klockan går."]]);
});
test("after the prologue a grid start skips its own count-down, says 'start on the tone' and gives the tone", async () => {
const calls = [];
const engine = createRecordingEngine(calls, { startCountdownSeconds: 30 });
await engine.runStartSequence({ id: "f1", type: "final", startMode: "position" }, { onTone: () => calls.push(["timing-start"]), skipCountdown: true, skipIntro: true });
assert.equal(calls.length, 4, "the call, the quiet and the tone");
assert.deepEqual(calls[0], ["voice", "Start på signalen"]);
assert.equal(calls[1][0], "wait");
assert.ok(calls[1][1] >= 1000 && calls[1][1] <= 3000, "1-3 s of quiet");
assert.deepEqual(calls.slice(2), [["effect", "start_tone.wav"], ["timing-start"]]);
});
test("after the count-down's 3 and the tone call it is quiet until the tone 1-3 s later, with the lights inside that time", async () => {
for (const [roll, totalMs] of [[0, 1000], [1, 3000]]) {
const calls = [];
const engine = createRaceAudioEngine({
fetchImpl: async () => ({ ok: true, json: async () => manifest }),
audioFactory: (src) => ({ play: () => { calls.push(["effect", src.split("/").pop()]); return Promise.resolve(); }, volume: 1 }),
speak: async (text) => { calls.push(["voice", text]); return true; },
wait: async (ms) => calls.push(["wait", ms]),
random: () => roll,
getSettings: () => normalizeRaceAudioSettings({ startLights: true, lightIntervalMs: 1000, minStartDelay: 4, maxStartDelay: 8 }),
});
await engine.runStartSequence({ id: "f1", type: "final", startMode: "position" }, { skipCountdown: true, skipIntro: true });
assert.equal(calls.filter(([kind]) => kind === "voice").length, 1, "only 'start on the tone' is said");
const waited = calls.filter(([kind]) => kind === "wait").reduce((sum, [, ms]) => sum + ms, 0);
assert.ok(Math.abs(waited - totalMs) <= 6, `horn ${totalMs} ms after the 3, was ${waited}`);
assert.deepEqual(calls.at(-1), ["effect", "start_tone.wav"]);
}
});
test("during a race only the passing tone and leader calls play by default - no personal bests", () => {
const race = { type: "heat" };
assert.equal(normalizeRaceAudioSettings({}).raceCallouts, "passing");
["personal_best", "fastest_lap", "track_record", "position_gain", "position_loss"].forEach((key) => {
assert.equal(isSilencedDuringRace(key, {}, race), true, key);
});
assert.equal(isSilencedDuringRace("new_leader", {}, race), false, "leader change is called by default");
assert.equal(isSilencedDuringRace("leader_update", {}, race), false);
assert.equal(isSilencedDuringRace("leader_update", { raceLeaderCalls: "change" }, race), true);
assert.equal(isSilencedDuringRace("new_leader", { raceLeaderCalls: "off" }, race), true);
["transponder_pass", "final_lap", "one_minute_remaining", "race_finished", "race_winner", "clock_running"].forEach((key) => {
assert.equal(isSilencedDuringRace(key, {}, race), false, `${key} is not a per-passing call`);
});
assert.equal(isSilencedDuringRace("personal_best", { raceCallouts: "full" }, race), false, "speaker mode keeps the calls");
assert.equal(isSilencedDuringRace("personal_best", {}, { type: "open_practice" }), false, "practice keeps the calls");
assert.equal(isSilencedDuringRace("personal_best", {}, null), false);
});
test("a mass-start session never calls out individual cars, even if a grid order is passed", async () => {
const calls = [];
const engine = createRaceAudioEngine({
fetchImpl: async () => ({ ok: true, json: async () => manifest }),
audioFactory: () => ({ play: () => Promise.resolve(), volume: 1 }),
speak: async (text) => { calls.push(text); return true; },
wait: async () => {},
getSettings: () => normalizeRaceAudioSettings({ startCountdownSeconds: 0, startLights: false, minStartDelay: 0, maxStartDelay: 0 }),
});
await engine.runStartSequence(
{ id: "final", type: "final", startMode: "mass" },
{ staggerOrder: ["111", "222"] }
);
assert.ok(!calls.some((text) => text.startsWith("Bil") || text.startsWith("Car")), "no per-car call-out for a mass start: " + JSON.stringify(calls));
});
test("cancelling a pending start prevents the official start callback", async () => {
let releaseDelay;
let started = false;
const engine = createRaceAudioEngine({
fetchImpl: async () => ({ ok: true, json: async () => manifest }),
audioFactory: () => ({ play: () => Promise.resolve(), volume: 1 }),
speak: async () => true,
wait: () => new Promise((resolve) => { releaseDelay = resolve; }),
getSettings: () => normalizeRaceAudioSettings({ startLights: false, minStartDelay: 1, maxStartDelay: 1 }),
});
const pending = engine.runStartSequence({ id: "race" }, { onTone: () => { started = true; } });
while (!releaseDelay) await new Promise((resolve) => setImmediate(resolve));
engine.cancelStartSequence();
releaseDelay();
assert.equal(await pending, false);
assert.equal(started, false);
});
test("event catalog covers every supported race-audio event", () => {
const keys = new Set(RACE_AUDIO_EVENT_DEFINITIONS.map((item) => item.key));
[
"grid_open", "grid_closed", "race_1_minute", "race_30_seconds", "race_10_seconds", "drivers_ready", "start_sequence", "start_tone", "false_start", "restart_race", "staggered_release", "prologue_start", "prologue_minutes", "prologue_grid", "prologue_count", "prologue_hold", "prologue_resumed", "prologue_cancelled", "clock_running",
"transponder_pass", "lap_completed", "personal_best", "fastest_lap", "track_record", "training_stable_pace", "new_leader", "position_gain", "position_loss", "final_lap", "one_minute_remaining", "thirty_seconds_remaining", "ten_seconds_remaining", "time_expired", "race_finished",
"track_call", "track_clear", "yellow_flag", "red_flag", "race_paused", "race_resumed", "marshal_warning", "marshal_required", "penalty", "stop_and_go", "drive_through", "disqualified",
"pit_lane_open", "pit_lane_closed", "entering_pits", "leaving_pits", "pit_speed_warning",
"qualifying_start", "qualifying_remaining", "qualifying_finished", "provisional_pole", "pole_position",
"race_winner", "second_place", "third_place", "podium", "heat_winner", "overall_winner",
"timing_connected", "timing_disconnected", "transponder_detected", "unknown_transponder", "audio_test",
].forEach((key) => assert.equal(keys.has(key), true, `missing event: ${key}`));
});
test("voice follows the selected language and interpolates dynamic race data", async () => {
let language = "sv";
const spoken = [];
const engine = createRaceAudioEngine({
fetchImpl: async () => ({ ok: true, json: async () => ({ ...manifest, voice_events: {
sv: { ...manifest.voice_events.sv, new_leader: "Ny ledare {driverName}" },
en: { ...manifest.voice_events.en, new_leader: "New leader {driverName}" },
} }) }),
audioFactory: () => ({ play: () => Promise.resolve(), volume: 1 }),
speak: async (text, options) => { spoken.push([text, options.language]); return true; },
getSettings: () => normalizeRaceAudioSettings({ language }),
});
await engine.trigger("new_leader", { variables: { driverName: "Alex" } }).voiceDone;
language = "en";
await engine.trigger("new_leader", { variables: { driverName: "Sam" }, force: true }).voiceDone;
assert.deepEqual(spoken, [["Ny ledare Alex", "sv"], ["New leader Sam", "en"]]);
});
test("simultaneous transponder pass effects overlap without entering the voice queue", async () => {
const releases = [];
const played = [];
const engine = createRaceAudioEngine({
fetchImpl: async () => ({ ok: true, json: async () => manifest }),
audioFactory: (src) => ({ play: () => { played.push(src); return new Promise((resolve) => releases.push(resolve)); }, volume: 1 }),
getSettings: () => normalizeRaceAudioSettings(),
});
const first = engine.trigger("transponder_pass", { competitorKey: "one" });
const second = engine.trigger("transponder_pass", { competitorKey: "two" });
while (played.length < 2) await new Promise((resolve) => setImmediate(resolve));
assert.equal(played.length, 2);
assert.equal(engine.getStatus().currentVoice, "");
releases.forEach((resolve) => resolve());
assert.deepEqual(await Promise.all([first.effectDone, second.effectDone]), [true, true]);
});
test("event cooldown debounces one scope without suppressing another competitor", async () => {
let timestamp = 1_000;
const logged = [];
const engine = createRaceAudioEngine({
fetchImpl: async () => ({ ok: true, json: async () => manifest }),
audioFactory: () => ({ play: () => Promise.resolve(), volume: 1 }),
speak: async () => true,
now: () => timestamp,
log: (entry) => logged.push(entry),
getSettings: () => normalizeRaceAudioSettings(),
});
engine.trigger("personal_best", { driverId: "d1" });
timestamp += 100;
engine.trigger("personal_best", { driverId: "d1" });
engine.trigger("personal_best", { driverId: "d2" });
timestamp += 1_500;
engine.trigger("personal_best", { driverId: "d1" });
await Promise.resolve();
assert.deepEqual(logged.map((entry) => entry.event), ["personal_best", "personal_best", "personal_best"]);
});
test("fastest lap, track record and leader events use mapped effects and dynamic voice", async () => {
const played = [];
const spoken = [];
const completeManifest = {
...manifest,
events: {
...manifest.events,
fastest_lap: { effect: "effects/fastest.wav" },
track_record: { effect: "effects/record.wav" },
},
voice_events: { sv: {
...manifest.voice_events.sv,
fastest_lap: "Snabbast {driverName} {lapTime}",
track_record: "Rekord {driverName} {lapTime}",
new_leader: "Ledare {driverName}",
} },
};
const engine = createRaceAudioEngine({
fetchImpl: async () => ({ ok: true, json: async () => completeManifest }),
audioFactory: (src) => ({ play: () => { played.push(src); return Promise.resolve(); }, volume: 1 }),
speak: async (text) => { spoken.push(text); return true; },
getSettings: () => normalizeRaceAudioSettings(),
});
for (const key of ["fastest_lap", "track_record", "new_leader"]) {
await engine.trigger(key, { variables: { driverName: "Kim", lapTime: "16.200" }, force: true }).voiceDone;
}
assert.deepEqual(played, ["/race-sounds/sounds/effects/fastest.wav", "/race-sounds/sounds/effects/record.wav"]);
assert.deepEqual(spoken, ["Snabbast Kim 16.200", "Rekord Kim 16.200", "Ledare Kim"]);
});
test("count-down calls replace each other instead of queueing, and late ones are dropped", async () => {
const spoken = [];
const resolvers = [];
let clock = 1000;
const engine = createRaceAudioEngine({
fetchImpl: async () => ({ ok: true, json: async () => manifest }),
audioFactory: () => ({ play: () => Promise.resolve(), volume: 1 }),
speak: (text) => new Promise((resolve) => { spoken.push(text); resolvers.push(resolve); }),
now: () => clock,
getSettings: () => normalizeRaceAudioSettings(),
});
const tick = async () => { for (let i = 0; i < 20; i += 1) await new Promise((resolve) => setImmediate(resolve)); };
const count = (seconds) => engine.trigger("prologue_count", { interrupt: true, force: true, group: "prologue", maxDelayMs: 1200, voiceText: String(seconds) });
// A slow voice: "9" is still being said when "8" and "7" are due.
count(9); await tick();
count(8); await tick();
count(7); await tick();
assert.deepEqual(spoken, ["9", "8", "7"], "each new call cuts the previous one");
// A call that waited longer than its limit is never said.
// Another call holds the voice past the limit: the waiting "6" is skipped.
engine.trigger("prologue_hold", { interrupt: true, force: true, priority: "critical", voiceText: "Håll" });
await tick();
const late = count(6);
await tick();
clock += 5000;
resolvers.forEach((resolve) => resolve(true));
assert.equal(await late.voiceDone, false);
assert.ok(!spoken.includes("6"));
});
test("the start and finish signals are chosen in Settings: tone and stop signal by default", async () => {
for (const [settings, start, finish] of [[{}, "start_tone.wav", "finish_stop.wav"], [{ startSound: "trumpet", finishSound: "fanfare" }, "start_trumpet.wav", "finish_fanfare.wav"], [{ startSound: "horn", finishSound: "classic" }, "start_horn.wav", "race_finish.wav"]]) {
const calls = [];
const engine = createRecordingEngine(calls, settings);
await engine.playEffect("start_tone", { force: true });
await engine.playEffect("race_finished", { force: true });
assert.deepEqual(calls, [["effect", start], ["effect", finish]]);
}
assert.equal(normalizeRaceAudioSettings({ startSound: "nope" }).startSound, "tone");
});
test("lap times are spoken as seconds with hundredths, no leading zero minute", () => {
assert.equal(formatSpokenLapTime(17189, "sv"), "17,18");
assert.equal(formatSpokenLapTime(17189, "en"), "17.18");
assert.equal(formatSpokenLapTime(9050, "sv"), "9,05");
assert.equal(formatSpokenLapTime(65320, "sv"), "1 minut 5,32");
assert.equal(formatSpokenLapTime(125000, "en"), "2 minutes 5.00");
});
test("practice hype calls only sound in practice and can be turned off", () => {
assert.equal(isSilencedDuringRace("practice_lap_milestone", {}, { type: "open_practice" }), false);
assert.equal(isSilencedDuringRace("practice_lap_milestone", {}, { type: "practice" }), false);
["qualification", "heat", "final", "team_race"].forEach((type) => {
assert.equal(isSilencedDuringRace("practice_duel", { raceCallouts: "full" }, { type }), true, type);
});
assert.equal(isSilencedDuringRace("practice_close_to_best", { practiceHype: false }, { type: "open_practice" }), true);
});
test("quick lap time call: seconds and tenths, practice only and without the name by default", () => {
assert.equal(formatShortLapCall(17620, "en"), "17 six");
assert.equal(formatShortLapCall(18040, "en"), "18 flat");
assert.equal(formatShortLapCall(18290, "sv"), "18 två");
assert.equal(formatShortLapCall(18000, "sv"), "18 jämnt");
assert.equal(formatShortLapCall(65200, "en"), "1 05 two");
const audio = normalizeRaceAudioSettings({});
assert.equal(audio.lapTimeCalls, "practice");
assert.equal(audio.lapTimeCallName, false);
assert.equal(isSilencedDuringRace("lap_completed", {}, { type: "open_practice" }), false);
assert.equal(isSilencedDuringRace("lap_completed", {}, { type: "final" }), true);
assert.equal(isSilencedDuringRace("lap_completed", { lapTimeCalls: "always" }, { type: "final" }), false);
assert.equal(isSilencedDuringRace("lap_completed", { lapTimeCalls: "off" }, { type: "open_practice" }), true);
});
test("a quick lap time call is dropped while the voice is busy", async () => {
const spoken = [];
let finish;
const engine = createRaceAudioEngine({
fetchImpl: async () => ({ ok: true, json: async () => manifest }),
audioFactory: () => ({ play: () => Promise.resolve(), volume: 1 }),
speak: (text) => { spoken.push(text); return new Promise((resolve) => { finish = resolve; }); },
wait: async () => {},
getSettings: () => normalizeRaceAudioSettings({}),
});
engine.trigger("audio_test", { voiceText: "busy" });
await new Promise((resolve) => setTimeout(resolve, 10));
const lap = await engine.trigger("lap_completed", { skipIfBusy: true, voiceText: "{lapShort}", variables: { lapShort: "17 six" } }).voiceDone;
assert.equal(lap, false);
finish(true);
await new Promise((resolve) => setTimeout(resolve, 10));
const free = await engine.trigger("lap_completed", { skipIfBusy: true, voiceText: "{lapShort}", variables: { lapShort: "18 flat" } });
await new Promise((resolve) => setTimeout(resolve, 10));
finish(true);
assert.equal(await free.voiceDone, true);
assert.deepEqual(spoken, ["busy", "18 flat"]);
});