Files
stimmwerk/src/ui/roll.rs
wlkns-dev c6aa2e25ba Karten Ziel, Original, Du, Akkord, Dein Ton, Referenzton melden Titel und Wert (#1070)
Ein Barrierefreiheits-Knoten je Karte in draw_pitch_cards. Neue kittest-Tests: Karten werden gefunden; in einer
simulierten Session zeigen Ziel und Du Notennamen (Sessions-Ordner umgelenkt, nichts gespeichert).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 12:13:41 +01:00

774 lines
26 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Piano-Roll-Ansicht: scrollende Tonhöhenkurve. Abbildung und Segmentierung sind rein und getestet.
use crate::chart::{ChordSpan, Grid, NoteChart, NoteKind};
use crate::config::UiConfig;
use crate::pitch::{HistoryPoint, note_name};
use crate::score::ChartScore;
use eframe::egui::{self, Align2, Color32, FontId, Rect, Stroke, pos2};
/// Abbildung Zeit/Tonhöhe → Bildschirm. Der rechte Rand liegt `lead_s` hinter „jetzt“
/// (0 = Tuner, > 0 = Vorschau auf kommende Noten im Chart-Modus).
pub struct Viewport {
pub rect: Rect,
pub t_now: f64,
pub window_s: f64,
pub lead_s: f64,
/// Tonhöhe (MIDI, kontinuierlich) am unteren und oberen Rand.
pub lo: f32,
pub hi: f32,
}
impl Viewport {
pub fn x(&self, t: f64) -> f32 {
let frac = ((t - (self.t_now + self.lead_s - self.window_s)) / self.window_s) as f32;
self.rect.left() + frac * self.rect.width()
}
pub fn y(&self, midi: f32) -> f32 {
let frac = (midi - self.lo) / (self.hi - self.lo);
self.rect.bottom() - frac * self.rect.height()
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CurvePoint {
pub t: f64,
pub midi: f32,
pub cents: f32,
}
/// Teilt den Verlauf an stimmlosen Stellen in zusammenhängende Kurvenstücke.
pub fn segments<'a>(points: impl Iterator<Item = &'a HistoryPoint>) -> Vec<Vec<CurvePoint>> {
let mut out: Vec<Vec<CurvePoint>> = Vec::new();
let mut open = false;
for p in points {
match p.est {
Some(e) => {
let cp = CurvePoint {
t: p.t,
midi: e.midi,
cents: e.cents,
};
if open {
out.last_mut().expect("offenes Segment").push(cp);
} else {
out.push(vec![cp]);
open = true;
}
}
None => open = false,
}
}
out
}
/// Kurvenstücke des Original-Gesangs für das Zeitfenster [t_from, t_to] (Sekunden), um `shift` Halbtöne
/// verschoben. Mit `fold_to` werden Oktavfehler der Erkennung auf die Oktave der Zielnote gefaltet.
pub fn original_segments(
frames: &[(f64, Option<f32>)],
t_from: f64,
t_to: f64,
shift: f32,
fold_to: Option<&NoteChart>,
) -> Vec<Vec<CurvePoint>> {
let lo = frames.partition_point(|f| f.0 < t_from);
let hi = frames.partition_point(|f| f.0 <= t_to);
let mut out: Vec<Vec<CurvePoint>> = Vec::new();
let mut open = false;
for &(t, m) in &frames[lo..hi.max(lo)] {
let Some(mut midi) = m else {
open = false;
continue;
};
midi += shift;
if let Some(c) = fold_to
&& let Some(i) = c.note_at(t * 1000.0)
{
midi = fold_to_target(midi, c.notes[i].midi_pitch);
}
let p = CurvePoint {
t,
midi,
cents: 0.0,
};
if open {
out.last_mut().expect("offenes Segment").push(p);
} else {
out.push(vec![p]);
open = true;
}
}
out
}
/// Eine Tonhöhen-Karte (Ziel, Original oder Du): großer Notenname, Zusatzzeilen und Cent-Anzeige.
pub struct PitchCard {
pub title: String,
pub color: Color32,
/// Kontinuierliche MIDI-Zahl; `None` = kein Ton (Karte gedämpft).
pub midi: Option<f32>,
/// Ersetzt den großen Notennamen durch einen anderen Text (z. B. Status).
pub big: Option<String>,
pub lines: Vec<(String, Color32)>,
/// Abweichung von der nächsten Halbtonstufe in Cent für die Anzeige unten.
pub meter: Option<f32>,
/// Pegel 0..=1 als LED-Kette (statt der Cent-Anzeige), z. B. für das Mikrofon.
pub level: Option<f32>,
}
/// Feste Höhe der Karten: die Anordnung darunter bleibt stabil, egal was angezeigt wird.
pub const CARD_H: f32 = 88.0;
/// Zeichnet die Karten nebeneinander als Geräte-Displays (dunkles Glas, leuchtende Schrift, LED-Anzeige).
pub fn draw_pitch_cards(ui: &mut egui::Ui, cards: &[PitchCard]) {
use super::gear;
// Etwas schmaler als die Fläche: die Bildlaufleiste schneidet sonst die rechte Karte an.
let (rect, _) = ui.allocate_exact_size(
egui::vec2(ui.available_width() - 14.0, CARD_H),
egui::Sense::hover(),
);
let painter = ui.painter_at(rect);
let gap = 8.0;
let w = (rect.width() - gap * (cards.len() as f32 - 1.0)) / cards.len() as f32;
for (i, c) in cards.iter().enumerate() {
let r = Rect::from_min_size(
pos2(rect.left() + i as f32 * (w + gap), rect.top()),
egui::vec2(w, CARD_H),
);
let active = c.midi.is_some();
// Gehäuse mit Rand, darin das dunkle Display.
painter.rect_filled(r, 7.0, gear::PLATE_BG);
painter.rect_stroke(
r,
7.0,
Stroke::new(1.5, gear::PLATE_EDGE),
egui::StrokeKind::Inside,
);
let lcd = r.shrink(5.0);
painter.rect_filled(lcd, 4.0, Color32::from_rgb(10, 13, 11));
painter.rect_stroke(
lcd,
4.0,
Stroke::new(
1.0,
if active {
c.color.gamma_multiply(0.45)
} else {
Color32::from_rgb(34, 38, 35)
},
),
egui::StrokeKind::Inside,
);
painter.text(
pos2(lcd.left() + 9.0, lcd.top() + 10.0),
Align2::LEFT_CENTER,
c.title.to_uppercase(),
FontId::proportional(11.5),
c.color.gamma_multiply(if active { 0.95 } else { 0.7 }),
);
let letter = c.big.clone().unwrap_or_else(|| {
c.midi
.map_or("–".to_string(), |m| note_name(m.round() as i32))
});
// Die Karte ist gemalt; für Barrierefreiheit und automatische Tests meldet sie Titel, Wert und Zusatzzeilen.
let spoken = std::iter::once(letter.clone())
.chain(c.lines.iter().take(2).map(|(t, _)| t.clone()))
.filter(|t| !t.trim().is_empty())
.collect::<Vec<_>>()
.join(", ");
ui.interact(
r,
ui.make_persistent_id(("pitch-card", i, &c.title)),
egui::Sense::hover(),
)
.widget_info(|| {
egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{}: {spoken}", c.title))
});
let glow = if active {
c.color
} else {
Color32::from_gray(70)
};
let letter_pos = pos2(lcd.left() + 9.0, lcd.top() + 38.0);
// Kurze große Texte (Notenname, Akkord) groß; lange Statustexte kleiner.
let font = FontId::monospace(if c.big.as_ref().is_some_and(|b| b.chars().count() > 4) {
20.0
} else {
38.0
});
// Schein hinter der Schrift.
painter.text(
letter_pos + egui::vec2(0.0, 0.0),
Align2::LEFT_CENTER,
&letter,
font.clone(),
glow.gamma_multiply(0.35),
);
painter.text(
letter_pos,
Align2::LEFT_CENTER,
letter,
font,
if active {
Color32::WHITE.gamma_multiply(0.92)
} else {
glow
},
);
for (k, (text, color)) in c.lines.iter().take(2).enumerate() {
if c.big.as_ref().is_some_and(|b| b.chars().count() > 4) {
// Statuskarten: Zusatzzeile rechts oben, damit sie den langen Statustext nicht überdeckt.
painter.text(
pos2(lcd.right() - 9.0, lcd.top() + 10.0 + k as f32 * 14.0),
Align2::RIGHT_CENTER,
text,
FontId::monospace(11.5),
*color,
);
} else {
painter.text(
pos2(
lcd.left() + lcd.width() * 0.46,
lcd.top() + 28.0 + k as f32 * 16.0,
),
Align2::LEFT_CENTER,
text,
FontId::monospace(12.5),
*color,
);
}
}
// Anzeige unten: LED-Pegelkette oder Cent-Skala (−50 … +50, Mitte = genau auf dem Ton).
let (ml, mw) = (lcd.left() + 9.0, lcd.width() - 18.0);
let my = lcd.bottom() - 10.0;
if let Some(level) = c.level {
let n = 28;
let lit = gear::lit_segments(level, n);
let step = mw / n as f32;
for k in 0..n {
gear::led(
&painter,
pos2(ml + (k as f32 + 0.5) * step, my),
k < lit,
gear::segment_color(k, n),
(step * 0.32).clamp(1.8, 3.6),
);
}
} else {
const N: usize = 21; // alle 5 Cent eine LED
let active_idx = c.meter.filter(|_| active).map(|cents| {
(((cents.clamp(-50.0, 50.0) + 50.0) / 5.0).round() as usize).min(N - 1)
});
let step = mw / N as f32;
for k in 0..N {
let cents = -50.0 + k as f32 * 5.0;
let color = if cents.abs() <= 15.0 {
gear::LED_GREEN
} else if cents.abs() <= 35.0 {
gear::LED_YELLOW
} else {
gear::LED_RED
};
let cx = ml + (k as f32 + 0.5) * step;
gear::led(
&painter,
pos2(cx, my),
Some(k) == active_idx,
color,
if k == N / 2 { 3.8 } else { 2.8 },
);
}
}
}
}
/// Farben im Chart-Modus: Original-Gesang und Gesang des Nutzers.
pub const ORIGINAL_COLOR: Color32 = Color32::from_rgb(80, 200, 235);
pub const USER_COLOR: Color32 = Color32::from_rgb(245, 110, 200);
/// Gewünschte Mitte des Ausschnitts: unverändert, solange das Ziel im Innenbereich liegt.
pub fn follow(center: f32, target: f32, half_range: f32, margin: f32) -> f32 {
let inner = half_range - margin;
if target > center + inner {
target - inner
} else if target < center - inner {
target + inner
} else {
center
}
}
/// Verschiebt `midi` um ganze Oktaven in die Nähe von `target` (für die oktavtolerante Anzeige).
pub fn fold_to_target(midi: f32, target: i32) -> f32 {
midi + 12.0 * ((target as f32 - midi) / 12.0).round()
}
/// Zusatzdaten für den Chart-Modus.
pub struct ChartOverlay<'a> {
pub chart: &'a NoteChart,
/// Kurve des Original-Gesangs (leer = ausgeblendet).
pub original: &'a [Vec<CurvePoint>],
/// Akkordleiste (leer = ausgeblendet) und ob mit Been geschrieben wird.
pub chords: &'a [ChordSpan],
pub chord_flats: bool,
/// Taktraster für Taktstriche und Zählzeiten (None = ohne).
pub grid: Option<Grid>,
pub now_ms: f64,
pub result: Option<&'a ChartScore>,
}
pub fn is_black_key(note: i32) -> bool {
matches!(note.rem_euclid(12), 1 | 3 | 6 | 8 | 10)
}
fn cents_color(cents: f32, cfg: &UiConfig) -> Color32 {
let c = cents.abs();
if c <= cfg.good_cents {
Color32::from_rgb(90, 210, 120)
} else if c <= cfg.ok_cents {
Color32::from_rgb(235, 200, 70)
} else {
Color32::from_rgb(240, 130, 60)
}
}
pub fn draw(
ui: &egui::Ui,
vp: &Viewport,
segs: &[Vec<CurvePoint>],
reference: Option<i32>,
cfg: &UiConfig,
overlay: Option<&ChartOverlay<'_>>,
) {
let painter = ui.painter_at(vp.rect);
painter.rect_filled(vp.rect, 4.0, Color32::from_rgb(24, 26, 32));
// Halbtonzeilen, zentriert auf ganzzahlige MIDI-Werte.
let row_h = vp.y(0.0) - vp.y(1.0);
for n in (vp.lo - 0.5).ceil() as i32..=(vp.hi + 0.5).floor() as i32 {
let band = Rect::from_min_max(
pos2(vp.rect.left(), vp.y(n as f32 + 0.5)),
pos2(vp.rect.right(), vp.y(n as f32 - 0.5)),
);
let fill = if is_black_key(n) {
Color32::from_rgb(18, 19, 24)
} else {
Color32::from_rgb(30, 33, 41)
};
painter.rect_filled(band, 0.0, fill);
if n.rem_euclid(12) == 0 {
let y = vp.y(n as f32 - 0.5);
painter.line_segment(
[pos2(vp.rect.left(), y), pos2(vp.rect.right(), y)],
Stroke::new(1.0, Color32::from_gray(70)),
);
}
if row_h >= 11.0 {
painter.text(
pos2(vp.rect.left() + 6.0, vp.y(n as f32)),
Align2::LEFT_CENTER,
note_name(n),
FontId::monospace((row_h * 0.7).min(13.0)),
Color32::from_gray(if is_black_key(n) { 110 } else { 150 }),
);
}
}
// Sekundenlinien.
let first = (vp.t_now - vp.window_s).ceil() as i64;
for s in first..=vp.t_now.floor() as i64 {
let x = vp.x(s as f64);
painter.line_segment(
[pos2(x, vp.rect.top()), pos2(x, vp.rect.bottom())],
Stroke::new(1.0, Color32::from_white_alpha(14)),
);
}
if let Some(n) = reference {
let y = vp.y(n as f32);
painter.line_segment(
[pos2(vp.rect.left() + 40.0, y), pos2(vp.rect.right(), y)],
Stroke::new(2.0, Color32::from_rgb(90, 150, 255)),
);
painter.text(
pos2(vp.rect.right() - 6.0, y - 3.0),
Align2::RIGHT_BOTTOM,
format!("Ref {}", note_name(n)),
FontId::proportional(12.0),
Color32::from_rgb(130, 175, 255),
);
}
if let Some(o) = overlay {
draw_grid_lines(&painter, vp, o);
draw_chord_lane(&painter, vp, o);
draw_notes(&painter, vp, o);
for seg in o.original {
for w in seg.windows(2) {
painter.line_segment(
[
pos2(vp.x(w[0].t), vp.y(w[0].midi)),
pos2(vp.x(w[1].t), vp.y(w[1].midi)),
],
Stroke::new(2.5, ORIGINAL_COLOR.gamma_multiply(0.9)),
);
}
}
// Legende.
let lx = vp.rect.right() - 150.0;
for (i, (color, label)) in [(ORIGINAL_COLOR, "Original"), (USER_COLOR, "Du")]
.into_iter()
.enumerate()
{
let lane = if o.chords.is_empty() { 0.0 } else { 26.0 };
let y = vp.rect.top() + 12.0 + lane + i as f32 * 16.0;
painter.line_segment([pos2(lx, y), pos2(lx + 22.0, y)], Stroke::new(3.0, color));
painter.text(
pos2(lx + 28.0, y),
Align2::LEFT_CENTER,
label,
FontId::proportional(12.0),
Color32::from_gray(210),
);
}
// „Jetzt“-Linie.
let x = vp.x(o.now_ms / 1000.0);
painter.line_segment(
[pos2(x, vp.rect.top()), pos2(x, vp.rect.bottom())],
Stroke::new(1.5, Color32::from_white_alpha(70)),
);
}
// Aktuelle Zielnote hervorheben und Kurve zeichnen.
if overlay.is_none()
&& let Some(last) = segs.last().and_then(|s| s.last())
{
let n = last.midi.round();
let band = Rect::from_min_max(
pos2(vp.rect.left(), vp.y(n + 0.5)),
pos2(vp.rect.right(), vp.y(n - 0.5)),
);
painter.rect_filled(band, 0.0, Color32::from_white_alpha(14));
}
for seg in segs {
for w in seg.windows(2) {
let (a, b) = (&w[0], &w[1]);
painter.line_segment(
[pos2(vp.x(a.t), vp.y(a.midi)), pos2(vp.x(b.t), vp.y(b.midi))],
Stroke::new(
3.0,
if overlay.is_some() {
USER_COLOR
} else {
cents_color(b.cents, cfg)
},
),
);
}
}
if let Some(last) = segs.last().and_then(|s| s.last()) {
// Markierung nur, wenn der letzte Punkt noch „frisch“ ist.
if (vp.t_now - last.t).abs() < 0.1 {
painter.circle_filled(
pos2(vp.x(last.t), vp.y(last.midi)),
6.0,
if overlay.is_some() {
USER_COLOR
} else {
cents_color(last.cents, cfg)
},
);
}
}
}
fn score_color(total: f32) -> Color32 {
let t = total.clamp(0.0, 1.0);
Color32::from_rgb((220.0 - 130.0 * t) as u8, (70.0 + 140.0 * t) as u8, 90)
}
/// Taktstriche (kräftig, mit Taktnummer unten) und Zählzeiten (schwach) hinter den Noten.
fn draw_grid_lines(painter: &egui::Painter, vp: &Viewport, o: &ChartOverlay<'_>) {
let Some(g) = o.grid else { return };
let (t_left, t_right) = (vp.t_now + vp.lead_s - vp.window_s, vp.t_now + vp.lead_s);
for (ms, beat, bar) in g.beats_between(t_left * 1000.0, t_right * 1000.0) {
let x = vp.x(ms / 1000.0);
if x < vp.rect.left() || x > vp.rect.right() {
continue;
}
let top = vp.rect.top();
if beat == 0 {
painter.line_segment(
[pos2(x, top), pos2(x, vp.rect.bottom())],
Stroke::new(1.6, Color32::from_white_alpha(70)),
);
if bar >= 1 {
painter.text(
pos2(x + 4.0, vp.rect.bottom() - 4.0),
Align2::LEFT_BOTTOM,
format!("{bar}"),
FontId::proportional(12.0),
Color32::from_white_alpha(130),
);
}
} else {
painter.line_segment(
[pos2(x, top), pos2(x, vp.rect.bottom())],
Stroke::new(1.0, Color32::from_white_alpha(22)),
);
}
}
}
/// Akkordleiste am oberen Rand: ein Feld je Akkord, der gerade klingende ist hervorgehoben.
fn draw_chord_lane(painter: &egui::Painter, vp: &Viewport, o: &ChartOverlay<'_>) {
const H: f32 = 22.0;
let (t_left, t_right) = (vp.t_now + vp.lead_s - vp.window_s, vp.t_now + vp.lead_s);
for c in o.chords {
let (a, b) = (c.start_ms / 1000.0, c.end_ms / 1000.0);
if b < t_left || a > t_right {
continue;
}
let (x0, x1) = (vp.x(a).max(vp.rect.left()), vp.x(b).min(vp.rect.right()));
if x1 - x0 < 2.0 {
continue;
}
let minor = c.name.ends_with('m');
let active = o.now_ms >= c.start_ms && o.now_ms < c.end_ms;
let fill = if active {
Color32::from_rgb(255, 176, 48)
} else if minor {
Color32::from_rgb(78, 62, 96)
} else {
Color32::from_rgb(58, 70, 92)
};
let r = Rect::from_min_max(
pos2(x0 + 1.0, vp.rect.top() + 2.0),
pos2(x1 - 1.0, vp.rect.top() + H),
);
painter.rect_filled(r, 4.0, fill);
if r.width() > 22.0 {
painter.text(
pos2(r.left() + 6.0, r.center().y),
Align2::LEFT_CENTER,
crate::import::chords::display_chord(&c.name, o.chord_flats),
FontId::proportional(14.0),
if active {
Color32::from_rgb(34, 22, 4)
} else {
Color32::WHITE
},
);
}
}
}
/// Zielbalken mit Silben; nach der Wertung nach Notenscore eingefärbt.
fn draw_notes(painter: &egui::Painter, vp: &Viewport, o: &ChartOverlay<'_>) {
for (i, n) in o.chart.notes.iter().enumerate() {
let (x0, x1) = (vp.x(n.start_ms / 1000.0), vp.x(n.end_ms() / 1000.0));
if x1 < vp.rect.left() || x0 > vp.rect.right() {
continue;
}
let rect = Rect::from_min_max(
pos2(x0 + 1.0, vp.y(n.midi_pitch as f32 + 0.42)),
pos2(x1 - 1.0, vp.y(n.midi_pitch as f32 - 0.42)),
);
let base = match n.typ {
NoteKind::Normal => Color32::from_rgb(70, 110, 190),
NoteKind::Golden => Color32::from_rgb(210, 170, 50),
NoteKind::Frei => Color32::from_rgb(140, 90, 180),
};
let fill = match o.result.and_then(|r| r.notes.get(i)) {
Some(s) => score_color(s.total),
None => base,
};
let active = o.now_ms >= n.start_ms && o.now_ms < n.end_ms();
painter.rect_filled(
rect,
5.0,
fill.gamma_multiply(if active { 1.0 } else { 0.75 }),
);
if active {
painter.rect_stroke(
rect,
5.0,
Stroke::new(2.0, Color32::WHITE),
egui::StrokeKind::Outside,
);
}
// Notenname im Balken, wenn Platz ist.
if rect.width() >= 26.0 && rect.height() >= 11.0 {
painter.text(
rect.center(),
Align2::CENTER_CENTER,
note_name(n.midi_pitch),
FontId::monospace((rect.height() * 0.62).clamp(9.0, 13.0)),
Color32::from_white_alpha(if active { 255 } else { 190 }),
);
}
}
}
/// Textzeile am unteren Rand: gesungene Silben gedämpft, aktuelle hervorgehoben.
pub fn draw_lyrics(ui: &egui::Ui, rect: Rect, chart: &NoteChart, now_ms: f64) {
let painter = ui.painter_at(rect);
let line = chart.lyric_line_at(now_ms);
let active = chart.note_at(now_ms);
let font = FontId::proportional(22.0);
let parts: Vec<(usize, String)> = line
.clone()
.filter_map(|i| {
let syl = chart.notes[i].silbe.as_deref()?;
let joined = match syl.strip_suffix('-') {
Some(stem) => stem.to_string(),
None => format!("{syl} "),
};
Some((i, joined))
})
.collect();
let galleys: Vec<_> = parts
.iter()
.map(|(i, text)| {
let color = if Some(*i) == active {
Color32::from_rgb(255, 215, 80)
} else if chart.notes[*i].end_ms() <= now_ms {
Color32::from_rgb(120, 200, 140)
} else {
Color32::from_gray(225)
};
painter.layout_no_wrap(text.clone(), font.clone(), color)
})
.collect();
let total: f32 = galleys.iter().map(|g| g.size().x).sum();
let mut x = rect.center().x - total / 2.0;
for g in galleys {
let w = g.size().x;
painter.galley(
pos2(x, rect.center().y - g.size().y / 2.0),
g,
Color32::WHITE,
);
x += w;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::pitch::PitchEstimate;
fn vp() -> Viewport {
Viewport {
rect: Rect::from_min_max(pos2(100.0, 50.0), pos2(900.0, 650.0)),
t_now: 20.0,
window_s: 8.0,
lead_s: 0.0,
lo: 48.0,
hi: 72.0,
}
}
#[test]
fn time_mapping() {
let v = vp();
assert!((v.x(20.0) - 900.0).abs() < 1e-3);
assert!((v.x(12.0) - 100.0).abs() < 1e-3);
assert!((v.x(16.0) - 500.0).abs() < 1e-3);
}
#[test]
fn lead_shifts_now_leftwards() {
let v = Viewport {
lead_s: 6.0,
..vp()
};
// „Jetzt“ bei 25 % der Breite, Zukunft rechts davon.
assert!((v.x(20.0) - 300.0).abs() < 1e-3);
assert!((v.x(26.0) - 900.0).abs() < 1e-3);
}
#[test]
fn octave_folding() {
assert!((fold_to_target(48.3, 60) - 60.3).abs() < 1e-4);
assert!((fold_to_target(75.0, 60) - 63.0).abs() < 1e-4);
assert!((fold_to_target(60.4, 60) - 60.4).abs() < 1e-4);
assert!(
(fold_to_target(65.9, 60) - 65.9).abs() < 1e-4,
"knapp unter Halboktave bleibt"
);
}
#[test]
fn pitch_mapping() {
let v = vp();
assert!((v.y(72.0) - 50.0).abs() < 1e-3);
assert!((v.y(48.0) - 650.0).abs() < 1e-3);
assert!((v.y(60.0) - 350.0).abs() < 1e-3);
}
#[test]
fn segments_split_at_unvoiced() {
let e = |m| Some(PitchEstimate::from_midi(m, 0.9));
let pts: Vec<HistoryPoint> = [e(60.0), e(60.2), None, None, e(62.0), None, e(64.0)]
.into_iter()
.enumerate()
.map(|(i, est)| HistoryPoint {
t: i as f64 * 0.01,
est,
})
.collect();
let s = segments(pts.iter());
assert_eq!(s.iter().map(Vec::len).collect::<Vec<_>>(), vec![2, 1, 1]);
assert!((s[0][1].cents - 20.0).abs() < 0.1);
}
#[test]
fn follow_keeps_center_inside_margin() {
// Bereich 24 → half 12, Rand 3 → innen ±9.
assert_eq!(follow(60.0, 65.0, 12.0, 3.0), 60.0);
assert_eq!(follow(60.0, 69.0, 12.0, 3.0), 60.0);
assert_eq!(follow(60.0, 73.0, 12.0, 3.0), 64.0);
assert_eq!(follow(60.0, 40.0, 12.0, 3.0), 49.0);
}
#[test]
fn original_segments_window_shift_fold_and_gaps() {
let frames: Vec<(f64, Option<f32>)> = (0..100)
.map(|i| {
(
i as f64 * 0.01,
if (40..50).contains(&i) {
None
} else {
Some(48.0)
},
)
})
.collect();
// Fenster 0,2–0,7 s: Lücke bei 0,40–0,50 teilt in zwei Stücke.
let s = original_segments(&frames, 0.2, 0.7, 0.0, None);
assert_eq!(s.len(), 2, "{s:?}");
assert!((s[0][0].t - 0.2).abs() < 1e-9 && s[1].last().unwrap().t <= 0.7 + 1e-9);
// Verschiebung.
assert!((original_segments(&frames, 0.0, 0.1, 3.0, None)[0][0].midi - 51.0).abs() < 1e-6);
// Oktavfaltung auf die Zielnote (60): 48 → 60.
let c = NoteChart::from_toml_str(
"title=\"t\"\n[[notes]]\nstart_ms=0\ndauer_ms=1000\nmidi_pitch=60",
None,
)
.unwrap();
let f = original_segments(&frames, 0.0, 0.3, 0.0, Some(&c));
assert!((f[0][0].midi - 60.0).abs() < 1e-6);
// Außerhalb der Daten: leer.
assert!(original_segments(&frames, 5.0, 6.0, 0.0, None).is_empty());
assert!(original_segments(&[], 0.0, 1.0, 0.0, None).is_empty());
}
#[test]
fn black_keys() {
assert!(is_black_key(61) && is_black_key(70) && is_black_key(-2));
assert!(!is_black_key(60) && !is_black_key(64));
}
}