use crate::synth::va::dsp::DelayLine;
use crate::synth::va::engine::param;
use crate::synth::va::fx::{Effect, Params};
use crate::synth::va::m;
const SCALES: [&[i32]; 7] = [
&[0, 2, 4, 5, 7, 9, 11],
&[0, 2, 3, 5, 7, 8, 10],
&[0, 2, 3, 5, 7, 9, 10],
&[0, 2, 4, 5, 7, 9, 10],
&[0, 2, 3, 5, 7, 8, 11],
&[0, 2, 4, 7, 9],
&[0, 3, 5, 7, 10],
];
const INT_ZERO: i32 = 24;
fn note_number(hz: f32) -> Option<i32> {
if hz <= 0.0 {
return None;
}
let n = 69.0 + 12.0 * m::ln(hz / 440.0) / core::f32::consts::LN_2;
Some(libm_round(n))
}
fn libm_round(x: f32) -> i32 {
if x >= 0.0 {
(x + 0.5) as i32
} else {
-((-x + 0.5) as i32)
}
}
fn div_mod_floor(a: i32, b: i32) -> (i32, i32) {
let q = a.div_euclid(b);
(q, a.rem_euclid(b))
}
pub(crate) fn scale_shift(note: i32, key: i32, scale: &[i32], degrees: i32) -> i32 {
let (oct, pc) = div_mod_floor(note - key, 12);
let mut idx = 0;
for (i, &s) in scale.iter().enumerate() {
if s <= pc {
idx = i as i32;
}
}
let len = scale.len() as i32;
let (oct2, idx2) = div_mod_floor(idx + degrees, len);
let target = (oct + oct2) * 12 + scale[idx2 as usize];
target - (note - key)
}
pub struct PitchShifter {
line: DelayLine,
window: f32,
phase: f32,
}
impl PitchShifter {
pub const WINDOW_SECS: f32 = 0.05;
pub fn new(sample_rate: u32) -> Self {
let window = Self::WINDOW_SECS * sample_rate.max(1) as f32;
PitchShifter {
line: DelayLine::new(window as usize + 4),
window,
phase: 0.0,
}
}
pub fn process(&mut self, x: f32, ratio: f32) -> f32 {
self.line.push(x);
let w = self.window;
let tri = |p: f32| 1.0 - (2.0 * p - 1.0).abs();
let p1 = self.phase;
let p2 = if p1 >= 0.5 { p1 - 0.5 } else { p1 + 0.5 };
let y = self.line.tap_frac(p1 * w) * tri(p1) + self.line.tap_frac(p2 * w) * tri(p2);
self.phase += (1.0 - ratio) / w;
self.phase -= self.phase.floor();
y
}
pub fn clear(&mut self) {
self.line.clear();
self.phase = 0.0;
}
}
pub(crate) struct HarmonizerFx {
shifters: [PitchShifter; 2],
on: bool,
mix: f32,
ratios: [f32; 2],
active: [bool; 2],
spread: f32,
last: Option<[u32; 8]>,
}
impl HarmonizerFx {
pub(crate) fn new(sample_rate: u32) -> Self {
HarmonizerFx {
shifters: [
PitchShifter::new(sample_rate),
PitchShifter::new(sample_rate),
],
on: false,
mix: 0.0,
ratios: [1.0; 2],
active: [false; 2],
spread: 0.0,
last: None,
}
}
fn semitones(p: &Params<'_>, int: u32, note: Option<i32>) -> i32 {
let steps = int as i32 - INT_ZERO;
if p.raw(param::HARM_MODE) == 0 {
return steps.clamp(-24, 24);
}
let Some(note) = note else { return 0 };
let scale = SCALES[(p.raw(param::HARM_SCALE) as usize).min(SCALES.len() - 1)];
scale_shift(note, p.raw(param::HARM_KEY) as i32, scale, steps)
}
}
impl Effect for HarmonizerFx {
fn update(&mut self, p: &Params<'_>, _sample_rate: f32) -> bool {
self.mix = p.get(param::HARM) / 100.0;
self.on |= self.mix > 0.0;
if !self.on {
return false;
}
let state = [
p.note_hz.to_bits(),
p.raw(param::HARM_MODE),
p.raw(param::HARM_INT),
p.raw(param::HARM_INT2),
p.raw(param::HARM_KEY),
p.raw(param::HARM_SCALE),
p.raw(param::HARM_DET),
p.raw(param::HARM_WIDTH),
];
if self.last != Some(state) {
self.last = Some(state);
let note = note_number(p.note_hz);
let ints = [p.raw(param::HARM_INT), p.raw(param::HARM_INT2)];
let det = p.get(param::HARM_DET) / 1200.0;
for (v, &int) in ints.iter().enumerate() {
self.active[v] = v == 0 || int as i32 != INT_ZERO;
let cents = if v == 0 { det } else { -det };
let semis = Self::semitones(p, int, note) as f32 / 12.0;
self.ratios[v] = m::exp2(semis + cents);
}
self.spread = p.get(param::HARM_WIDTH) / 100.0;
}
true
}
fn process(&mut self, x: [f32; 2], _sample_rate: f32) -> [f32; 2] {
let mid = (x[0] + x[1]) * 0.5;
let mut wet = [0.0f32; 2];
let both = self.active[0] && self.active[1];
for v in 0..2 {
if !self.active[v] {
continue;
}
let y = self.shifters[v].process(mid, self.ratios[v]) * self.mix;
if both {
let to_own = 0.5 + 0.5 * self.spread;
let own = if v == 0 { 0 } else { 1 };
wet[own] += y * to_own;
wet[1 - own] += y * (1.0 - to_own);
} else {
wet[0] += y * 0.5 * core::f32::consts::SQRT_2;
wet[1] += y * 0.5 * core::f32::consts::SQRT_2;
}
}
[x[0] + wet[0], x[1] + wet[1]]
}
fn clear(&mut self) {
for s in &mut self.shifters {
s.clear();
}
self.on = false;
self.last = None;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn note_number_of_a440_is_69() {
assert_eq!(note_number(440.0), Some(69));
assert_eq!(note_number(261.63), Some(60));
assert_eq!(note_number(0.0), None);
}
#[test]
fn scale_shift_goes_up_a_third_inside_major() {
let major = SCALES[0];
assert_eq!(scale_shift(60, 0, major, 2), 4);
assert_eq!(scale_shift(64, 0, major, 2), 3);
assert_eq!(scale_shift(71, 0, major, 2), 3);
}
#[test]
fn scale_shift_of_seven_degrees_is_an_octave() {
for note in 55..80 {
if SCALES[0].contains(&(note % 12)) {
assert_eq!(scale_shift(note, 0, SCALES[0], 7), 12);
assert_eq!(scale_shift(note, 0, SCALES[0], -7), -12);
}
}
}
#[test]
fn scale_shift_follows_the_key() {
assert_eq!(scale_shift(67, 7, SCALES[0], 2), 4);
assert_eq!(scale_shift(66, 0, SCALES[0], 2), 3);
}
#[test]
fn shifter_doubles_the_frequency() {
let sr = 48_000u32;
let mut s = PitchShifter::new(sr);
let mut prev = 0.0f32;
let mut crossings = 0;
let n = sr as usize;
for i in 0..n {
let x = m::sin(core::f32::consts::TAU * 480.0 * i as f32 / sr as f32);
let y = s.process(x, 2.0);
if i > sr as usize / 4 && prev < 0.0 && y >= 0.0 {
crossings += 1;
}
prev = y;
}
let hz = crossings as f32 / 0.75;
assert!((hz - 960.0).abs() < 30.0, "{hz}");
}
}