forked from wlkns-dev/stimmwerk
Singtrainer: Phasen 0-6, Stimmfinder und Latenzkalibrierung
Rust-Desktop-App (egui/eframe, cpal) zum Singüben. - Audio: Geräteauswahl, Pegelanzeige, Mixer ohne Locks im Callback (Backing, Original-Gesang, Führungston, Aufnahme, Klick), Dekodierung mit symphonia, Resampling mit rubato, Mikroaufnahme als WAV - Pitch: YIN mit Konfidenz, Median-Glättung, Oktavsprung-Schutz - Live-Ansicht: scrollende Tonhöhenkurve, Referenzton - Chart: NoteChart (TOML), Scoring (Tonhöhe oktavtolerant, Timing, Stabilität), Session mit Countdown, Testchart - Aufnahme und Review: Session-Datei (JSON) mit Mikrospur, Verlauf, Wiedergabe solo oder gemischt - Stimmfinder: Sprechlage, Legato, Sirene, Haltetöne, Tessitura, Profil-Verlauf, Transponierung und Warnung für Charts - Latenzkalibrierung: Klickzug, Einsatzerkennung, Offset in der Config - Simulationsmodus (--sim) und Tests ohne Audiogerät Manuelle Abnahmen am Gerät stehen noch aus (siehe README). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
100
src/pitch/history.rs
Normal file
100
src/pitch/history.rs
Normal file
@ -0,0 +1,100 @@
|
||||
//! 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<PitchEstimate>,
|
||||
}
|
||||
|
||||
pub struct PitchHistory {
|
||||
points: VecDeque<HistoryPoint>,
|
||||
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<PitchEstimate>) {
|
||||
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<Item = &HistoryPoint> {
|
||||
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<PitchEstimate> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
226
src/pitch/mod.rs
Normal file
226
src/pitch/mod.rs
Normal file
@ -0,0 +1,226 @@
|
||||
//! Tonhöhenerkennung (YIN) mit Glättung. Rein funktional, ohne Audiogerät testbar.
|
||||
|
||||
mod history;
|
||||
mod note;
|
||||
mod track;
|
||||
mod yin;
|
||||
|
||||
pub use history::{HistoryPoint, PitchHistory};
|
||||
pub use note::note_name;
|
||||
pub use track::{PitchEstimate, Tracker};
|
||||
pub use yin::detect;
|
||||
|
||||
use crate::config::PitchConfig;
|
||||
|
||||
/// Frame → geglätteter Schätzwert. Hält den Tracker-Zustand.
|
||||
pub struct Analyzer {
|
||||
cfg: PitchConfig,
|
||||
sample_rate: f32,
|
||||
tracker: Tracker,
|
||||
}
|
||||
|
||||
impl Analyzer {
|
||||
pub fn new(cfg: PitchConfig, sample_rate: f32) -> Self {
|
||||
Self {
|
||||
tracker: Tracker::new(cfg.clone()),
|
||||
cfg,
|
||||
sample_rate,
|
||||
}
|
||||
}
|
||||
|
||||
/// Anzahl Samples pro Analysefenster.
|
||||
pub fn frame_len(&self) -> usize {
|
||||
(self.cfg.frame_ms * 0.001 * self.sample_rate) as usize
|
||||
}
|
||||
|
||||
/// Anzahl Samples zwischen zwei Analysen.
|
||||
pub fn hop_len(&self) -> usize {
|
||||
((self.cfg.hop_ms * 0.001 * self.sample_rate) as usize).max(1)
|
||||
}
|
||||
|
||||
pub fn process(&mut self, frame: &[f32]) -> Option<PitchEstimate> {
|
||||
let raw = detect(frame, self.sample_rate, &self.cfg);
|
||||
self.tracker.push(raw)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::f32::consts::TAU;
|
||||
|
||||
const RATES: [f32; 2] = [44_100.0, 48_000.0];
|
||||
|
||||
fn cents_err(measured: f32, expected: f32) -> f32 {
|
||||
1200.0 * (measured / expected).log2()
|
||||
}
|
||||
|
||||
fn frame_len(sr: f32, cfg: &PitchConfig) -> usize {
|
||||
(cfg.frame_ms * 0.001 * sr) as usize
|
||||
}
|
||||
|
||||
fn sine(f: f32, sr: f32, n: usize, phase: f32) -> Vec<f32> {
|
||||
(0..n)
|
||||
.map(|i| 0.5 * (TAU * f * i as f32 / sr + phase).sin())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Obertonreiche Stimme; `fund` skaliert die Grundwelle (klein = „fehlende Grundwelle“).
|
||||
fn voice(f: f32, sr: f32, n: usize, fund: f32) -> Vec<f32> {
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let t = i as f32 / sr;
|
||||
(1..=8)
|
||||
.filter(|h| f * (*h as f32) < sr / 2.0)
|
||||
.map(|h| {
|
||||
let amp = if h == 1 { fund } else { 1.0 / h as f32 };
|
||||
amp * (TAU * f * h as f32 * t).sin()
|
||||
})
|
||||
.sum::<f32>()
|
||||
* 0.2
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn saw(f: f32, sr: f32, n: usize) -> Vec<f32> {
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let p = (f * i as f32 / sr).fract();
|
||||
0.5 * (2.0 * p - 1.0)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sine_accuracy_over_range() {
|
||||
let cfg = PitchConfig::default();
|
||||
for sr in RATES {
|
||||
let n = frame_len(sr, &cfg);
|
||||
let mut f = 75.0f32;
|
||||
while f < 1050.0 {
|
||||
let r = detect(&sine(f, sr, n, 0.3), sr, &cfg)
|
||||
.unwrap_or_else(|| panic!("keine Erkennung bei {f} Hz / {sr}"));
|
||||
let e = cents_err(r.freq_hz, f);
|
||||
assert!(e.abs() < 5.0, "{f} Hz @ {sr}: {e:.2} Cent");
|
||||
assert!(r.confidence > 0.9, "{f} Hz: Konfidenz {}", r.confidence);
|
||||
f *= 1.07;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sawtooth_accuracy() {
|
||||
let cfg = PitchConfig::default();
|
||||
for sr in RATES {
|
||||
let n = frame_len(sr, &cfg);
|
||||
for f in [82.4, 110.0, 196.0, 261.6, 440.0, 659.3, 880.0] {
|
||||
let r = detect(&saw(f, sr, n), sr, &cfg).expect("Erkennung");
|
||||
let e = cents_err(r.freq_hz, f);
|
||||
assert!(e.abs() < 5.0, "{f} Hz @ {sr}: {e:.2} Cent");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weak_fundamental_no_octave_error() {
|
||||
let cfg = PitchConfig::default();
|
||||
let sr = 48_000.0;
|
||||
let n = frame_len(sr, &cfg);
|
||||
for f in [110.0, 165.0, 220.0, 330.0, 440.0] {
|
||||
let r = detect(&voice(f, sr, n, 0.15), sr, &cfg).expect("Erkennung");
|
||||
assert!(
|
||||
cents_err(r.freq_hz, f).abs() < 5.0,
|
||||
"{f} Hz erkannt als {}",
|
||||
r.freq_hz
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silence_and_noise_are_unvoiced() {
|
||||
let cfg = PitchConfig::default();
|
||||
let sr = 48_000.0;
|
||||
let n = frame_len(sr, &cfg);
|
||||
assert!(detect(&vec![0.0; n], sr, &cfg).is_none());
|
||||
assert!(
|
||||
detect(
|
||||
&sine(220.0, sr, n, 0.0)
|
||||
.iter()
|
||||
.map(|s| s * 0.001)
|
||||
.collect::<Vec<_>>(),
|
||||
sr,
|
||||
&cfg
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
// Deterministisches Rauschen (LCG), laut genug für das Stille-Gate.
|
||||
let mut x = 12345u32;
|
||||
let noise: Vec<f32> = (0..n)
|
||||
.map(|_| {
|
||||
x = x.wrapping_mul(1664525).wrapping_add(1013904223);
|
||||
(x >> 8) as f32 / (1u32 << 24) as f32 - 0.5
|
||||
})
|
||||
.collect();
|
||||
let conf = detect(&noise, sr, &cfg).map_or(0.0, |r| r.confidence);
|
||||
assert!(conf < cfg.min_confidence, "Rauschen mit Konfidenz {conf}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_short_frame_is_rejected() {
|
||||
let cfg = PitchConfig::default();
|
||||
assert!(detect(&sine(220.0, 48_000.0, 500, 0.0), 48_000.0, &cfg).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analyzer_follows_stream_with_vibrato() {
|
||||
let cfg = PitchConfig::default();
|
||||
let sr = 48_000.0;
|
||||
let mut a = Analyzer::new(cfg, sr);
|
||||
// 1,5 s A3 (220 Hz) mit 5,5 Hz Vibrato ±20 Cent, sauber phasenkontinuierlich.
|
||||
let total = (1.5 * sr) as usize;
|
||||
let mut phase = 0.0f32;
|
||||
let sig: Vec<f32> = (0..total)
|
||||
.map(|i| {
|
||||
let t = i as f32 / sr;
|
||||
let f = 220.0 * 2f32.powf(20.0 * (TAU * 5.5 * t).sin() / 1200.0);
|
||||
phase += TAU * f / sr;
|
||||
0.5 * phase.sin()
|
||||
})
|
||||
.collect();
|
||||
let (n, hop) = (a.frame_len(), a.hop_len());
|
||||
let mut count = 0;
|
||||
let mut start = 0;
|
||||
while start + n <= sig.len() {
|
||||
if let Some(e) = a.process(&sig[start..start + n]) {
|
||||
count += 1;
|
||||
assert_eq!(
|
||||
e.note,
|
||||
57,
|
||||
"A3 erwartet, bekam {} ({:.1} Hz)",
|
||||
note_name(e.note),
|
||||
e.freq_hz
|
||||
);
|
||||
assert!(e.cents.abs() < 25.0, "{:.1} Cent", e.cents);
|
||||
}
|
||||
start += hop;
|
||||
}
|
||||
assert!(count > 100, "zu wenige Schätzwerte: {count}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analyzer_reports_note_and_cents() {
|
||||
let cfg = PitchConfig::default();
|
||||
let sr = 44_100.0;
|
||||
let mut a = Analyzer::new(cfg, sr);
|
||||
// 20 Cent über C4
|
||||
let f = 261.6256 * 2f32.powf(20.0 / 1200.0);
|
||||
let sig = sine(f, sr, a.frame_len(), 0.0);
|
||||
let mut e = None;
|
||||
for _ in 0..5 {
|
||||
e = a.process(&sig);
|
||||
}
|
||||
let e = e.expect("Schätzwert");
|
||||
assert_eq!(note_name(e.note), "C4");
|
||||
assert!((e.cents - 20.0).abs() < 3.0, "{} Cent", e.cents);
|
||||
}
|
||||
}
|
||||
40
src/pitch/note.rs
Normal file
40
src/pitch/note.rs
Normal file
@ -0,0 +1,40 @@
|
||||
//! Umrechnung Frequenz ↔ MIDI ↔ Notenname ↔ Cent (A4 = 440 Hz = MIDI 69).
|
||||
|
||||
pub fn midi_from_hz(hz: f32) -> f32 {
|
||||
69.0 + 12.0 * (hz / 440.0).log2()
|
||||
}
|
||||
|
||||
/// Abweichung in Cent von der nächsten Halbtonstufe, in -50..=50.
|
||||
pub fn cents_from_midi(midi: f32) -> f32 {
|
||||
(midi - midi.round()) * 100.0
|
||||
}
|
||||
|
||||
pub fn note_name(midi: i32) -> String {
|
||||
const NAMES: [&str; 12] = [
|
||||
"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B",
|
||||
];
|
||||
let octave = midi.div_euclid(12) - 1;
|
||||
format!("{}{}", NAMES[midi.rem_euclid(12) as usize], octave)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reference_pitches() {
|
||||
assert!((midi_from_hz(440.0) - 69.0).abs() < 1e-4);
|
||||
assert!((midi_from_hz(261.6256) - 60.0).abs() < 1e-3);
|
||||
assert_eq!(note_name(69), "A4");
|
||||
assert_eq!(note_name(60), "C4");
|
||||
assert_eq!(note_name(61), "C#4");
|
||||
assert_eq!(note_name(0), "C-1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cents() {
|
||||
assert!(cents_from_midi(69.0).abs() < 1e-4);
|
||||
assert!((cents_from_midi(69.25) - 25.0).abs() < 1e-3);
|
||||
assert!((cents_from_midi(68.75) + 25.0).abs() < 1e-3);
|
||||
}
|
||||
}
|
||||
204
src/pitch/track.rs
Normal file
204
src/pitch/track.rs
Normal file
@ -0,0 +1,204 @@
|
||||
//! Glättung (Median), Voiced/Unvoiced-Entscheidung und Oktavsprung-Schutz.
|
||||
|
||||
use super::note::{cents_from_midi, midi_from_hz};
|
||||
use super::yin::RawPitch;
|
||||
use crate::config::PitchConfig;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct PitchEstimate {
|
||||
pub freq_hz: f32,
|
||||
/// Kontinuierliche MIDI-Zahl (A4 = 69.0).
|
||||
pub midi: f32,
|
||||
/// Nächste Halbtonstufe.
|
||||
pub note: i32,
|
||||
/// Abweichung von `note` in Cent (-50..=50).
|
||||
pub cents: f32,
|
||||
pub confidence: f32,
|
||||
/// Überbrückter Aussetzer: der Wert stammt aus dem Verlauf, der aktuelle Frame war stimmlos.
|
||||
pub held: bool,
|
||||
}
|
||||
|
||||
impl PitchEstimate {
|
||||
/// Baut einen Schätzwert aus einer kontinuierlichen MIDI-Zahl.
|
||||
pub fn from_midi(midi: f32, confidence: f32) -> Self {
|
||||
Self {
|
||||
freq_hz: 440.0 * 2f32.powf((midi - 69.0) / 12.0),
|
||||
midi,
|
||||
note: midi.round() as i32,
|
||||
cents: cents_from_midi(midi),
|
||||
confidence,
|
||||
held: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Tracker {
|
||||
cfg: PitchConfig,
|
||||
history: VecDeque<f32>,
|
||||
unvoiced_run: usize,
|
||||
/// Anzahl aufeinanderfolgender Frames mit gleichem, noch unbestätigtem Oktavsprung (Vorzeichen, Zähler).
|
||||
pending_jump: Option<(f32, usize)>,
|
||||
last_conf: f32,
|
||||
}
|
||||
|
||||
impl Tracker {
|
||||
pub fn new(cfg: PitchConfig) -> Self {
|
||||
Self {
|
||||
cfg,
|
||||
history: VecDeque::new(),
|
||||
unvoiced_run: 0,
|
||||
pending_jump: None,
|
||||
last_conf: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn push(&mut self, raw: Option<RawPitch>) -> Option<PitchEstimate> {
|
||||
match raw.filter(|r| r.confidence >= self.cfg.min_confidence) {
|
||||
None => {
|
||||
self.unvoiced_run += 1;
|
||||
self.pending_jump = None;
|
||||
if self.unvoiced_run > self.cfg.release_frames {
|
||||
self.history.clear();
|
||||
}
|
||||
// Kurze Aussetzer überbrücken, damit die Anzeige nicht flackert.
|
||||
return self.smoothed();
|
||||
}
|
||||
Some(r) => {
|
||||
self.unvoiced_run = 0;
|
||||
self.last_conf = r.confidence;
|
||||
self.accept(midi_from_hz(r.freq_hz));
|
||||
}
|
||||
}
|
||||
self.smoothed()
|
||||
}
|
||||
|
||||
fn accept(&mut self, midi: f32) {
|
||||
if let Some(reference) = self.median() {
|
||||
let d = midi - reference;
|
||||
let octaves = (d / 12.0).round();
|
||||
let is_octave =
|
||||
octaves != 0.0 && (d - octaves * 12.0).abs() <= self.cfg.octave_tolerance_semitones;
|
||||
if is_octave {
|
||||
let sign = octaves.signum();
|
||||
let count = match self.pending_jump {
|
||||
Some((s, n)) if s == sign => n + 1,
|
||||
_ => 1,
|
||||
};
|
||||
if count < self.cfg.octave_confirm_frames {
|
||||
self.pending_jump = Some((sign, count));
|
||||
return; // Ausreißer verwerfen, alter Wert bleibt
|
||||
}
|
||||
// Sprung bestätigt: neu beginnen.
|
||||
self.history.clear();
|
||||
}
|
||||
}
|
||||
self.pending_jump = None;
|
||||
self.history.push_back(midi);
|
||||
while self.history.len() > self.cfg.median_len.max(1) {
|
||||
self.history.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
fn median(&self) -> Option<f32> {
|
||||
if self.history.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut v: Vec<f32> = self.history.iter().copied().collect();
|
||||
v.sort_by(f32::total_cmp);
|
||||
Some(v[v.len() / 2])
|
||||
}
|
||||
|
||||
fn smoothed(&self) -> Option<PitchEstimate> {
|
||||
// Während eines längeren stimmlosen Abschnitts gibt es nichts anzuzeigen.
|
||||
if self.unvoiced_run > self.cfg.release_frames {
|
||||
return None;
|
||||
}
|
||||
let midi = self.median()?;
|
||||
Some(PitchEstimate {
|
||||
held: self.unvoiced_run > 0,
|
||||
..PitchEstimate::from_midi(midi, self.last_conf)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn raw(hz: f32) -> Option<RawPitch> {
|
||||
Some(RawPitch {
|
||||
freq_hz: hz,
|
||||
confidence: 0.95,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_octave_outlier_is_suppressed() {
|
||||
let mut t = Tracker::new(PitchConfig::default());
|
||||
for _ in 0..5 {
|
||||
t.push(raw(220.0));
|
||||
}
|
||||
let e = t.push(raw(440.0)).unwrap();
|
||||
assert!((e.freq_hz - 220.0).abs() < 0.5, "{e:?}");
|
||||
let e = t.push(raw(110.0)).unwrap();
|
||||
assert!((e.freq_hz - 220.0).abs() < 0.5, "{e:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sustained_octave_change_is_accepted() {
|
||||
let mut t = Tracker::new(PitchConfig::default());
|
||||
for _ in 0..5 {
|
||||
t.push(raw(220.0));
|
||||
}
|
||||
let mut last = None;
|
||||
for _ in 0..PitchConfig::default().octave_confirm_frames {
|
||||
last = t.push(raw(440.0));
|
||||
}
|
||||
assert!((last.unwrap().freq_hz - 440.0).abs() < 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_interval_is_not_delayed() {
|
||||
let mut t = Tracker::new(PitchConfig::default());
|
||||
for _ in 0..5 {
|
||||
t.push(raw(220.0));
|
||||
}
|
||||
// Quinte aufwärts: kein Oktavsprung, Median folgt nach wenigen Frames.
|
||||
let mut e = None;
|
||||
for _ in 0..3 {
|
||||
e = t.push(raw(330.0));
|
||||
}
|
||||
assert!((e.unwrap().freq_hz - 330.0).abs() < 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bridged_gaps_are_marked_held() {
|
||||
let mut t = Tracker::new(PitchConfig::default());
|
||||
assert!(!t.push(raw(220.0)).unwrap().held);
|
||||
let weak = Some(RawPitch {
|
||||
freq_hz: 500.0,
|
||||
confidence: 0.3,
|
||||
});
|
||||
assert!(t.push(weak).unwrap().held);
|
||||
assert!(!t.push(raw(220.0)).unwrap().held);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn low_confidence_is_unvoiced_and_releases() {
|
||||
let cfg = PitchConfig::default();
|
||||
let mut t = Tracker::new(cfg.clone());
|
||||
for _ in 0..5 {
|
||||
t.push(raw(220.0));
|
||||
}
|
||||
let weak = Some(RawPitch {
|
||||
freq_hz: 500.0,
|
||||
confidence: 0.3,
|
||||
});
|
||||
assert!(t.push(weak).is_some(), "kurzer Aussetzer wird überbrückt");
|
||||
for _ in 0..=cfg.release_frames {
|
||||
t.push(weak);
|
||||
}
|
||||
assert!(t.push(weak).is_none());
|
||||
}
|
||||
}
|
||||
84
src/pitch/yin.rs
Normal file
84
src/pitch/yin.rs
Normal file
@ -0,0 +1,84 @@
|
||||
//! YIN (de Cheveigné & Kawahara 2002): Differenzfunktion, kumulative Normierung,
|
||||
//! absolute Schwelle, parabolische Interpolation.
|
||||
|
||||
use crate::config::PitchConfig;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct RawPitch {
|
||||
pub freq_hz: f32,
|
||||
/// 1 - d'(tau); 1.0 = perfekt periodisch.
|
||||
pub confidence: f32,
|
||||
}
|
||||
|
||||
/// Erkennt die Grundfrequenz in einem Frame. `None` bei Stille, zu kurzem Frame oder ohne Treffer.
|
||||
pub fn detect(frame: &[f32], sample_rate: f32, cfg: &PitchConfig) -> Option<RawPitch> {
|
||||
let tau_min = ((sample_rate / cfg.max_hz).floor() as usize).max(2);
|
||||
let tau_max = (sample_rate / cfg.min_hz).ceil() as usize;
|
||||
if frame.len() <= tau_max + 2 * tau_min || tau_max <= tau_min {
|
||||
return None;
|
||||
}
|
||||
let window = frame.len() - tau_max;
|
||||
|
||||
let rms = (frame.iter().map(|s| s * s).sum::<f32>() / frame.len() as f32).sqrt();
|
||||
if rms < cfg.silence_rms {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Differenzfunktion d(tau) und kumulativ normierte d'(tau).
|
||||
let mut cmnd = vec![1.0f32; tau_max + 1];
|
||||
let mut running = 0.0f32;
|
||||
for tau in 1..=tau_max {
|
||||
let mut d = 0.0f32;
|
||||
for j in 0..window {
|
||||
let diff = frame[j] - frame[j + tau];
|
||||
d += diff * diff;
|
||||
}
|
||||
running += d;
|
||||
cmnd[tau] = if running > 0.0 {
|
||||
d * tau as f32 / running
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
}
|
||||
|
||||
// Erstes Tal unter der Schwelle, dann bis zum lokalen Minimum absteigen.
|
||||
let mut tau = None;
|
||||
let mut t = tau_min;
|
||||
while t < tau_max {
|
||||
if cmnd[t] < cfg.yin_threshold {
|
||||
while t + 1 < tau_max && cmnd[t + 1] < cmnd[t] {
|
||||
t += 1;
|
||||
}
|
||||
tau = Some(t);
|
||||
break;
|
||||
}
|
||||
t += 1;
|
||||
}
|
||||
// Ohne Schwellentreffer: globales Minimum; die Konfidenz-Schwelle entscheidet später.
|
||||
let tau = tau.unwrap_or_else(|| {
|
||||
(tau_min..tau_max)
|
||||
.min_by(|&a, &b| cmnd[a].total_cmp(&cmnd[b]))
|
||||
.unwrap_or(tau_min)
|
||||
});
|
||||
|
||||
let better = parabolic(&cmnd, tau);
|
||||
let confidence = (1.0 - cmnd[tau]).clamp(0.0, 1.0);
|
||||
(better > 0.0).then_some(RawPitch {
|
||||
freq_hz: sample_rate / better,
|
||||
confidence,
|
||||
})
|
||||
}
|
||||
|
||||
/// Parabel durch drei Punkte um `tau`; liefert die verfeinerte Periodenlänge.
|
||||
fn parabolic(c: &[f32], tau: usize) -> f32 {
|
||||
if tau == 0 || tau + 1 >= c.len() {
|
||||
return tau as f32;
|
||||
}
|
||||
let (a, b, d) = (c[tau - 1], c[tau], c[tau + 1]);
|
||||
let denom = a - 2.0 * b + d;
|
||||
if denom.abs() < 1e-12 {
|
||||
tau as f32
|
||||
} else {
|
||||
tau as f32 + 0.5 * (a - d) / denom
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user