use crate::pitch::pitch_ratio;
use crate::{key_to_hz, round_u32, DcBlocker, Synth};
pub const MAX_CHANNELS: usize = 4;
pub const DEFAULT_SLOT_MS: u32 = 16;
pub const SLOT_MS_RANGE: (u32, u32) = (1, 100);
const AMP: f32 = 0.3;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Duty {
Half,
Quarter,
Eighth,
}
impl Duty {
pub const fn from_tone(tone: u8) -> Self {
match tone {
1 => Duty::Quarter,
2 => Duty::Eighth,
_ => Duty::Half,
}
}
pub const fn eighths(self) -> u32 {
match self {
Duty::Half => 4,
Duty::Quarter => 2,
Duty::Eighth => 1,
}
}
pub const fn permille(self) -> u16 {
match self {
Duty::Half => 500,
Duty::Quarter => 250,
Duty::Eighth => 125,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Tone {
pub channel: u8,
pub freq_mhz: u32,
pub duty: Duty,
pub velocity: u8,
}
impl Tone {
pub const fn freq_hz(&self) -> u32 {
(self.freq_mhz + 500) / 1000
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BuzzerConfig {
pub slot_ms: u32,
}
impl Default for BuzzerConfig {
fn default() -> Self {
BuzzerConfig {
slot_ms: DEFAULT_SLOT_MS,
}
}
}
#[derive(Debug, Clone, Copy)]
struct Channel {
on: bool,
key: u8,
vel: u8,
pitch_q8: i32,
duty: Duty,
freq_mhz: u32,
}
impl Channel {
const OFF: Channel = Channel {
on: false,
key: 69,
vel: 15,
pitch_q8: 0,
duty: Duty::Half,
freq_mhz: 0,
};
fn update_freq(&mut self) {
self.freq_mhz = round_u32(key_to_hz(self.key) * pitch_ratio(self.pitch_q8) * 1000.0);
}
}
#[derive(Debug, Clone)]
pub struct BuzzerSynth {
ch: [Channel; MAX_CHANNELS],
channels: usize,
sample_rate: u32,
slot_frames: u32,
sfx_mask: u32,
current: Option<u8>,
count: u32,
output: Option<Tone>,
changed: bool,
phase: u32,
step: u32,
dc: DcBlocker,
}
impl BuzzerSynth {
pub fn new(config: BuzzerConfig, sample_rate: u32, channels: usize) -> Self {
let sample_rate = sample_rate.max(1);
let ms = config.slot_ms.clamp(SLOT_MS_RANGE.0, SLOT_MS_RANGE.1);
let slot_frames = ((sample_rate as u64 * ms as u64 + 500) / 1000).max(1) as u32;
let mut c = BuzzerSynth {
ch: [Channel::OFF; MAX_CHANNELS],
channels: channels.clamp(1, MAX_CHANNELS),
sample_rate,
slot_frames,
sfx_mask: 0,
current: None,
count: 0,
output: None,
changed: false,
phase: 0,
step: 0,
dc: DcBlocker::new(sample_rate),
};
c.reset();
c
}
pub fn output(&self) -> Option<Tone> {
self.output
}
pub fn take_changed(&mut self) -> bool {
core::mem::take(&mut self.changed)
}
pub fn sfx_mask(&self) -> u32 {
self.sfx_mask
}
pub fn slot_frames(&self) -> u32 {
self.slot_frames
}
pub fn tick(&mut self, audible: u32) {
let mut sounding = 0u32;
for (i, c) in self.ch[..self.channels].iter().enumerate() {
if c.on && c.vel > 0 && audible & (1 << i) != 0 {
sounding |= 1 << i;
}
}
let cand = if sounding & self.sfx_mask != 0 {
sounding & self.sfx_mask
} else {
sounding
};
if cand == 0 {
self.current = None;
self.count = 0;
self.set_output(None);
return;
}
match self.current {
Some(c) if cand & (1 << c) != 0 => {
self.count += 1;
if self.count >= self.slot_frames && cand.count_ones() > 1 {
self.current = Some(self.next_after(c as usize, cand));
self.count = 0;
}
}
prev => {
let from = prev.map_or(self.channels - 1, |c| c as usize);
self.current = Some(self.next_after(from, cand));
self.count = 0;
}
}
let i = self.current.unwrap_or(0) as usize;
let c = &self.ch[i];
self.set_output(Some(Tone {
channel: i as u8,
freq_mhz: c.freq_mhz,
duty: c.duty,
velocity: c.vel,
}));
}
fn next_after(&self, from: usize, cand: u32) -> u8 {
let n = self.channels;
for k in 1..=n {
let i = (from + k) % n;
if cand & (1 << i) != 0 {
return i as u8;
}
}
0
}
fn set_output(&mut self, t: Option<Tone>) {
if self.output == t {
return;
}
self.output = t;
self.changed = true;
self.step = match t {
Some(t) => (((t.freq_mhz as u64) << 32) / (self.sample_rate as u64 * 1000))
.min(u32::MAX as u64) as u32,
None => 0,
};
}
}
impl Synth for BuzzerSynth {
fn channels(&self) -> usize {
self.channels
}
fn reset(&mut self) {
self.ch = [Channel::OFF; MAX_CHANNELS];
for c in &mut self.ch {
c.update_freq();
}
self.sfx_mask = 0;
self.current = None;
self.count = 0;
self.set_output(None);
self.phase = 0;
self.dc.reset();
}
fn set_tone(&mut self, ch: usize, tone: u8) {
if let Some(c) = self.ch[..self.channels].get_mut(ch) {
c.duty = Duty::from_tone(tone);
}
}
fn set_param(&mut self, _ch: usize, _param: u8, _value: u32) {}
fn note_on(&mut self, ch: usize, key: u8, vel: u8) {
if let Some(c) = self.ch[..self.channels].get_mut(ch) {
c.on = true;
c.key = key;
c.vel = vel.min(15);
c.update_freq();
}
}
fn note_off(&mut self, ch: usize) {
if let Some(c) = self.ch[..self.channels].get_mut(ch) {
c.on = false;
}
}
fn set_volume(&mut self, ch: usize, vel: u8) {
if let Some(c) = self.ch[..self.channels].get_mut(ch) {
if c.on {
c.vel = vel.min(15);
}
}
}
fn set_pitch(&mut self, ch: usize, cents_q8: i32) {
if let Some(c) = self.ch[..self.channels].get_mut(ch) {
if c.pitch_q8 != cents_q8 {
c.pitch_q8 = cents_q8;
c.update_freq();
}
}
}
fn next(&mut self, audible: u32) -> [f32; 2] {
self.tick(audible);
let x = match self.output {
Some(t) => {
self.phase = self.phase.wrapping_add(self.step);
if self.phase < t.duty.eighths() << 29 {
AMP
} else {
-AMP
}
}
None => 0.0,
};
let y = self.dc.process(x);
[y, y]
}
fn set_sfx_mask(&mut self, mask: u32) {
self.sfx_mask = mask;
}
}
#[cfg(test)]
mod tests {
use super::*;
fn synth(n: usize, slot_ms: u32) -> BuzzerSynth {
BuzzerSynth::new(BuzzerConfig { slot_ms }, 1_000, n)
}
fn channels_over(c: &mut BuzzerSynth, frames: usize) -> [usize; MAX_CHANNELS + 1] {
let mut n = [0; MAX_CHANNELS + 1];
for _ in 0..frames {
c.tick(u32::MAX);
match c.output() {
Some(t) => n[t.channel as usize] += 1,
None => n[MAX_CHANNELS] += 1,
}
}
n
}
#[test]
fn single_note_is_steady() {
let mut c = synth(3, 16);
assert!(c.output().is_none());
c.note_on(1, 69, 12);
c.tick(u32::MAX);
let t = c.output().unwrap();
assert_eq!(t.channel, 1);
assert_eq!(t.freq_hz(), 440);
assert_eq!(t.freq_mhz, 440_000);
assert_eq!(t.duty, Duty::Half);
assert_eq!(t.velocity, 12);
assert!(c.take_changed());
assert!(!c.take_changed());
for _ in 0..100 {
c.tick(u32::MAX);
}
assert!(!c.take_changed(), "1 本だけなら切り替えない");
c.note_off(1);
c.tick(u32::MAX);
assert!(c.take_changed());
assert!(c.output().is_none());
}
#[test]
fn tracks_take_turns_every_slot() {
let mut c = synth(3, 10);
c.note_on(0, 60, 15);
c.note_on(2, 67, 15);
let mut seq = [0u8; 40];
for s in &mut seq {
c.tick(u32::MAX);
*s = c.output().unwrap().channel;
}
assert_eq!(&seq[..10], &[0; 10]);
assert_eq!(&seq[10..20], &[2; 10]);
assert_eq!(&seq[20..30], &[0; 10]);
assert_eq!(&seq[30..40], &[2; 10]);
}
#[test]
fn sfx_mask_takes_priority_and_returns() {
let mut c = synth(3, 8);
c.note_on(0, 60, 15);
c.note_on(1, 64, 15);
c.note_on(2, 67, 15);
let n = channels_over(&mut c, 240);
assert_eq!(&n[..3], &[80, 80, 80]);
c.set_sfx_mask(0b100);
let n = channels_over(&mut c, 100);
assert_eq!(&n[..4], &[0, 0, 100, 0], "効果音のチャンネルだけを鳴らす");
c.note_off(2);
let n = channels_over(&mut c, 160);
assert_eq!(&n[..3], &[80, 80, 0]);
c.set_sfx_mask(0);
c.note_on(2, 67, 15);
let n = channels_over(&mut c, 240);
assert_eq!(&n[..3], &[80, 80, 80]);
}
#[test]
fn velocity_zero_and_mute_are_silent() {
let mut c = synth(2, 16);
c.note_on(0, 60, 0);
c.tick(u32::MAX);
assert!(c.output().is_none());
c.set_volume(0, 3);
c.note_on(1, 72, 15);
let n = channels_over(&mut c, 64);
assert_eq!(&n[..2], &[32, 32]);
for _ in 0..20 {
c.tick(0b10);
assert_eq!(c.output().unwrap().channel, 1);
}
c.tick(0);
assert!(c.output().is_none());
}
#[test]
fn tone_and_pitch_change_the_output() {
let mut c = synth(1, 16);
c.set_tone(0, 2);
c.note_on(0, 69, 15);
c.tick(u32::MAX);
assert_eq!(c.output().unwrap().duty, Duty::Eighth);
assert_eq!(c.output().unwrap().duty.permille(), 125);
c.set_pitch(0, 1200 * 256);
c.tick(u32::MAX);
assert_eq!(c.output().unwrap().freq_hz(), 880);
c.set_tone(0, 1);
c.tick(u32::MAX);
assert_eq!(c.output().unwrap().duty, Duty::Quarter);
c.reset();
assert!(c.output().is_none());
assert_eq!(c.sfx_mask(), 0);
}
#[test]
fn waveform_matches_frequency_and_duty() {
let sr = 48_000;
let mut c = BuzzerSynth::new(BuzzerConfig::default(), sr, 1);
assert_eq!(c.slot_frames(), 768);
c.set_tone(0, 1);
c.note_on(0, 69, 15);
let mut rises = 0;
let mut high = 0;
let mut prev = 0.0f32;
for _ in 0..sr {
let [l, r] = c.next(u32::MAX);
assert_eq!(l, r);
if l - prev > 0.3 {
rises += 1;
}
if c.phase < Duty::Quarter.eighths() << 29 {
high += 1;
}
prev = l;
}
assert!((439..=441).contains(&rises), "{rises}");
let ratio = high as f32 / sr as f32;
assert!((ratio - 0.25).abs() < 0.01, "{ratio}");
}
#[test]
fn channel_count_is_capped() {
let c = synth(9, 16);
assert_eq!(c.channels(), MAX_CHANNELS);
let c = synth(0, 16);
assert_eq!(c.channels(), 1);
let c = BuzzerSynth::new(BuzzerConfig { slot_ms: 0 }, 1_000, 2);
assert_eq!(c.slot_frames(), 1);
}
}