mirror of
https://github.com/bleackstorm/SteamFrame-FPV-Control-Center.git
synced 2026-12-03 07:31:57 +01:00
feat(audio): add GStreamer PCM audio alerts for battery, LQ, arming, and DVR
This commit is contained in:
1 parent
4715505800
commit
56f37d1320
9 files changed
+570
-2
No files matched your search
@@ -0,0 +1,385 @@
|
||||
use gstreamer as gst;
|
||||
use gstreamer::prelude::*;
|
||||
use gstreamer_app as gst_app;
|
||||
use parking_lot::Mutex;
|
||||
use std::f32::consts::TAU;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
|
||||
use std::sync::mpsc::{self, SyncSender};
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub const AUDIO_SAMPLE_RATE: u32 = 44_100;
|
||||
|
||||
/// Types d'alertes sonores synthétisées dans le casque (PipeWire / PulseAudio via GStreamer).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AudioAlertKind {
|
||||
BatteryCritical,
|
||||
BatteryLow,
|
||||
LinkQualityLow,
|
||||
Armed,
|
||||
Disarmed,
|
||||
DvrStart,
|
||||
DvrStop,
|
||||
ReplaySaved,
|
||||
TestBeep,
|
||||
}
|
||||
|
||||
impl AudioAlertKind {
|
||||
/// Durée minimale anti-spam entre deux alertes identiques (`Duration::ZERO` = immédiat).
|
||||
pub const fn cooldown(self) -> Duration {
|
||||
match self {
|
||||
Self::BatteryCritical => Duration::from_secs(5),
|
||||
Self::BatteryLow => Duration::from_secs(15),
|
||||
Self::LinkQualityLow => Duration::from_secs(3),
|
||||
Self::Armed
|
||||
| Self::Disarmed
|
||||
| Self::DvrStart
|
||||
| Self::DvrStop
|
||||
| Self::ReplaySaved
|
||||
| Self::TestBeep => Duration::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
const fn slot_index(self) -> usize {
|
||||
match self {
|
||||
Self::BatteryCritical => 0,
|
||||
Self::BatteryLow => 1,
|
||||
Self::LinkQualityLow => 2,
|
||||
Self::Armed => 3,
|
||||
Self::Disarmed => 4,
|
||||
Self::DvrStart => 5,
|
||||
Self::DvrStop => 6,
|
||||
Self::ReplaySaved => 7,
|
||||
Self::TestBeep => 8,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Segment élémentaire d'une séquence sonore (fréquence 0.0 = silence).
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct ToneSegment {
|
||||
freq_hz: f32,
|
||||
duration_ms: u32,
|
||||
gain: f32,
|
||||
}
|
||||
|
||||
fn tone_pattern(kind: AudioAlertKind) -> &'static [ToneSegment] {
|
||||
match kind {
|
||||
AudioAlertKind::BatteryCritical => &[
|
||||
ToneSegment { freq_hz: 440.0, duration_ms: 110, gain: 0.90 },
|
||||
ToneSegment { freq_hz: 0.0, duration_ms: 50, gain: 0.0 },
|
||||
ToneSegment { freq_hz: 330.0, duration_ms: 180, gain: 0.95 },
|
||||
],
|
||||
AudioAlertKind::BatteryLow => &[
|
||||
ToneSegment { freq_hz: 660.0, duration_ms: 130, gain: 0.65 },
|
||||
],
|
||||
AudioAlertKind::LinkQualityLow => &[
|
||||
ToneSegment { freq_hz: 1200.0, duration_ms: 45, gain: 0.80 },
|
||||
ToneSegment { freq_hz: 0.0, duration_ms: 40, gain: 0.0 },
|
||||
ToneSegment { freq_hz: 1200.0, duration_ms: 45, gain: 0.80 },
|
||||
ToneSegment { freq_hz: 0.0, duration_ms: 40, gain: 0.0 },
|
||||
ToneSegment { freq_hz: 1200.0, duration_ms: 45, gain: 0.85 },
|
||||
],
|
||||
AudioAlertKind::Armed => &[
|
||||
ToneSegment { freq_hz: 523.25, duration_ms: 70, gain: 0.70 },
|
||||
ToneSegment { freq_hz: 0.0, duration_ms: 20, gain: 0.0 },
|
||||
ToneSegment { freq_hz: 783.99, duration_ms: 120, gain: 0.80 },
|
||||
],
|
||||
AudioAlertKind::Disarmed => &[
|
||||
ToneSegment { freq_hz: 783.99, duration_ms: 70, gain: 0.70 },
|
||||
ToneSegment { freq_hz: 0.0, duration_ms: 20, gain: 0.0 },
|
||||
ToneSegment { freq_hz: 440.0, duration_ms: 120, gain: 0.75 },
|
||||
],
|
||||
AudioAlertKind::DvrStart => &[
|
||||
ToneSegment { freq_hz: 1000.0, duration_ms: 35, gain: 0.60 },
|
||||
ToneSegment { freq_hz: 0.0, duration_ms: 15, gain: 0.0 },
|
||||
ToneSegment { freq_hz: 1400.0, duration_ms: 45, gain: 0.65 },
|
||||
],
|
||||
AudioAlertKind::DvrStop => &[
|
||||
ToneSegment { freq_hz: 1400.0, duration_ms: 35, gain: 0.60 },
|
||||
ToneSegment { freq_hz: 0.0, duration_ms: 15, gain: 0.0 },
|
||||
ToneSegment { freq_hz: 900.0, duration_ms: 50, gain: 0.60 },
|
||||
],
|
||||
AudioAlertKind::ReplaySaved => &[
|
||||
ToneSegment { freq_hz: 880.0, duration_ms: 50, gain: 0.65 },
|
||||
ToneSegment { freq_hz: 0.0, duration_ms: 20, gain: 0.0 },
|
||||
ToneSegment { freq_hz: 1318.5, duration_ms: 95, gain: 0.75 },
|
||||
],
|
||||
AudioAlertKind::TestBeep => &[
|
||||
ToneSegment { freq_hz: 880.0, duration_ms: 75, gain: 0.70 },
|
||||
ToneSegment { freq_hz: 0.0, duration_ms: 25, gain: 0.0 },
|
||||
ToneSegment { freq_hz: 1174.66, duration_ms: 100, gain: 0.75 },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/// Synthétise un tampon PCM mono `S16LE` (44.1 kHz) avec enveloppe d'attaque/relâchement douce
|
||||
/// pour éviter tout clic parasite dans le casque.
|
||||
pub fn synthesize_alert_pcm_s16le(kind: AudioAlertKind, volume_pct: u8) -> Vec<u8> {
|
||||
let master = (volume_pct.min(100) as f32 / 100.0) * 0.45;
|
||||
let pattern = tone_pattern(kind);
|
||||
let total_samples: usize = pattern
|
||||
.iter()
|
||||
.map(|seg| ((seg.duration_ms as u64 * AUDIO_SAMPLE_RATE as u64) / 1000) as usize)
|
||||
.sum();
|
||||
let mut bytes = Vec::with_capacity(total_samples * 2);
|
||||
let fade_samples = ((AUDIO_SAMPLE_RATE as usize) * 5) / 1000; // 5 ms attack/release
|
||||
|
||||
for seg in pattern {
|
||||
let count = ((seg.duration_ms as u64 * AUDIO_SAMPLE_RATE as u64) / 1000) as usize;
|
||||
if seg.freq_hz <= 0.0 || master <= 0.0 || seg.gain <= 0.0 {
|
||||
bytes.resize(bytes.len() + count * 2, 0);
|
||||
continue;
|
||||
}
|
||||
let amp = (master * seg.gain).clamp(0.0, 0.95) * i16::MAX as f32;
|
||||
let fade = fade_samples.min(count / 2).max(1);
|
||||
for i in 0..count {
|
||||
let env = if i < fade {
|
||||
i as f32 / fade as f32
|
||||
} else if i >= count - fade {
|
||||
(count - 1 - i) as f32 / fade as f32
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
let phase = TAU * seg.freq_hz * (i as f32 / AUDIO_SAMPLE_RATE as f32);
|
||||
let sample = (phase.sin() * amp * env).round().clamp(i16::MIN as f32, i16::MAX as f32) as i16;
|
||||
bytes.extend_from_slice(&sample.to_le_bytes());
|
||||
}
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct AlertTracker {
|
||||
last_played: [Option<Instant>; 9],
|
||||
last_armed: Option<bool>,
|
||||
}
|
||||
|
||||
impl AlertTracker {
|
||||
fn allow(&mut self, kind: AudioAlertKind, now: Instant) -> bool {
|
||||
let cd = kind.cooldown();
|
||||
let slot = &mut self.last_played[kind.slot_index()];
|
||||
if !cd.is_zero() {
|
||||
if let Some(prev) = *slot {
|
||||
if now.saturating_duration_since(prev) < cd {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
*slot = Some(now);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Moteur d'alertes sonores asynchrone non-bloquant (fil dédié + GStreamer `appsrc ! autoaudiosink`).
|
||||
pub struct AudioAlertEngine {
|
||||
enabled: Arc<AtomicBool>,
|
||||
volume_pct: Arc<AtomicU8>,
|
||||
tracker: Mutex<AlertTracker>,
|
||||
tx: Mutex<Option<SyncSender<(AudioAlertKind, u8)>>>,
|
||||
}
|
||||
|
||||
impl AudioAlertEngine {
|
||||
pub fn new(initial_enabled: bool, initial_volume_pct: u8) -> Self {
|
||||
Self {
|
||||
enabled: Arc::new(AtomicBool::new(initial_enabled)),
|
||||
volume_pct: Arc::new(AtomicU8::new(initial_volume_pct.min(100))),
|
||||
tracker: Mutex::new(AlertTracker::default()),
|
||||
tx: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_enabled(&self, enabled: bool) {
|
||||
self.enabled.store(enabled, Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn is_enabled(&self) -> bool {
|
||||
self.enabled.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn set_volume_pct(&self, pct: u8) {
|
||||
self.volume_pct.store(pct.min(100), Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn volume_pct(&self) -> u8 {
|
||||
self.volume_pct.load(Ordering::Acquire).min(100)
|
||||
}
|
||||
|
||||
/// Déclenche une alerte sonore si le système audio est activé et hors cooldown.
|
||||
/// Ne bloque jamais le thread appelant.
|
||||
pub fn trigger(&self, kind: AudioAlertKind) {
|
||||
let vol = self.volume_pct();
|
||||
if vol == 0 {
|
||||
return;
|
||||
}
|
||||
if kind != AudioAlertKind::TestBeep && !self.is_enabled() {
|
||||
return;
|
||||
}
|
||||
let now = Instant::now();
|
||||
{
|
||||
let mut tr = self.tracker.lock();
|
||||
if !tr.allow(kind, now) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.ensure_worker_started();
|
||||
if let Some(ref sender) = *self.tx.lock() {
|
||||
let _ = sender.try_send((kind, vol));
|
||||
}
|
||||
}
|
||||
|
||||
/// Évalue les transitions d'armement et les seuils télémétriques (batterie LiPo + LQ < 50 %)
|
||||
/// à chaque mise à jour OSD.
|
||||
pub fn evaluate_live_alerts(
|
||||
&self,
|
||||
armed: bool,
|
||||
telem_live: bool,
|
||||
cell_v: Option<f32>,
|
||||
warn_cell_v: f32,
|
||||
crit_cell_v: f32,
|
||||
lq_pct: Option<u8>,
|
||||
) {
|
||||
let arm_transition = {
|
||||
let mut tr = self.tracker.lock();
|
||||
let prev = tr.last_armed;
|
||||
tr.last_armed = Some(armed);
|
||||
match (prev, armed) {
|
||||
(Some(false), true) => Some(AudioAlertKind::Armed),
|
||||
(Some(true), false) => Some(AudioAlertKind::Disarmed),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
if let Some(kind) = arm_transition {
|
||||
self.trigger(kind);
|
||||
}
|
||||
|
||||
if !telem_live {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(cv) = cell_v {
|
||||
if cv > 1.5 && cv < crit_cell_v {
|
||||
self.trigger(AudioAlertKind::BatteryCritical);
|
||||
} else if cv > 1.5 && cv < warn_cell_v {
|
||||
self.trigger(AudioAlertKind::BatteryLow);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(lq) = lq_pct {
|
||||
if lq < 50 {
|
||||
self.trigger(AudioAlertKind::LinkQualityLow);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_worker_started(&self) {
|
||||
let mut guard = self.tx.lock();
|
||||
if guard.is_some() {
|
||||
return;
|
||||
}
|
||||
let (tx, rx) = mpsc::sync_channel::<(AudioAlertKind, u8)>(8);
|
||||
*guard = Some(tx);
|
||||
drop(guard);
|
||||
|
||||
let _ = thread::Builder::new()
|
||||
.name("audio-alerts".to_string())
|
||||
.spawn(move || {
|
||||
audio_worker_loop(rx);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn audio_worker_loop(rx: mpsc::Receiver<(AudioAlertKind, u8)>) {
|
||||
if gst::init().is_err() {
|
||||
log::warn!("[Audio] Impossible d'initialiser GStreamer pour les alertes sonores.");
|
||||
return;
|
||||
}
|
||||
|
||||
let pipeline_desc = format!(
|
||||
"appsrc name=src is-live=true format=time block=false \
|
||||
caps=audio/x-raw,format=S16LE,rate={},channels=1,layout=interleaved \
|
||||
! audioconvert ! audioresample ! autoaudiosink sync=false",
|
||||
AUDIO_SAMPLE_RATE
|
||||
);
|
||||
let pipeline = match gst::parse::launch(&pipeline_desc) {
|
||||
Ok(el) => match el.downcast::<gst::Pipeline>() {
|
||||
Ok(p) => p,
|
||||
Err(_) => {
|
||||
log::warn!("[Audio] Pipeline GStreamer invalide.");
|
||||
return;
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
log::warn!("[Audio] Sortie audio indisponible ({}) — alertes sonores désactivées.", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let appsrc = match pipeline
|
||||
.by_name("src")
|
||||
.and_then(|el| el.downcast::<gst_app::AppSrc>().ok())
|
||||
{
|
||||
Some(s) => s,
|
||||
None => return,
|
||||
};
|
||||
|
||||
if pipeline.set_state(gst::State::Playing).is_err() {
|
||||
log::warn!("[Audio] Impossible de démarrer le sink audio GStreamer.");
|
||||
return;
|
||||
}
|
||||
|
||||
while let Ok((kind, vol_pct)) = rx.recv() {
|
||||
let pcm = synthesize_alert_pcm_s16le(kind, vol_pct);
|
||||
if pcm.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut buf = gst::Buffer::with_size(pcm.len()).unwrap_or_else(|_| gst::Buffer::new());
|
||||
if let Some(buf_ref) = buf.get_mut() {
|
||||
if let Ok(mut map) = buf_ref.map_writable() {
|
||||
map.as_mut_slice().copy_from_slice(&pcm);
|
||||
}
|
||||
}
|
||||
let _ = appsrc.push_buffer(buf);
|
||||
}
|
||||
|
||||
let _ = pipeline.set_state(gst::State::Null);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_synthesize_pcm_bounds_and_silence_at_zero_volume() {
|
||||
let silent = synthesize_alert_pcm_s16le(AudioAlertKind::BatteryCritical, 0);
|
||||
assert!(!silent.is_empty());
|
||||
assert!(silent.iter().all(|&b| b == 0));
|
||||
|
||||
let loud = synthesize_alert_pcm_s16le(AudioAlertKind::Armed, 100);
|
||||
assert_eq!(loud.len() % 2, 0);
|
||||
let samples: Vec<i16> = loud
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|&c| i16::from_le_bytes(c))
|
||||
.collect();
|
||||
// L'enveloppe ADSR démarre à 0 (zéro clic) et possède une amplitude non nulle au milieu
|
||||
assert_eq!(samples[0], 0);
|
||||
let peak = samples.iter().map(|s| s.unsigned_abs()).max().unwrap_or(0);
|
||||
assert!(peak > 5000 && peak < 20000, "amplitude attendue raisonnable: {}", peak);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_alert_tracker_cooldown_anti_spam() {
|
||||
let mut tr = AlertTracker::default();
|
||||
let t0 = Instant::now();
|
||||
assert!(tr.allow(AudioAlertKind::BatteryCritical, t0));
|
||||
assert!(!tr.allow(AudioAlertKind::BatteryCritical, t0 + Duration::from_secs(2)));
|
||||
assert!(tr.allow(AudioAlertKind::BatteryCritical, t0 + Duration::from_secs(6)));
|
||||
|
||||
// Les événements immédiats (Armement / DVR) ne sont pas bloqués par un cooldown
|
||||
assert!(tr.allow(AudioAlertKind::Armed, t0));
|
||||
assert!(tr.allow(AudioAlertKind::Armed, t0 + Duration::from_millis(10)));
|
||||
}
|
||||
}
|
||||
+16
-1
@@ -264,6 +264,14 @@ pub struct AppConfig {
|
||||
#[arg(long, default_value_t = false)]
|
||||
pub gst_latency_trace: bool,
|
||||
|
||||
/// Active les alertes sonores dans le casque (batterie, LQ < 50%, armement, DVR)
|
||||
#[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
|
||||
pub audio_alerts_enabled: bool,
|
||||
|
||||
/// Volume des alertes sonores dans le casque (0 = muet, 1..=100%)
|
||||
#[arg(long, default_value_t = 70)]
|
||||
pub audio_volume_pct: u8,
|
||||
|
||||
/// Chemin du fichier journal d'erreurs et de diagnostic
|
||||
#[arg(long, default_value = "steamframe_fpv.log")]
|
||||
pub log_file: String,
|
||||
@@ -660,7 +668,9 @@ impl AppConfig {
|
||||
video_sharpness = {:.3}\n\
|
||||
horizon_stabilization = {}\n\
|
||||
stereo_sbs = {}\n\
|
||||
zero_copy_dmabuf = {}\n",
|
||||
zero_copy_dmabuf = {}\n\
|
||||
audio_alerts_enabled = {}\n\
|
||||
audio_volume_pct = {}\n",
|
||||
esc(&self.usb_video_mode),
|
||||
esc(&self.uvc_device),
|
||||
esc(&self.usb_bind_ip),
|
||||
@@ -721,6 +731,8 @@ impl AppConfig {
|
||||
self.horizon_stabilization,
|
||||
self.stereo_sbs,
|
||||
self.zero_copy_dmabuf,
|
||||
self.audio_alerts_enabled,
|
||||
self.audio_volume_pct,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -870,6 +882,8 @@ impl AppConfig {
|
||||
load_parse!(horizon_stabilization);
|
||||
load_parse!(stereo_sbs);
|
||||
load_parse!(zero_copy_dmabuf);
|
||||
load_parse!(audio_alerts_enabled);
|
||||
load_parse!(audio_volume_pct);
|
||||
|
||||
// Sécurité bornes numériques
|
||||
self.video_width = self.video_width.clamp(320, 3840);
|
||||
@@ -879,6 +893,7 @@ impl AppConfig {
|
||||
self.screen_distance_m = self.screen_distance_m.clamp(0.5, 5.0);
|
||||
self.vr_hud_smoothing = self.vr_hud_smoothing.clamp(0.0, 1.0);
|
||||
self.controller_vibration = self.controller_vibration.min(100);
|
||||
self.audio_volume_pct = self.audio_volume_pct.min(100);
|
||||
self.controller_throttle_expo = self.controller_throttle_expo.clamp(0.0, 0.8);
|
||||
self.battery_cells = self.battery_cells.min(6);
|
||||
self.battery_warn_cell_v = self.battery_warn_cell_v.clamp(3.0, 4.2);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::radxa_ssh::spawn_apply_radxa_channel;
|
||||
use super::types::{DvrConfig, EngineSharedState, LiveOpticalParams};
|
||||
use crate::audio_alerts::AudioAlertKind;
|
||||
use crate::config::{AppConfig, VehicleProfile};
|
||||
use crate::controller::{ControlSource, GearSpeedLimits};
|
||||
use crate::dome_projection::{ProjectionMode, VrLockMode};
|
||||
@@ -77,6 +78,8 @@ impl EngineControlHandle {
|
||||
cfg.battery_cells = bat_cells;
|
||||
cfg.battery_warn_cell_v = bat_warn;
|
||||
cfg.battery_crit_cell_v = bat_crit;
|
||||
cfg.audio_alerts_enabled = self.shared.audio_alerts.is_enabled();
|
||||
cfg.audio_volume_pct = self.shared.audio_alerts.volume_pct();
|
||||
Some(cfg.clone())
|
||||
} else {
|
||||
None
|
||||
@@ -731,6 +734,24 @@ impl EngineControlHandle {
|
||||
let next = (cur + step * 10).clamp(0, 100) as u8;
|
||||
self.set_controller_vibration_pct(next);
|
||||
}
|
||||
(VrMenuPage::Advanced, 8) => {
|
||||
if is_activate {
|
||||
let next = !self.shared.audio_alerts.is_enabled();
|
||||
self.set_audio_alerts_enabled(next);
|
||||
if next {
|
||||
self.trigger_audio_test_beep();
|
||||
}
|
||||
self.shared
|
||||
.vr_menu_state
|
||||
.lock()
|
||||
.set_feedback(if next { "AUDIO : ON" } else { "AUDIO : OFF" }, false);
|
||||
} else {
|
||||
let cur = self.shared.audio_alerts.volume_pct() as i32;
|
||||
let next = (cur + step * 10).clamp(0, 100) as u8;
|
||||
self.shared.audio_alerts.set_enabled(next > 0);
|
||||
self.set_audio_volume_pct(next);
|
||||
}
|
||||
}
|
||||
(VrMenuPage::Advanced, _) => {
|
||||
if is_activate {
|
||||
let (ch, ip_str) = {
|
||||
@@ -792,6 +813,8 @@ impl EngineControlHandle {
|
||||
.controller_vibration_pct
|
||||
.load(Ordering::Relaxed)
|
||||
.min(100),
|
||||
audio_alerts_on: self.shared.audio_alerts.is_enabled(),
|
||||
audio_volume_pct: self.shared.audio_alerts.volume_pct(),
|
||||
wifi_channel,
|
||||
quit_confirm_pending,
|
||||
feedback_msg,
|
||||
@@ -826,5 +849,19 @@ impl EngineControlHandle {
|
||||
.replay_save_requested
|
||||
.store(true, Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn set_audio_alerts_enabled(&self, enabled: bool) {
|
||||
self.shared.audio_alerts.set_enabled(enabled);
|
||||
self.persist_live_config();
|
||||
}
|
||||
|
||||
pub fn set_audio_volume_pct(&self, pct: u8) {
|
||||
self.shared.audio_alerts.set_volume_pct(pct.min(100));
|
||||
self.persist_live_config();
|
||||
}
|
||||
|
||||
pub fn trigger_audio_test_beep(&self) {
|
||||
self.shared.audio_alerts.trigger(AudioAlertKind::TestBeep);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ pub use types::{
|
||||
};
|
||||
pub use vr_menu::VrMenuState;
|
||||
|
||||
use crate::audio_alerts::{AudioAlertEngine, AudioAlertKind};
|
||||
use crate::config::AppConfig;
|
||||
use crate::controller::{
|
||||
ControlSource, GearSpeedLimits, SteamControllerConfig, SteamControllerWorker,
|
||||
@@ -86,6 +87,7 @@ impl FpvEngineController {
|
||||
replay_buffer: Arc::new(ReplayRingBuffer::default()),
|
||||
replay_save_requested: Arc::new(AtomicBool::new(false)),
|
||||
battery_params: Arc::new(Mutex::new((0, 3.5, 3.3))),
|
||||
audio_alerts: Arc::new(AudioAlertEngine::new(true, 70)),
|
||||
});
|
||||
|
||||
Self {
|
||||
@@ -188,6 +190,8 @@ impl FpvEngineController {
|
||||
cfg.battery_warn_cell_v,
|
||||
cfg.battery_crit_cell_v,
|
||||
);
|
||||
self.shared.audio_alerts.set_enabled(cfg.audio_alerts_enabled);
|
||||
self.shared.audio_alerts.set_volume_pct(cfg.audio_volume_pct);
|
||||
*self.shared.persisted_cfg.lock() = Some(cfg.clone());
|
||||
*self.shared.gear_speed_limits.lock() = GearSpeedLimits {
|
||||
forward_min: cfg.gaz_avant_min,
|
||||
@@ -486,6 +490,7 @@ pub fn handle_dvr_lifecycle(ctx: &mut EngineWorkerRefs<'_>) {
|
||||
}
|
||||
}
|
||||
ctx.shared.dvr_recording_flag.store(true, Ordering::Release);
|
||||
ctx.shared.audio_alerts.trigger(AudioAlertKind::DvrStart);
|
||||
let mut mon = ctx.shared.monitor.lock();
|
||||
mon.dvr_recording = true;
|
||||
mon.dvr_file_path = recorder.file_path().to_string_lossy().to_string();
|
||||
@@ -518,6 +523,7 @@ pub fn handle_dvr_lifecycle(ctx: &mut EngineWorkerRefs<'_>) {
|
||||
ctx.shared
|
||||
.dvr_recording_flag
|
||||
.store(false, Ordering::Release);
|
||||
ctx.shared.audio_alerts.trigger(AudioAlertKind::DvrStop);
|
||||
{
|
||||
let mut mon = ctx.shared.monitor.lock();
|
||||
mon.dvr_recording = false;
|
||||
@@ -560,6 +566,7 @@ pub fn handle_dvr_lifecycle(ctx: &mut EngineWorkerRefs<'_>) {
|
||||
let codec = ctx.cfg.codec.clone();
|
||||
let replay_buf = Arc::clone(&ctx.shared.replay_buffer);
|
||||
let monitor = Arc::clone(&ctx.shared.monitor);
|
||||
let audio = Arc::clone(&ctx.shared.audio_alerts);
|
||||
monitor.lock().replay_status_text = "Export Replay 30s en cours...".to_string();
|
||||
if let Ok(h) = thread::Builder::new()
|
||||
.name("dvr-instant-replay".into())
|
||||
@@ -571,6 +578,7 @@ pub fn handle_dvr_lifecycle(ctx: &mut EngineWorkerRefs<'_>) {
|
||||
.unwrap_or_default();
|
||||
monitor.lock().replay_status_text =
|
||||
format!("Replay OK : {} ({:.1}s, {} pkts)", fname, dur_s, pkts);
|
||||
audio.trigger(AudioAlertKind::ReplaySaved);
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("[Replay] Impossible d'exporter l'Instant Replay : {}", e);
|
||||
@@ -721,6 +729,18 @@ pub fn compose_osd_and_publish(
|
||||
)
|
||||
};
|
||||
let (bat_cells, bat_warn, bat_crit) = *ctx.shared.battery_params.lock();
|
||||
ctx.shared.audio_alerts.evaluate_live_alerts(
|
||||
hud_ctrl_snapshot.armed,
|
||||
telem_snapshot.is_live(),
|
||||
telem_snapshot.cell_voltage_v(bat_cells),
|
||||
bat_warn,
|
||||
bat_crit,
|
||||
if telem_snapshot.is_live() {
|
||||
Some(telem_snapshot.link_quality_pct)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
);
|
||||
let extra_osd = OsdExtraOptions {
|
||||
battery_cells: bat_cells,
|
||||
battery_warn_cell_v: bat_warn,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::vr_menu::VrMenuState;
|
||||
use crate::audio_alerts::AudioAlertEngine;
|
||||
use crate::config::AppConfig;
|
||||
use crate::controller::{ControlSource, GearSpeedLimits, SteamControllerState};
|
||||
use crate::dome_projection::{ProjectionMode, VrLockMode};
|
||||
@@ -159,6 +160,8 @@ pub struct EngineSharedState {
|
||||
pub replay_save_requested: Arc<AtomicBool>,
|
||||
/// Paramètres batterie live : `(cells, warn_cell_v, crit_cell_v)`
|
||||
pub battery_params: Arc<Mutex<(u8, f32, f32)>>,
|
||||
/// Moteur d'alertes audio PCM non-bloquant (GStreamer `appsrc ! autoaudiosink`)
|
||||
pub audio_alerts: Arc<AudioAlertEngine>,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
mod audio_alerts;
|
||||
mod config;
|
||||
mod controller;
|
||||
mod dome_projection;
|
||||
|
||||
@@ -88,6 +88,8 @@ mod tests {
|
||||
dvr_recording: false,
|
||||
gear_3_max: 1220,
|
||||
vibration_pct: 100,
|
||||
audio_alerts_on: true,
|
||||
audio_volume_pct: 70,
|
||||
wifi_channel: 161,
|
||||
quit_confirm_pending: false,
|
||||
feedback_msg: Some((StackStr::from_truncated("TARE HT OK"), false)),
|
||||
|
||||
@@ -24,7 +24,7 @@ impl VrMenuPage {
|
||||
/// Nombre d'entrées dans le menu principal minimaliste VR (actions essentielles).
|
||||
pub const VR_MENU_MAIN_COUNT: usize = 9;
|
||||
/// Nombre d'entrées dans le sous-menu Avancé VR.
|
||||
pub const VR_MENU_ADV_COUNT: usize = 9;
|
||||
pub const VR_MENU_ADV_COUNT: usize = 10;
|
||||
|
||||
/// Données d'affichage zéro-allocation (`Copy`) pour le Menu Minimaliste VR dans le casque.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@@ -44,6 +44,8 @@ pub struct VrMenuRenderData {
|
||||
pub dvr_recording: bool,
|
||||
pub gear_3_max: u16,
|
||||
pub vibration_pct: u8,
|
||||
pub audio_alerts_on: bool,
|
||||
pub audio_volume_pct: u8,
|
||||
pub wifi_channel: u16,
|
||||
pub quit_confirm_pending: bool,
|
||||
pub feedback_msg: Option<(StackStr<48>, bool)>,
|
||||
@@ -707,6 +709,16 @@ impl OsdOverlay {
|
||||
let _ = write!(val_buf, "< {}% >", menu.vibration_pct);
|
||||
[100, 225, 255, 255]
|
||||
}
|
||||
(VrMenuPage::Advanced, 8) => {
|
||||
let _ = write!(label_buf, "{}ALERTES AUDIO", prefix);
|
||||
if menu.audio_alerts_on && menu.audio_volume_pct > 0 {
|
||||
let _ = write!(val_buf, "< {}% >", menu.audio_volume_pct);
|
||||
[90, 255, 130, 255]
|
||||
} else {
|
||||
let _ = write!(val_buf, "< OFF >");
|
||||
[160, 175, 195, 255]
|
||||
}
|
||||
}
|
||||
(VrMenuPage::Advanced, _) => {
|
||||
let _ = write!(label_buf, "{}CANAL RADXA 5.8G", prefix);
|
||||
let _ = write!(val_buf, "< CH {} >", menu.wifi_channel);
|
||||
|
||||
@@ -363,6 +363,99 @@ self.render_settings_card(
|
||||
.text_xs()
|
||||
.text_color(rgb(COLOR_TEXT_MAIN))
|
||||
.child(format!("0.0.0.0:{}", self.cfg.telemetry_udp_port)),
|
||||
))
|
||||
.child(self.render_setting_row(
|
||||
"Alertes Audio Casque (Batterie / LQ / Armement / DVR)",
|
||||
div()
|
||||
.flex()
|
||||
.flex_wrap()
|
||||
.items_center()
|
||||
.gap_2()
|
||||
.child(self.render_selectable_pill(
|
||||
"pill_audio_on",
|
||||
"🔊 Activées",
|
||||
self.cfg.audio_alerts_enabled,
|
||||
cx.listener(|this, _, _, cx| {
|
||||
this.cfg.audio_alerts_enabled = true;
|
||||
this.controls.set_audio_alerts_enabled(true);
|
||||
cx.notify();
|
||||
}),
|
||||
))
|
||||
.child(self.render_selectable_pill(
|
||||
"pill_audio_off",
|
||||
"🔇 Muet",
|
||||
!self.cfg.audio_alerts_enabled,
|
||||
cx.listener(|this, _, _, cx| {
|
||||
this.cfg.audio_alerts_enabled = false;
|
||||
this.controls.set_audio_alerts_enabled(false);
|
||||
cx.notify();
|
||||
}),
|
||||
))
|
||||
.child(
|
||||
div()
|
||||
.id("btn_audio_vol_down")
|
||||
.px_2p5()
|
||||
.py_1()
|
||||
.rounded_md()
|
||||
.bg(rgb(COLOR_SURFACE_ELEVATED))
|
||||
.border_1()
|
||||
.border_color(rgb(COLOR_BORDER_SUBTLE))
|
||||
.text_xs()
|
||||
.font_weight(gpui::FontWeight::BOLD)
|
||||
.text_color(rgb(COLOR_TEXT_MAIN))
|
||||
.cursor_pointer()
|
||||
.on_click(cx.listener(|this, _, _, cx| {
|
||||
let next = this.cfg.audio_volume_pct.saturating_sub(10);
|
||||
this.cfg.audio_volume_pct = next;
|
||||
this.controls.set_audio_volume_pct(next);
|
||||
cx.notify();
|
||||
}))
|
||||
.child("-10%"),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_xs()
|
||||
.font_weight(gpui::FontWeight::BOLD)
|
||||
.text_color(rgb(COLOR_CYAN))
|
||||
.child(format!("{}%", self.cfg.audio_volume_pct)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.id("btn_audio_vol_up")
|
||||
.px_2p5()
|
||||
.py_1()
|
||||
.rounded_md()
|
||||
.bg(rgb(COLOR_SURFACE_ELEVATED))
|
||||
.border_1()
|
||||
.border_color(rgb(COLOR_BORDER_SUBTLE))
|
||||
.text_xs()
|
||||
.font_weight(gpui::FontWeight::BOLD)
|
||||
.text_color(rgb(COLOR_TEXT_MAIN))
|
||||
.cursor_pointer()
|
||||
.on_click(cx.listener(|this, _, _, cx| {
|
||||
let next = (this.cfg.audio_volume_pct + 10).min(100);
|
||||
this.cfg.audio_volume_pct = next;
|
||||
this.controls.set_audio_volume_pct(next);
|
||||
cx.notify();
|
||||
}))
|
||||
.child("+10%"),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.id("btn_audio_test_beep")
|
||||
.px_2p5()
|
||||
.py_1()
|
||||
.rounded_md()
|
||||
.bg(rgb(COLOR_CYAN))
|
||||
.text_color(rgb(0x000000))
|
||||
.text_xs()
|
||||
.font_weight(gpui::FontWeight::BOLD)
|
||||
.cursor_pointer()
|
||||
.on_click(cx.listener(|this, _, _, _cx| {
|
||||
this.controls.trigger_audio_test_beep();
|
||||
}))
|
||||
.child("🔔 Tester Bip"),
|
||||
),
|
||||
)),
|
||||
)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user