//! Zeitgestempelter Verlauf der Pitch-Schätzwerte (für Live-Ansicht, später Review). use super::track::PitchEstimate; use std::collections::VecDeque; #[derive(Debug, Clone, Copy, PartialEq)] pub struct HistoryPoint { /// Sekunden seit Streamstart. pub t: f64, pub est: Option, } pub struct PitchHistory { points: VecDeque, max_age_s: f64, } impl PitchHistory { pub fn new(max_age_s: f64) -> Self { Self { points: VecDeque::new(), max_age_s, } } pub fn push(&mut self, t: f64, est: Option) { self.points.push_back(HistoryPoint { t, est }); while self .points .front() .is_some_and(|p| p.t < t - self.max_age_s) { self.points.pop_front(); } } /// Hebt die Aufbewahrungsdauer an (z. B. für eine ganze Session); verkürzt nie. pub fn ensure_retention(&mut self, secs: f64) { self.max_age_s = self.max_age_s.max(secs); } pub fn clear(&mut self) { self.points.clear(); } pub fn latest(&self) -> Option<&HistoryPoint> { self.points.back() } /// Alle Punkte mit `t >= t0`. pub fn since(&self, t0: f64) -> impl Iterator { let start = self.points.partition_point(|p| p.t < t0); self.points.range(start..) } } #[cfg(test)] mod tests { use super::*; fn est(midi: f32) -> Option { Some(PitchEstimate::from_midi(midi, 0.9)) } #[test] fn trims_old_points() { let mut h = PitchHistory::new(1.0); for i in 0..300 { h.push(i as f64 * 0.01, est(60.0)); } let first = h.since(0.0).next().unwrap().t; assert!(first >= 2.99 - 1.0 - 1e-9, "{first}"); assert!((h.latest().unwrap().t - 2.99).abs() < 1e-9); } #[test] fn retention_can_grow_but_not_shrink() { let mut h = PitchHistory::new(1.0); h.ensure_retention(5.0); for i in 0..600 { h.push(i as f64 * 0.01, None); } assert!(h.since(0.0).next().unwrap().t >= 5.99 - 5.0 - 1e-9); assert!(h.since(0.0).next().unwrap().t < 1.1, "5 s bleiben erhalten"); h.ensure_retention(2.0); h.push(20.0, None); assert_eq!(h.since(0.0).count(), 1, "alte Punkte fallen heraus"); } #[test] fn since_selects_window() { let mut h = PitchHistory::new(10.0); for i in 0..100 { h.push(i as f64 * 0.1, if i % 2 == 0 { est(60.0) } else { None }); } let n = h.since(5.0).count(); assert_eq!(n, 50); assert_eq!(h.since(100.0).count(), 0); } }