v0.6.6 — Optional QRS/pulse beep

Added a separate **QRS tone** checkbox (enabled by default). An 85 ms
single-note beep follows actual ECG or mechanical beat events. With a valid
SpO₂ reading, the delayed pleth pulse determines the timing and the oxygen
saturation determines the pitch in eleven steps from 740 to 87 Hz; otherwise
ECG QRS or ART pulses trigger a fixed 500 Hz tone. The two-tone alarm sounds
remain unchanged. Added regression tests for band boundaries, event selection
and single-tone WAV output.
This commit is contained in:
GABRIEL Sebastian 2026-11-12 22:36:24 +01:00
commit f98fc7412f
11 changed files with 1247 additions and 34 deletions

View file

@ -12,7 +12,7 @@ use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use crate::model::{AlarmLimits, AlarmState, Parameters, PulseConduction, Spo2Status};
use crate::simulation::Simulator;
use crate::simulation::{BeatEvent, BeatSource, Simulator};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub enum AlarmLevel {
@ -84,6 +84,88 @@ pub fn level(p: &Parameters, sim: &Simulator) -> AlarmLevel {
result
}
/// Single-note QRS/pulse beep. The oximeter is the source when it has a
/// reading; otherwise use an ECG QRS or an available arterial pulse.
/// Mid is the fixed pitch used when no SpO2 reading is present.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum QrsTone { Mid, Saturation(usize) }
const QRS_MID_HZ: f64 = 500.0;
const QRS_SPO2_HZ: [f64; 11] = [
740.0, 675.0, 609.0, 544.0, 479.0, 413.0,
348.0, 283.0, 218.0, 152.0, 87.0,
];
/// Stepwise saturation-to-pitch mapping: 100–97, 96–94, 93–90,
/// then 89–80, 79–70, ..., 19–10%. 10% or less always gives 87 Hz.
fn spo2_tone_index(saturation: i32) -> usize {
match saturation.clamp(0, 100) {
97..=100 => 0,
94..=96 => 1,
90..=93 => 2,
80..=89 => 3,
70..=79 => 4,
60..=69 => 5,
50..=59 => 6,
40..=49 => 7,
30..=39 => 8,
20..=29 => 9,
_ => 10,
}
}
pub fn qrs_tone(p: &Parameters, sim: &Simulator, events: &[BeatEvent]) -> Option<QrsTone> {
if p.show_spo2 && sim.spo2_status(p) == Spo2Status::Available {
// Actual peripheral pulses, not an independent HR metronome. This
// respects mechanical capture ratios and good-quality CPR.
return events.iter().any(|event| event.source == BeatSource::Pleth
&& sim.time() - event.time <= 0.25)
.then_some(QrsTone::Saturation(spo2_tone_index(p.spo2)));
}
// ECG takes precedence over the delayed arterial signal: never beep twice
// for the same QRS when both monitor channels are visible.
if p.show_ecg && p.ecg_rhythm.has_qrs() && p.heart_rate > 0 {
return events.iter().any(|event| event.source == BeatSource::Ecg
&& sim.time() - event.time <= 0.25)
.then_some(QrsTone::Mid);
}
if p.show_art {
return events.iter().any(|event| event.source == BeatSource::Art
&& sim.time() - event.time <= 0.25)
.then_some(QrsTone::Mid);
}
None
}
/// Original, brief PCM16 sine wave with smooth fades to avoid clicks.
fn single_beep_wav(frequency: f64) -> Vec<u8> {
const SAMPLE_RATE: u32 = 44_100;
const DURATION: f64 = 0.085;
let samples = (DURATION * f64::from(SAMPLE_RATE)).round() as usize;
let size = (samples * 2) as u32;
let mut bytes = Vec::with_capacity(44 + size as usize);
bytes.extend_from_slice(b"RIFF");
bytes.extend_from_slice(&(size + 36).to_le_bytes());
bytes.extend_from_slice(b"WAVEfmt ");
bytes.extend_from_slice(&16_u32.to_le_bytes());
bytes.extend_from_slice(&1_u16.to_le_bytes());
bytes.extend_from_slice(&1_u16.to_le_bytes());
bytes.extend_from_slice(&SAMPLE_RATE.to_le_bytes());
bytes.extend_from_slice(&(SAMPLE_RATE * 2).to_le_bytes());
bytes.extend_from_slice(&2_u16.to_le_bytes());
bytes.extend_from_slice(&16_u16.to_le_bytes());
bytes.extend_from_slice(b"data");
bytes.extend_from_slice(&size.to_le_bytes());
for i in 0..samples {
let t = i as f64 / f64::from(SAMPLE_RATE);
let remaining = (samples - i) as f64 / f64::from(SAMPLE_RATE);
let envelope = (t / 0.010).min(1.0).min(remaining / 0.016).max(0.0);
let value = (std::f64::consts::TAU * frequency * t).sin() * envelope * 0.13;
bytes.extend_from_slice(&((value * f64::from(i16::MAX)).round() as i16).to_le_bytes());
}
bytes
}
/// Both alarm priorities sound as two successive, different pitches.
/// A future QRS beep will be a separate, single-tone signal.
/// Zero-frequency segments are short silences between the notes.
@ -175,6 +257,115 @@ impl SoundFiles {
}
}
/// Prepared once on startup. Reuse the same playback utility as the alarms,
/// but use an independent child so the two-tone alarm is never interrupted by
/// single QRS/pulse beeps.
struct QrsSoundFiles {
mid: PathBuf,
saturations: Vec<PathBuf>,
}
impl Drop for QrsSoundFiles {
fn drop(&mut self) {
let _ = fs::remove_file(&self.mid);
for file in &self.saturations { let _ = fs::remove_file(file); }
}
}
impl QrsSoundFiles {
fn create_in(directory: &Path) -> io::Result<Self> {
let nonce = SystemTime::now().duration_since(UNIX_EPOCH)
.unwrap_or_default().as_nanos();
let prefix = format!("pamsim-qrs-{}-{nonce}", std::process::id());
let mid = directory.join(format!("{prefix}-mid.wav"));
write_new(&mid, &single_beep_wav(QRS_MID_HZ))?;
let mut files = Self { mid, saturations: Vec::new() };
for (i, &frequency) in QRS_SPO2_HZ.iter().enumerate() {
let path = directory.join(format!("{prefix}-spo2-{i}.wav"));
write_new(&path, &single_beep_wav(frequency))?;
files.saturations.push(path);
}
Ok(files)
}
fn create() -> io::Result<Self> {
if let Some(runtime) = env::var_os("XDG_RUNTIME_DIR") {
if let Ok(files) = Self::create_in(Path::new(&runtime)) {
return Ok(files);
}
}
Self::create_in(&env::temp_dir())
}
fn path(&self, tone: QrsTone) -> &Path {
match tone {
QrsTone::Mid => &self.mid,
QrsTone::Saturation(index) => &self.saturations[index.min(self.saturations.len() - 1)],
}
}
}
pub struct QrsAudio {
player: Option<&'static str>,
files: Option<QrsSoundFiles>,
child: Option<Child>,
error_reported: 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
}
}
} 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();
}
}
/// 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.
pub fn update(&mut self, tone: Option<QrsTone>, enabled: bool) {
if !enabled {
self.stop_child();
return;
}
if let Some(child) = self.child.as_mut() {
match child.try_wait() {
Ok(Some(_)) | Err(_) => self.child = None,
Ok(None) => return,
}
}
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(_) => {}
}
}
}
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| {
@ -317,6 +508,59 @@ mod tests {
use super::*;
use crate::model::{AlarmSettings, EcgRhythm};
#[test]
fn saturation_pitches_follow_exact_bands_and_decrease_to_87_hz() {
assert_eq!(QRS_SPO2_HZ.first(), Some(&740.0));
assert_eq!(QRS_SPO2_HZ.last(), Some(&87.0));
for (saturation, expected) in [
(100, 0), (97, 0), (96, 1), (94, 1), (93, 2), (90, 2),
(89, 3), (80, 3), (79, 4), (70, 4), (69, 5), (60, 5),
(59, 6), (50, 6), (49, 7), (40, 7), (39, 8), (30, 8),
(29, 9), (20, 9), (19, 10), (10, 10), (0, 10),
] {
assert_eq!(spo2_tone_index(saturation), expected, "SpO2 {saturation}%");
}
assert!(QRS_SPO2_HZ.windows(2).all(|hz| hz[0] > hz[1]));
assert_eq!(QRS_MID_HZ, 500.0);
}
#[test]
fn qrs_audio_uses_pleth_when_available_and_electrical_fallback_without_reading() {
let mut p = Parameters::default();
let mut sim = Simulator::new(&p);
let mut events = Vec::new();
for _ in 0..40 {
sim.advance(0.05, &p);
let current = sim.take_audio_events();
if current.iter().any(|e| e.source == BeatSource::Pleth
&& sim.time() - e.time <= 0.25) {
events = current;
break;
}
}
assert!(events.iter().any(|e| e.source == BeatSource::Pleth));
assert_eq!(qrs_tone(&p, &sim, &events), Some(QrsTone::Saturation(0)));
p.spo2_sensor_attached = false;
let fallback = [BeatEvent { source: BeatSource::Ecg, time: sim.time() },
BeatEvent { source: BeatSource::Art, time: sim.time() }];
assert_eq!(qrs_tone(&p, &sim, &fallback), Some(QrsTone::Mid));
p.show_ecg = false;
assert_eq!(qrs_tone(&p, &sim, &fallback), Some(QrsTone::Mid));
p.show_art = false;
assert_eq!(qrs_tone(&p, &sim, &fallback), None);
}
#[test]
fn single_beep_is_valid_wav_independent_of_two_tone_alarm() {
for hz in QRS_SPO2_HZ.iter().copied().chain([QRS_MID_HZ]) {
let bytes = single_beep_wav(hz);
assert_eq!(&bytes[..4], b"RIFF");
assert_eq!(&bytes[8..12], b"WAVE");
assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize + 8, bytes.len());
}
assert_ne!(single_beep_wav(740.0), single_beep_wav(87.0));
}
#[test]
fn valid_wav_files_and_distinct_tone_patterns() {
for critical in [false, true] {

View file

@ -267,6 +267,7 @@ pub struct Parameters {
pub patient_name: String, // displayed in the monitor header, blank = generic title
pub alarms: AlarmSettings,
pub audible_alarms: bool, // mute only the sound, never the visual alarms
pub qrs_tone_enabled: bool, // beat-synchronous single beep; separate from two-tone alarms
pub chest_compressions_active: bool,
pub chest_compression_quality: ChestCompressionQuality,
pub ecg_rhythm: EcgRhythm,
@ -346,6 +347,7 @@ impl Default for Parameters {
patient_name: String::new(),
alarms: AlarmSettings::default(),
audible_alarms: true,
qrs_tone_enabled: true,
chest_compressions_active: false,
chest_compression_quality: ChestCompressionQuality::Adequate,
ecg_rhythm: EcgRhythm::Sinus,

View file

@ -29,6 +29,18 @@ fn ppv_multiplier(ppv_percent: i32, respiratory_phase: f64) -> f64 {
* (std::f64::consts::TAU * respiratory_phase).sin()
}
/// One distinct electrical or mechanical beat event for the optional beep.
/// Electrical QRS, arterial and peripheral pulses are generated at their
/// respective physiological simulation times, not at the audio-timer rate.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BeatSource { Ecg, Art, Pleth }
#[derive(Clone, Copy, Debug)]
pub struct BeatEvent {
pub time: f64,
pub source: BeatSource,
}
#[derive(Clone, Copy, Debug)]
pub struct Sample {
pub time: f64,
@ -121,12 +133,12 @@ impl ChestCompressions {
};
}
fn update(&mut self, enabled: bool, quality: ChestCompressionQuality) {
fn update(&mut self, enabled: bool, quality: ChestCompressionQuality) -> bool {
if !enabled {
self.active = false;
self.phase = 0.0;
self.peak_pressure = 0.0;
return;
return false;
}
if !self.active {
self.active = true;
@ -143,7 +155,9 @@ impl ChestCompressions {
self.phase = self.phase.fract();
self.rate_bpm = 90.0 + self.random_unit() * 20.0;
self.choose_peak();
return true;
}
false
}
fn pressure_wave(&self) -> f64 {
@ -184,6 +198,7 @@ pub struct Simulator {
ecg_beat_number: u64,
conducted_qrs: VecDeque<ConductedBeat>, // captured QRS with respiratory beat amplitude
rate_qrs: VecDeque<f64>, // captured beats for measured PR; reset after rate changes
audio_events: VecDeque<BeatEvent>, // consumed by the 100-ms UI audio timer
filtered_pleth: f64,
previous_rhythm: EcgRhythm,
previous_conduction: PulseConduction,
@ -205,6 +220,7 @@ impl Simulator {
ecg_beat_number: 0,
conducted_qrs: VecDeque::new(),
rate_qrs: VecDeque::new(),
audio_events: VecDeque::new(),
filtered_pleth: 0.0,
previous_rhythm: params.ecg_rhythm,
previous_conduction: params.pulse_conduction,
@ -219,6 +235,8 @@ impl Simulator {
for _ in 0..(8.0 / SAMPLE_STEP) as usize {
sim.step(params);
}
// Initial history is visual-only; never replay warmup beats as sound.
sim.audio_events.clear();
sim
}
@ -336,6 +354,18 @@ impl Simulator {
&self.samples
}
/// Drain beat events since the previous sound callback. Kept bounded so
/// a suspended window cannot replay a long backlog of old beats.
pub fn take_audio_events(&mut self) -> Vec<BeatEvent> {
self.audio_events.drain(..).collect()
}
fn emit_beat(&mut self, source: BeatSource, time: f64) {
if time < 0.0 { return; } // no audio events from history warmup
if self.audio_events.len() >= 32 { self.audio_events.pop_front(); }
self.audio_events.push_back(BeatEvent { source, time });
}
/// Average of recent *mechanically captured* beat intervals, not an independent setting.
pub fn pulse_rate(&self) -> Option<i32> {
if self.rate_qrs.len() < 2 {
@ -355,8 +385,18 @@ impl Simulator {
fn step(&mut self, params: &Parameters) {
self.time += SAMPLE_STEP;
self.compressions.update(params.chest_compressions_active,
let compression_event = self.compressions.update(params.chest_compressions_active,
params.chest_compression_quality);
if compression_event {
// Good CPR generates a pleth beat. Any effective CPR generates
// an arterial beat, even without underlying organized ECG.
if self.compressions.peak_pressure > 0.0 {
self.emit_beat(BeatSource::Art, self.time);
}
if params.chest_compression_quality == ChestCompressionQuality::Good {
self.emit_beat(BeatSource::Pleth, self.time);
}
}
self.poor_signal_outages.update(self.time,
!params.chest_compressions_active && params.spo2_quality == Spo2Quality::Poor
&& params.spo2_sensor_attached);
@ -413,6 +453,7 @@ impl Simulator {
// Interpolate within the 4 ms sample so mechanical onsets stay aligned.
let qrs_time = self.time - SAMPLE_STEP * (next_phase - QRS_PHASE) / increment;
self.ecg_beat_number += 1;
self.emit_beat(BeatSource::Ecg, qrs_time);
if params.ecg_rhythm.can_generate_pulse()
&& params.pulse_conduction.conducts(self.ecg_beat_number) {
let pulse_pressure_scale = if params.respiratory_rate > 0 {
@ -429,6 +470,29 @@ impl Simulator {
self.ecg_phase = 0.0;
}
// Schedule single beeps at the delayed mechanical onsets. During CPR,
// the compression clock replaces the intrinsic ART/pleth sound source
// except for a perfusing native arterial pulse under ineffective CPR.
let mut mechanical_events = Vec::new();
for beat in &self.conducted_qrs {
let art_time = beat.qrs_time + ART_DELAY;
let pleth_time = beat.qrs_time + PLETH_DELAY;
if art_time > self.time - SAMPLE_STEP && art_time <= self.time
&& (!params.chest_compressions_active
|| params.chest_compression_quality == ChestCompressionQuality::Bad)
{
mechanical_events.push((BeatSource::Art, art_time));
}
if pleth_time > self.time - SAMPLE_STEP && pleth_time <= self.time
&& !params.chest_compressions_active
{
mechanical_events.push((BeatSource::Pleth, pleth_time));
}
}
for (source, time) in mechanical_events {
self.emit_beat(source, time);
}
// Preserve up to 30s of delivered events for stable derived PR calculations.
while self.conducted_qrs.front().is_some_and(|beat| beat.qrs_time < self.time - 30.0) {
self.conducted_qrs.pop_front();
@ -709,6 +773,60 @@ mod tests {
sim
}
#[test]
fn audio_events_follow_actual_qrs_and_delayed_mechanical_pulses() {
let p = Parameters::default();
let mut sim = Simulator::new(&p);
for _ in 0..30 { sim.advance(0.1, &p); }
let events = sim.take_audio_events();
let qrs = events.iter().find(|e| e.source == BeatSource::Ecg).unwrap().time;
assert!(events.iter().any(|e| e.source == BeatSource::Art
&& ((e.time - qrs) - ART_DELAY).abs() <= SAMPLE_STEP));
assert!(events.iter().any(|e| e.source == BeatSource::Pleth
&& ((e.time - qrs) - PLETH_DELAY).abs() <= SAMPLE_STEP));
assert!(sim.take_audio_events().is_empty(), "events must be consumed once");
}
#[test]
fn two_to_one_capture_has_half_as_many_peripheral_audio_beats() {
let p = Parameters { pulse_conduction: PulseConduction::TwoToOne,
..Parameters::default() };
let mut sim = Simulator::new(&p);
let mut qrs = 0;
let mut pleth = 0;
for _ in 0..100 {
sim.advance(0.1, &p);
for event in sim.take_audio_events() {
match event.source {
BeatSource::Ecg => qrs += 1,
BeatSource::Pleth => pleth += 1,
BeatSource::Art => {}
}
}
}
assert!(qrs >= 10);
assert!((2 * pleth as i32 - qrs as i32).abs() <= 2,
"2:1 capture: {qrs} QRS events, {pleth} peripheral events");
}
#[test]
fn vf_generates_no_beats_without_cpr_but_compressions_generate_art_events() {
let mut p = Parameters { ecg_rhythm: EcgRhythm::VentricularFibrillation,
..Parameters::default() };
let mut sim = Simulator::new(&p);
for _ in 0..20 { sim.advance(0.1, &p); }
assert!(sim.take_audio_events().is_empty());
p.chest_compressions_active = true;
p.chest_compression_quality = ChestCompressionQuality::Adequate;
for _ in 0..20 { sim.advance(0.1, &p); }
let events = sim.take_audio_events();
assert!(events.iter().any(|e| e.source == BeatSource::Art));
assert!(!events.iter().any(|e| e.source == BeatSource::Pleth));
p.chest_compression_quality = ChestCompressionQuality::Good;
for _ in 0..20 { sim.advance(0.1, &p); }
assert!(sim.take_audio_events().iter().any(|e| e.source == BeatSource::Pleth));
}
#[test]
fn compression_rate_varies_only_between_90_and_110_bpm() {
let mut cpr = ChestCompressions::new();

View file

@ -8,7 +8,7 @@ use gtk::glib;
use gtk::prelude::*;
use gtk::{Application, ApplicationWindow, Orientation};
use crate::alarm::{self, AlarmAudio};
use crate::alarm::{self, AlarmAudio, QrsAudio};
use crate::model::{AlarmLimits, AlarmSettings, ArterialShape, CapnoShape,
ChestCompressionQuality, EcgLead, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
use crate::render;
@ -33,6 +33,7 @@ pub fn create_windows(app: &Application) {
let parameters = Rc::new(RefCell::new(Parameters::default()));
let simulator = Rc::new(RefCell::new(Simulator::new(&parameters.borrow())));
let audio = Rc::new(RefCell::new(AlarmAudio::new()));
let qrs_audio = Rc::new(RefCell::new(QrsAudio::new()));
install_ecg_menu_style(); // neutral style shared by all parameter panels
let admin_changed: AdminChanged = Rc::new(RefCell::new(None));
let monitor = create_monitor(app, parameters.clone(), simulator.clone(),
@ -44,8 +45,13 @@ pub fn create_windows(app: &Application) {
// on sound playback. Audio also continues if the monitor is not mapped.
glib::timeout_add_local(Duration::from_millis(100), move || {
let config = parameters.borrow();
let current = alarm::level(&config, &simulator.borrow());
let mut sim = simulator.borrow_mut();
let events = sim.take_audio_events();
let current = alarm::level(&config, &sim);
let beat_tone = alarm::qrs_tone(&config, &sim, &events);
drop(sim);
audio.borrow_mut().update(current, config.audible_alarms);
qrs_audio.borrow_mut().update(beat_tone, config.qrs_tone_enabled);
glib::ControlFlow::Continue
});
@ -210,6 +216,13 @@ fn create_admin(app: &Application, params: SharedParams,
move |button| params.borrow_mut().audible_alarms = button.is_active()
});
sound_row.append(&audible);
let qrs_enabled = gtk::CheckButton::with_label("QRS tone");
qrs_enabled.set_active(params.borrow().qrs_tone_enabled);
qrs_enabled.connect_toggled({
let params = params.clone();
move |button| params.borrow_mut().qrs_tone_enabled = button.is_active()
});
sound_row.append(&qrs_enabled);
let test_sound = gtk::Button::with_label("Test tone");
test_sound.connect_clicked({
let audio = audio.clone();