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

@ -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);
struct AlarmSamples {
standard: Arc<[u8]>,
critical: Arc<[u8]>,
}
impl AlarmSamples {
fn new() -> Self {
Self { standard: pcm(wav(false)), critical: pcm(wav(true)) }
}
}
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 QrsSamples {
mid: Arc<[u8]>,
saturations: Vec<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);
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(),
}
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())
}
}
/// 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); }
}
}
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);
}
}
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 }
};
Self { worker, samples: QrsSamples::new(), enabled_last_tick: false }
}
fn stop_child(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
}
/// 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();
if self.enabled_last_tick {
if let Some(worker) = &self.worker { worker.stop(); }
}
self.enabled_last_tick = false;
return;
}
if let Some(child) = self.child.as_mut() {
match child.try_wait() {
Ok(Some(_)) | Err(_) => self.child = None,
Ok(None) => 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()
self.worker.is_some()
}
fn stop_child(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
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 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 stop(&self) {
if let Some(worker) = &self.worker { worker.stop(); }
}
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(_) => {}
}
}
/// 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] {

View file

@ -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.
}
}
}
}
}
}

View file

@ -1,4 +1,5 @@
mod actions;
mod audio_backend;
mod alarm;
mod model;
mod nibp;

View file

@ -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);
}