Skip to main content

qualia_vision/biosense/rppg/
respiration_from_rppg_harmonic.rs

1//! Secondary RR from rPPG low-frequency content (RSA / baseline wander band).
2//!
3//! Uses the same breath band (~0.1–0.5 Hz) as motion RR. Not a second harmonic of HR;
4//! it is the low-frequency residual peak of a pulse-like trace after optional
5//! HR-band energy is ignored by band-limiting the spectral search.
6//! Fail closed on low SNR. No training.
7
8use crate::biosense::respiration::respiration_rate_from_motion_trace::spectral_rr_peak;
9use crate::biosense::respiration::rr_estimate::{RrEstimate, RR_MIN_SNR_DEFAULT};
10use crate::cv::error::CvError;
11
12/// Estimate respiratory rate from an rPPG (or raw green/pulse) trace by peaking
13/// in the respiratory band only.
14///
15/// * `rppg_trace` — pulse proxy (POS/CHROM/green), one sample per frame.
16/// * `fps` — sample rate.
17/// * `min_snr` — SNR gate; `None` → [`RR_MIN_SNR_DEFAULT`].
18pub fn respiration_from_rppg_harmonic(
19    rppg_trace: &[f32],
20    fps: f32,
21    min_snr: Option<f32>,
22) -> Result<RrEstimate, CvError> {
23    // Optional mild high-pass residual: subtract a short moving average so slow
24    // DC drift does not dominate, while leaving the 0.1–0.5 Hz band intact.
25    let n = rppg_trace.len();
26    if n < 64 || fps <= 1.0 {
27        return Err(CvError::InvalidParameter);
28    }
29    let win = ((fps * 0.35) as usize).clamp(3, 15) | 1; // odd, ~0.35 s
30    let half = win / 2;
31    let mut residual = vec![0.0f32; n];
32    for i in 0..n {
33        let lo = i.saturating_sub(half);
34        let hi = (i + half + 1).min(n);
35        let mut s = 0.0f32;
36        let mut c = 0u32;
37        for j in lo..hi {
38            s += rppg_trace[j];
39            c += 1;
40        }
41        let ma = s / c as f32;
42        residual[i] = rppg_trace[i] - ma;
43    }
44    spectral_rr_peak(&residual, fps, min_snr.unwrap_or(RR_MIN_SNR_DEFAULT))
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    fn synth_pulse_with_rr(hr_bpm: f32, rr_bpm: f32, fps: f32, n: usize, rr_amp: f32) -> Vec<f32> {
52        let f_hr = hr_bpm / 60.0;
53        let f_rr = rr_bpm / 60.0;
54        let mut t = vec![0.0f32; n];
55        for i in 0..n {
56            let ti = i as f32 / fps;
57            // Cardiac carrier + respiratory AM/baseline (low-freq sinusoid).
58            let pulse = (core::f32::consts::TAU * f_hr * ti).sin();
59            let breath = rr_amp * (core::f32::consts::TAU * f_rr * ti).sin();
60            t[i] = pulse * (1.0 + 0.15 * breath) + breath;
61        }
62        t
63    }
64
65    #[test]
66    fn recovers_rr_from_rppg_like_trace() {
67        let fps = 30.0;
68        let t = synth_pulse_with_rr(72.0, 16.0, fps, 480, 0.8);
69        let e = respiration_from_rppg_harmonic(&t, fps, Some(2.0)).unwrap();
70        assert!(
71            (e.breaths_per_min - 16.0).abs() < 2.0,
72            "rr={}",
73            e.breaths_per_min
74        );
75        assert!(e.confidence > 0.15);
76    }
77
78    #[test]
79    fn fails_closed_on_flat_trace() {
80        let t = vec![1.0f32; 200];
81        assert!(respiration_from_rppg_harmonic(&t, 30.0, Some(4.0)).is_err());
82    }
83}