From 94ec278f53049ba0a6a00fcd8a21d01210d3f700 Mon Sep 17 00:00:00 2001 From: larssand Date: Thu, 5 Nov 2026 08:19:45 +0100 Subject: [PATCH] feat(audio): practice hype calls and leader calls in qualifying and finals (1.61.0) --- CHANGELOG.md | 11 +++ package-lock.json | 4 +- package.json | 2 +- rc-race-sound-pack/sound_manifest.json | 16 ++++ src/app.js | 12 +++ src/decoder_runtime.js | 62 ++++++++++++- src/practice_hype_logic.js | 117 +++++++++++++++++++++++++ src/race_audio.js | 21 ++++- src/settings.js | 4 + tests/decoder_runtime.test.js | 10 +++ tests/practice_hype.test.js | 66 ++++++++++++++ tests/race_audio.test.js | 17 +++- tests/run.js | 1 + 13 files changed, 334 insertions(+), 9 deletions(-) create mode 100644 src/practice_hype_logic.js create mode 100644 tests/practice_hype.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index a797294..365b410 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,17 @@ The application version is maintained in `package.json` and displayed in the adm No changes recorded yet. +## 1.61.0 - 2026-11-05 + +### Added + +- Practice hype calls to cheer drivers on, practice only (never qualifying or finals): every 50 laps, only 0.1 s or less off the best, three faster laps in a row, average down since the first 10 laps, faster than the best of the last day driven on this layout, top 3 in class today, and duels (two drivers on track within 0.2 s). At most one call per lap and one every 30 s per driver. On/off in Settings → Race sounds ("Practice hype calls"), and each call in the event list. +- Qualifying and finals call the leader: when the leader changes (not in the first 30 s, at most every 10 s) and "Anders leads, 12 laps" every 2 minutes as the leader crosses the line. Settings → "Leader in qualifying and finals": on change and every 2 minutes (default), only on change, or off. + +### Fixed + +- Leader calls use the driver's spoken name. + ## 1.60.0 - 2026-11-05 ### Added diff --git a/package-lock.json b/package-lock.json index 2860cf5..f1a4ebb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rc-racecore", - "version": "1.60.0", + "version": "1.61.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rc-racecore", - "version": "1.60.0", + "version": "1.61.0", "hasInstallScript": true, "dependencies": { "better-sqlite3": "^12.11.1", diff --git a/package.json b/package.json index 4a1cd5f..9064776 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rc-racecore", - "version": "1.60.0", + "version": "1.61.0", "private": true, "description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence", "engines": { diff --git a/rc-race-sound-pack/sound_manifest.json b/rc-race-sound-pack/sound_manifest.json index a9e5eee..e015199 100644 --- a/rc-race-sound-pack/sound_manifest.json +++ b/rc-race-sound-pack/sound_manifest.json @@ -59,6 +59,14 @@ "personal_best": "Personal best. {driverName}. {lapTime}.", "fastest_lap": "Fastest lap. {driverName}. {lapTime}.", "training_stable_pace": "{driverName}, good pace and consistent driving. Average {avgLap}.", "track_record": "New track record. {driverName}. {lapTime}.", "new_leader": "New race leader. {driverName}.", + "leader_update": "{driverName} leads, {laps} laps.", + "practice_beat_last_time": "{driverName}, {gap} faster than last time!", + "practice_class_rank": "{driverName}, now {rank} in class today.", + "practice_lap_milestone": "{driverName}, {laps} laps today. Keep it up!", + "practice_faster_streak": "{driverName}, {laps} faster laps in a row!", + "practice_average_down": "{driverName}, average down {gap}. Now {avgLap}.", + "practice_close_to_best": "{driverName}, only {gap} off your best.", + "practice_duel": "Duel! {driverName} is {gap} {relation} {rival}.", "final_lap": "Final lap.", "one_minute_remaining": "One minute remaining.", "thirty_seconds_remaining": "Thirty seconds remaining.", "ten_seconds_remaining": "Ten seconds remaining.", "time_expired": "Time has expired. Finish the lap you are on.", "race_finished": "Race is finished.", "track_call": "Track call. Track call.", "track_clear": "Track is clear.", "yellow_flag": "Yellow flag.", "red_flag": "Red flag. Stop all cars.", @@ -90,6 +98,14 @@ "personal_best": "Personbästa. {driverName}. {lapTime}.", "fastest_lap": "Snabbaste varv. {driverName}. {lapTime}.", "training_stable_pace": "{driverName}, bra tempo och stabil körning. Snitt {avgLap}.", "track_record": "Nytt banrekord. {driverName}. {lapTime}.", "new_leader": "Ny ledare. {driverName}.", + "leader_update": "{driverName} leder, {laps} varv.", + "practice_beat_last_time": "{driverName}, {gap} snabbare än förra gången!", + "practice_class_rank": "{driverName}, nu {rank} i klassen idag.", + "practice_lap_milestone": "{driverName}, {laps} varv idag. Snyggt jobbat!", + "practice_faster_streak": "{driverName}, {laps} snabbare varv i rad!", + "practice_average_down": "{driverName}, snittet ner {gap}. Nu {avgLap}.", + "practice_close_to_best": "{driverName}, bara {gap} från ditt bästa.", + "practice_duel": "Duell! {driverName} ligger {gap} {relation} {rival}.", "final_lap": "Sista varvet.", "one_minute_remaining": "En minut kvar.", "thirty_seconds_remaining": "Trettio sekunder kvar.", "ten_seconds_remaining": "Tio sekunder kvar.", "time_expired": "Tiden är slut. Slutför pågående varv.", "race_finished": "Racet är avslutat.", "track_call": "Stopp på banan. Stopp på banan.", "track_clear": "Banan är fri.", "yellow_flag": "Gul flagg.", "red_flag": "Röd flagg. Stoppa alla bilar.", diff --git a/src/app.js b/src/app.js index f2bf4f2..76ac4c1 100644 --- a/src/app.js +++ b/src/app.js @@ -2531,6 +2531,12 @@ const TRANSLATIONS = { "audio.practice_pb_warmup": "Träning: tyst personbästa första varven", "audio.practice_pb_cooldown": "Träning: sekunder mellan PB-utrop per förare", "audio.practice_pb_min_gain": "Träning: minsta förbättring för utrop (s)", + "audio.practice_hype": "Peppande träningsutrop", + "audio.practice_hype_hint": "Bara i träning, aldrig i kval eller final: varvjubileum, nära bästa varvet, snittet går ner, snabbare varv i rad, snabbare än förra gången, placering i klassen och dueller. Varje utrop kan också stängas av i listan nedan.", + "audio.race_leader_calls": "Ledare i kval och final", + "audio.race_leader_both": "Vid byte och var 2:a minut", + "audio.race_leader_change": "Bara när ledaren byts", + "audio.race_leader_off": "Av", "audio.practice_pb_hint": "Gäller open practice. På nyladdade ackar slår alla sin bästa tid nästan varje varv i början av dagen. Bästa varvet visas ändå på skärm och overlay. 0 stänger av regeln.", "audio.race_callouts_passing": "Bara passeringsljud (som tidtagningssystem)", "audio.race_callouts_full": "Speaker - namn, bästa varv, ny ledare", @@ -4512,6 +4518,12 @@ const TRANSLATIONS = { "audio.practice_pb_warmup": "Practice: silent personal best for first laps", "audio.practice_pb_cooldown": "Practice: seconds between PB calls per driver", "audio.practice_pb_min_gain": "Practice: minimum improvement to call (s)", + "audio.practice_hype": "Practice hype calls", + "audio.practice_hype_hint": "Practice only, never in qualifying or finals: lap milestones, close to best, average going down, faster laps in a row, faster than last time, class rank and duels. Each call can also be turned off in the list below.", + "audio.race_leader_calls": "Leader in qualifying and finals", + "audio.race_leader_both": "On change and every 2 minutes", + "audio.race_leader_change": "Only when the leader changes", + "audio.race_leader_off": "Off", "audio.practice_pb_hint": "Open Practice. On fresh packs everyone beats their best almost every lap early in the day. The best lap is still shown on screen and in the overlay. 0 turns a rule off.", "audio.race_callouts_passing": "Passing tone only (like timing systems)", "audio.race_callouts_full": "Speaker - names, best laps, new leader", diff --git a/src/decoder_runtime.js b/src/decoder_runtime.js index 351adcb..13dcf22 100644 --- a/src/decoder_runtime.js +++ b/src/decoder_runtime.js @@ -3,13 +3,52 @@ import { getControlledLapStreak } from "./training_logic.js"; import { usesPersonalClock, getLatestClockStartTs } from "./prologue_logic.js"; import { isSuspectLap, getSuspectReferenceLaps, releaseSettledSuspectLaps } from "./suspect_laps_logic.js"; import { shouldCallPracticePersonalBest } from "./practice_callouts_logic.js"; -import { normalizeRaceAudioSettings, formatSpokenLapTime } from "./race_audio.js"; +import { normalizeRaceAudioSettings, formatSpokenLapTime, LEADER_UPDATE_INTERVAL_MS } from "./race_audio.js"; +import { pickPracticeHype, getDriverLapTimes, getClassRank, getLastTimeBestMs, findDuelRival } from "./practice_hype_logic.js"; import { decoderClockCheck, describeDecoderClockSkew } from "./decoder_clock_check.js"; import { getCompetitorEndTs } from "./timing_logic.js"; const PRACTICE_SESSION_TYPES = new Set(["open_practice", "free_practice", "practice"]); // Last personal best *called* per driver, per practice day and layout (practice_callouts_logic.js). const lastPracticePbCall = new Map(); +const practiceHypeMemory = new Map(); +const lastLeaderCallBySession = new Map(); +const spokenName = (row) => row?.speechName || row?.displayName || row?.driverName || ""; + +// Practice hype (practice_hype_logic.js): gathers this lap's numbers and returns at most one +// call with its spoken variables, or null. +function buildPracticeHype({ state, session, result, entry, key, lapMs, previousPersonalBest, memoryKey, timestamp }) { + const memory = practiceHypeMemory.get(memoryKey) || {}; + practiceHypeMemory.set(memoryKey, memory); + const rows = Object.values(result.competitors || {}); + const classId = state.drivers?.find((driver) => driver.id === entry.driverId)?.classId || ""; + const classRows = classId ? rows.filter((row) => state.drivers.find((driver) => driver.id === row.driverId)?.classId === classId) : []; + const after = getClassRank(classRows, key); + const before = getClassRank(classRows.map((row) => (row.key === key ? { ...row, bestLapMs: previousPersonalBest } : row)), key); + const isPb = Boolean(previousPersonalBest && lapMs < previousPersonalBest); + if (isPb && !memory.beatLastTime && memory.lastTimeBestMs === undefined) { + const dayStartTs = new Date(timestamp).setHours(0, 0, 0, 0); + const lists = (state.sessions || []).map((item) => state.resultsBySession?.[item.id]?.passings); + memory.lastTimeBestMs = getLastTimeBestMs(lists, { driverId: entry.driverId, layoutId: session.trackLayoutId, dayStartTs }); + } + const rival = isPb ? findDuelRival(rows, { key, bestLapMs: lapMs, now: timestamp }) : null; + const pick = pickPracticeHype({ + laps: getDriverLapTimes(result.passings, key), lapMs, previousBestMs: previousPersonalBest, lapCount: entry.laps, + classRankBefore: before.rank, classRankAfter: after.rank, classSize: after.size, + lastTimeBestMs: memory.lastTimeBestMs, rival: rival ? { gapMs: rival.gapMs, name: spokenName(rival) } : null, + now: Date.now(), memory, + }); + if (!pick) return null; + const language = normalizeRaceAudioSettings(state.settings?.raceAudio).language; + const en = language === "en"; + const v = pick.variables; + const variables = { driverName: spokenName(entry), laps: v.laps, rival: v.rival }; + if (v.gapMs !== undefined) variables.gap = formatSpokenLapTime(Math.max(10, v.gapMs), language); + if (v.avgMs) variables.avgLap = formatSpokenLapTime(v.avgMs, language); + if (v.rank) variables.rank = (en ? ["the fastest", "second fastest", "third fastest"] : ["snabbast", "näst snabbast", "tredje snabbast"])[v.rank - 1]; + if (v.ahead !== undefined) variables.relation = v.ahead ? (en ? "ahead of" : "före") : (en ? "behind" : "efter"); + return { key: pick.key, variables }; +} function getCurrentPracticePaceLaps(result, competitorKey) { const laps = []; @@ -603,13 +642,32 @@ export function processDecoderMessageHelper(msg, deps, decoderRole = "main") { if (callPersonalBest) triggerRaceAudio("personal_best", { variables: audioVariables, driverId: entry.driverId, competitorKey: key, logData: { raceId: session.eventId, driverId: entry.driverId, lapNumber: entry.laps, lapTime: lapMs } }); if (!suspect && previousSessionFastest && lapMs < previousSessionFastest) triggerRaceAudio("fastest_lap", { variables: audioVariables, driverId: entry.driverId, competitorKey: key, logData: { raceId: session.eventId, driverId: entry.driverId, lapNumber: entry.laps, lapTime: lapMs } }); if (!suspect && previousTrackRecord && lapMs < previousTrackRecord) triggerRaceAudio("track_record", { variables: audioVariables, driverId: entry.driverId, competitorKey: key, logData: { raceId: session.eventId, driverId: entry.driverId, lapNumber: entry.laps, lapTime: lapMs } }); + if (isPracticeSession && entry.driverId && !suspect && !validationWarning) { + const hype = buildPracticeHype({ state, session, result, entry, key, lapMs, previousPersonalBest, memoryKey: pbCallKey, timestamp }); + if (hype) triggerRaceAudio(hype.key, { variables: hype.variables, driverId: entry.driverId, competitorKey: key, logData: { raceId: session.eventId, sessionId: session.id, driverId: entry.driverId, lapNumber: entry.laps, lapTime: lapMs } }); + } if (previousPosition >= 0 && currentPosition >= 0 && currentPosition < previousPosition) triggerRaceAudio("position_gain", { driverId: entry.driverId, competitorKey: key }); if (previousPosition >= 0 && currentPosition > previousPosition) triggerRaceAudio("position_loss", { driverId: entry.driverId, competitorKey: key }); const leader = leaderboard[0]; if (leader?.key && lastOverlayLeaderKeyBySession[session.id] !== leader.key) { lastOverlayLeaderKeyBySession[session.id] = leader.key; pushOverlayEvent("leader", `${leader.displayName || leader.driverName} • P1`); - if (previousLeaderKey && previousLeaderKey !== leader.key) triggerRaceAudio("new_leader", { variables: { driverName: leader.displayName || leader.driverName }, driverId: leader.driverId, competitorKey: leader.key, logData: { raceId: session.eventId, driverId: leader.driverId } }); + // Qualifying and finals: no leader calls in the first 30 s (everyone swaps places on the + // first lap) and at most one every 10 s. + const settled = isPracticeSession || Date.now() - Number(session.startedAt || 0) >= 30000; + if (previousLeaderKey && previousLeaderKey !== leader.key && settled) { + const raceScope = isPracticeSession ? {} : { scope: `leader:${session.id}`, cooldownMs: 10000 }; + const call = triggerRaceAudio("new_leader", { ...raceScope, variables: { driverName: spokenName(leader) }, driverId: leader.driverId, competitorKey: leader.key, logData: { raceId: session.eventId, driverId: leader.driverId } }); + if (!call?.skipped) lastLeaderCallBySession.set(session.id, Date.now()); + } + } + // Qualifying and finals: "Anders leads, 12 laps" when the leader crosses the line, every 2 minutes. + if (!isPracticeSession && leader?.key === key && !entry.finishedAt) { + if (!lastLeaderCallBySession.has(session.id)) lastLeaderCallBySession.set(session.id, Date.now()); + else if (Date.now() - lastLeaderCallBySession.get(session.id) >= LEADER_UPDATE_INTERVAL_MS) { + lastLeaderCallBySession.set(session.id, Date.now()); + triggerRaceAudio("leader_update", { variables: { driverName: spokenName(leader), laps: leader.laps ?? entry.laps }, driverId: leader.driverId, competitorKey: leader.key, logData: { raceId: session.eventId, sessionId: session.id, driverId: leader.driverId } }); + } } if (entry.bestLapMs && Number.isFinite(entry.bestLapMs)) { const bestKey = `${session.id}:${entry.key}`; diff --git a/src/practice_hype_logic.js b/src/practice_hype_logic.js new file mode 100644 index 0000000..2d10830 --- /dev/null +++ b/src/practice_hype_logic.js @@ -0,0 +1,117 @@ +// Practice "hype" calls: short, upbeat stats the speaker calls during practice to cheer a +// driver on. Pure functions: decoder_runtime.js gathers the numbers and plays what +// pickPracticeHype returns. At most one call per lap, and at least MIN_GAP_MS between two +// calls for the same driver (lap milestones excepted), so the speaker never nags. +export const PRACTICE_HYPE_EVENTS = Object.freeze([ + "practice_beat_last_time", "practice_class_rank", "practice_lap_milestone", "practice_faster_streak", + "practice_average_down", "practice_close_to_best", "practice_duel", +]); +export const MIN_GAP_MS = 30000; +const COOLDOWN_MS = { + practice_class_rank: 60000, practice_faster_streak: 120000, practice_average_down: 900000, + practice_close_to_best: 90000, practice_duel: 300000, +}; +const MILESTONE_EVERY = 50; +const CLOSE_TO_BEST_MS = 100; +const AVERAGE_WINDOW = 10; +const AVERAGE_MIN_GAIN_MS = 200; +const DUEL_WINDOW_MS = 200; +const DUEL_ACTIVE_MS = 120000; + +const average = (values) => values.reduce((sum, value) => sum + value, 0) / values.length; + +// This driver's valid lap times in the session, oldest first. +export function getDriverLapTimes(passings, competitorKey) { + return (Array.isArray(passings) ? passings : []) + .filter((item) => String(item?.competitorKey || "") === String(competitorKey || "") && item.validLap !== false && !item.suspect && Number(item.lapMs) > 500) + .map((item) => Number(item.lapMs)); +} + +// Laps that end a run of faster laps: 17.9, 17.6, 17.4, 17.2 is 3. +export function countFasterStreak(laps) { + let streak = 0; + for (let index = laps.length - 1; index > 0 && laps[index] < laps[index - 1]; index -= 1) streak += 1; + return streak; +} + +// First 10 laps against the last 10, crash and pit laps (over 130 % of the best) left out. +export function getAverageGain(laps) { + if (laps.length < AVERAGE_WINDOW * 2) return null; + const best = Math.min(...laps); + const clean = laps.filter((ms) => ms <= best * 1.3); + if (clean.length < AVERAGE_WINDOW * 2) return null; + const first = average(clean.slice(0, AVERAGE_WINDOW)); + const last = average(clean.slice(-AVERAGE_WINDOW)); + return { gainMs: first - last, lastAvgMs: last }; +} + +// 1-based rank by best lap among the rows of one class (rows: { key, bestLapMs }). +export function getClassRank(rows, key) { + const ranked = rows.filter((row) => Number(row.bestLapMs) > 500).sort((a, b) => a.bestLapMs - b.bestLapMs); + const index = ranked.findIndex((row) => row.key === key); + return { rank: index >= 0 ? index + 1 : null, size: ranked.length }; +} + +// The driver's best lap on the most recent earlier day they drove this layout. +// sessions: [{ passings }] from any session; dayStartTs: midnight today. +export function getLastTimeBestMs(passingLists, { driverId, layoutId, dayStartTs }) { + const byDay = new Map(); + passingLists.forEach((passings) => (passings || []).forEach((item) => { + if (!driverId || item?.driverId !== driverId || item.validLap === false || item.suspect) return; + if (String(item.trackLayoutId || "") !== String(layoutId || "")) return; + const ms = Number(item.lapMs), ts = Number(item.timestamp); + if (!(ms > 500) || !(ts < dayStartTs)) return; + const day = new Date(ts).toDateString(); + byDay.set(day, { ts: Math.max(byDay.get(day)?.ts || 0, ts), best: Math.min(byDay.get(day)?.best ?? Infinity, ms) }); + })); + const latest = [...byDay.values()].sort((a, b) => b.ts - a.ts)[0]; + return latest ? latest.best : null; +} + +// The closest other driver on track whose best lap is within 0.2 s of this driver's. +export function findDuelRival(rows, { key, bestLapMs, now }) { + return rows + .filter((row) => row.key !== key && Number(row.bestLapMs) > 500 && now - Number(row.lastTimestamp || 0) <= DUEL_ACTIVE_MS) + .map((row) => ({ ...row, gapMs: row.bestLapMs - bestLapMs })) + .filter((row) => Math.abs(row.gapMs) <= DUEL_WINDOW_MS) + .sort((a, b) => Math.abs(a.gapMs) - Math.abs(b.gapMs))[0] || null; +} + +// ctx: { laps (incl. this lap), lapMs, previousBestMs, lapCount, classRankBefore, classRankAfter, +// classSize, lastTimeBestMs, rival, now, memory }. memory is kept per driver per session by the +// caller and updated here. Returns { key, variables } (gaps in ms) or null. +export function pickPracticeHype(ctx) { + const { laps, lapMs, previousBestMs, lapCount, now, memory } = ctx; + memory.calledAt ||= {}; + const isPb = Boolean(previousBestMs && lapMs < previousBestMs); + const ready = (key) => now - (memory.calledAt[key] ?? -Infinity) >= (COOLDOWN_MS[key] || 0); + const gapOk = now - (memory.lastHypeAt ?? -Infinity) >= MIN_GAP_MS; + const candidates = []; + + if (isPb && ctx.lastTimeBestMs && lapMs < ctx.lastTimeBestMs && !memory.beatLastTime) { + candidates.push({ key: "practice_beat_last_time", variables: { gapMs: ctx.lastTimeBestMs - lapMs }, once: "beatLastTime" }); + } + if (ctx.classRankAfter && ctx.classRankAfter <= 3 && ctx.classSize >= 3 && (!ctx.classRankBefore || ctx.classRankAfter < ctx.classRankBefore)) { + candidates.push({ key: "practice_class_rank", variables: { rank: ctx.classRankAfter } }); + } + if (lapCount > 0 && lapCount % MILESTONE_EVERY === 0 && memory.lastMilestone !== lapCount) { + candidates.push({ key: "practice_lap_milestone", variables: { laps: lapCount }, milestone: true }); + } + if (countFasterStreak(laps) === 3) candidates.push({ key: "practice_faster_streak", variables: { laps: 3 } }); + if (laps.length % 5 === 0) { + const gain = getAverageGain(laps); + if (gain && gain.gainMs >= AVERAGE_MIN_GAIN_MS) candidates.push({ key: "practice_average_down", variables: { gapMs: gain.gainMs, avgMs: gain.lastAvgMs } }); + } + if (!isPb && previousBestMs && laps.length >= 5 && lapMs - previousBestMs <= CLOSE_TO_BEST_MS) { + candidates.push({ key: "practice_close_to_best", variables: { gapMs: lapMs - previousBestMs } }); + } + if (isPb && ctx.rival) candidates.push({ key: "practice_duel", variables: { gapMs: Math.abs(ctx.rival.gapMs), ahead: ctx.rival.gapMs >= 0, rival: ctx.rival.name } }); + + const pick = candidates.find((item) => ready(item.key) && (gapOk || item.milestone)); + if (!pick) return null; + memory.calledAt[pick.key] = now; + memory.lastHypeAt = now; + if (pick.milestone) memory.lastMilestone = lapCount; + if (pick.once) memory[pick.once] = true; + return { key: pick.key, variables: pick.variables }; +} diff --git a/src/race_audio.js b/src/race_audio.js index b670483..2f1498e 100644 --- a/src/race_audio.js +++ b/src/race_audio.js @@ -1,3 +1,5 @@ +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"]); @@ -21,6 +23,8 @@ export const RACE_AUDIO_EVENT_DEFINITIONS = Object.freeze([ event("track_record", "race", "normal", true, "effects/track_record_fanfare.wav", 2000), event("training_stable_pace", "training", "low", true, "", 120000), 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"), @@ -93,6 +97,11 @@ export function normalizeRaceAudioSettings(value = {}) { 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, + // 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", // 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)), @@ -109,9 +118,17 @@ export function normalizeRaceAudioSettings(value = {}) { 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) { - if (!session || PRACTICE_TYPES.has(String(session.type || ""))) return false; - if (normalizeRaceAudioSettings(settings).raceCallouts === "full") return false; + 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 (!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); } diff --git a/src/settings.js b/src/settings.js index 29f6870..1ac6b71 100644 --- a/src/settings.js +++ b/src/settings.js @@ -252,6 +252,8 @@ export function renderSettings(deps) { + + @@ -637,6 +639,8 @@ Erik Eriksson;654321;4WD;Associated;; randomStartDelay: form.get("raceAudioRandomDelay") === "on", minStartDelay: Number(form.get("raceAudioMinDelay")), maxStartDelay: Number(form.get("raceAudioMaxDelay")), perCompetitorPassingTone: form.get("raceAudioPerCompetitor") === "on", raceCallouts: String(form.get("raceAudioRaceCallouts") || "passing"), + practiceHype: form.get("raceAudioPracticeHype") === "on", + raceLeaderCalls: String(form.get("raceAudioLeaderCalls") || "both"), startSound: String(form.get("raceAudioStartSound") || "tone"), finishSound: String(form.get("raceAudioFinishSound") || "stop"), practicePbWarmupLaps: Number(form.get("raceAudioPbWarmup")), diff --git a/tests/decoder_runtime.test.js b/tests/decoder_runtime.test.js index f6c3e7e..b66d27c 100644 --- a/tests/decoder_runtime.test.js +++ b/tests/decoder_runtime.test.js @@ -298,3 +298,13 @@ test("non-passing decoder messages do not persist race state", () => { assert.equal(Boolean(changed), false); assert.equal(harness.getSaveCount(), 0); }); + +test("practice hype: 50 laps calls a lap milestone; a race session never gets hype calls", () => { + const practice = createHarness({ sessionType: "open_practice" }); + for (let lap = 1; lap <= 50; lap += 1) practice.passing(1_000 + lap * 20_000, "main"); + const milestone = practice.audioCalls.find((item) => item.key === "practice_lap_milestone"); + assert.equal(milestone?.variables.laps, 50); + const race = createHarness({ sessionType: "heat" }); + for (let lap = 1; lap <= 50; lap += 1) race.passing(1_000 + lap * (20_000 - lap * 10), "main"); + assert.equal(race.audioEvents.some((key) => key.startsWith("practice_")), false); +}); diff --git a/tests/practice_hype.test.js b/tests/practice_hype.test.js new file mode 100644 index 0000000..56245d9 --- /dev/null +++ b/tests/practice_hype.test.js @@ -0,0 +1,66 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { pickPracticeHype, countFasterStreak, getAverageGain, getClassRank, getLastTimeBestMs, findDuelRival, MIN_GAP_MS } from "../src/practice_hype_logic.js"; + +const base = (over = {}) => ({ laps: [20000, 20500, 20300], lapMs: 20300, previousBestMs: 20000, lapCount: 3, now: 1_000_000, memory: {}, ...over }); + +test("lap milestones every 50 laps, once each", () => { + const memory = {}; + assert.deepEqual(pickPracticeHype(base({ lapCount: 50, memory })), { key: "practice_lap_milestone", variables: { laps: 50 } }); + assert.equal(pickPracticeHype(base({ lapCount: 50, memory, now: 2_000_000 })), null); + assert.equal(pickPracticeHype(base({ lapCount: 49, memory: {} })), null); +}); + +test("close to best: within 0.1 s of the best, not on the best itself", () => { + const laps = [20000, 20700, 20800, 21000, 20080]; + assert.deepEqual(pickPracticeHype(base({ laps, lapMs: 20080, lapCount: 5 })), { key: "practice_close_to_best", variables: { gapMs: 80 } }); + assert.equal(pickPracticeHype(base({ laps, lapMs: 20200, lapCount: 5 })), null); +}); + +test("three faster laps in a row", () => { + assert.equal(countFasterStreak([21000, 20900, 20800, 20700]), 3); + assert.equal(countFasterStreak([21000, 20900, 21100]), 0); + const hype = pickPracticeHype(base({ laps: [22000, 21000, 20900, 20800], lapMs: 20800, previousBestMs: 20000 })); + assert.equal(hype.key, "practice_faster_streak"); +}); + +test("average going down compares the first 10 clean laps with the last 10", () => { + const laps = [...Array(10).fill(21000), 40000, ...Array(10).fill(20500)]; + const gain = getAverageGain(laps); + assert.equal(gain.gainMs, 500); + assert.equal(gain.lastAvgMs, 20500); + assert.equal(getAverageGain(Array(19).fill(20000)), null); +}); + +test("class rank and duel rival", () => { + const rows = [{ key: "a", bestLapMs: 20000 }, { key: "b", bestLapMs: 20100 }, { key: "c", bestLapMs: 0 }]; + assert.deepEqual(getClassRank(rows, "b"), { rank: 2, size: 2 }); + const now = 500000; + const rival = findDuelRival([{ key: "a", bestLapMs: 20150, lastTimestamp: now - 1000 }, { key: "x", bestLapMs: 20050, lastTimestamp: now - 600000 }], { key: "b", bestLapMs: 20000, now }); + assert.equal(rival.key, "a"); + assert.equal(rival.gapMs, 150); + const hype = pickPracticeHype(base({ lapMs: 19900, rival: { gapMs: 150, name: "Per" } })); + assert.deepEqual(hype, { key: "practice_duel", variables: { gapMs: 150, ahead: true, rival: "Per" } }); +}); + +test("faster than last time: best of the most recent earlier day, called once", () => { + const day = (d, h = 12) => new Date(2026, 10, d, h).getTime(); + const lists = [[ + { driverId: "d1", trackLayoutId: "L", lapMs: 19000, timestamp: day(1) }, + { driverId: "d1", trackLayoutId: "L", lapMs: 20000, timestamp: day(3) }, + { driverId: "d1", trackLayoutId: "L", lapMs: 20400, timestamp: day(3, 13) }, + { driverId: "d1", trackLayoutId: "other", lapMs: 15000, timestamp: day(4) }, + { driverId: "d1", trackLayoutId: "L", lapMs: 18000, timestamp: day(5) }, + ]]; + assert.equal(getLastTimeBestMs(lists, { driverId: "d1", layoutId: "L", dayStartTs: new Date(2026, 10, 5).getTime() }), 20000); + const memory = {}; + assert.deepEqual(pickPracticeHype(base({ lapMs: 19700, lastTimeBestMs: 20000, memory })), { key: "practice_beat_last_time", variables: { gapMs: 300 } }); + assert.notEqual(pickPracticeHype(base({ lapMs: 19600, previousBestMs: 19700, lastTimeBestMs: 20000, memory, now: 9_000_000 }))?.key, "practice_beat_last_time"); +}); + +test("at most one call every 30 s per driver", () => { + const memory = {}; + const laps = [20000, 20700, 20800, 21000, 20080]; + assert.ok(pickPracticeHype(base({ laps, lapMs: 20080, lapCount: 5, memory }))); + assert.equal(pickPracticeHype(base({ laps: [22000, 21000, 20900, 20800], lapMs: 20800, memory, now: 1_000_000 + MIN_GAP_MS - 1 })), null); +}); diff --git a/tests/race_audio.test.js b/tests/race_audio.test.js index b859299..9cc81a6 100644 --- a/tests/race_audio.test.js +++ b/tests/race_audio.test.js @@ -138,12 +138,16 @@ test("after the count-down's 3 and the tone call it is quiet until the tone 1-3 } }); -test("during a race only the passing tone plays by default - no names, personal bests or leader calls", () => { +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", "new_leader", "position_gain", "position_loss"].forEach((key) => { + ["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`); }); @@ -333,3 +337,12 @@ test("lap times are spoken as seconds with hundredths, no leading zero minute", 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); +}); diff --git a/tests/run.js b/tests/run.js index b3825fd..838c96b 100644 --- a/tests/run.js +++ b/tests/run.js @@ -1,4 +1,5 @@ import "./auth.test.js"; +import "./practice_hype.test.js"; import "./race_day_fixes.test.js"; import "./race_list.test.js"; import "./day_schedule.test.js";