v0.6.11 — Native PulseAudio / PipeWire audio output

Replaced external `pw-play` / `paplay` subprocesses and temporary WAV files
with two dedicated Rust playback workers using `libpulse-simple-binding`.
The existing two-tone alarm sounds, SpO₂-dependent QRS tones, rhythms, mute
controls, alarm priorities and selective alarm-pause logic are retained.
A manual test tone remains available with audible alarms switched off.
Flatpak requires the PulseAudio socket and `libpulse-simple` in its SDK/runtime.
This commit is contained in:
GABRIEL Sebastian 2026-11-13 20:09:25 +01:00
commit 56f9f2e932
12 changed files with 2071 additions and 247 deletions

View file

@ -0,0 +1,763 @@
diff --git a/Cargo.toml b/Cargo.toml
index e9b87df..c19e486 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,9 +1,11 @@
[package]
name = "patient-monitor-simulation"
-version = "0.6.10"
+version = "0.6.11"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
[dependencies]
gtk = { package = "gtk4", version = "0.11" }
+libpulse-binding = "2.30.1"
+libpulse-simple-binding = "2.29.0"
diff --git a/README.de.md b/README.de.md
index 3743f15..457310f 100644
--- a/README.de.md
+++ b/README.de.md
@@ -1,4 +1,4 @@
-# SimPaM — Patientenmonitor-Simulation v0.6.10
+# SimPaM — Patientenmonitor-Simulation v0.6.11
Der in Rust/GTK4 entwickelte **SimPaM** simuliert einen Patientenmonitor
für die Lehre unter Fedora Linux. Die Anwendung besitzt ein **Admin-Fenster**
@@ -38,7 +38,7 @@ Intensiv- und Notfallmedizin. Die Lehrperson kann Parameter unmittelbar
### Installation, Kompilierung und Start unter Fedora
```bash
-sudo dnf install rust cargo gcc pkgconf-pkg-config gtk4-devel pipewire-utils
+sudo dnf install rust cargo gcc pkgconf-pkg-config gtk4-devel pulseaudio-libs-devel
cargo test
cargo run --release
```
@@ -551,7 +551,7 @@ Standardmäßig sind alle numerischen Alarme deaktiviert, damit bestehende Unter
Numerische Grenzwertalarme werden nur für tatsächlich verfügbare Messwerte ausgewertet.
`--`, `NO SENSOR` und andere nicht verfügbare Anzeigen lösen keine numerischen Untergrenzenalarme aus.
Die aus dem EKG abgeleitete Pulsfrequenz und die Sichtbarkeit der Signale funktionieren weiterhin wie in v0.3.2.
-Alarme sind derzeit rein visuell: Es gibt **keine akustischen Alarme, Alarmspeicherung bis zur Quittierung, Prioritätsklassifizierung oder klinische Alarmvalidierung**.
+Akustische Alarme und Tonprioritäten werden unterstützt; eine klinisch validierte Alarmierung oder Alarmspeicherung bis zur Quittierung existiert nicht.
Die Einstellungen bleiben nur während der laufenden Programmsitzung erhalten und werden beim Neustart zurückgesetzt.
### Akustische Alarme und QRS-Ton (aktualisiert v0.6.7)
@@ -616,12 +616,17 @@ Die Frequenzen sind ausschließlich didaktische Simulationen, keine
kalibrierten Töne eines klinischen Pulsoxymeters. QRS-/Pulston und
Zweitonalarm können unabhängig voneinander erklingen.
-Unter Fedora wird **`pw-play`** aus dem Paket `pipewire-utils` verwendet,
-alternativ **`paplay`**. Es sind weder zusätzliche Rust-Bibliotheken noch
-mitzuliefernde Audiodateien notwendig: Das Programm erzeugt seine WAV-Töne
-zur Laufzeit. Falls kein Wiedergabeprogramm verfügbar ist, erscheint im
-Admin-Fenster ein entsprechender Hinweis; der Monitor bleibt funktionstüchtig.
-Wiedergabegerät und Lautstärke werden über die Systemeinstellungen verwaltet.
+Seit **v0.6.11** erfolgt die Tonausgabe unmittelbar über die Rust-Bibliothek
+`libpulse-simple-binding`, ohne `pw-play` oder `paplay` aufzurufen.
+SimPaM erzeugt die bisherigen Signale als Mono-PCM mit 44,1 kHz und
+16 Bit im Arbeitsspeicher. Zwei getrennte PulseAudio-Wiedergabeströme
+(Alarme und QRS-Töne) besitzen jeweils einen eigenen Worker-Thread.
+Dadurch blockiert die synchrone Audioausgabe nicht die GTK-Oberfläche.
+PipeWire stellt hierfür seine PulseAudio-Kompatibilität bereit.
+Verbindungs- und Ausgabefehler werden protokolliert; bei der nächsten
+Tonausgabe kann die Verbindung erneut aufgebaut werden. Der Testton
+funktioniert unabhängig von der Alarmstummschaltung. Temporäre
+WAV-Dateien und externe Wiedergabeprogramme entfallen.
**Wichtig:** Diese didaktischen Tonsignale entsprechen nicht den Anforderungen
an Medizinproduktealarme (insbesondere IEC 60601-1-8) und dürfen nicht zur
@@ -665,6 +670,23 @@ src/
ui.rs Admin-Bedienelemente und Monitorfenster
```
+### Audioausgabe in Flatpak
+
+In der Flatpak-Konfiguration muss `--socket=pulseaudio` erhalten bleiben.
+Prüfen, ob das **verwendete SDK** die Entwicklungsdateien für `libpulse-simple`
+enthält:
+
+```bash
+flatpak run --command=sh org.gnome.Sdk//51 \
+ -c 'pkg-config --modversion libpulse-simple'
+```
+
+Die dazugehörigen Laufzeitbibliotheken müssen in der Flatpak-Runtime
+vorhanden sein. `pipewire-utils` wird auf dem Host nicht mehr benötigt.
+Nach dem Aktualisieren von `Cargo.lock` muss `cargo-sources.json` mit
+`flatpak-cargo-generator` neu erzeugt werden. Das vorhandene Flatpak-Manifest
+wird gesondert gepflegt und ist nicht Teil dieser Quellcodeänderung.
+
## Changelog
### Änderungen seit v0.2.2
@@ -852,3 +874,12 @@ gelbe Defibrillation-Schaltfläche mit rotem Blitz löst nur das kurzzeitige
Defibrillationsartefakt im EKG aus. Die Rhythmuskonversion bleibt eine separate
Maßnahme.
+
+### v0.6.11 – Native Audioausgabe über PulseAudio / PipeWire
+
+Externe Aufrufe von `pw-play`/`paplay` und temporäre WAV-Dateien wurden durch
+zwei Rust-Worker mit `libpulse-simple-binding` ersetzt. Zweitonige Alarme,
+sättigungsabhängige QRS-Töne, Stummschaltung, Alarmprioritäten und die
+selektive zweiminütige Alarmpause bleiben erhalten. Der Testton ist auch bei
+deaktivierten akustischen Alarmen verfügbar. In Flatpak werden die
+PulseAudio-Socket-Berechtigung und `libpulse-simple` benötigt.
diff --git a/README.md b/README.md
index 0eb2732..30ee6f0 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# SimPaM — Patient Monitor Simulation v0.6.10
+# SimPaM — Patient Monitor Simulation v0.6.11
A Rust/GTK4 patient-monitor simulator with two main windows for teaching on Fedora Linux.
@@ -38,7 +38,7 @@ monitoring.
### Build and run on Fedora
```bash
-sudo dnf install rust cargo gcc pkgconf-pkg-config gtk4-devel pipewire-utils
+sudo dnf install rust cargo gcc pkgconf-pkg-config gtk4-devel pulseaudio-libs-devel
cargo test
cargo run --release
```
@@ -553,9 +553,9 @@ scenarios do not unexpectedly flash.
Numerical threshold alarms only evaluate actual displayed measurements:
`--`, `NO SENSOR`, and other unavailable readings do not trigger low-value
alarms. ECG-derived PR and signal visibility continue to work as in v0.3.2.
-Alarms are presentation-only: there is **no audible alarm, alarm latching,
-priority classification or clinical alarm validation**. Instructor settings
-are held in memory and reset on restart.
+Audible alarms with two priorities are supported, but there is **no alarm
+latching or clinical alarm validation**. Instructor settings are held in
+memory and reset on restart.
### Audible alarms and QRS tone (updated v0.6.7)
@@ -614,12 +614,16 @@ Saturation tone pitches are deliberately simplified teaching tones, not
calibrated clinical pulse-oximeter sounds. The QRS beep and two-tone alarm can
sound independently; no alarm priority or visual alarm logic was changed.
-On Fedora, sound is played through **`pw-play`** from `pipewire-utils`, with
-**`paplay`** as a fallback. No additional Rust crates or sound files are needed:
-the application creates its own short WAV tones at runtime. If neither player
-is installed, Admin reports that audio is unavailable; the monitor continues
-to work normally. `Test tone` helps verify the desktop audio output. The
-application uses the system output device and mixer volume.
+As of **v0.6.11**, audio uses the Rust `libpulse-simple-binding` backend
+directly, rather than launching `pw-play` or `paplay`. SimPaM synthesizes
+the same 44.1 kHz mono PCM16 tones in memory and sends them to two
+independent PulseAudio streams (alarm and QRS). Each stream has a
+dedicated playback thread so synchronous audio I/O never blocks GTK.
+PipeWire supports this through its PulseAudio compatibility server.
+The system mixer controls output volume. If connecting or writing to
+the audio server fails, the worker logs an error and can retry on the
+next sound. `Test tone` verifies playback independently of the mute
+checkbox. No temporary WAV files or external player programs are used.
**Important:** These simple teaching tones do not comply with medical-device
alarm standards (including IEC 60601-1-8) and must never be relied on for
@@ -665,6 +669,8 @@ are simulated.
```text
src/
main.rs GTK application entry point
+ audio_backend.rs Native PulseAudio playback workers
+ alarm.rs Alarm/QRS tone synthesis, scheduling and pause
model.rs Parameters, rhythm/capture settings, display flags
simulation.rs QRS-timed mechanical signals, PPV and respiratory synthesis
render.rs Cairo monitor layout, dynamic visibility, fixed ART axis
@@ -672,6 +678,23 @@ src/
ui.rs Admin controls and monitor window
```
+### Building audio in Flatpak
+
+For Flatpak, keep `--socket=pulseaudio` in `finish-args` and verify the
+**target SDK** provides the `libpulse-simple` development library:
+
+```bash
+flatpak run --command=sh org.gnome.Sdk//51 \
+ -c 'pkg-config --modversion libpulse-simple'
+```
+
+The Flatpak runtime must also ship the corresponding shared libraries.
+The host's `pipewire-utils` package is no longer required. Update `Cargo.lock`
+with Cargo after changing dependencies, then regenerate `cargo-sources.json`
+using `flatpak-cargo-generator` before building offline. The project archive
+contains application sources; an existing Flatpak manifest is maintained
+separately and was not modified by this update.
+
## Changelog
### Changes since v0.2.2
@@ -855,3 +878,12 @@ same controls are now permanently available. A high-contrast yellow one-tap
Defibrillation button with a red lightning symbol triggers only the transient
ECG shock artifact; rhythm conversion remains available as a separate action.
+
+### v0.6.11 — Native PulseAudio / PipeWire audio output
+
+Replaced external `pw-play` / `paplay` subprocesses and temporary WAV files
+with two dedicated Rust playback workers using `libpulse-simple-binding`.
+The existing two-tone alarm sounds, SpO₂-dependent QRS tones, rhythms, mute
+controls, alarm priorities and selective alarm-pause logic are retained.
+A manual test tone remains available with audible alarms switched off.
+Flatpak requires the PulseAudio socket and `libpulse-simple` in its SDK/runtime.
diff --git a/src/alarm.rs b/src/alarm.rs
index f992589..bb0c521 100644
--- a/src/alarm.rs
+++ b/src/alarm.rs
@@ -1,17 +1,14 @@
//! Audible teaching alarms. This is not a clinical alarm system.
//!
//! The decision uses the same available readings, visibility settings and limits
-//! as the monitor. Sound is played using Fedora's PipeWire command-line player
-//! (or paplay) without adding a native audio-library dependency to Cargo.
+//! as the monitor. Pre-synthesized PCM audio is sent to independent
+//! PulseAudio/PipeWire streams by dedicated workers, never from the GTK thread.
use std::collections::{BTreeMap, BTreeSet};
-use std::env;
-use std::fs::{self, OpenOptions};
-use std::io::{self, Write};
-use std::path::{Path, PathBuf};
-use std::process::{Child, Command, Stdio};
-use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+use crate::audio_backend::PulseAudioWorker;
use crate::model::{AlarmLimits, AlarmState, EcgRhythm, Parameters, PulseConduction, Spo2Status};
use crate::simulation::{BeatEvent, BeatSource, Simulator};
@@ -276,269 +273,145 @@ fn wav(critical: bool) -> Vec<u8> {
bytes
}
-struct SoundFiles {
- standard: PathBuf,
- critical: PathBuf,
+// Keep the original waveform synthesis (and WAV unit tests), but send only
+// the PCM payload to the audio server. No temporary files or subprocesses.
+fn pcm(wav_bytes: Vec<u8>) -> Arc<[u8]> {
+ debug_assert_eq!(&wav_bytes[0..4], b"RIFF");
+ debug_assert_eq!(&wav_bytes[8..12], b"WAVE");
+ debug_assert_eq!(&wav_bytes[36..40], b"data");
+ Arc::from(&wav_bytes[44..])
}
-impl Drop for SoundFiles {
- fn drop(&mut self) {
- let _ = fs::remove_file(&self.standard);
- let _ = fs::remove_file(&self.critical);
- }
-}
-
-fn write_new(path: &Path, content: &[u8]) -> io::Result<()> {
- let mut out = OpenOptions::new().write(true).create_new(true).open(path)?;
- out.write_all(content)
+struct AlarmSamples {
+ standard: Arc<[u8]>,
+ critical: Arc<[u8]>,
}
-impl SoundFiles {
- fn create_in(directory: &Path) -> io::Result<Self> {
- let nonce = SystemTime::now().duration_since(UNIX_EPOCH)
- .unwrap_or_default().as_nanos();
- let prefix = format!("pamsim-{}-{nonce}", std::process::id());
- let standard = directory.join(format!("{prefix}-alarm.wav"));
- let critical = directory.join(format!("{prefix}-critical.wav"));
- write_new(&standard, &wav(false))?;
- if let Err(err) = write_new(&critical, &wav(true)) {
- let _ = fs::remove_file(&standard);
- return Err(err);
- }
- Ok(Self { standard, critical })
- }
-
- fn create() -> io::Result<Self> {
- if let Some(runtime) = env::var_os("XDG_RUNTIME_DIR") {
- if let Ok(files) = Self::create_in(Path::new(&runtime)) {
- return Ok(files);
- }
- }
- Self::create_in(&env::temp_dir())
+impl AlarmSamples {
+ fn new() -> Self {
+ Self { standard: pcm(wav(false)), critical: pcm(wav(true)) }
}
}
-/// Prepared once on startup. Reuse the same playback utility as the alarms,
-/// but use an independent child so the two-tone alarm is never interrupted by
-/// single QRS/pulse beeps.
-struct QrsSoundFiles {
- mid: PathBuf,
- saturations: Vec<PathBuf>,
-}
-
-impl Drop for QrsSoundFiles {
- fn drop(&mut self) {
- let _ = fs::remove_file(&self.mid);
- for file in &self.saturations { let _ = fs::remove_file(file); }
- }
+struct QrsSamples {
+ mid: Arc<[u8]>,
+ saturations: Vec<Arc<[u8]>>,
}
-impl QrsSoundFiles {
- fn create_in(directory: &Path) -> io::Result<Self> {
- let nonce = SystemTime::now().duration_since(UNIX_EPOCH)
- .unwrap_or_default().as_nanos();
- let prefix = format!("pamsim-qrs-{}-{nonce}", std::process::id());
- let mid = directory.join(format!("{prefix}-mid.wav"));
- write_new(&mid, &single_beep_wav(QRS_MID_HZ))?;
- let mut files = Self { mid, saturations: Vec::new() };
- for (i, &frequency) in QRS_SPO2_HZ.iter().enumerate() {
- let path = directory.join(format!("{prefix}-spo2-{i}.wav"));
- write_new(&path, &single_beep_wav(frequency))?;
- files.saturations.push(path);
- }
- Ok(files)
- }
-
- fn create() -> io::Result<Self> {
- if let Some(runtime) = env::var_os("XDG_RUNTIME_DIR") {
- if let Ok(files) = Self::create_in(Path::new(&runtime)) {
- return Ok(files);
- }
+impl QrsSamples {
+ fn new() -> Self {
+ Self {
+ mid: pcm(single_beep_wav(QRS_MID_HZ)),
+ saturations: QRS_SPO2_HZ.iter()
+ .map(|&hz| pcm(single_beep_wav(hz))).collect(),
}
- Self::create_in(&env::temp_dir())
}
- fn path(&self, tone: QrsTone) -> &Path {
+ fn get(&self, tone: QrsTone) -> Arc<[u8]> {
match tone {
- QrsTone::Mid => &self.mid,
- QrsTone::Saturation(index) => &self.saturations[index.min(self.saturations.len() - 1)],
+ QrsTone::Mid => self.mid.clone(),
+ QrsTone::Saturation(index) => self.saturations
+ .get(index).unwrap_or(&self.mid).clone(),
}
}
}
+/// A dedicated audio stream for QRS/pulse sounds. GTK never waits for playback.
+/// A separate stream handles the two-tone alarms so both can sound concurrently.
pub struct QrsAudio {
- player: Option<&'static str>,
- files: Option<QrsSoundFiles>,
- child: Option<Child>,
- error_reported: bool,
+ worker: Option<PulseAudioWorker>,
+ samples: QrsSamples,
+ enabled_last_tick: bool,
}
impl QrsAudio {
pub fn new() -> Self {
- let player = ["pw-play", "paplay"].into_iter().find(|name| command_on_path(name));
- let files = if player.is_some() {
- match QrsSoundFiles::create() {
- Ok(files) => Some(files),
- Err(error) => {
- eprintln!("PaMSim: cannot prepare QRS beeps: {error}");
- None
- }
+ let worker = match PulseAudioWorker::new("QRS / pulse") {
+ Ok(worker) => Some(worker),
+ Err(error) => {
+ eprintln!("SimPaM: cannot start QRS audio worker: {error}");
+ None
}
- } else { None };
- Self { player, files, child: None, error_reported: false }
- }
-
- fn stop_child(&mut self) {
- if let Some(mut child) = self.child.take() {
- let _ = child.kill();
- let _ = child.wait();
- }
+ };
+ Self { worker, samples: QrsSamples::new(), enabled_last_tick: false }
}
- /// The audio timer delivers at most one beat in a 100-ms tick. Do not
- /// replay events after disabling sound; do not restart an active beep.
+ /// The caller supplies only newly occurring beats every 100 ms. PCM is
+ /// queued on a worker thread and never written from the GTK event loop.
pub fn update(&mut self, tone: Option<QrsTone>, enabled: bool) {
if !enabled {
- self.stop_child();
- return;
- }
- if let Some(child) = self.child.as_mut() {
- match child.try_wait() {
- Ok(Some(_)) | Err(_) => self.child = None,
- Ok(None) => return,
+ if self.enabled_last_tick {
+ if let Some(worker) = &self.worker { worker.stop(); }
}
+ self.enabled_last_tick = false;
+ return;
}
- let (Some(tone), Some(player), Some(files)) = (tone, self.player, self.files.as_ref())
- else { return; };
- match Command::new(player).arg(files.path(tone))
- .stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn()
- {
- Ok(child) => self.child = Some(child),
- Err(error) if !self.error_reported => {
- eprintln!("PaMSim: QRS sound playback failed: {error}");
- self.error_reported = true;
- }
- Err(_) => {}
+ self.enabled_last_tick = true;
+ if let (Some(tone), Some(worker)) = (tone, &self.worker) {
+ worker.play(self.samples.get(tone));
}
}
}
-impl Drop for QrsAudio {
- fn drop(&mut self) { self.stop_child(); }
-}
-
-fn command_on_path(name: &str) -> bool {
- env::var_os("PATH").is_some_and(|paths| {
- env::split_paths(&paths).any(|dir| {
- let candidate = dir.join(name);
- if !candidate.is_file() { return false; }
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- fs::metadata(&candidate).is_ok_and(|meta| meta.permissions().mode() & 0o111 != 0)
- }
- #[cfg(not(unix))]
- { true }
- })
- })
-}
-
-/// Sound playback runs outside the GTK drawing callback. At most one short
-/// player process exists at a time; stopping or muting kills an active tone.
+/// Short-lived audio triggers are scheduled here, while connection and sample
+/// writes happen asynchronously in a worker owning a persistent PA stream.
pub struct AlarmAudio {
- player: Option<&'static str>,
- files: Option<SoundFiles>,
- child: Option<Child>,
+ worker: Option<PulseAudioWorker>,
+ samples: AlarmSamples,
previous: AlarmLevel,
next_at: Instant,
- error_reported: bool,
+ test_until: Option<Instant>,
}
impl AlarmAudio {
pub fn new() -> Self {
- let player = ["pw-play", "paplay"].into_iter().find(|name| command_on_path(name));
- let files = if player.is_some() {
- match SoundFiles::create() {
- Ok(files) => Some(files),
- Err(error) => {
- eprintln!("PaMSim: cannot prepare alarm tones: {error}");
- None
- }
+ let worker = match PulseAudioWorker::new("Alarm") {
+ Ok(worker) => Some(worker),
+ Err(error) => {
+ eprintln!("SimPaM: cannot start alarm audio worker: {error}");
+ None
}
- } else { None };
- if player.is_none() {
- eprintln!("PaMSim: alarm audio unavailable; install pipewire-utils (pw-play) on Fedora.");
- }
+ };
Self {
- player, files, child: None, previous: AlarmLevel::None,
- next_at: Instant::now(), error_reported: false,
+ worker, samples: AlarmSamples::new(), previous: AlarmLevel::None,
+ next_at: Instant::now(), test_until: None,
}
}
+ /// Reports whether the thread started; PulseAudio connection errors are
+ /// logged by the worker because connecting must never block GTK startup.
pub fn available(&self) -> bool {
- self.player.is_some() && self.files.is_some()
- }
-
- fn stop_child(&mut self) {
- if let Some(mut child) = self.child.take() {
- let _ = child.kill();
- let _ = child.wait();
- }
+ self.worker.is_some()
}
- fn reap(&mut self) {
- if let Some(child) = self.child.as_mut() {
- match child.try_wait() {
- Ok(Some(status)) => {
- self.child = None;
- if !status.success() && !self.error_reported {
- eprintln!("PaMSim: alarm sound player exited with {status}; check PipeWire and the output device.");
- self.error_reported = true;
- }
- }
- Err(error) => {
- self.child = None;
- if !self.error_reported {
- eprintln!("PaMSim: could not check alarm playback: {error}");
- self.error_reported = true;
- }
- }
- Ok(None) => {}
- }
+ fn play(&self, level: AlarmLevel) {
+ if let Some(worker) = &self.worker {
+ let samples = if level == AlarmLevel::Critical {
+ &self.samples.critical
+ } else { &self.samples.standard };
+ worker.play(samples.clone());
}
}
- fn play(&mut self, level: AlarmLevel) {
- self.reap();
- if self.child.is_some() { return; }
- let (Some(player), Some(files)) = (self.player, self.files.as_ref()) else { return; };
- let filename = if level == AlarmLevel::Critical { &files.critical } else { &files.standard };
- match Command::new(player).arg(filename)
- .stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn()
- {
- Ok(child) => self.child = Some(child),
- Err(error) if !self.error_reported => {
- eprintln!("PaMSim: alarm sound playback failed: {error}");
- self.error_reported = true;
- }
- Err(_) => {}
- }
+ fn stop(&self) {
+ if let Some(worker) = &self.worker { worker.stop(); }
}
- /// Called from a 100-ms GLib timer, not the 250-Hz waveform simulator.
- /// Critical rhythms: higher-pitched two-tone alert every 1.5 s;
- /// other alarms: lower-pitched two-tone alert every 2.5 s.
- /// Stop promptly when muted or all alarm states clear.
+ /// Called from a 100-ms GLib timer, not the waveform renderer.
+ /// Critical alerts repeat every 1.5 s, standard alerts every 2.5 s.
pub fn update(&mut self, level: AlarmLevel, enabled: bool) {
- self.reap();
+ let now = Instant::now();
+ if self.test_until.is_some_and(|deadline| now < deadline) {
+ return; // Finish a manual test even if audible alarms are muted.
+ }
+ self.test_until = None;
if !enabled || level == AlarmLevel::None {
- self.stop_child();
+ if self.previous != AlarmLevel::None { self.stop(); }
self.previous = AlarmLevel::None;
return;
}
- let now = Instant::now();
if level != self.previous {
- self.stop_child();
+ self.stop();
self.previous = level;
self.next_at = now;
}
@@ -550,20 +423,16 @@ impl AlarmAudio {
}
}
- /// Manual test is independent of the audible-alarm enable checkbox.
+ /// Test is independent of the audible-alarm enable checkbox.
pub fn test(&mut self) {
- self.stop_child();
+ self.stop();
self.play(AlarmLevel::Standard);
+ self.test_until = Some(Instant::now() + Duration::from_millis(340));
+ self.previous = AlarmLevel::None;
self.next_at = Instant::now() + Duration::from_millis(2500);
}
}
-impl Drop for AlarmAudio {
- fn drop(&mut self) {
- self.stop_child();
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -687,6 +556,17 @@ mod tests {
assert_ne!(single_beep_wav(740.0), single_beep_wav(87.0));
}
+ #[test]
+ fn wav_payload_can_be_streamed_as_mono_pcm16_without_header() {
+ for bytes in [wav(false), wav(true), single_beep_wav(740.0)] {
+ let payload = pcm(bytes.clone());
+ assert_eq!(payload.len() + 44, bytes.len());
+ assert_eq!(&*payload, &bytes[44..]);
+ assert_eq!(payload.len() % 2, 0);
+ assert!(!payload.is_empty());
+ }
+ }
+
#[test]
fn valid_wav_files_and_distinct_tone_patterns() {
for critical in [false, true] {
diff --git a/src/audio_backend.rs b/src/audio_backend.rs
new file mode 100644
index 0000000..a38616b
--- /dev/null
+++ b/src/audio_backend.rs
@@ -0,0 +1,107 @@
+//! Non-blocking GTK-facing audio delivery via PulseAudio's simple API.
+//!
+//! The libpulse-simple API is synchronous; each independent output has its
+//! own Rust worker thread and its own persistent playback stream. PipeWire's
+//! PulseAudio compatibility server accepts these streams in Fedora/Flatpak.
+//! The GTK thread only sends commands and never opens the audio connection.
+
+use std::io;
+use std::sync::{mpsc, Arc};
+use std::thread;
+
+use libpulse_binding as pulse;
+use libpulse_simple_binding::Simple;
+use pulse::sample::{Format, Spec};
+use pulse::stream::Direction;
+
+/// Generated sounds are mono, 16-bit little-endian PCM at 44.1 kHz.
+const SAMPLE_RATE: u32 = 44_100;
+
+enum Command {
+ Play(Arc<[u8]>),
+ Stop,
+}
+
+/// A channel is intentionally unbounded: STOP and silence cannot be lost if
+/// a synchronous write is still in progress. The worker coalesces queued
+/// commands so stale pulses never accumulate while the server is busy.
+pub struct PulseAudioWorker {
+ tx: mpsc::Sender<Command>,
+}
+
+impl PulseAudioWorker {
+ pub fn new(stream_name: &'static str) -> io::Result<Self> {
+ let (tx, rx) = mpsc::channel();
+ thread::Builder::new()
+ .name(format!("SimPaM audio: {stream_name}"))
+ .spawn(move || playback_loop(stream_name, rx))?;
+ Ok(Self { tx })
+ }
+
+ pub fn play(&self, pcm_samples: Arc<[u8]>) {
+ let _ = self.tx.send(Command::Play(pcm_samples));
+ }
+
+ pub fn stop(&self) {
+ let _ = self.tx.send(Command::Stop);
+ }
+}
+
+fn playback_loop(stream_name: &str, rx: mpsc::Receiver<Command>) {
+ let spec = Spec { format: Format::S16le, channels: 1, rate: SAMPLE_RATE };
+ debug_assert!(spec.is_valid());
+ let mut stream: Option<Simple> = None;
+ let mut error_reported = false;
+
+ while let Ok(mut command) = rx.recv() {
+ // Only the most recent event matters. This also prioritizes a STOP
+ // received during a blocked write over any earlier queued beeps.
+ while let Ok(next) = rx.try_recv() { command = next; }
+
+ if matches!(&command, Command::Stop) {
+ if let Some(output) = &stream {
+ if output.flush().is_err() { stream = None; }
+ }
+ continue;
+ }
+
+ // Establish the PulseAudio connection on this worker, never GTK.
+ if stream.is_none() {
+ match Simple::new(None, "SimPaM", Direction::Playback, None,
+ stream_name, &spec, None, None) {
+ Ok(output) => { stream = Some(output); error_reported = false; }
+ Err(error) => {
+ if !error_reported {
+ eprintln!("SimPaM: {stream_name} audio connection failed: {error:?}");
+ error_reported = true;
+ }
+ continue; // Retry on the next requested sound.
+ }
+ }
+ }
+
+ // Connecting may have taken some time. Do not play an obsolete beep
+ // when the instructor muted alarms in the meantime.
+ while let Ok(next) = rx.try_recv() { command = next; }
+ match command {
+ Command::Stop => {
+ if let Some(output) = &stream {
+ if output.flush().is_err() { stream = None; }
+ }
+ }
+ Command::Play(samples) => {
+ if let Some(output) = &stream {
+ // Flush any previous queued samples on *this* stream to
+ // minimize latency when the pitch or alarm priority changes.
+ if let Err(error) = output.flush().and_then(|_| output.write(&samples)) {
+ if !error_reported {
+ eprintln!("SimPaM: {stream_name} audio write failed: {error:?}");
+ error_reported = true;
+ }
+ stream = None; // Reconnect on the next command.
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/main.rs b/src/main.rs
index 85b412d..f196d5f 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,4 +1,5 @@
mod actions;
+mod audio_backend;
mod alarm;
mod model;
mod nibp;
diff --git a/src/ui.rs b/src/ui.rs
index 80effa8..2fab238 100644
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -285,7 +285,7 @@ fn create_admin(app: &Application, params: SharedParams,
});
sound_row.append(&test_sound);
if !audio.borrow().available() {
- let missing = gtk::Label::new(Some("Audio unavailable — install pipewire-utils"));
+ let missing = gtk::Label::new(Some("Audio worker unavailable"));
missing.set_xalign(0.0);
sound_row.append(&missing);
}