use pikopiko_runtime::WAVE_LEN;
pub const TONE_COUNT: u8 = 6;
pub trait Voice: Send {
fn set_tone(&mut self, tone: u8);
fn note_on(&mut self, key: u8, vel: u8);
fn note_off(&mut self);
fn set_volume(&mut self, vel: u8);
fn set_pitch(&mut self, _cents_q8: i32) {}
fn supports_pitch(&self) -> bool {
false
}
fn set_wave(&mut self, _wave: &[i8]) {}
fn next(&mut self) -> f32;
}
pub use pikopiko_runtime::key_to_hz;
#[derive(Debug, Clone)]
pub struct SynthVoice {
sample_rate: u32,
tone: u8,
on: bool,
amp: f32,
phase: u32,
inc: u32,
lfsr: u16,
wave: [i8; WAVE_LEN],
key: u8,
pitch_q8: i32,
}
pub const VOICE_GAIN: f32 = 0.25;
impl SynthVoice {
pub fn new(sample_rate: u32) -> Self {
SynthVoice {
sample_rate: sample_rate.max(1),
tone: crate::compiler::song::DEFAULT_TONE,
on: false,
amp: 0.0,
phase: 0,
inc: 0,
lfsr: 1,
wave: initial_wave(),
key: 69,
pitch_q8: 0,
}
}
fn compute_inc(&self, key: u8) -> u32 {
let mul = if self.tone == 4 { 16.0 } else { 1.0 };
let ratio = pikopiko_runtime::pitch::pitch_ratio(self.pitch_q8);
let r = key_to_hz(key) * ratio * mul / self.sample_rate as f64 * 4_294_967_296.0;
r.clamp(0.0, (u32::MAX / 2) as f64) as u32
}
}
impl Voice for SynthVoice {
fn supports_pitch(&self) -> bool {
true
}
fn set_tone(&mut self, tone: u8) {
self.tone = tone.min(TONE_COUNT - 1);
}
fn set_wave(&mut self, wave: &[i8]) {
self.wave = [0; WAVE_LEN];
let n = wave.len().min(WAVE_LEN);
self.wave[..n].copy_from_slice(&wave[..n]);
}
fn note_on(&mut self, key: u8, vel: u8) {
self.key = key;
self.inc = self.compute_inc(key);
self.amp = vel.min(15) as f32 / 15.0 * VOICE_GAIN;
self.on = true;
}
fn note_off(&mut self) {
self.on = false;
}
fn set_volume(&mut self, vel: u8) {
self.amp = vel.min(15) as f32 / 15.0 * VOICE_GAIN;
}
fn set_pitch(&mut self, cents_q8: i32) {
self.pitch_q8 = cents_q8;
if self.on {
self.inc = self.compute_inc(self.key);
}
}
fn next(&mut self) -> f32 {
if !self.on {
return 0.0;
}
let (p, overflow) = self.phase.overflowing_add(self.inc);
let before = self.phase;
self.phase = p;
let v = match self.tone {
0 => square(before, 0x2000_0000),
1 => square(before, 0x4000_0000),
3 => {
let step = (before >> 27) as i32; let tri = if step < 16 { 15 - step } else { step - 16 };
tri as f32 / 7.5 - 1.0
}
5 => self.wave[(before >> 27) as usize] as f32 / 128.0,
4 => {
if overflow {
let bit = (self.lfsr ^ (self.lfsr >> 1)) & 1;
self.lfsr = (self.lfsr >> 1) | (bit << 14);
}
if self.lfsr & 1 == 1 {
1.0
} else {
-1.0
}
}
_ => square(before, 0x8000_0000),
};
v * self.amp
}
}
fn square(phase: u32, duty: u32) -> f32 {
if phase < duty {
1.0
} else {
-1.0
}
}
fn initial_wave() -> [i8; WAVE_LEN] {
core::array::from_fn(|step| {
let tri = if step < 16 {
15 - step as i32
} else {
step as i32 - 16
};
((tri * 255 + 7) / 15 - 128) as i8
})
}