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)));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user