From 56f9f2e932bebf18858930ea48f33f39bee8b5b8 Mon Sep 17 00:00:00 2001 From: GABRIEL Sebastian Date: Fri, 13 Nov 2026 20:09:25 +0100 Subject: [PATCH] =?UTF-8?q?v0.6.11=20=E2=80=94=20Native=20PulseAudio=20/?= =?UTF-8?q?=20PipeWire=20audio=20output?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- patches/SimPaM-v0.6.10-to-v0.6.11.patch | 763 ++++++++++++++++ patient-monitor-simulation/Cargo.lock | 113 ++- patient-monitor-simulation/Cargo.toml | 4 +- patient-monitor-simulation/README.de.md | 49 +- patient-monitor-simulation/README.md | 54 +- .../at.criticalcare.SimPaM.desktop | 8 + .../at.criticalcare.SimPaM.yml | 57 ++ patient-monitor-simulation/cargo-sources.json | 840 ++++++++++++++++++ patient-monitor-simulation/src/alarm.rs | 324 +++---- .../src/audio_backend.rs | 107 +++ patient-monitor-simulation/src/main.rs | 1 + patient-monitor-simulation/src/ui.rs | 2 +- 12 files changed, 2073 insertions(+), 249 deletions(-) create mode 100644 patches/SimPaM-v0.6.10-to-v0.6.11.patch create mode 100644 patient-monitor-simulation/at.criticalcare.SimPaM.desktop create mode 100644 patient-monitor-simulation/at.criticalcare.SimPaM.yml create mode 100644 patient-monitor-simulation/cargo-sources.json create mode 100644 patient-monitor-simulation/src/audio_backend.rs diff --git a/patches/SimPaM-v0.6.10-to-v0.6.11.patch b/patches/SimPaM-v0.6.10-to-v0.6.11.patch new file mode 100644 index 0000000..ab702e3 --- /dev/null +++ b/patches/SimPaM-v0.6.10-to-v0.6.11.patch @@ -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 { + 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) -> 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 { +- 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 { +- 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, +-} +- +-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>, + } + +-impl QrsSoundFiles { +- fn create_in(directory: &Path) -> io::Result { +- 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 { +- 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, +- child: Option, +- error_reported: bool, ++ worker: Option, ++ 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, 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, +- child: Option, ++ worker: Option, ++ samples: AlarmSamples, + previous: AlarmLevel, + next_at: Instant, +- error_reported: bool, ++ test_until: Option, + } + + 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, ++} ++ ++impl PulseAudioWorker { ++ pub fn new(stream_name: &'static str) -> io::Result { ++ 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) { ++ let spec = Spec { format: Format::S16le, channels: 1, rate: SAMPLE_RATE }; ++ debug_assert!(spec.is_valid()); ++ let mut stream: Option = 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); + } diff --git a/patient-monitor-simulation/Cargo.lock b/patient-monitor-simulation/Cargo.lock index 5d3e624..0a9ecde 100644 --- a/patient-monitor-simulation/Cargo.lock +++ b/patient-monitor-simulation/Cargo.lock @@ -103,7 +103,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -242,7 +242,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -348,7 +348,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -398,6 +398,54 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libpulse-binding" +version = "2.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "909eb3049e16e373680fe65afe6e2a722ace06b671250cc4849557bc57d6a397" +dependencies = [ + "bitflags", + "libc", + "libpulse-sys", + "num-derive", + "num-traits", + "winapi", +] + +[[package]] +name = "libpulse-simple-binding" +version = "2.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7bebef0381c8e3e4b23cc24aaf36fab37472bece128de96f6a111efa464cfef" +dependencies = [ + "libpulse-binding", + "libpulse-simple-sys", + "libpulse-sys", +] + +[[package]] +name = "libpulse-simple-sys" +version = "1.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd96888fe37ad270d16abf5e82cccca1424871cf6afa2861824d2a52758eebc" +dependencies = [ + "libpulse-sys", + "pkg-config", +] + +[[package]] +name = "libpulse-sys" +version = "1.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d74371848b22e989f829cc1621d2ebd74960711557d8b45cfe740f60d0a05e61" +dependencies = [ + "libc", + "num-derive", + "num-traits", + "pkg-config", + "winapi", +] + [[package]] name = "memchr" version = "2.8.3" @@ -413,6 +461,26 @@ dependencies = [ "autocfg", ] +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + [[package]] name = "pango" version = "0.22.9" @@ -438,9 +506,11 @@ dependencies = [ [[package]] name = "patient-monitor-simulation" -version = "0.6.10" +version = "0.6.11" dependencies = [ "gtk4", + "libpulse-binding", + "libpulse-simple-binding", ] [[package]] @@ -514,7 +584,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -538,6 +608,17 @@ version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.10" @@ -631,6 +712,28 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + [[package]] name = "windows-link" version = "0.2.1" diff --git a/patient-monitor-simulation/Cargo.toml b/patient-monitor-simulation/Cargo.toml index e9b87df..c19e486 100644 --- a/patient-monitor-simulation/Cargo.toml +++ b/patient-monitor-simulation/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/patient-monitor-simulation/README.de.md b/patient-monitor-simulation/README.de.md index 3743f15..457310f 100644 --- a/patient-monitor-simulation/README.de.md +++ b/patient-monitor-simulation/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/patient-monitor-simulation/README.md b/patient-monitor-simulation/README.md index 0eb2732..30ee6f0 100644 --- a/patient-monitor-simulation/README.md +++ b/patient-monitor-simulation/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/patient-monitor-simulation/at.criticalcare.SimPaM.desktop b/patient-monitor-simulation/at.criticalcare.SimPaM.desktop new file mode 100644 index 0000000..1f21122 --- /dev/null +++ b/patient-monitor-simulation/at.criticalcare.SimPaM.desktop @@ -0,0 +1,8 @@ +[Desktop Entry] +Type=Application +Name=SimPaM +Comment=Patient Monitor Simulation +Exec=patient-monitor-simulation +Icon=at.criticalcare.SimPaM +Terminal=false +Categories=Education;Science; diff --git a/patient-monitor-simulation/at.criticalcare.SimPaM.yml b/patient-monitor-simulation/at.criticalcare.SimPaM.yml new file mode 100644 index 0000000..cf8838e --- /dev/null +++ b/patient-monitor-simulation/at.criticalcare.SimPaM.yml @@ -0,0 +1,57 @@ + +app-id: at.criticalcare.SimPaM + +runtime: org.gnome.Platform +runtime-version: "51" +sdk: org.gnome.Sdk + +sdk-extensions: + - org.freedesktop.Sdk.Extension.rust-stable + +command: patient-monitor-simulation + +finish-args: + # GTK4 / display + - --socket=wayland + - --socket=fallback-x11 + - --share=ipc + - --device=dri + + # Audio (PulseAudio / PipeWire) + - --socket=pulseaudio + + # Instructor web interface / TCP server + - --share=network + +modules: + - name: simpam + buildsystem: simple + + build-options: + append-path: /usr/lib/sdk/rust-stable/bin + env: + CARGO_HOME: /run/build/simpam/cargo + CARGO_NET_OFFLINE: "true" + + build-commands: + - cargo build --release --locked --offline + + - install -Dm755 + target/release/patient-monitor-simulation + /app/bin/patient-monitor-simulation + + - install -Dm644 + at.criticalcare.SimPaM.desktop + /app/share/applications/at.criticalcare.SimPaM.desktop + + sources: + - type: dir + path: . + skip: + - target + - build-flatpak + - flatpak-repo + - .flatpak-builder + - .git + + - cargo-sources.json diff --git a/patient-monitor-simulation/cargo-sources.json b/patient-monitor-simulation/cargo-sources.json new file mode 100644 index 0000000..2c27dde --- /dev/null +++ b/patient-monitor-simulation/cargo-sources.json @@ -0,0 +1,840 @@ +[ + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/autocfg/autocfg-1.5.1.crate", + "sha256": "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53", + "dest": "cargo/vendor/autocfg-1.5.1" + }, + { + "type": "inline", + "contents": "{\"package\": \"f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53\", \"files\": {}}", + "dest": "cargo/vendor/autocfg-1.5.1", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/bitflags/bitflags-2.13.2.crate", + "sha256": "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06", + "dest": "cargo/vendor/bitflags-2.13.2" + }, + { + "type": "inline", + "contents": "{\"package\": \"3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06\", \"files\": {}}", + "dest": "cargo/vendor/bitflags-2.13.2", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/cairo-rs/cairo-rs-0.22.9.crate", + "sha256": "df683f1d30b457964673a5541a4603208ef95ab6873d2a55871895cf310f3b56", + "dest": "cargo/vendor/cairo-rs-0.22.9" + }, + { + "type": "inline", + "contents": "{\"package\": \"df683f1d30b457964673a5541a4603208ef95ab6873d2a55871895cf310f3b56\", \"files\": {}}", + "dest": "cargo/vendor/cairo-rs-0.22.9", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/cairo-sys-rs/cairo-sys-rs-0.22.9.crate", + "sha256": "ee548131103ad8f698c6725669647b9c757b3b66992dd6a026037596417bee21", + "dest": "cargo/vendor/cairo-sys-rs-0.22.9" + }, + { + "type": "inline", + "contents": "{\"package\": \"ee548131103ad8f698c6725669647b9c757b3b66992dd6a026037596417bee21\", \"files\": {}}", + "dest": "cargo/vendor/cairo-sys-rs-0.22.9", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/cfg-expr/cfg-expr-0.20.10.crate", + "sha256": "9ba9e9ec16c447027685b1f897b720e18e9a8afd00bd7332c483537e38086c9f", + "dest": "cargo/vendor/cfg-expr-0.20.10" + }, + { + "type": "inline", + "contents": "{\"package\": \"9ba9e9ec16c447027685b1f897b720e18e9a8afd00bd7332c483537e38086c9f\", \"files\": {}}", + "dest": "cargo/vendor/cfg-expr-0.20.10", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/equivalent/equivalent-1.0.3.crate", + "sha256": "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826", + "dest": "cargo/vendor/equivalent-1.0.3" + }, + { + "type": "inline", + "contents": "{\"package\": \"00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826\", \"files\": {}}", + "dest": "cargo/vendor/equivalent-1.0.3", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/field-offset/field-offset-0.3.6.crate", + "sha256": "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f", + "dest": "cargo/vendor/field-offset-0.3.6" + }, + { + "type": "inline", + "contents": "{\"package\": \"38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f\", \"files\": {}}", + "dest": "cargo/vendor/field-offset-0.3.6", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/futures-channel/futures-channel-0.3.34.crate", + "sha256": "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4", + "dest": "cargo/vendor/futures-channel-0.3.34" + }, + { + "type": "inline", + "contents": "{\"package\": \"b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4\", \"files\": {}}", + "dest": "cargo/vendor/futures-channel-0.3.34", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/futures-core/futures-core-0.3.34.crate", + "sha256": "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e", + "dest": "cargo/vendor/futures-core-0.3.34" + }, + { + "type": "inline", + "contents": "{\"package\": \"92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e\", \"files\": {}}", + "dest": "cargo/vendor/futures-core-0.3.34", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/futures-executor/futures-executor-0.3.34.crate", + "sha256": "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432", + "dest": "cargo/vendor/futures-executor-0.3.34" + }, + { + "type": "inline", + "contents": "{\"package\": \"031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432\", \"files\": {}}", + "dest": "cargo/vendor/futures-executor-0.3.34", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/futures-io/futures-io-0.3.34.crate", + "sha256": "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed", + "dest": "cargo/vendor/futures-io-0.3.34" + }, + { + "type": "inline", + "contents": "{\"package\": \"53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed\", \"files\": {}}", + "dest": "cargo/vendor/futures-io-0.3.34", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/futures-macro/futures-macro-0.3.34.crate", + "sha256": "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44", + "dest": "cargo/vendor/futures-macro-0.3.34" + }, + { + "type": "inline", + "contents": "{\"package\": \"9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44\", \"files\": {}}", + "dest": "cargo/vendor/futures-macro-0.3.34", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/futures-task/futures-task-0.3.34.crate", + "sha256": "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd", + "dest": "cargo/vendor/futures-task-0.3.34" + }, + { + "type": "inline", + "contents": "{\"package\": \"cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd\", \"files\": {}}", + "dest": "cargo/vendor/futures-task-0.3.34", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/futures-util/futures-util-0.3.34.crate", + "sha256": "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc", + "dest": "cargo/vendor/futures-util-0.3.34" + }, + { + "type": "inline", + "contents": "{\"package\": \"0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc\", \"files\": {}}", + "dest": "cargo/vendor/futures-util-0.3.34", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/gdk-pixbuf/gdk-pixbuf-0.22.0.crate", + "sha256": "25f420376dbee041b2db374ce4573892a36222bb3f6c0c43e24f0d67eae9b646", + "dest": "cargo/vendor/gdk-pixbuf-0.22.0" + }, + { + "type": "inline", + "contents": "{\"package\": \"25f420376dbee041b2db374ce4573892a36222bb3f6c0c43e24f0d67eae9b646\", \"files\": {}}", + "dest": "cargo/vendor/gdk-pixbuf-0.22.0", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/gdk-pixbuf-sys/gdk-pixbuf-sys-0.22.9.crate", + "sha256": "9d5209294ba3775f9b650bf78bfadeba4332089f2329b3e2f6ce0a4957a45bff", + "dest": "cargo/vendor/gdk-pixbuf-sys-0.22.9" + }, + { + "type": "inline", + "contents": "{\"package\": \"9d5209294ba3775f9b650bf78bfadeba4332089f2329b3e2f6ce0a4957a45bff\", \"files\": {}}", + "dest": "cargo/vendor/gdk-pixbuf-sys-0.22.9", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/gdk4/gdk4-0.11.5.crate", + "sha256": "e77c579bac9eff8b84c0625d5f533da6d69988c063062fe92c2e955ede8f28eb", + "dest": "cargo/vendor/gdk4-0.11.5" + }, + { + "type": "inline", + "contents": "{\"package\": \"e77c579bac9eff8b84c0625d5f533da6d69988c063062fe92c2e955ede8f28eb\", \"files\": {}}", + "dest": "cargo/vendor/gdk4-0.11.5", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/gdk4-sys/gdk4-sys-0.11.5.crate", + "sha256": "3eff6238a30c1f198fb3c8d3d445fa7faf211d11d9075af0772e6e0ca32ae001", + "dest": "cargo/vendor/gdk4-sys-0.11.5" + }, + { + "type": "inline", + "contents": "{\"package\": \"3eff6238a30c1f198fb3c8d3d445fa7faf211d11d9075af0772e6e0ca32ae001\", \"files\": {}}", + "dest": "cargo/vendor/gdk4-sys-0.11.5", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/gio/gio-0.22.10.crate", + "sha256": "4620fbafdf19dba814473e19f18e75290cb3338662f6ae35f0402affd3b2b699", + "dest": "cargo/vendor/gio-0.22.10" + }, + { + "type": "inline", + "contents": "{\"package\": \"4620fbafdf19dba814473e19f18e75290cb3338662f6ae35f0402affd3b2b699\", \"files\": {}}", + "dest": "cargo/vendor/gio-0.22.10", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/gio-sys/gio-sys-0.22.9.crate", + "sha256": "6c28739f914c15b87a9856000bed9cbd5b3a8afbca5e982d9a299e1601422cb5", + "dest": "cargo/vendor/gio-sys-0.22.9" + }, + { + "type": "inline", + "contents": "{\"package\": \"6c28739f914c15b87a9856000bed9cbd5b3a8afbca5e982d9a299e1601422cb5\", \"files\": {}}", + "dest": "cargo/vendor/gio-sys-0.22.9", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/glib/glib-0.22.10.crate", + "sha256": "e4cf9e5bd8713f1990a92c422998826e0fb34824277b46bc59757373483c6694", + "dest": "cargo/vendor/glib-0.22.10" + }, + { + "type": "inline", + "contents": "{\"package\": \"e4cf9e5bd8713f1990a92c422998826e0fb34824277b46bc59757373483c6694\", \"files\": {}}", + "dest": "cargo/vendor/glib-0.22.10", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/glib-macros/glib-macros-0.22.9.crate", + "sha256": "c9597c68fa7bdf4154a3079642cd21c4dccac0b0bdd2897d82861523bf91e7b9", + "dest": "cargo/vendor/glib-macros-0.22.9" + }, + { + "type": "inline", + "contents": "{\"package\": \"c9597c68fa7bdf4154a3079642cd21c4dccac0b0bdd2897d82861523bf91e7b9\", \"files\": {}}", + "dest": "cargo/vendor/glib-macros-0.22.9", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/glib-sys/glib-sys-0.22.9.crate", + "sha256": "99b38907e67e40dec9b60f858bcada952598719cb512a13eb13d6cdcd16f8295", + "dest": "cargo/vendor/glib-sys-0.22.9" + }, + { + "type": "inline", + "contents": "{\"package\": \"99b38907e67e40dec9b60f858bcada952598719cb512a13eb13d6cdcd16f8295\", \"files\": {}}", + "dest": "cargo/vendor/glib-sys-0.22.9", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/gobject-sys/gobject-sys-0.22.9.crate", + "sha256": "07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834", + "dest": "cargo/vendor/gobject-sys-0.22.9" + }, + { + "type": "inline", + "contents": "{\"package\": \"07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834\", \"files\": {}}", + "dest": "cargo/vendor/gobject-sys-0.22.9", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/graphene-rs/graphene-rs-0.22.8.crate", + "sha256": "eb856b9c558971c3f13ab692358926da710b046932a4e087aedcc35b040d7dff", + "dest": "cargo/vendor/graphene-rs-0.22.8" + }, + { + "type": "inline", + "contents": "{\"package\": \"eb856b9c558971c3f13ab692358926da710b046932a4e087aedcc35b040d7dff\", \"files\": {}}", + "dest": "cargo/vendor/graphene-rs-0.22.8", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/graphene-sys/graphene-sys-0.22.9.crate", + "sha256": "97842c7543828f98aa5583aa54fcda28aa84fa2b0f8c556142177f7bbb638057", + "dest": "cargo/vendor/graphene-sys-0.22.9" + }, + { + "type": "inline", + "contents": "{\"package\": \"97842c7543828f98aa5583aa54fcda28aa84fa2b0f8c556142177f7bbb638057\", \"files\": {}}", + "dest": "cargo/vendor/graphene-sys-0.22.9", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/gsk4/gsk4-0.11.5.crate", + "sha256": "eee23d7425c5281ec5a2f40f7b69384aac66c15861d990d248e9d9c9368be464", + "dest": "cargo/vendor/gsk4-0.11.5" + }, + { + "type": "inline", + "contents": "{\"package\": \"eee23d7425c5281ec5a2f40f7b69384aac66c15861d990d248e9d9c9368be464\", \"files\": {}}", + "dest": "cargo/vendor/gsk4-0.11.5", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/gsk4-sys/gsk4-sys-0.11.5.crate", + "sha256": "27900c92e47df410bbe43b51818104051e3409da43fb88547a41c0bafddfd39c", + "dest": "cargo/vendor/gsk4-sys-0.11.5" + }, + { + "type": "inline", + "contents": "{\"package\": \"27900c92e47df410bbe43b51818104051e3409da43fb88547a41c0bafddfd39c\", \"files\": {}}", + "dest": "cargo/vendor/gsk4-sys-0.11.5", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/gtk4/gtk4-0.11.5.crate", + "sha256": "e0f8226c94dd0b65ba2e8fcd8ff402d380e890f6e5a6488e652a0158e827b9bf", + "dest": "cargo/vendor/gtk4-0.11.5" + }, + { + "type": "inline", + "contents": "{\"package\": \"e0f8226c94dd0b65ba2e8fcd8ff402d380e890f6e5a6488e652a0158e827b9bf\", \"files\": {}}", + "dest": "cargo/vendor/gtk4-0.11.5", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/gtk4-macros/gtk4-macros-0.11.5.crate", + "sha256": "eb906c98f0b4cc9002594e337e83f40492aa6dca22c97242f13be5b046c5f338", + "dest": "cargo/vendor/gtk4-macros-0.11.5" + }, + { + "type": "inline", + "contents": "{\"package\": \"eb906c98f0b4cc9002594e337e83f40492aa6dca22c97242f13be5b046c5f338\", \"files\": {}}", + "dest": "cargo/vendor/gtk4-macros-0.11.5", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/gtk4-sys/gtk4-sys-0.11.5.crate", + "sha256": "bd14af0137f269bdecee73404157d2a852f9651af7d68bd1023d3b8b914a14c3", + "dest": "cargo/vendor/gtk4-sys-0.11.5" + }, + { + "type": "inline", + "contents": "{\"package\": \"bd14af0137f269bdecee73404157d2a852f9651af7d68bd1023d3b8b914a14c3\", \"files\": {}}", + "dest": "cargo/vendor/gtk4-sys-0.11.5", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/hashbrown/hashbrown-0.17.1.crate", + "sha256": "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a", + "dest": "cargo/vendor/hashbrown-0.17.1" + }, + { + "type": "inline", + "contents": "{\"package\": \"ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a\", \"files\": {}}", + "dest": "cargo/vendor/hashbrown-0.17.1", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/heck/heck-0.5.0.crate", + "sha256": "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea", + "dest": "cargo/vendor/heck-0.5.0" + }, + { + "type": "inline", + "contents": "{\"package\": \"2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea\", \"files\": {}}", + "dest": "cargo/vendor/heck-0.5.0", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/indexmap/indexmap-2.14.2.crate", + "sha256": "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855", + "dest": "cargo/vendor/indexmap-2.14.2" + }, + { + "type": "inline", + "contents": "{\"package\": \"cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855\", \"files\": {}}", + "dest": "cargo/vendor/indexmap-2.14.2", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/libc/libc-0.2.191.crate", + "sha256": "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a", + "dest": "cargo/vendor/libc-0.2.191" + }, + { + "type": "inline", + "contents": "{\"package\": \"65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a\", \"files\": {}}", + "dest": "cargo/vendor/libc-0.2.191", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/memchr/memchr-2.8.3.crate", + "sha256": "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98", + "dest": "cargo/vendor/memchr-2.8.3" + }, + { + "type": "inline", + "contents": "{\"package\": \"cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98\", \"files\": {}}", + "dest": "cargo/vendor/memchr-2.8.3", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/memoffset/memoffset-0.9.1.crate", + "sha256": "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a", + "dest": "cargo/vendor/memoffset-0.9.1" + }, + { + "type": "inline", + "contents": "{\"package\": \"488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a\", \"files\": {}}", + "dest": "cargo/vendor/memoffset-0.9.1", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/pango/pango-0.22.9.crate", + "sha256": "0b2022dbbd82e1c42bd950a6f1df9b98c796e725dce5ec275e03cbf9772e4efa", + "dest": "cargo/vendor/pango-0.22.9" + }, + { + "type": "inline", + "contents": "{\"package\": \"0b2022dbbd82e1c42bd950a6f1df9b98c796e725dce5ec275e03cbf9772e4efa\", \"files\": {}}", + "dest": "cargo/vendor/pango-0.22.9", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/pango-sys/pango-sys-0.22.9.crate", + "sha256": "ca02d64761b74d56cdd4b437db6d73dc95e6c0d40f27e1c707952c0f09052948", + "dest": "cargo/vendor/pango-sys-0.22.9" + }, + { + "type": "inline", + "contents": "{\"package\": \"ca02d64761b74d56cdd4b437db6d73dc95e6c0d40f27e1c707952c0f09052948\", \"files\": {}}", + "dest": "cargo/vendor/pango-sys-0.22.9", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/pin-project-lite/pin-project-lite-0.2.17.crate", + "sha256": "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd", + "dest": "cargo/vendor/pin-project-lite-0.2.17" + }, + { + "type": "inline", + "contents": "{\"package\": \"a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd\", \"files\": {}}", + "dest": "cargo/vendor/pin-project-lite-0.2.17", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/pkg-config/pkg-config-0.3.34.crate", + "sha256": "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548", + "dest": "cargo/vendor/pkg-config-0.3.34" + }, + { + "type": "inline", + "contents": "{\"package\": \"f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548\", \"files\": {}}", + "dest": "cargo/vendor/pkg-config-0.3.34", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/proc-macro-crate/proc-macro-crate-3.5.0.crate", + "sha256": "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f", + "dest": "cargo/vendor/proc-macro-crate-3.5.0" + }, + { + "type": "inline", + "contents": "{\"package\": \"e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f\", \"files\": {}}", + "dest": "cargo/vendor/proc-macro-crate-3.5.0", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/proc-macro2/proc-macro2-1.0.107.crate", + "sha256": "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9", + "dest": "cargo/vendor/proc-macro2-1.0.107" + }, + { + "type": "inline", + "contents": "{\"package\": \"985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9\", \"files\": {}}", + "dest": "cargo/vendor/proc-macro2-1.0.107", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/quote/quote-1.0.47.crate", + "sha256": "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001", + "dest": "cargo/vendor/quote-1.0.47" + }, + { + "type": "inline", + "contents": "{\"package\": \"1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001\", \"files\": {}}", + "dest": "cargo/vendor/quote-1.0.47", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/rustc_version/rustc_version-0.4.1.crate", + "sha256": "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92", + "dest": "cargo/vendor/rustc_version-0.4.1" + }, + { + "type": "inline", + "contents": "{\"package\": \"cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92\", \"files\": {}}", + "dest": "cargo/vendor/rustc_version-0.4.1", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/semver/semver-1.0.28.crate", + "sha256": "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd", + "dest": "cargo/vendor/semver-1.0.28" + }, + { + "type": "inline", + "contents": "{\"package\": \"8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd\", \"files\": {}}", + "dest": "cargo/vendor/semver-1.0.28", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/serde_core/serde_core-1.0.229.crate", + "sha256": "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48", + "dest": "cargo/vendor/serde_core-1.0.229" + }, + { + "type": "inline", + "contents": "{\"package\": \"67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48\", \"files\": {}}", + "dest": "cargo/vendor/serde_core-1.0.229", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/serde_derive/serde_derive-1.0.229.crate", + "sha256": "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348", + "dest": "cargo/vendor/serde_derive-1.0.229" + }, + { + "type": "inline", + "contents": "{\"package\": \"e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348\", \"files\": {}}", + "dest": "cargo/vendor/serde_derive-1.0.229", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/serde_spanned/serde_spanned-1.1.3.crate", + "sha256": "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782", + "dest": "cargo/vendor/serde_spanned-1.1.3" + }, + { + "type": "inline", + "contents": "{\"package\": \"9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782\", \"files\": {}}", + "dest": "cargo/vendor/serde_spanned-1.1.3", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/slab/slab-0.4.12.crate", + "sha256": "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5", + "dest": "cargo/vendor/slab-0.4.12" + }, + { + "type": "inline", + "contents": "{\"package\": \"0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5\", \"files\": {}}", + "dest": "cargo/vendor/slab-0.4.12", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/smallvec/smallvec-1.16.5.crate", + "sha256": "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46", + "dest": "cargo/vendor/smallvec-1.16.5" + }, + { + "type": "inline", + "contents": "{\"package\": \"149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46\", \"files\": {}}", + "dest": "cargo/vendor/smallvec-1.16.5", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/syn/syn-3.0.10.crate", + "sha256": "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79", + "dest": "cargo/vendor/syn-3.0.10" + }, + { + "type": "inline", + "contents": "{\"package\": \"4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79\", \"files\": {}}", + "dest": "cargo/vendor/syn-3.0.10", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/system-deps/system-deps-9.0.1.crate", + "sha256": "db551ad38aac61d5e0343e0eeeb0163be3115c4e23b6a025959570ee0c03c67d", + "dest": "cargo/vendor/system-deps-9.0.1" + }, + { + "type": "inline", + "contents": "{\"package\": \"db551ad38aac61d5e0343e0eeeb0163be3115c4e23b6a025959570ee0c03c67d\", \"files\": {}}", + "dest": "cargo/vendor/system-deps-9.0.1", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/target-lexicon/target-lexicon-0.13.5.crate", + "sha256": "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca", + "dest": "cargo/vendor/target-lexicon-0.13.5" + }, + { + "type": "inline", + "contents": "{\"package\": \"adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca\", \"files\": {}}", + "dest": "cargo/vendor/target-lexicon-0.13.5", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/toml/toml-1.2.1+spec-1.1.0.crate", + "sha256": "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7", + "dest": "cargo/vendor/toml-1.2.1+spec-1.1.0" + }, + { + "type": "inline", + "contents": "{\"package\": \"d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7\", \"files\": {}}", + "dest": "cargo/vendor/toml-1.2.1+spec-1.1.0", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/toml_datetime/toml_datetime-1.1.3+spec-1.1.0.crate", + "sha256": "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49", + "dest": "cargo/vendor/toml_datetime-1.1.3+spec-1.1.0" + }, + { + "type": "inline", + "contents": "{\"package\": \"173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49\", \"files\": {}}", + "dest": "cargo/vendor/toml_datetime-1.1.3+spec-1.1.0", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/toml_edit/toml_edit-0.25.19+spec-1.1.0.crate", + "sha256": "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218", + "dest": "cargo/vendor/toml_edit-0.25.19+spec-1.1.0" + }, + { + "type": "inline", + "contents": "{\"package\": \"dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218\", \"files\": {}}", + "dest": "cargo/vendor/toml_edit-0.25.19+spec-1.1.0", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/toml_parser/toml_parser-1.1.5+spec-1.1.0.crate", + "sha256": "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c", + "dest": "cargo/vendor/toml_parser-1.1.5+spec-1.1.0" + }, + { + "type": "inline", + "contents": "{\"package\": \"baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c\", \"files\": {}}", + "dest": "cargo/vendor/toml_parser-1.1.5+spec-1.1.0", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/toml_writer/toml_writer-1.2.0+spec-1.1.0.crate", + "sha256": "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a", + "dest": "cargo/vendor/toml_writer-1.2.0+spec-1.1.0" + }, + { + "type": "inline", + "contents": "{\"package\": \"009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a\", \"files\": {}}", + "dest": "cargo/vendor/toml_writer-1.2.0+spec-1.1.0", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/unicode-ident/unicode-ident-1.0.27.crate", + "sha256": "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563", + "dest": "cargo/vendor/unicode-ident-1.0.27" + }, + { + "type": "inline", + "contents": "{\"package\": \"a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563\", \"files\": {}}", + "dest": "cargo/vendor/unicode-ident-1.0.27", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/version-compare/version-compare-0.2.1.crate", + "sha256": "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e", + "dest": "cargo/vendor/version-compare-0.2.1" + }, + { + "type": "inline", + "contents": "{\"package\": \"03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e\", \"files\": {}}", + "dest": "cargo/vendor/version-compare-0.2.1", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/windows-link/windows-link-0.2.1.crate", + "sha256": "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5", + "dest": "cargo/vendor/windows-link-0.2.1" + }, + { + "type": "inline", + "contents": "{\"package\": \"f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5\", \"files\": {}}", + "dest": "cargo/vendor/windows-link-0.2.1", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/windows-sys/windows-sys-0.61.2.crate", + "sha256": "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc", + "dest": "cargo/vendor/windows-sys-0.61.2" + }, + { + "type": "inline", + "contents": "{\"package\": \"ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc\", \"files\": {}}", + "dest": "cargo/vendor/windows-sys-0.61.2", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "archive", + "archive-type": "tar-gzip", + "url": "https://static.crates.io/crates/winnow/winnow-1.0.5.crate", + "sha256": "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef", + "dest": "cargo/vendor/winnow-1.0.5" + }, + { + "type": "inline", + "contents": "{\"package\": \"8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef\", \"files\": {}}", + "dest": "cargo/vendor/winnow-1.0.5", + "dest-filename": ".cargo-checksum.json" + }, + { + "type": "inline", + "contents": "[source.vendored-sources]\ndirectory = \"cargo/vendor\"\n\n[source.crates-io]\nreplace-with = \"vendored-sources\"\n", + "dest": "cargo", + "dest-filename": "config" + } +] \ No newline at end of file diff --git a/patient-monitor-simulation/src/alarm.rs b/patient-monitor-simulation/src/alarm.rs index f992589..bb0c521 100644 --- a/patient-monitor-simulation/src/alarm.rs +++ b/patient-monitor-simulation/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 { 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) -> 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>, } -impl SoundFiles { - fn create_in(directory: &Path) -> io::Result { - 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 { - 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, -} - -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 { - 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 { - 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, - child: Option, - error_reported: bool, + worker: Option, + 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, 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, - child: Option, + worker: Option, + samples: AlarmSamples, previous: AlarmLevel, next_at: Instant, - error_reported: bool, + test_until: Option, } 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] { diff --git a/patient-monitor-simulation/src/audio_backend.rs b/patient-monitor-simulation/src/audio_backend.rs new file mode 100644 index 0000000..a38616b --- /dev/null +++ b/patient-monitor-simulation/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, +} + +impl PulseAudioWorker { + pub fn new(stream_name: &'static str) -> io::Result { + 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) { + let spec = Spec { format: Format::S16le, channels: 1, rate: SAMPLE_RATE }; + debug_assert!(spec.is_valid()); + let mut stream: Option = 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/patient-monitor-simulation/src/main.rs b/patient-monitor-simulation/src/main.rs index a553c8f..f563c1e 100644 --- a/patient-monitor-simulation/src/main.rs +++ b/patient-monitor-simulation/src/main.rs @@ -1,4 +1,5 @@ mod actions; +mod audio_backend; mod alarm; mod model; mod nibp; diff --git a/patient-monitor-simulation/src/ui.rs b/patient-monitor-simulation/src/ui.rs index 80effa8..2fab238 100644 --- a/patient-monitor-simulation/src/ui.rs +++ b/patient-monitor-simulation/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); }