use super::*;
pub(crate) struct KickEngine {
pub(crate) sample_rate: f32,
pub(crate) trigger: GridTrigger,
pub(crate) voices: Vec<KickVoice>,
pub(crate) rng: StdRng,
pub(crate) telemetry: Arc<FluidTelemetry>,
}
impl KickEngine {
pub(crate) fn new(sample_rate: f32, telemetry: Arc<FluidTelemetry>) -> Self {
Self {
sample_rate,
trigger: GridTrigger::new(),
voices: Vec::with_capacity(4),
rng: StdRng::from_entropy(),
telemetry,
}
}
pub(crate) fn next(&mut self, c: &KickControls, timing: TimingContext) -> (f32, f32) {
if self
.trigger
.pop_swung(timing, c.interval_beats, c.offset_beats, c.swing)
{
self.voices.push(KickVoice::new(
wrapped_index(c.voice_type, KICK_TYPES.len()),
c,
self.sample_rate,
&mut self.rng,
));
self.telemetry.kick_pulse.fetch_add(1, Ordering::Relaxed);
}
let rng = &mut self.rng;
mix_and_retain(&mut self.voices, |v| v.next(rng), KickVoice::is_done)
}
}
pub(crate) struct KickVoiceCore {
pub(crate) amp: f32,
pub(crate) amp_decay: f32,
pub(crate) click_remaining: u64,
pub(crate) click_level: f32,
pub(crate) attack_remaining: u64,
pub(crate) attack_gain: f32,
pub(crate) attack_inc: f32,
pub(crate) pan_gains: (f32, f32),
}
impl KickVoiceCore {
pub(crate) fn new(
c: &KickControls,
sample_rate: f32,
rng: &mut StdRng,
attack_ms: f32,
click_scale: f32,
) -> Self {
let amp_tau = (c.amp_decay_ms * 0.001 * sample_rate / 3.0).max(1.0);
let attack_samples = (attack_ms * 0.001 * sample_rate).round().max(0.0) as u64;
Self {
amp: c.level,
amp_decay: (-1.0 / amp_tau).exp(),
click_remaining: (c.amp_decay_ms * 0.001 * sample_rate * 0.04).round() as u64,
click_level: c.click * click_scale,
attack_remaining: attack_samples,
attack_gain: 0.0,
attack_inc: if attack_samples == 0 {
0.0
} else {
1.0 / attack_samples as f32
},
pan_gains: StereoPanner::gains(rng.gen_range(-0.15f32..0.15)),
}
}
#[inline]
pub(crate) fn shape<R: Rng>(&mut self, body: f32, rng: &mut R) -> f32 {
let mut s = body * self.amp;
if self.click_remaining > 0 {
s += rng.gen_range(-1.0f32..1.0) * self.click_level * self.amp;
self.click_remaining -= 1;
}
if self.attack_remaining > 0 {
s *= self.attack_gain;
self.attack_gain = (self.attack_gain + self.attack_inc).min(1.0);
self.attack_remaining -= 1;
}
self.amp *= self.amp_decay;
s
}
pub(crate) fn is_done(&self) -> bool {
self.amp < 0.0001
}
}
pub(crate) enum KickVoice {
Lowpass(LowpassKickVoice),
Wood(WoodKickVoice),
}
impl KickVoice {
pub(crate) fn new(
voice_type: usize,
c: &KickControls,
sample_rate: f32,
rng: &mut StdRng,
) -> Self {
match voice_type {
0 => Self::Lowpass(LowpassKickVoice::new(&KICK_SUB, c, sample_rate, rng)),
1 => Self::Lowpass(LowpassKickVoice::new(&KICK_WARM, c, sample_rate, rng)),
2 => Self::Wood(WoodKickVoice::new(c, sample_rate, rng)),
_ => Self::Lowpass(LowpassKickVoice::new(&KICK_FELT, c, sample_rate, rng)),
}
}
pub(crate) fn next<R: Rng>(&mut self, rng: &mut R) -> (f32, f32) {
match self {
Self::Lowpass(voice) => voice.next(rng),
Self::Wood(voice) => voice.next(rng),
}
}
pub(crate) fn is_done(&self) -> bool {
match self {
Self::Lowpass(voice) => voice.is_done(),
Self::Wood(voice) => voice.is_done(),
}
}
}
pub(crate) struct KickFmBody {
pub(crate) freq: f32,
pub(crate) target_freq: f32,
pub(crate) freq_glide: f32,
pub(crate) stack: FmStack,
}
impl KickFmBody {
pub(crate) fn new(
c: &KickControls,
sample_rate: f32,
pitch_drop_ratio: f32,
mod_ratio: f32,
fm_depth: f32,
carrier_wave: FmWave,
) -> Self {
let tau = (c.pitch_decay_ms * 0.001 * sample_rate / 3.0).max(1.0);
let fm_tau = (c.pitch_decay_ms * 0.001 * sample_rate / 9.0).max(1.0);
Self {
freq: c.start_freq,
target_freq: c.start_freq * pitch_drop_ratio,
freq_glide: 1.0 / tau,
stack: FmStack::new(sample_rate).with_pair(
FmPair::new(mod_ratio, KICK_CARRIER_RATIO, fm_depth)
.with_wave(carrier_wave)
.with_index_decay(fm_tau),
),
}
}
#[inline]
pub(crate) fn next(&mut self) -> f32 {
self.freq += (self.target_freq - self.freq) * self.freq_glide;
self.stack.next(self.freq)
}
}
const KICK_CARRIER_RATIO: f32 = 1.0;
pub(crate) const KICK_CHARACTER_FILTER_POSITION: f32 = 0.7;
pub(crate) struct KickLowPass {
pub(crate) state: f32,
pub(crate) coeff: f32,
}
impl KickLowPass {
pub(crate) fn new(filter: f32, bias: f32) -> Self {
Self {
state: 0.0,
coeff: 10_f32.powf(filter * 3.0 + bias).clamp(0.01, 0.99),
}
}
#[inline]
pub(crate) fn process(&mut self, s: f32) -> f32 {
self.state += self.coeff * (s - self.state);
self.state
}
}
pub(crate) struct LowpassKickRecipe {
attack_ms: f32,
click_scale: f32,
pitch_drop_ratio: f32,
fm_mod_ratio: f32,
fm_depth: f32,
wave: FmWave,
filter_bias: f32,
output_gain: f32,
}
pub(crate) const KICK_SUB: LowpassKickRecipe = LowpassKickRecipe {
attack_ms: 0.0,
click_scale: 1.0,
pitch_drop_ratio: 0.28,
fm_mod_ratio: 2.0,
fm_depth: 3.5,
wave: FmWave::Sine,
filter_bias: -2.5,
output_gain: 1.0,
};
pub(crate) const KICK_WARM: LowpassKickRecipe = LowpassKickRecipe {
attack_ms: 6.0,
click_scale: 0.45,
pitch_drop_ratio: 0.42,
fm_mod_ratio: 1.5,
fm_depth: 1.2,
wave: FmWave::Sine,
filter_bias: -2.35,
output_gain: 1.11,
};
pub(crate) const KICK_FELT: LowpassKickRecipe = LowpassKickRecipe {
attack_ms: 8.0,
click_scale: 0.25,
pitch_drop_ratio: 0.28,
fm_mod_ratio: KICK_SUB.fm_mod_ratio,
fm_depth: 1.8,
wave: FmWave::Triangle,
filter_bias: -2.9,
output_gain: 1.36,
};
pub(crate) struct LowpassKickVoice {
pub(crate) core: KickVoiceCore,
pub(crate) body: KickFmBody,
pub(crate) lowpass: KickLowPass,
pub(crate) output_gain: f32,
}
impl LowpassKickVoice {
pub(crate) fn new(
recipe: &LowpassKickRecipe,
c: &KickControls,
sample_rate: f32,
rng: &mut StdRng,
) -> Self {
Self {
core: KickVoiceCore::new(c, sample_rate, rng, recipe.attack_ms, recipe.click_scale),
body: KickFmBody::new(
c,
sample_rate,
recipe.pitch_drop_ratio,
recipe.fm_mod_ratio,
recipe.fm_depth,
recipe.wave,
),
lowpass: KickLowPass::new(KICK_CHARACTER_FILTER_POSITION, recipe.filter_bias),
output_gain: recipe.output_gain,
}
}
pub(crate) fn next<R: Rng>(&mut self, rng: &mut R) -> (f32, f32) {
if self.core.is_done() {
return (0.0, 0.0);
}
let body = self.body.next();
let s = self
.lowpass
.process(self.core.shape(body, rng) * self.output_gain);
(s * self.core.pan_gains.0, s * self.core.pan_gains.1)
}
pub(crate) fn is_done(&self) -> bool {
self.core.is_done()
}
}
const KICK_WOOD_CENTER_MIN_HZ: f32 = 110.0;
const KICK_WOOD_CENTER_MAX_HZ: f32 = 400.0;
const KICK_WOOD_DAMP: f32 = 0.9;
const KICK_WOOD_PITCH_DROP_RATIO: f32 = 0.35;
const KICK_WOOD_BANDPASS_MIX: f32 = 0.6;
const KICK_WOOD_ATTACK_MS: f32 = 5.0;
const KICK_WOOD_CLICK_SCALE: f32 = 0.35;
const KICK_WOOD_OUTPUT_GAIN_AT_DARKEST: f32 = 0.78;
const KICK_WOOD_OUTPUT_GAIN_SPAN: f32 = 1.91;
const KICK_WOOD_OUTPUT_GAIN_CURVE: f32 = 0.7;
fn kick_wood_output_gain(filter: f32) -> f32 {
KICK_WOOD_OUTPUT_GAIN_AT_DARKEST
* (1.0 + KICK_WOOD_OUTPUT_GAIN_SPAN * filter.powf(KICK_WOOD_OUTPUT_GAIN_CURVE))
}
pub(crate) struct WoodKickVoice {
pub(crate) core: KickVoiceCore,
pub(crate) body: KickFmBody,
pub(crate) svf_low: f32,
pub(crate) svf_band: f32,
pub(crate) svf_f: f32,
pub(crate) output_gain: f32,
}
impl WoodKickVoice {
pub(crate) fn new(c: &KickControls, sample_rate: f32, rng: &mut StdRng) -> Self {
let filter = KICK_CHARACTER_FILTER_POSITION;
let center_hz = KICK_WOOD_CENTER_MIN_HZ
* (KICK_WOOD_CENTER_MAX_HZ / KICK_WOOD_CENTER_MIN_HZ).powf(filter);
let svf_f = (2.0 * (std::f32::consts::PI * center_hz / sample_rate).sin()).clamp(0.0, 1.9);
Self {
core: KickVoiceCore::new(
c,
sample_rate,
rng,
KICK_WOOD_ATTACK_MS,
KICK_WOOD_CLICK_SCALE,
),
body: KickFmBody::new(
c,
sample_rate,
KICK_WOOD_PITCH_DROP_RATIO,
KICK_SUB.fm_mod_ratio,
KICK_SUB.fm_depth,
FmWave::Sine,
),
svf_low: 0.0,
svf_band: 0.0,
svf_f,
output_gain: kick_wood_output_gain(filter),
}
}
pub(crate) fn next<R: Rng>(&mut self, rng: &mut R) -> (f32, f32) {
if self.core.is_done() {
return (0.0, 0.0);
}
let body = self.body.next();
let dry = self.core.shape(body, rng);
let high = dry - self.svf_low - KICK_WOOD_DAMP * self.svf_band;
self.svf_band += self.svf_f * high;
self.svf_low += self.svf_f * self.svf_band;
let s = (self.svf_band * KICK_WOOD_BANDPASS_MIX + dry * (1.0 - KICK_WOOD_BANDPASS_MIX))
* self.output_gain;
(s * self.core.pan_gains.0, s * self.core.pan_gains.1)
}
pub(crate) fn is_done(&self) -> bool {
self.core.is_done()
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::*;
#[test]
fn swing_delays_the_kicks_odd_subdivision() {
let telemetry = Arc::new(FluidTelemetry::default());
let mut kick = KickEngine::new(48_000.0, Arc::clone(&telemetry));
let controls = KickControls {
level: 1.0,
interval_beats: 0.5,
swing: 1.0,
..KickControls::default()
};
kick.next(&controls, TimingContext::new(48_000.0, 120.0, 0.0));
kick.next(&controls, TimingContext::new(48_000.0, 120.0, 0.5));
assert_eq!(telemetry.kick_pulse.load(Ordering::Relaxed), 1);
kick.next(&controls, TimingContext::new(48_000.0, 120.0, 0.75));
assert_eq!(telemetry.kick_pulse.load(Ordering::Relaxed), 2);
}
fn render_one_hit(voice_type: usize) -> Vec<f32> {
const SAMPLE_RATE: f32 = 48_000.0;
let controls = KickControls {
level: 1.0,
..KickControls::default()
};
let mut rng = StdRng::seed_from_u64(42);
let mut voice = KickVoice::new(voice_type, &controls, SAMPLE_RATE, &mut rng);
let mut rendered = Vec::new();
while !voice.is_done() && rendered.len() < SAMPLE_RATE as usize {
let (left, right) = voice.next(&mut rng);
rendered.push((left * left + right * right).sqrt());
}
rendered
}
#[test]
fn kick_types_render_at_a_matched_level() {
let reference = crate::synth::fm::rms(&render_one_hit(0));
for (voice_type, label) in KICK_TYPES.iter().enumerate().skip(1) {
let level = crate::synth::fm::rms(&render_one_hit(voice_type));
let ratio = level / reference;
assert!(
(ratio - 1.0).abs() <= MATCHED_LEVEL_TOLERANCE,
"kick type {voice_type} ({label}) renders at {ratio:.2}x Sub; \
retune its output trim",
);
}
}
#[test]
fn no_kick_type_exceeds_the_headroom_budget() {
for (voice_type, label) in KICK_TYPES.iter().enumerate() {
let peak = render_one_hit(voice_type)
.into_iter()
.fold(0.0f32, f32::max);
assert!(
peak <= MAX_KICK_PEAK,
"kick type {voice_type} ({label}) peaks at {peak:.2}",
);
}
}
const MATCHED_LEVEL_TOLERANCE: f32 = 0.15;
const MAX_KICK_PEAK: f32 = 1.8;
}