mirror of
https://github.com/sunnypilot/sunnypilot.git
synced 2026-12-02 01:03:44 +08:00
robo-ui: more expressive, better sound control
This commit is contained in:
@@ -12,7 +12,6 @@ from openpilot.common.utils import retry
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
|
||||
from openpilot.system import micd
|
||||
from openpilot.common.hardware import HARDWARE
|
||||
|
||||
from openpilot.sunnypilot.selfdrive.ui.quiet_mode import QuietMode
|
||||
from openpilot.sunnypilot.selfdrive.ui.robotic_sounds import REACTIVE_CHIRP_IDS, RoboticSoundPack
|
||||
@@ -20,18 +19,16 @@ from openpilot.sunnypilot.selfdrive.ui.robotic_sounds import REACTIVE_CHIRP_IDS,
|
||||
SAMPLE_RATE = 48000
|
||||
SAMPLE_BUFFER = 4096 # (approx 100ms)
|
||||
MAX_VOLUME = 1.0
|
||||
MIN_VOLUME = 0.1
|
||||
|
||||
AMBIENT_DB = 10.0 # DB where MIN_VOLUME is applied
|
||||
DB_SCALE = 25.0 # AMBIENT_DB + DB_SCALE is where MAX_VOLUME is applied
|
||||
MIN_VOLUME = 0.45
|
||||
|
||||
ALERT_RAMP_TIME = 4 # seconds to ramp to max volume for immediate warnings
|
||||
SELFDRIVE_STATE_TIMEOUT = 5 # 5 seconds
|
||||
FILTER_DT = 1. / (micd.SAMPLE_RATE / micd.FFT_SAMPLES)
|
||||
|
||||
AMBIENT_DB = 26 # DB where MIN_VOLUME is applied
|
||||
DB_SCALE = 30 # AMBIENT_DB + DB_SCALE is where MAX_VOLUME is applied
|
||||
|
||||
VOLUME_BASE = 20
|
||||
if HARDWARE.get_device_type() == "tizi":
|
||||
AMBIENT_DB = 30
|
||||
VOLUME_BASE = 10
|
||||
|
||||
AudibleAlert = log.SelfdriveState.AudibleAlert
|
||||
AudibleAlertSP = custom.SelfdriveStateSP.AudibleAlert
|
||||
@@ -119,13 +116,23 @@ class Soundd(QuietMode):
|
||||
if self.robotic_sound_pack.refresh_param():
|
||||
self.current_sound_frame = 0
|
||||
|
||||
def _sound_buffer(self, alert_id: int) -> np.ndarray | None:
|
||||
"""Resolve the buffer for an alert id, or None when this id has no sound loaded."""
|
||||
if alert_id == AudibleAlert.none:
|
||||
return None
|
||||
try:
|
||||
return self.robotic_sound_pack.get_buffer(alert_id, self.loaded_sounds)
|
||||
except KeyError:
|
||||
return None
|
||||
|
||||
def get_sound_data(self, frames): # get "frames" worth of data from the current alert sound, looping when required
|
||||
|
||||
ret = np.zeros(frames, dtype=np.float32)
|
||||
sound_data = self._sound_buffer(self.current_alert)
|
||||
|
||||
if self.should_play_sound(self.current_alert):
|
||||
if sound_data is not None:
|
||||
audible = self.should_play_sound(self.current_alert)
|
||||
num_loops = 1 if self.current_alert in REACTIVE_CHIRP_IDS else sound_list[self.current_alert][1]
|
||||
sound_data = self.robotic_sound_pack.get_buffer(self.current_alert, self.loaded_sounds)
|
||||
written_frames = 0
|
||||
|
||||
current_sound_frame = self.current_sound_frame % len(sound_data)
|
||||
@@ -134,7 +141,8 @@ class Soundd(QuietMode):
|
||||
while written_frames < frames and (num_loops is None or loops < num_loops):
|
||||
available_frames = sound_data.shape[0] - current_sound_frame
|
||||
frames_to_write = min(available_frames, frames - written_frames)
|
||||
ret[written_frames:written_frames+frames_to_write] = sound_data[current_sound_frame:current_sound_frame+frames_to_write]
|
||||
if audible:
|
||||
ret[written_frames:written_frames+frames_to_write] = sound_data[current_sound_frame:current_sound_frame+frames_to_write]
|
||||
written_frames += frames_to_write
|
||||
self.current_sound_frame += frames_to_write
|
||||
current_sound_frame = self.current_sound_frame % len(sound_data)
|
||||
@@ -154,11 +162,18 @@ class Soundd(QuietMode):
|
||||
cloudlog.warning(f"soundd stream over/underflow: {status}")
|
||||
data_out[:frames, 0] = self.get_sound_data(frames)
|
||||
|
||||
def _note_play(self, alert_id: int) -> None:
|
||||
"""Log the alert start together with the routing decision and the gain it plays at."""
|
||||
if alert_id == AudibleAlert.none:
|
||||
return
|
||||
|
||||
audible = self.should_play_sound(alert_id)
|
||||
robotic = self.robotic_sound_pack.enabled and alert_id in self.robotic_sound_pack.sounds
|
||||
cloudlog.debug(f"soundd play alert={alert_id} robotic={robotic} audible={audible} gain={self.current_volume:.2f}")
|
||||
|
||||
def update_alert(self, new_alert):
|
||||
current_alert_played_once = (
|
||||
self.current_alert == AudibleAlert.none or
|
||||
self.current_sound_frame >= len(self.robotic_sound_pack.get_buffer(self.current_alert, self.loaded_sounds))
|
||||
)
|
||||
current_buffer = self._sound_buffer(self.current_alert)
|
||||
current_alert_played_once = current_buffer is None or self.current_sound_frame >= len(current_buffer)
|
||||
# let looping sounds finish the current loop instead of cutting off mid tone
|
||||
if (
|
||||
new_alert == AudibleAlert.none
|
||||
@@ -179,6 +194,7 @@ class Soundd(QuietMode):
|
||||
self.ramp_start_time = time.monotonic()
|
||||
self.current_alert = new_alert
|
||||
self.current_sound_frame = 0
|
||||
self._note_play(new_alert)
|
||||
|
||||
def get_audible_alert(self, sm):
|
||||
if sm.updated['selfdriveState']:
|
||||
|
||||
@@ -12,6 +12,7 @@ import time
|
||||
|
||||
from openpilot.cereal import log
|
||||
from openpilot.common.constants import CV
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.selfdrive.ui.mici.onroad.alert_renderer import Alert
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import MusicState
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_visualizer import groove_prism_color
|
||||
@@ -29,8 +30,13 @@ SHARP_ACCEL_THRESHOLD = 2.2 # m/s^2 triggers excited boost eyes
|
||||
STANDSTILL_POUT_DELAY = 8.0 # seconds at standstill before pouting
|
||||
STANDSTILL_SLEEPY_DELAY = 35.0 # seconds at standstill before sleepy
|
||||
MIN_TURN_SPEED_MS = 6.5 # m/s (~15 mph) min speed for passenger centrifugal feel
|
||||
MIN_LAT_ACCEL_MS2 = 1.8 # m/s^2 (~0.18 g) deadzone so gentle/low-speed turns stay calm
|
||||
MAX_LAT_ACCEL_MS2 = 5.2 # m/s^2 (~0.53 g) full wall-squish lateral acceleration
|
||||
MIN_LAT_ACCEL_MS2 = 1.6
|
||||
FULL_LAT_ACCEL_MS2 = 3.6
|
||||
LAT_JERK_WEIGHT = 0.5
|
||||
LAT_JERK_LOW = 400.0
|
||||
LAT_JERK_HIGH = 900.0
|
||||
SQUISH_ATTACK_RATE = 20.0
|
||||
SQUISH_RELEASE_RATE = 3.3
|
||||
SET_SPEED_SHOW_DURATION = 3.0 # seconds to show speed arc on set-speed change
|
||||
ENGAGE_HAPPY_DURATION = 0.9 # seconds of joyful crescent eyes on engage
|
||||
ENGAGE_SPEED_CONFIRM = 2.0 # seconds of speed readout right after happy engage
|
||||
@@ -39,6 +45,16 @@ BOOST_HOLD_DURATION = 1.2 # seconds to hold sharp-accel boost expressio
|
||||
LOVE_HOLD_DURATION = 1.6 # seconds to hold heart/pet expression
|
||||
MANUAL_SPEED_PEEK_DURATION = 4.0 # seconds for swipe-up speed peek
|
||||
|
||||
BLINK_CLOSE_S = 0.070
|
||||
BLINK_HOLD_S = 0.035
|
||||
BLINK_OPEN_S = 0.130
|
||||
BLINK_LID_MIN = 0.08
|
||||
BLINK_LID_MAX = 0.92
|
||||
|
||||
REACTION_DELAY_S = 0.10
|
||||
|
||||
DEBUG_PARAM = "MiciRoboticDebug"
|
||||
|
||||
|
||||
class RoboticMood(Enum):
|
||||
CRITICAL = "critical"
|
||||
@@ -68,6 +84,130 @@ class IdleAction(Enum):
|
||||
CURIOUS_LOOK = "curious_look"
|
||||
CHEEKY_WINK = "cheeky_wink"
|
||||
GROOVE_BOB = "groove_bob"
|
||||
STRETCH = "stretch"
|
||||
SETTLE = "settle"
|
||||
PERK_UP = "perk_up"
|
||||
DAYDREAM = "daydream"
|
||||
DOODLE = "doodle"
|
||||
DOUBLE_BLINK_TILT = "double_blink_tilt"
|
||||
|
||||
|
||||
class GrooveStyle(Enum):
|
||||
"""Music animations. One is picked per segment; the set reads as one character."""
|
||||
HEAD_BOB = "head_bob"
|
||||
SIDE_SWAY = "side_sway"
|
||||
JELLY = "jelly"
|
||||
SNARE_BLINK = "snare_blink"
|
||||
LOOK_AROUND = "look_around"
|
||||
ANTICIPATION_POP = "anticipation_pop"
|
||||
GLOW_PULSE = "glow_pulse"
|
||||
|
||||
|
||||
IDLE_ACTION_DURATION = {
|
||||
IdleAction.HAPPY_SQUINT: 0.9,
|
||||
IdleAction.CURIOUS_LOOK: 1.6,
|
||||
IdleAction.CHEEKY_WINK: 0.6,
|
||||
IdleAction.GROOVE_BOB: 2.0,
|
||||
IdleAction.STRETCH: 1.8,
|
||||
IdleAction.SETTLE: 2.4,
|
||||
IdleAction.PERK_UP: 1.0,
|
||||
IdleAction.DAYDREAM: 3.4,
|
||||
IdleAction.DOODLE: 2.8,
|
||||
IdleAction.DOUBLE_BLINK_TILT: 0.9,
|
||||
}
|
||||
|
||||
IDLE_ACTION_WEIGHTS = {
|
||||
IdleAction.HAPPY_SQUINT: 1.0,
|
||||
IdleAction.CURIOUS_LOOK: 1.2,
|
||||
IdleAction.CHEEKY_WINK: 0.7,
|
||||
IdleAction.GROOVE_BOB: 0.6,
|
||||
IdleAction.STRETCH: 0.8,
|
||||
IdleAction.SETTLE: 0.7,
|
||||
IdleAction.PERK_UP: 0.8,
|
||||
IdleAction.DAYDREAM: 0.9,
|
||||
IdleAction.DOODLE: 0.8,
|
||||
IdleAction.DOUBLE_BLINK_TILT: 1.1,
|
||||
}
|
||||
|
||||
GROOVE_WEIGHTS = {
|
||||
GrooveStyle.HEAD_BOB: 1.2,
|
||||
GrooveStyle.SIDE_SWAY: 1.1,
|
||||
GrooveStyle.JELLY: 1.0,
|
||||
GrooveStyle.SNARE_BLINK: 0.8,
|
||||
GrooveStyle.LOOK_AROUND: 0.9,
|
||||
GrooveStyle.ANTICIPATION_POP: 0.7,
|
||||
GrooveStyle.GLOW_PULSE: 0.6,
|
||||
}
|
||||
|
||||
|
||||
def _ease_in_quad(p: float) -> float:
|
||||
p = max(0.0, min(1.0, p))
|
||||
return p * p
|
||||
|
||||
|
||||
def _ease_out_back(p: float, s: float = 1.35) -> float:
|
||||
p = max(0.0, min(1.0, p)) - 1.0
|
||||
return p * p * ((s + 1.0) * p + s) + 1.0
|
||||
|
||||
|
||||
def _smoothstep(edge0: float, edge1: float, x: float) -> float:
|
||||
if edge1 <= edge0:
|
||||
return 1.0 if x >= edge1 else 0.0
|
||||
p = max(0.0, min(1.0, (x - edge0) / (edge1 - edge0)))
|
||||
return p * p * (3.0 - 2.0 * p)
|
||||
|
||||
|
||||
class MotionScheduler:
|
||||
"""Weighted random picker with per-clip cooldown and no immediate repeats.
|
||||
|
||||
Shared by groove and idle so the two systems cannot drift apart in behaviour. The old
|
||||
rng.choice() had no memory at all, so the same idle could repeat forever.
|
||||
"""
|
||||
|
||||
def __init__(self, options, rng: random.Random, weights: dict | None = None, cooldown: float = 30.0):
|
||||
self._options = list(options)
|
||||
self._rng = rng
|
||||
self._weights = {o: (weights or {}).get(o, 1.0) for o in self._options}
|
||||
self._cooldown = cooldown
|
||||
self._cooldowns = dict.fromkeys(self._options, -1e9)
|
||||
self._current = None
|
||||
|
||||
@property
|
||||
def current(self):
|
||||
return self._current
|
||||
|
||||
def pick(self, now: float):
|
||||
candidates = [o for o in self._options if o != self._current and now - self._cooldowns[o] >= self._cooldown]
|
||||
if not candidates:
|
||||
candidates = [o for o in self._options if o != self._current] or list(self._options)
|
||||
choice = self._rng.choices(candidates, weights=[self._weights[o] for o in candidates], k=1)[0]
|
||||
self._current = choice
|
||||
self._cooldowns[choice] = now
|
||||
return choice
|
||||
|
||||
|
||||
class _GyroBiasEstimator:
|
||||
"""Tracks the stationary yaw-gyro bias so a DC offset is not read as a permanent corner.
|
||||
|
||||
An uncalibrated bias of 0.03 rad/s at 20 m/s is 0.6 m/s^2 of phantom lateral acceleration,
|
||||
which is a third of the squish deadband.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.bias = 0.0
|
||||
self._seeded = False
|
||||
|
||||
def correct(self, yaw_rate: float, v_ego: float, dt: float) -> float:
|
||||
if v_ego < 0.5:
|
||||
if not self._seeded:
|
||||
self.bias = yaw_rate
|
||||
self._seeded = True
|
||||
elif dt > 0.0:
|
||||
self.bias += (yaw_rate - self.bias) * min(1.0, dt / 2.0)
|
||||
return yaw_rate - self.bias
|
||||
|
||||
|
||||
_GYRO_BIAS = _GyroBiasEstimator()
|
||||
|
||||
|
||||
class EyeGlyph(Enum):
|
||||
@@ -163,8 +303,10 @@ class DrivingSnapshot:
|
||||
class RoboticMoodEngine:
|
||||
"""Priority-based EMO-inspired mood & lively autonomous personality state machine."""
|
||||
|
||||
def __init__(self, rng: random.Random | None = None):
|
||||
def __init__(self, rng: random.Random | None = None, params=None):
|
||||
self._rng = rng or random.Random()
|
||||
self._params = params
|
||||
self._debug_frame = 0
|
||||
self.mood: RoboticMood = RoboticMood.IDLE_CURIOUS
|
||||
self.idle_action: IdleAction = IdleAction.NONE
|
||||
self.showing_speed: bool = False
|
||||
@@ -187,11 +329,10 @@ class RoboticMoodEngine:
|
||||
# Blink, gaze, and playful idle personality schedulers
|
||||
now = time.monotonic()
|
||||
self._next_blink_at: float = now + self._rng.uniform(1.8, 3.6)
|
||||
self._blink_end_at: float = 0.0
|
||||
self._blink_rebound_until: float = 0.0
|
||||
self._blink_start_at: float = now - 999.0
|
||||
self._double_blink_pending: bool = False
|
||||
|
||||
self._next_glance_at: float = now + self._rng.uniform(1.2, 2.6)
|
||||
self._next_glance_at: float = now + self._rng.uniform(2.5, 7.0)
|
||||
self._idle_gaze_x: float = 0.0
|
||||
self._idle_gaze_y: float = 0.0
|
||||
self._idle_tilt_y: float = 0.0
|
||||
@@ -200,9 +341,25 @@ class RoboticMoodEngine:
|
||||
self._idle_action_until: float = 0.0
|
||||
self._idle_action_dir: float = 1.0
|
||||
|
||||
self._idle_scheduler = MotionScheduler(
|
||||
[a for a in IdleAction if a is not IdleAction.NONE], self._rng,
|
||||
weights=IDLE_ACTION_WEIGHTS, cooldown=30.0,
|
||||
)
|
||||
self._groove_scheduler = MotionScheduler(list(GrooveStyle), self._rng, weights=GROOVE_WEIGHTS, cooldown=24.0)
|
||||
self._groove_style: GrooveStyle = GrooveStyle.HEAD_BOB
|
||||
self._groove_switch_at: float = 0.0
|
||||
self._groove_intensity: float = 0.0
|
||||
|
||||
self._prev_update_t: float | None = None
|
||||
self._prev_abs_lat: float = 0.0
|
||||
self._squish_shown: float = 0.0
|
||||
|
||||
self._love_from: float = 0.0
|
||||
|
||||
def trigger_love(self, now: float | None = None, wink: bool = False) -> None:
|
||||
t = time.monotonic() if now is None else now
|
||||
self._love_until = t + LOVE_HOLD_DURATION
|
||||
self._love_from = t + REACTION_DELAY_S
|
||||
self._love_until = self._love_from + LOVE_HOLD_DURATION
|
||||
self._love_wink = wink
|
||||
|
||||
def trigger_speed_peek(self, now: float | None = None) -> None:
|
||||
@@ -235,66 +392,65 @@ class RoboticMoodEngine:
|
||||
squash_x = 1.0
|
||||
stretch_y = 1.0
|
||||
|
||||
if now < self._blink_end_at:
|
||||
blink_closure = 1.0
|
||||
squash_x = 1.16
|
||||
stretch_y = 0.86
|
||||
elif now < self._blink_rebound_until:
|
||||
# Juicy bubbly pop-open after blink
|
||||
squash_x = 0.93
|
||||
stretch_y = 1.10
|
||||
close_s = BLINK_CLOSE_S * (2.2 if sleepy else 1.0)
|
||||
hold_s = BLINK_HOLD_S * (2.0 if sleepy else 1.0)
|
||||
open_s = BLINK_OPEN_S * (1.8 if sleepy else 1.0)
|
||||
blink_total = close_s + hold_s + open_s
|
||||
|
||||
elapsed = now - self._blink_start_at
|
||||
if 0.0 <= elapsed <= blink_total:
|
||||
if elapsed <= close_s:
|
||||
blink_closure = _ease_in_quad(elapsed / close_s)
|
||||
squash_x = 1.0 + 0.10 * blink_closure
|
||||
stretch_y = 1.0 - 0.08 * blink_closure
|
||||
elif elapsed <= close_s + hold_s:
|
||||
blink_closure = 1.0
|
||||
squash_x = 1.10
|
||||
stretch_y = 0.92
|
||||
else:
|
||||
open_p = (elapsed - close_s - hold_s) / open_s
|
||||
raw = 1.0 - _ease_out_back(open_p)
|
||||
pop = max(0.0, -raw)
|
||||
blink_closure = max(0.0, raw)
|
||||
squash_x = (1.0 + 0.10 * blink_closure) * (1.0 - 0.06 * pop)
|
||||
stretch_y = (1.0 - 0.08 * blink_closure) * (1.0 + 0.05 * pop)
|
||||
elif now >= self._next_blink_at:
|
||||
blink_dur = 0.22 if sleepy else 0.11
|
||||
self._blink_end_at = now + blink_dur
|
||||
self._blink_rebound_until = self._blink_end_at + 0.12
|
||||
blink_closure = 1.0
|
||||
squash_x = 1.16
|
||||
stretch_y = 0.86
|
||||
if not sleepy and not self._double_blink_pending and self._rng.random() < 0.30:
|
||||
self._blink_start_at = now
|
||||
if not sleepy and not self._double_blink_pending and self._rng.random() < 0.25:
|
||||
self._double_blink_pending = True
|
||||
self._next_blink_at = self._blink_end_at + 0.13
|
||||
self._next_blink_at = now + blink_total + 0.12
|
||||
else:
|
||||
self._double_blink_pending = False
|
||||
lo, hi = (1.6, 3.0) if sleepy else (2.2, 4.4)
|
||||
self._next_blink_at = self._blink_end_at + self._rng.uniform(lo, hi)
|
||||
lo, hi = (1.8, 3.6) if sleepy else (2.4, 6.5)
|
||||
self._next_blink_at = now + blink_total + self._rng.uniform(lo, hi)
|
||||
|
||||
if now >= self._next_glance_at:
|
||||
roll = self._rng.random()
|
||||
if roll < 0.28:
|
||||
if roll < 0.34:
|
||||
self._idle_gaze_x = 0.0
|
||||
self._idle_gaze_y = 0.0
|
||||
self._idle_tilt_y = 0.0
|
||||
else:
|
||||
self._idle_gaze_x = self._rng.uniform(-34.0, 34.0)
|
||||
self._idle_gaze_y = self._rng.uniform(-12.0, 10.0)
|
||||
self._idle_tilt_y = self._rng.uniform(-9.0, 9.0)
|
||||
self._next_glance_at = now + self._rng.uniform(1.3, 2.8)
|
||||
self._idle_gaze_x = self._rng.uniform(-30.0, 30.0)
|
||||
self._idle_gaze_y = self._rng.uniform(-10.0, 8.0)
|
||||
self._idle_tilt_y = self._rng.uniform(-7.0, 7.0)
|
||||
self._next_glance_at = now + self._rng.uniform(2.5, 7.0)
|
||||
|
||||
# Playful autonomous micro-behaviors during normal cruising/idle
|
||||
if now >= self._idle_action_until:
|
||||
self.idle_action = IdleAction.NONE
|
||||
if not sleepy and now >= self._next_idle_action_at:
|
||||
choice = self._rng.choice([
|
||||
IdleAction.HAPPY_SQUINT,
|
||||
IdleAction.CURIOUS_LOOK,
|
||||
IdleAction.CHEEKY_WINK,
|
||||
IdleAction.GROOVE_BOB,
|
||||
])
|
||||
choice = self._idle_scheduler.pick(now)
|
||||
self.idle_action = choice
|
||||
self._idle_action_dir = -1.0 if self._rng.random() < 0.5 else 1.0
|
||||
dur = {
|
||||
IdleAction.HAPPY_SQUINT: 0.80,
|
||||
IdleAction.CURIOUS_LOOK: 1.50,
|
||||
IdleAction.CHEEKY_WINK: 0.55,
|
||||
IdleAction.GROOVE_BOB: 1.80,
|
||||
}[choice]
|
||||
self._idle_action_until = now + dur
|
||||
self._next_idle_action_at = self._idle_action_until + self._rng.uniform(2.0, 3.8)
|
||||
self._idle_action_until = now + IDLE_ACTION_DURATION[choice]
|
||||
self._next_idle_action_at = self._idle_action_until + self._rng.uniform(6.0, 18.0)
|
||||
|
||||
return blink_closure, squash_x, stretch_y
|
||||
|
||||
def update(self, snap: DrivingSnapshot, now: float | None = None) -> EyeTarget:
|
||||
t = time.monotonic() if now is None else now
|
||||
dt = 0.0 if self._prev_update_t is None else max(0.0, min(0.5, t - self._prev_update_t))
|
||||
self._prev_update_t = t
|
||||
|
||||
# Track standstill duration
|
||||
if snap.standstill or not snap.started:
|
||||
@@ -365,12 +521,32 @@ class RoboticMoodEngine:
|
||||
effective_yaw = snap.v_ego * snap.curvature
|
||||
|
||||
squish_force = 0.0
|
||||
target_squish = 0.0
|
||||
jerk = 0.0
|
||||
abs_lat = 0.0
|
||||
if not snap.standstill and snap.v_ego >= MIN_TURN_SPEED_MS:
|
||||
lat_accel = -snap.v_ego * effective_yaw # opposite side of the turn
|
||||
abs_lat = abs(lat_accel)
|
||||
if abs_lat >= MIN_LAT_ACCEL_MS2:
|
||||
mag = min(1.0, (abs_lat - MIN_LAT_ACCEL_MS2) / (MAX_LAT_ACCEL_MS2 - MIN_LAT_ACCEL_MS2))
|
||||
squish_force = mag if lat_accel > 0 else -mag
|
||||
base = _smoothstep(MIN_LAT_ACCEL_MS2, FULL_LAT_ACCEL_MS2, abs_lat)
|
||||
if dt > 1e-4:
|
||||
jerk = abs(abs_lat - self._prev_abs_lat) / dt
|
||||
jerk_term = LAT_JERK_WEIGHT * _smoothstep(LAT_JERK_LOW, LAT_JERK_HIGH, jerk)
|
||||
mag = min(1.0, base + jerk_term)
|
||||
target_squish = mag if lat_accel > 0 else -mag
|
||||
self._prev_abs_lat = abs_lat
|
||||
|
||||
delta = target_squish - self._squish_shown
|
||||
if dt <= 0.0:
|
||||
step = abs(delta)
|
||||
elif abs(target_squish) < abs(self._squish_shown):
|
||||
step = SQUISH_RELEASE_RATE * dt
|
||||
else:
|
||||
step = SQUISH_ATTACK_RATE * dt
|
||||
self._squish_shown += max(-step, min(step, delta))
|
||||
squish_force = self._squish_shown
|
||||
|
||||
self._log_squish_debug(snap, abs_lat, jerk, effective_yaw, squish_force)
|
||||
|
||||
if alert is not None and alert_status == AlertStatus.critical:
|
||||
self.mood = RoboticMood.CRITICAL
|
||||
@@ -384,7 +560,7 @@ class RoboticMoodEngine:
|
||||
self.mood = RoboticMood.LANE_CHANGE
|
||||
elif bsm_side != 0 and blinker_side != 0:
|
||||
self.mood = RoboticMood.BLIND_SPOT
|
||||
elif t < self._love_until:
|
||||
elif self._love_from <= t < self._love_until:
|
||||
self.mood = RoboticMood.BOOKMARK_LOVE
|
||||
elif t < self._happy_engage_until:
|
||||
self.mood = RoboticMood.HAPPY_ENGAGE
|
||||
@@ -413,11 +589,12 @@ class RoboticMoodEngine:
|
||||
base_color = self._status_color(snap)
|
||||
blink, squash_x, stretch_y = self._update_blink_and_personality(t, sleepy=(self.mood == RoboticMood.SLEEPY))
|
||||
|
||||
# Lively, clearly visible breathing & energetic bounce so the face is always bubbling with life
|
||||
energy = 1.0 + min(0.55, snap.v_ego / 35.0)
|
||||
breathe_y = math.sin(t * 2.8 * energy) * 6.5 + math.sin(t * 1.3) * 2.5
|
||||
breathe_scale = 1.0 + 0.035 * math.sin(t * 2.8 * energy - 0.35)
|
||||
micro_drift_x = math.sin(t * 1.1) * 6.0
|
||||
bus_phase = t * 2.2 * energy
|
||||
breath = math.sin(bus_phase) * 0.72 + math.sin(bus_phase * 0.5 + 0.9) * 0.28
|
||||
breathe_y = breath * 6.5
|
||||
breathe_scale = 1.0 + 0.032 * breath
|
||||
micro_drift_x = math.sin(bus_phase * 0.33) * 5.0
|
||||
|
||||
# Steering-coupled gaze (clamped to [-40, +40])
|
||||
steer_gaze = max(-40.0, min(40.0, -snap.steering_angle_deg * 0.78))
|
||||
@@ -542,7 +719,7 @@ class RoboticMoodEngine:
|
||||
target.width = 104.0
|
||||
target.height = 76.0
|
||||
target.roundness = 0.45
|
||||
target.top_lid = 0.58 + 0.09 * math.sin(t * 1.5)
|
||||
target.top_lid = 0.60 + 0.06 * math.sin(t * 1.5)
|
||||
target.bottom_lid = 0.14
|
||||
target.gaze_y = 8.0
|
||||
target.gaze_x = math.sin(t * 0.7) * 8.0
|
||||
@@ -576,20 +753,11 @@ class RoboticMoodEngine:
|
||||
|
||||
elif self.mood == RoboticMood.MUSIC_GROOVE:
|
||||
m = snap.music or MusicState()
|
||||
sway = math.sin(m.groove_phase)
|
||||
beat = m.beat_pulse
|
||||
target.color = groove_prism_color(t)
|
||||
target.width = 108.0
|
||||
target.height = 112.0
|
||||
target.gaze_x = sway * 22.0
|
||||
target.gaze_y = -6.0 - beat * 6.0
|
||||
target.tilt_y = sway * 12.0
|
||||
target.bounce_y = -14.0 * beat - abs(sway) * 6.0 - 8.0
|
||||
target.scale_x = 1.0 + 0.11 * beat
|
||||
target.scale_y = 1.0 - 0.08 * beat
|
||||
target.mouth = MouthGlyph.BIG_GRIN
|
||||
if beat > 0.58:
|
||||
target.glyph = EyeGlyph.CRESCENT
|
||||
self._groove_intensity = 0.45 + 0.55 * _smoothstep(0.30, 0.80, m.confidence)
|
||||
if t >= self._groove_switch_at:
|
||||
self._groove_style = self._groove_scheduler.pick(t)
|
||||
self._groove_switch_at = t + max(8.0, 32.0 * 60.0 / max(60.0, m.bpm))
|
||||
self._apply_groove(target, t, m)
|
||||
|
||||
elif self.mood == RoboticMood.CRUISING_HAPPY:
|
||||
target.width = 106.0
|
||||
@@ -609,13 +777,90 @@ class RoboticMoodEngine:
|
||||
target.tilt_y = self._idle_tilt_y + math.sin(t * 1.4) * 3.0
|
||||
self._apply_idle_action(target, t)
|
||||
|
||||
# Apply natural blink closure to standard rounded-rect eyes
|
||||
if target.glyph == EyeGlyph.ROUND_RECT and not target.wink_right and blink > 0.0:
|
||||
target.top_lid = max(target.top_lid, 0.52 * blink)
|
||||
target.bottom_lid = max(target.bottom_lid, 0.48 * blink)
|
||||
cover = BLINK_LID_MIN + (BLINK_LID_MAX - BLINK_LID_MIN) * blink
|
||||
target.top_lid = max(target.top_lid, 0.55 * cover)
|
||||
target.bottom_lid = max(target.bottom_lid, 0.45 * cover)
|
||||
|
||||
return target
|
||||
|
||||
def _log_squish_debug(self, snap: DrivingSnapshot, abs_lat: float, jerk: float, yaw_rate: float, squish_force: float) -> None:
|
||||
"""Param-gated trace so the squish thresholds get set from a real drive, not a guess."""
|
||||
if self._params is None:
|
||||
return
|
||||
self._debug_frame += 1
|
||||
if self._debug_frame % 60 != 0:
|
||||
return
|
||||
try:
|
||||
if not self._params.get_bool(DEBUG_PARAM):
|
||||
return
|
||||
cloudlog.info(f"MICI squish lat={abs_lat:.2f} jerk={jerk:.0f} yaw={yaw_rate:.3f} bias={_GYRO_BIAS.bias:.4f} squish={squish_force:.2f} v={snap.v_ego:.1f}")
|
||||
except Exception:
|
||||
self._params = None
|
||||
|
||||
def _apply_groove(self, target: EyeTarget, t: float, m: MusicState) -> None:
|
||||
"""Render the currently scheduled groove variant, intensity-scaled by detector confidence."""
|
||||
style = self._groove_style
|
||||
beat = m.beat_pulse
|
||||
phase = m.groove_phase
|
||||
sway = math.sin(phase)
|
||||
amp = self._groove_intensity
|
||||
|
||||
target.color = groove_prism_color(t)
|
||||
target.mouth = MouthGlyph.BIG_GRIN
|
||||
target.width = 108.0
|
||||
target.height = 112.0
|
||||
|
||||
if style is GrooveStyle.HEAD_BOB:
|
||||
target.bounce_y = (-13.0 * beat - abs(sway) * 4.0 - 6.0) * amp
|
||||
target.gaze_x = sway * 8.0 * amp
|
||||
target.gaze_y = -6.0 - 5.0 * beat * amp
|
||||
target.scale_x = 1.0 + 0.05 * beat * amp
|
||||
target.scale_y = 1.0 - 0.04 * beat * amp
|
||||
if beat > 0.58:
|
||||
target.glyph = EyeGlyph.CRESCENT
|
||||
elif style is GrooveStyle.SIDE_SWAY:
|
||||
target.bounce_y = -abs(sway) * 5.0 * amp - 4.0
|
||||
target.gaze_x = sway * 24.0 * amp
|
||||
target.tilt_y = sway * 14.0 * amp
|
||||
target.scale_x = 1.0 - 0.06 * abs(sway) * amp
|
||||
target.scale_y = 1.0 + 0.05 * abs(sway) * amp
|
||||
elif style is GrooveStyle.JELLY:
|
||||
target.height = 116.0
|
||||
target.scale_x = 1.0 + 0.13 * beat * amp
|
||||
target.scale_y = 1.0 - 0.11 * beat * amp
|
||||
target.bounce_y = -8.0 * beat * amp
|
||||
target.gaze_y = -4.0
|
||||
elif style is GrooveStyle.SNARE_BLINK:
|
||||
half = math.sin(phase * 0.5)
|
||||
target.height = 110.0
|
||||
target.gaze_x = sway * 10.0 * amp
|
||||
target.bounce_y = -abs(half) * 7.0 * amp
|
||||
target.glyph = EyeGlyph.CRESCENT if half > 0.6 else EyeGlyph.ROUND_RECT
|
||||
elif style is GrooveStyle.LOOK_AROUND:
|
||||
look = math.sin(phase * 0.5)
|
||||
target.gaze_x = look * 26.0 * amp
|
||||
target.tilt_y = look * 10.0 * amp
|
||||
target.bounce_y = -6.0 * beat * amp
|
||||
elif style is GrooveStyle.ANTICIPATION_POP:
|
||||
cycle = (phase / math.tau) % 1.0
|
||||
if cycle < 0.75:
|
||||
build = cycle / 0.75
|
||||
target.scale_y = 1.0 - 0.12 * build * amp
|
||||
target.scale_x = 1.0 + 0.10 * build * amp
|
||||
target.bounce_y = 6.0 * build * amp
|
||||
else:
|
||||
pop = math.sin((cycle - 0.75) / 0.25 * math.pi)
|
||||
target.scale_y = 1.0 + 0.16 * pop * amp
|
||||
target.scale_x = 1.0 - 0.12 * pop * amp
|
||||
target.bounce_y = -18.0 * pop * amp
|
||||
elif style is GrooveStyle.GLOW_PULSE:
|
||||
target.height = 110.0
|
||||
target.scale_x = 1.0 + 0.04 * beat * amp
|
||||
target.scale_y = 1.0 + 0.04 * beat * amp
|
||||
target.gaze_y = -4.0 - 3.0 * m.energy
|
||||
target.color = groove_prism_color(t * 0.6)
|
||||
|
||||
def _apply_idle_action(self, target: EyeTarget, t: float) -> None:
|
||||
"""Layer bubbly autonomous micro-behaviors onto normal cruising/idle states."""
|
||||
if self.idle_action == IdleAction.HAPPY_SQUINT:
|
||||
@@ -636,6 +881,38 @@ class RoboticMoodEngine:
|
||||
target.bounce_y = math.sin(t * 7.2) * 11.0
|
||||
target.tilt_y = math.sin(t * 3.6) * 8.0
|
||||
target.mouth = MouthGlyph.BIG_GRIN
|
||||
elif self.idle_action == IdleAction.STRETCH:
|
||||
s = math.sin(t * 3.0)
|
||||
target.scale_y = 1.0 + 0.12 * s
|
||||
target.scale_x = 1.0 - 0.09 * s
|
||||
target.bounce_y = -10.0 * abs(s)
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
elif self.idle_action == IdleAction.SETTLE:
|
||||
target.top_lid = 0.34
|
||||
target.height = 92.0
|
||||
target.bounce_y = 6.0
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
elif self.idle_action == IdleAction.PERK_UP:
|
||||
target.width = 112.0
|
||||
target.height = 122.0
|
||||
target.gaze_x = math.sin(t * 11.0) * 16.0
|
||||
target.gaze_y = -8.0
|
||||
target.mouth = MouthGlyph.SURPRISED
|
||||
elif self.idle_action == IdleAction.DAYDREAM:
|
||||
target.gaze_x = 26.0 + math.sin(t * 0.9) * 4.0
|
||||
target.gaze_y = -10.0 - math.sin(t * 0.6) * 3.0
|
||||
target.tilt_y = 7.0
|
||||
target.top_lid = 0.16
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
elif self.idle_action == IdleAction.DOODLE:
|
||||
ang = t * 3.4
|
||||
target.gaze_x = math.cos(ang) * 20.0
|
||||
target.gaze_y = math.sin(ang * 2.0) * 8.0
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
elif self.idle_action == IdleAction.DOUBLE_BLINK_TILT:
|
||||
target.tilt_y = 5.0
|
||||
target.top_lid = max(target.top_lid, 0.30)
|
||||
target.mouth = MouthGlyph.SMILE
|
||||
|
||||
|
||||
def snapshot_from_ui_state(ui_state, alert: Alert | None) -> DrivingSnapshot:
|
||||
@@ -677,6 +954,8 @@ def snapshot_from_ui_state(ui_state, alert: Alert | None) -> DrivingSnapshot:
|
||||
pitch_rate = 0.5 * pitch_rate + 0.5 * float(gv[1]) if pitch_rate != 0.0 else float(gv[1])
|
||||
yaw_rate = 0.5 * yaw_rate + 0.5 * float(gv[2]) if yaw_rate != 0.0 else float(gv[2])
|
||||
|
||||
yaw_rate = _GYRO_BIAS.correct(yaw_rate, max(0.0, float(v_ego)), 1.0 / 60.0)
|
||||
|
||||
return DrivingSnapshot(
|
||||
started=ui_state.started,
|
||||
engaged=ui_state.engaged,
|
||||
|
||||
@@ -27,10 +27,10 @@ class ProceduralFaceRenderer:
|
||||
# Bubbly spring-overshoot filters for juicy EMO-style squash-and-stretch motion
|
||||
self._w = BounceFilter(104.0, 0.065, dt, bounce=4.2)
|
||||
self._h = BounceFilter(112.0, 0.065, dt, bounce=4.2)
|
||||
self._gaze_x = BounceFilter(0.0, 0.075, dt, bounce=3.4)
|
||||
self._gaze_y = BounceFilter(0.0, 0.075, dt, bounce=3.0)
|
||||
self._gaze_x = BounceFilter(0.0, 0.050, dt, bounce=3.4)
|
||||
self._gaze_y = BounceFilter(0.0, 0.055, dt, bounce=3.0)
|
||||
self._bounce_y = BounceFilter(0.0, 0.055, dt, bounce=4.4)
|
||||
self._tilt_y = BounceFilter(0.0, 0.075, dt, bounce=3.2)
|
||||
self._tilt_y = BounceFilter(0.0, 0.095, dt, bounce=3.2)
|
||||
self._scale_x = BounceFilter(1.0, 0.055, dt, bounce=4.5)
|
||||
self._scale_y = BounceFilter(1.0, 0.055, dt, bounce=4.5)
|
||||
self._squish = BounceFilter(0.0, 0.075, dt, bounce=3.6)
|
||||
@@ -67,7 +67,7 @@ class ProceduralFaceRenderer:
|
||||
bounce_y = self._bounce_y.update(target.bounce_y)
|
||||
tilt_y = self._tilt_y.update(target.tilt_y)
|
||||
squish = max(-1.0, min(1.0, self._squish.update(target.squish_force)))
|
||||
pitch_y = self._pitch_y.update(target.pitch_offset_y)
|
||||
self._pitch_y.update(target.pitch_offset_y)
|
||||
squish_abs = abs(squish)
|
||||
|
||||
r = max(0, min(255, int(self._r.update(target.color[0]))))
|
||||
@@ -255,7 +255,8 @@ class ProceduralFaceRenderer:
|
||||
# Glossy dual specular catchlights (centered-dynamic so eyes never appear stuck staring at top-left)
|
||||
glint_dx = gaze_x * 0.16 + math.sin(t * 3.0) * 1.8
|
||||
glint_dy = gaze_y * 0.14 + math.cos(t * 2.4) * 1.4
|
||||
hi_col = rl.Color(255, 255, 255, int(105 * alpha))
|
||||
glint_fade = 0.30 + 0.70 * visible_frac
|
||||
hi_col = rl.Color(255, 255, 255, int(105 * alpha * glint_fade))
|
||||
rl.draw_rectangle_rounded(
|
||||
rl.Rectangle(cx - w * 0.14 + glint_dx, cy - h * 0.30 + glint_dy, w * 0.28, h * 0.16),
|
||||
0.90,
|
||||
@@ -266,7 +267,7 @@ class ProceduralFaceRenderer:
|
||||
int(cx + w * 0.18 + glint_dx * 0.6),
|
||||
int(cy + h * 0.22 + glint_dy * 0.6),
|
||||
max(3.5, min(w, h) * 0.055),
|
||||
rl.Color(255, 255, 255, int(75 * alpha)),
|
||||
rl.Color(255, 255, 255, int(75 * alpha * glint_fade)),
|
||||
)
|
||||
|
||||
# Sparkle glint inside eyes during sharp acceleration boost
|
||||
|
||||
@@ -11,44 +11,72 @@ import math
|
||||
import numpy as np
|
||||
|
||||
DEFAULT_SAMPLE_RATE = 16000
|
||||
FRAME_RATE = 20.0 # micd publishes 800 samples @ 16kHz = 50ms (20 Hz)
|
||||
FRAME_RATE = 20.0
|
||||
FFT_SIZE = 1024 # ~64ms analysis window
|
||||
NUM_BANDS = 12
|
||||
HISTORY_FRAMES = 50 # 2.5 seconds of flux/energy history @ 20 Hz
|
||||
|
||||
# Software mic gain boost so moderate-volume car stereo music is cleanly analyzed on MICI MEMS mic
|
||||
MIC_GAIN = 6.0
|
||||
MIC_TARGET_RMS = 0.12
|
||||
MIC_MAX_GAIN = 6.0
|
||||
SOFT_KNEE = 0.7
|
||||
|
||||
# Tempo autocorrelation lag bounds @ 20 Hz: 7..18 frames -> 67..171 BPM
|
||||
MIN_TEMPO_LAG = 7
|
||||
MAX_TEMPO_LAG = 18
|
||||
|
||||
# Hysteresis thresholds for stable real-cabin music detection (rejects road noise & talking)
|
||||
ENTER_MUSIC_CONF = 0.44
|
||||
EXIT_MUSIC_CONF = 0.26
|
||||
ENTER_DWELL_S = 0.9
|
||||
ENTER_DWELL_NO_BEAT_S = 2.0
|
||||
EXIT_DWELL_S = 2.5
|
||||
HOLDOFF_S = 3.0
|
||||
|
||||
BEAT_LOCK_PERIODS = 3
|
||||
BEAT_PERIOD_CV_TOLERANCE = 0.25
|
||||
BEAT_HISTORY = 32
|
||||
|
||||
SYLLABIC_LOW_HZ = 3.0
|
||||
SYLLABIC_HIGH_HZ = 8.0
|
||||
SYLLABIC_FRAMES = 40
|
||||
|
||||
MIN_ACTIVE_RMS = 0.0025 # pre-gain RMS (~ -52 dBFS)
|
||||
|
||||
|
||||
def _soft_limit(x: np.ndarray, knee: float = SOFT_KNEE) -> np.ndarray:
|
||||
"""Linear below `knee`, smoothly saturating above it. Unlike np.clip this adds no harmonics."""
|
||||
ax = np.abs(x)
|
||||
if not np.any(ax > knee):
|
||||
return x.astype(np.float32)
|
||||
out = x.astype(np.float32).copy()
|
||||
over = ax > knee
|
||||
span = 1.0 - knee
|
||||
out[over] = np.sign(x[over]) * (knee + span * np.tanh((ax[over] - knee) / span))
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
class MusicState:
|
||||
is_music: bool = False
|
||||
confidence: float = 0.0
|
||||
beat_pulse: float = 0.0 # 0..1 sharp onset with smooth decay
|
||||
groove_phase: float = 0.0 # radians advancing at estimated tempo
|
||||
groove_phase: float = 0.0
|
||||
bpm: float = 116.0
|
||||
energy: float = 0.0 # 0..1 normalized musical loudness
|
||||
bands: tuple[float, ...] = field(default_factory=lambda: (0.0,) * NUM_BANDS)
|
||||
beat_locked: bool = False
|
||||
|
||||
|
||||
class MusicAnalyzer:
|
||||
"""Low-CPU pure-NumPy cabin music detector, beat tracker, and 12-band equalizer analyzer.
|
||||
|
||||
Tuned for real car cabins (road/wind/HVAC rumble + conversation):
|
||||
1. Software mic gain boost + per-bin adaptive spectral noise-floor subtraction
|
||||
2. Harmonic peak prominence & spectral tonality (rejects broadband road/wind noise)
|
||||
3. Musical bandwidth (bass + treble excess energy) + spectral frame stability (rejects speech)
|
||||
4. Rhythmic tempo periodicity (spectral flux autocorrelation at 67-171 BPM)
|
||||
5. Temporal continuity (rejects sporadic talking pauses)
|
||||
1. Adaptive mic gain + soft limiting (never hard-clips the analysis buffer)
|
||||
2. Per-bin adaptive spectral noise-floor subtraction
|
||||
3. Harmonic peak prominence & spectral tonality (rejects broadband road/wind noise)
|
||||
4. Musical bandwidth + spectral frame stability (rejects speech formants)
|
||||
5. Rhythmic tempo periodicity (spectral flux autocorrelation at 67-171 BPM)
|
||||
6. Syllabic 3-8 Hz envelope modulation as an explicit speech term
|
||||
7. Dwell + holdoff + beat lock before claiming "music"
|
||||
"""
|
||||
|
||||
def __init__(self, sample_rate: int = DEFAULT_SAMPLE_RATE):
|
||||
@@ -71,6 +99,14 @@ class MusicAnalyzer:
|
||||
self._active_hist: deque[float] = deque(maxlen=HISTORY_FRAMES)
|
||||
self._bass_flux_hist: deque[float] = deque(maxlen=20)
|
||||
self._stability_hist: deque[float] = deque(maxlen=20)
|
||||
self._speech_env: deque[float] = deque(maxlen=SYLLABIC_FRAMES)
|
||||
self._beat_onsets: deque[float] = deque(maxlen=BEAT_HISTORY)
|
||||
|
||||
self._t: float = 0.0
|
||||
self._enter_timer: float = 0.0
|
||||
self._exit_timer: float = 0.0
|
||||
self._holdoff_until: float = 0.0
|
||||
self._beat_locked: bool = False
|
||||
|
||||
self._build_frequency_masks(sample_rate)
|
||||
|
||||
@@ -101,13 +137,14 @@ class MusicAnalyzer:
|
||||
bpm=self._bpm,
|
||||
energy=self._energy,
|
||||
bands=tuple(float(b) for b in self._bands),
|
||||
beat_locked=self._beat_locked,
|
||||
)
|
||||
|
||||
def step_visual_decay(self, dt: float) -> MusicState:
|
||||
"""Advance smooth 60 FPS groove phase and beat decay between 20 Hz audio chunks."""
|
||||
if self._is_music:
|
||||
rad_per_sec = (self._bpm / 60.0) * math.pi
|
||||
self._groove_phase = (self._groove_phase + rad_per_sec * dt) % (math.tau * 4.0)
|
||||
rad_per_sec = (self._bpm / 60.0) * math.tau
|
||||
self._groove_phase = (self._groove_phase + rad_per_sec * dt) % math.tau
|
||||
decay = math.exp(-dt * 7.5)
|
||||
self._beat_pulse *= decay
|
||||
if not self._is_music:
|
||||
@@ -129,16 +166,23 @@ class MusicAnalyzer:
|
||||
if n == 0:
|
||||
return self.state
|
||||
|
||||
# Apply software mic gain so quiet/moderate cabin music has strong dynamic range
|
||||
boosted = np.clip(samples * MIC_GAIN, -1.0, 1.0)
|
||||
dt = 1.0 / FRAME_RATE
|
||||
self._t += dt
|
||||
|
||||
raw_rms = float(np.sqrt(np.mean(samples * samples)))
|
||||
|
||||
if raw_rms > 1e-6:
|
||||
mic_gain = float(np.clip(MIC_TARGET_RMS / raw_rms, 1.0, MIC_MAX_GAIN))
|
||||
else:
|
||||
mic_gain = MIC_MAX_GAIN
|
||||
boosted = _soft_limit(samples * mic_gain)
|
||||
|
||||
if n >= FFT_SIZE:
|
||||
self._ring[:] = boosted[-FFT_SIZE:]
|
||||
else:
|
||||
self._ring[:-n] = self._ring[n:]
|
||||
self._ring[-n:] = boosted
|
||||
|
||||
# Check raw (pre-gain) RMS against minimal mic silence floor
|
||||
raw_rms = float(np.sqrt(np.mean(samples * samples)))
|
||||
rms = float(np.sqrt(np.mean(self._ring * self._ring)))
|
||||
|
||||
# FFT magnitude & power spectrum
|
||||
@@ -185,7 +229,8 @@ class MusicAnalyzer:
|
||||
treble_ratio = float(np.sum(power[self._treble_mask])) / total_p
|
||||
non_speech_ratio = bass_ratio + treble_ratio
|
||||
bandwidth_score = float(np.clip(non_speech_ratio / 0.24, 0.0, 1.0))
|
||||
if speech_ratio > 0.82 and bass_ratio < 0.09 and treble_ratio < 0.06:
|
||||
narrowband_speech = speech_ratio > 0.82 and bass_ratio < 0.09 and treble_ratio < 0.06
|
||||
if narrowband_speech:
|
||||
bandwidth_score *= 0.20
|
||||
|
||||
# 3. Spectral harmonic stability (sustained musical chords/notes vs shifting speech formants)
|
||||
@@ -230,41 +275,81 @@ class MusicAnalyzer:
|
||||
est_bpm = (60.0 * FRAME_RATE) / best_lag
|
||||
self._bpm = 0.88 * self._bpm + 0.12 * float(np.clip(est_bpm, 72.0, 172.0))
|
||||
|
||||
# 5. Temporal continuity (music is continuous; talking has inter-word/sentence silences)
|
||||
beat_onset = False
|
||||
if len(self._bass_flux_hist) >= 6:
|
||||
bf_mean = float(np.mean(self._bass_flux_hist))
|
||||
bf_std = float(np.std(self._bass_flux_hist)) + 1e-6
|
||||
if bass_flux > bf_mean + 0.85 * bf_std and bass_flux > 0.008:
|
||||
beat_onset = True
|
||||
strength = float(np.clip((bass_flux - bf_mean) / (2.0 * bf_std), 0.45, 1.0))
|
||||
if self._is_music:
|
||||
self._beat_pulse = max(self._beat_pulse, strength)
|
||||
self._beat_onsets.append(self._t)
|
||||
|
||||
self._beat_locked = False
|
||||
if len(self._beat_onsets) >= BEAT_LOCK_PERIODS:
|
||||
recent = np.array(list(self._beat_onsets)[-BEAT_LOCK_PERIODS:], dtype=np.float32)
|
||||
periods = np.diff(recent)
|
||||
if periods.size and float(periods.mean()) > 1e-3:
|
||||
cv = float(periods.std() / periods.mean())
|
||||
self._beat_locked = cv <= BEAT_PERIOD_CV_TOLERANCE
|
||||
if self._beat_locked and beat_onset and self._is_music:
|
||||
self._groove_phase = 0.0
|
||||
|
||||
speech_band = float(np.sqrt(np.sum(power[self._speech_mask]) + 1e-12))
|
||||
self._speech_env.append(speech_band)
|
||||
syllabic_score = 0.0
|
||||
if len(self._speech_env) >= SYLLABIC_FRAMES:
|
||||
env = np.array(self._speech_env, dtype=np.float32)
|
||||
env = env - float(env.mean())
|
||||
if float(np.abs(env).sum()) > 1e-9:
|
||||
env_spec = np.abs(np.fft.rfft(env * np.hanning(env.size)))
|
||||
env_freqs = np.fft.rfftfreq(env.size, d=1.0 / FRAME_RATE)
|
||||
band = (env_freqs >= SYLLABIC_LOW_HZ) & (env_freqs <= SYLLABIC_HIGH_HZ)
|
||||
total_env = float(env_spec.sum()) + 1e-9
|
||||
ratio = float(env_spec[band].sum()) / total_env
|
||||
syllabic_score = float(np.clip((ratio - 0.20) / 0.45, 0.0, 1.0))
|
||||
|
||||
speech_likeness = max(syllabic_score, 0.75 if narrowband_speech else 0.0)
|
||||
|
||||
continuity = float(np.mean(self._active_hist)) if self._active_hist else 0.0
|
||||
continuity_score = float(np.clip((continuity - 0.48) / 0.40, 0.0, 1.0))
|
||||
|
||||
# Combine features: accepts both rhythmic pop/EDM/hip-hop AND harmonic acoustic/chill music,
|
||||
# while rejecting flat road noise (low tonality) and narrowband/intermittent talking.
|
||||
if not above_floor:
|
||||
frame_score = 0.0
|
||||
else:
|
||||
musical_drive = max(rhythm_score, 0.72 * stability_score)
|
||||
frame_score = (
|
||||
0.28 * tonality_score
|
||||
+ 0.26 * bandwidth_score
|
||||
+ 0.28 * musical_drive
|
||||
+ 0.18 * continuity_score
|
||||
0.26 * tonality_score
|
||||
+ 0.24 * bandwidth_score
|
||||
+ 0.26 * musical_drive
|
||||
+ 0.16 * continuity_score
|
||||
- 0.22 * speech_likeness
|
||||
)
|
||||
frame_score = float(np.clip(frame_score, 0.0, 1.0))
|
||||
if tonality_score < 0.24 or bandwidth_score < 0.22:
|
||||
frame_score *= 0.25
|
||||
|
||||
# Smooth confidence with hysteresis (~1.2s attack, ~2.0s release @ 20 Hz)
|
||||
alpha = 0.075 if frame_score > self._confidence else 0.035
|
||||
self._confidence = (1.0 - alpha) * self._confidence + alpha * frame_score
|
||||
|
||||
if not self._is_music and self._confidence >= ENTER_MUSIC_CONF:
|
||||
self._is_music = True
|
||||
elif self._is_music and self._confidence <= EXIT_MUSIC_CONF:
|
||||
self._is_music = False
|
||||
|
||||
# Beat onset pulse (bass + overall flux spike above rolling mean)
|
||||
if self._is_music and len(self._bass_flux_hist) >= 6:
|
||||
bf_mean = float(np.mean(self._bass_flux_hist))
|
||||
bf_std = float(np.std(self._bass_flux_hist)) + 1e-6
|
||||
if bass_flux > bf_mean + 0.85 * bf_std and bass_flux > 0.008:
|
||||
strength = float(np.clip((bass_flux - bf_mean) / (2.0 * bf_std), 0.45, 1.0))
|
||||
self._beat_pulse = max(self._beat_pulse, strength)
|
||||
if self._is_music:
|
||||
self._exit_timer = self._exit_timer + dt if self._confidence <= EXIT_MUSIC_CONF else 0.0
|
||||
if self._exit_timer >= EXIT_DWELL_S:
|
||||
self._is_music = False
|
||||
self._exit_timer = 0.0
|
||||
self._enter_timer = 0.0
|
||||
self._holdoff_until = self._t + HOLDOFF_S
|
||||
elif self._t >= self._holdoff_until:
|
||||
confident = self._confidence >= ENTER_MUSIC_CONF
|
||||
eligible = confident and (self._beat_locked or self._confidence >= ENTER_MUSIC_CONF + 0.12)
|
||||
self._enter_timer = self._enter_timer + dt if eligible else 0.0
|
||||
required = ENTER_DWELL_S if self._beat_locked else ENTER_DWELL_NO_BEAT_S
|
||||
if self._enter_timer >= required:
|
||||
self._is_music = True
|
||||
self._enter_timer = 0.0
|
||||
self._exit_timer = 0.0
|
||||
|
||||
# Normalized energy & 12-band equalizer bars
|
||||
self._energy = float(np.clip(rms / 0.35, 0.0, 1.0))
|
||||
|
||||
@@ -43,7 +43,7 @@ class RoboticOnroadView(Widget):
|
||||
super().__init__()
|
||||
self._bookmark_callback = bookmark_callback
|
||||
|
||||
self._mood_engine = RoboticMoodEngine()
|
||||
self._mood_engine = RoboticMoodEngine(params=getattr(ui_state, "params", None))
|
||||
self._face_renderer = ProceduralFaceRenderer()
|
||||
self._speed_renderer = SpeedArcRenderer()
|
||||
self._alert_overlay = RoboticAlertOverlay()
|
||||
|
||||
Reference in New Issue
Block a user