import { PRACTICE_HYPE_EVENTS } from "./practice_hype_logic.js"; export const RACE_AUDIO_PRIORITIES = Object.freeze({ pass: 0, low: 10, normal: 20, high: 30, critical: 40 }); export const START_LIGHT_STATES = Object.freeze(["IDLE", "GRID", "READY", "LIGHT_1", "LIGHT_2", "LIGHT_3", "LIGHT_4", "LIGHT_5", "WAIT_RANDOM", "GO"]); const event = (key, group, priority, voice = true, effect = "", cooldownMs = 0) => ({ key, group, priority, voice, effect, cooldownMs }); export const RACE_AUDIO_EVENT_DEFINITIONS = Object.freeze([ event("grid_open", "start", "normal"), event("grid_closed", "start", "normal"), event("race_1_minute", "start", "normal"), event("race_30_seconds", "start", "normal"), event("race_10_seconds", "start", "normal", true, "effects/warning.wav"), event("drivers_ready", "start", "high"), event("start_sequence", "start", "high"), event("start_tone", "start", "high", false, "effects/start_tone.wav"), event("false_start", "start", "critical", true, "effects/warning.wav", 1000), event("restart_race", "start", "high"), event("staggered_release", "start", "normal"), event("prologue_start", "start", "normal"), event("prologue_minutes", "start", "normal"), event("prologue_grid", "start", "high"), event("prologue_count", "start", "high"), event("prologue_hold", "start", "high", true, "effects/warning.wav"), event("prologue_resumed", "start", "normal"), event("prologue_cancelled", "start", "normal"), event("clock_running", "start", "high"), event("heat_call", "start", "normal"), event("transponder_pass", "race", "pass", false, "effects/transponder_pass.wav"), event("lap_completed", "race", "pass"), event("personal_best", "race", "low", true, "effects/personal_best.wav", 1500), event("fastest_lap", "race", "normal", true, "effects/fastest_lap_trophy.wav", 1500), event("track_record", "race", "normal", true, "effects/track_record_fanfare.wav", 2000), event("training_stable_pace", "training", "low", true, "", 120000), event("seed_improved", "training", "low", true, "", 0), event("new_leader", "race", "normal", true, "", 1000), event("leader_update", "race", "normal"), ...PRACTICE_HYPE_EVENTS.map((key) => event(key, "training", "low")), event("position_gain", "race", "low", false, "effects/position_gain.wav", 750), event("position_loss", "race", "low", false, "effects/position_loss.wav", 750), event("final_lap", "race", "high", true, "effects/final_lap.wav"), event("one_minute_remaining", "race", "normal"), event("thirty_seconds_remaining", "race", "normal"), event("ten_seconds_remaining", "race", "normal", true, "effects/warning.wav"), event("time_expired", "race", "high", true, "effects/warning.wav"), event("race_finished", "race", "high", true, "effects/finish_stop.wav"), event("track_call", "control", "critical", true, "effects/warning.wav", 1000), event("track_clear", "control", "critical"), event("yellow_flag", "control", "critical", true, "effects/warning.wav"), event("red_flag", "control", "critical", true, "effects/warning.wav"), event("race_paused", "control", "critical", true, "effects/warning.wav"), event("race_resumed", "control", "high"), event("marshal_warning", "control", "high", true, "effects/warning.wav", 1000), event("marshal_required", "control", "high", true, "effects/warning.wav", 1000), event("penalty", "control", "high", true, "effects/warning.wav", 750), event("stop_and_go", "control", "high", true, "effects/warning.wav"), event("drive_through", "control", "high", true, "effects/warning.wav"), event("disqualified", "control", "high", true, "effects/warning.wav"), // EFRA 9.1-9.3: "Attention driver (name)" (blue flag) and an official warning (2 = DSQ). event("driver_attention", "control", "high", true, "effects/warning.wav", 750), event("official_warning", "control", "high", true, "effects/warning.wav"), event("pit_lane_open", "pit", "normal"), event("pit_lane_closed", "pit", "normal"), event("entering_pits", "pit", "low", false, "effects/transponder_pass.wav"), event("leaving_pits", "pit", "low", false, "effects/transponder_pass.wav"), event("pit_speed_warning", "pit", "high", true, "effects/warning.wav"), event("qualifying_start", "qualifying", "high"), event("qualifying_remaining", "qualifying", "normal"), event("qualifying_finished", "qualifying", "high", true, "effects/finish_stop.wav"), event("provisional_pole", "qualifying", "normal"), event("pole_position", "qualifying", "normal", true, "effects/fastest_lap_trophy.wav"), event("race_winner", "results", "high", true, "effects/fastest_lap_trophy.wav"), event("second_place", "results", "normal"), event("third_place", "results", "normal"), event("podium", "results", "normal"), event("heat_winner", "results", "high", true, "effects/fastest_lap_trophy.wav"), event("overall_winner", "results", "high", true, "effects/fastest_lap_trophy.wav"), event("timing_connected", "system", "normal"), event("timing_disconnected", "system", "critical", true, "effects/warning.wav", 2000), event("transponder_detected", "system", "pass", false, "effects/transponder_pass.wav"), event("unknown_transponder", "system", "low", true, "effects/warning.wav", 2000), event("audio_test", "system", "normal", true, "effects/start_beep.wav"), ]); const EVENT_BY_KEY = new Map(RACE_AUDIO_EVENT_DEFINITIONS.map((item) => [item.key, item])); const DEFAULT_PASSING_SOUND = "effects/transponder_pass.wav"; const clamp = (value, fallback, min = 0, max = 1) => { const number = Number(value); return Math.max(min, Math.min(max, Number.isFinite(number) ? number : fallback)); }; // The start and finish signals can be chosen in Settings (the files are in the sound pack). export const START_SOUNDS = Object.freeze({ tone: "effects/start_tone.wav", trumpet: "effects/start_trumpet.wav", horn: "effects/start_horn.wav", beep: "effects/start_beep.wav" }); export const FINISH_SOUNDS = Object.freeze({ stop: "effects/finish_stop.wav", fanfare: "effects/finish_fanfare.wav", horn: "effects/finish_horn.wav", classic: "effects/race_finish.wav" }); const FINISH_EVENTS = new Set(["race_finished", "qualifying_finished"]); export function normalizeRaceAudioSettings(value = {}) { const source = value && typeof value === "object" ? value : {}; const events = {}; RACE_AUDIO_EVENT_DEFINITIONS.forEach((definition) => { const configured = source.events?.[definition.key] || {}; events[definition.key] = { effect: Boolean(definition.effect) && configured.effect !== false, voice: Boolean(definition.voice) && configured.voice !== false, }; }); const minStartDelay = clamp(source.minStartDelay ?? source.start?.randomDelay?.min, 1, 0, 10); const maxStartDelay = clamp(source.maxStartDelay ?? source.start?.randomDelay?.max, 4, minStartDelay, 10); return { enabled: source.enabled !== false, muted: source.muted === true, language: source.language === "en" ? "en" : "sv", voiceUri: String(source.voiceUri || ""), voiceRate: clamp(source.voiceRate, 1.08, 0.65, 1.35), voicePitch: clamp(source.voicePitch, 0.9, 0.7, 1.3), masterVolume: clamp(source.masterVolume ?? source.volume?.master, 0.8), effectsVolume: clamp(source.effectsVolume ?? source.volume?.effects, 0.8), voiceVolume: clamp(source.voiceVolume ?? source.volume?.voice, 0.9), passingVolume: clamp(source.passingVolume ?? source.volume?.passing, 0.45), startCountdownSeconds: [0, 10, 30, 60].includes(Number(source.startCountdownSeconds)) ? Number(source.startCountdownSeconds) : 0, startLights: source.startLights !== false, lightIntervalMs: Math.round(clamp(source.lightIntervalMs, 300, 100, 2000)), randomStartDelay: source.randomStartDelay !== false, minStartDelay, maxStartDelay, perCompetitorPassingTone: source.perCompetitorPassingTone === true, // How the heat call and a staggered start name the drivers (see resolveDriverCallStyle). driverCallStyle: ["auto", "names", "numbers", "both"].includes(source.driverCallStyle) ? source.driverCallStyle : "auto", startSound: Object.hasOwn(START_SOUNDS, source.startSound) ? source.startSound : "tone", finishSound: Object.hasOwn(FINISH_SOUNDS, source.finishSound) ? source.finishSound : "stop", raceCallouts: source.raceCallouts === "full" ? "full" : "passing", // Practice hype calls (practice_hype_logic.js); never in qualifying or finals. practiceHype: source.practiceHype !== false, // Banner + warning when the decoder drops or goes silent during a heat (decoder_watch.js). decoderAlarm: source.decoderAlarm !== false, // Short lap time per passing, "Anders, 17 six": "practice" (default), "always" or "off". lapTimeCalls: ["practice", "always", "off"].includes(source.lapTimeCalls) ? source.lapTimeCalls : "practice", lapTimeCallName: source.lapTimeCallName === true, // Qualifying and finals: "both" = when the leader changes and every 2 minutes, // "change" = only when the leader changes, "off" = never (unless raceCallouts is "full"). raceLeaderCalls: ["off", "change", "both"].includes(source.raceLeaderCalls) ? source.raceLeaderCalls : "both", // Practice: "new leader" is fun info for many, but nobody races anyone - it can be turned off. practiceLeaderCalls: source.practiceLeaderCalls === "off" ? "off" : "on", // Open Practice personal best calls (practice_callouts_logic.js); 0 turns a rule off. practicePbWarmupLaps: Math.round(clamp(source.practicePbWarmupLaps, 10, 0, 30)), practicePbCooldownSec: Math.round(clamp(source.practicePbCooldownSec, 60, 0, 600)), practicePbMinGainMs: Math.round(clamp(source.practicePbMinGainMs, 100, 0, 2000)), events, templates: source.templates && typeof source.templates === "object" ? { ...source.templates } : {}, }; } // During a race, timing systems give each passing its tone and nothing more: no names, no // "personal best" / "new leader" calls per lap. raceCallouts "passing" (the default) keeps it // that way for race sessions; "full" is the speaker mode. Practice always gets the full set, // and the clock, start, final-lap and results calls are never affected. export const RACE_PASSING_CALLOUT_EVENTS = Object.freeze(["personal_best", "fastest_lap", "track_record", "new_leader", "position_gain", "position_loss", "provisional_pole"]); const PRACTICE_TYPES = new Set(["open_practice", "free_practice", "practice"]); const PRACTICE_HYPE_SET = new Set(PRACTICE_HYPE_EVENTS); export const LEADER_UPDATE_INTERVAL_MS = 120000; export function isSilencedDuringRace(eventKey, settings, session) { const audio = normalizeRaceAudioSettings(settings); const practice = Boolean(session) && PRACTICE_TYPES.has(String(session.type || "")); if (PRACTICE_HYPE_SET.has(eventKey)) return !practice || !audio.practiceHype; if (eventKey === "lap_completed") return audio.lapTimeCalls === "off" || (audio.lapTimeCalls === "practice" && !practice); if (practice && eventKey === "new_leader") return audio.practiceLeaderCalls === "off"; if (!session || practice) return false; if (eventKey === "leader_update") return audio.raceLeaderCalls !== "both"; if (eventKey === "new_leader" && audio.raceLeaderCalls !== "off") return false; if (audio.raceCallouts === "full") return false; return RACE_PASSING_CALLOUT_EVENTS.includes(eventKey); } // Heat call / staggered start: "names" (Roy), "numbers" (car 1 - the grid slot) or "both" // (car 1 Roy). "auto" = numbers in finals, where drivers go by their grid slot, names otherwise. export function resolveDriverCallStyle(style, sessionType) { if (["names", "numbers", "both"].includes(style)) return style; return String(sessionType || "") === "final" ? "numbers" : "names"; } const CAR_WORD = { sv: "Bil", en: "Car" }; // One car at a staggered start: "Bil 1", "Bil 1 Roy" or "Roy" (index = grid slot - 1). export function formatCarCall(index, name, style, language = "sv") { const car = `${CAR_WORD[language] || CAR_WORD.sv} ${index + 1}`; const spoken = String(name || "").trim(); if (style === "names") return spoken || car; return style === "both" && spoken ? `${car} ${spoken}` : car; } // The drivers in a heat call, in grid order: "Förare: Roy, Eddie. ", "Bil 1, 2, 3. " or // "Bil 1 Roy, bil 2 Eddie. " - empty when the heat has no drivers. export function formatHeatCallDrivers(names, style, language = "sv") { const list = (names || []).map((name) => String(name || "").trim()); if (!list.length) return ""; const word = CAR_WORD[language] || CAR_WORD.sv; if (style === "numbers") return `${word} ${list.map((_name, index) => index + 1).join(", ")}. `; if (style === "both") return `${list.map((name, index) => `${index ? word.toLowerCase() : word} ${index + 1}${name ? ` ${name}` : ""}`).join(", ")}. `; const named = list.filter(Boolean); return named.length ? `${language === "en" ? "Drivers" : "Förare"}: ${named.join(", ")}. ` : ""; } // The quick passing call used at race tracks: seconds and tenths, "17 six", "18 flat" // ("17 sex", "18 jämnt"). Over a minute: "1 05 two". const TENTHS = { en: ["flat", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"], sv: ["jämnt", "ett", "två", "tre", "fyra", "fem", "sex", "sju", "åtta", "nio"] }; export function formatShortLapCall(ms, language = "sv") { const value = Math.max(0, Math.floor(Number(ms) || 0)); if (!value) return ""; const minutes = Math.floor(value / 60000); const seconds = Math.floor((value % 60000) / 1000); const tenth = TENTHS[language === "en" ? "en" : "sv"][Math.floor((value % 1000) / 100)]; return minutes ? `${minutes} ${String(seconds).padStart(2, "0")} ${tenth}` : `${seconds} ${tenth}`; } // A lap time as a speaker says it: seconds and hundredths as two numbers, "18 63" -> "18 // sixty-three" ("18 sextiotre"), not "0:18.630" or "18 point six three". Over a minute: // "1 minut 05 32". Hundredths are cut, not rounded, as on the timing screens. export function formatSpokenLapTime(ms, language = "sv") { const value = Math.max(0, Math.floor(Number(ms) || 0)); if (!value) return ""; const minutes = Math.floor(value / 60000); const seconds = Math.floor((value % 60000) / 1000); // "00" would be read "hundred" by some voices: say "flat" / "jämnt" as on the passing call. const cut = Math.floor((value % 1000) / 10); const hundredths = cut ? String(cut).padStart(2, "0") : TENTHS[language === "en" ? "en" : "sv"][0]; if (!minutes) return `${seconds} ${hundredths}`; const word = language === "en" ? (minutes === 1 ? "minute" : "minutes") : (minutes === 1 ? "minut" : "minuter"); return `${minutes} ${word} ${String(seconds).padStart(2, "0")} ${hundredths}`; } // A gap or other short time with a decimal mark: "0,30" (sv) / "0.30" (en), read as "zero // point three zero" - a gap said as "0 30" would sound like a clock. export function formatSpokenGap(ms, language = "sv") { const value = Math.max(0, Math.floor(Number(ms) || 0)); if (!value) return ""; const minutes = Math.floor(value / 60000); const sep = language === "en" ? "." : ","; const seconds = `${Math.floor((value % 60000) / 1000)}${sep}${String(Math.floor((value % 1000) / 10)).padStart(2, "0")}`; if (!minutes) return seconds; return language === "en" ? `${minutes} ${minutes === 1 ? "minute" : "minutes"} ${seconds}` : `${minutes} ${minutes === 1 ? "minut" : "minuter"} ${seconds}`; } const joinUrl = (baseUrl, filePath) => `${String(baseUrl || "").replace(/\/+$/, "")}/${String(filePath || "").replace(/^\/+/, "")}`; const interpolate = (template, variables = {}) => String(template || "").replace(/\{(\w+)\}/g, (_match, key) => String(variables[key] ?? "")); function safeEffectPath(value) { const clean = String(value || "").trim().replace(/\\/g, "/"); if (!clean || clean.includes("..") || clean.startsWith("/") || /^https?:/i.test(clean)) return ""; return clean.includes("/") ? clean : `effects/${clean}`; } function variantPlaybackRate(value) { let hash = 0; for (const char of String(value || "")) hash = ((hash << 5) - hash + char.charCodeAt(0)) | 0; return 0.92 + (Math.abs(hash) % 17) / 100; } export function createRaceAudioEngine(options = {}) { const manifestUrl = options.manifestUrl || "/race-sounds/sound_manifest.json"; const baseUrl = options.baseUrl || "/race-sounds/sounds"; const fetchImpl = options.fetchImpl || globalThis.fetch?.bind(globalThis); const audioFactory = options.audioFactory || ((src) => new Audio(src)); const speak = options.speak || (() => false); const getSettings = options.getSettings || (() => normalizeRaceAudioSettings()); const wait = options.wait || ((ms) => new Promise((resolve) => setTimeout(resolve, ms))); 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