pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
//! テンポに合わせたピンポンディレイ(センド。`%dly` で送り、`%dly_steps`・`%dly_fb`・`%dly_tone`・
//! `%dly_lowcut`)。
//!
//! 合成の部品 [`PingPong`] と、センドのバスに入れる [`DelayFx`] を置く。遅延線は作るときに
//! 最も遅い間隔(40BPM の 16 分音符 16 個)の分だけ確保する。

use crate::synth::va::dsp::{DelayLine, Svf};
use crate::synth::va::engine::param;
use crate::synth::va::engine::{cutoff_hz, FILTER_UPDATE};
use crate::synth::va::fx::send::tail::{Tail, TailWatch};
use crate::synth::va::fx::send::{SendCtx, SendFx};
use crate::synth::va::fx::Params;
use crate::synth::va::m;

/// ピンポンディレイ(左右に交互に跳ね返る)。
pub struct PingPong {
    left: DelayLine,
    right: DelayLine,
    damp_l: f32,
    damp_r: f32,
}

impl PingPong {
    pub fn new(max_samples: usize) -> Self {
        PingPong {
            left: DelayLine::new(max_samples),
            right: DelayLine::new(max_samples),
            damp_l: 0.0,
            damp_r: 0.0,
        }
    }

    /// 左右が独立のディレイ。左右それぞれが自分の線へ戻る(交互に跳ね返らない)。入力は両方へ入れる。
    /// `delay_l`・`delay_r` は端数のあるサンプル数(テープの揺れで変わる)。`sat` は帰還の歪み(0 で歪まない)。
    pub fn process_free(
        &mut self,
        input: f32,
        delay: [f32; 2],
        feedback: f32,
        tone: f32,
        sat: f32,
    ) -> [f32; 2] {
        let dl = self.left.tap_frac(delay[0]);
        let dr = self.right.tap_frac(delay[1]);
        self.damp_l += (dl - self.damp_l) * tone;
        self.damp_r += (dr - self.damp_r) * tone;
        self.left
            .push(input + soft_clip(self.damp_l * feedback, sat));
        self.right
            .push(input + soft_clip(self.damp_r * feedback, sat));
        [dl, dr]
    }

    /// ピンポンのまま、揺れと歪みを足した版(テープ)。
    pub fn process_pingpong_free(
        &mut self,
        input: f32,
        delay: [f32; 2],
        feedback: f32,
        tone: f32,
        sat: f32,
    ) -> [f32; 2] {
        let dl = self.left.tap_frac(delay[0]);
        let dr = self.right.tap_frac(delay[1]);
        self.damp_l += (dr - self.damp_l) * tone;
        self.damp_r += (dl - self.damp_r) * tone;
        self.left
            .push(input + soft_clip(self.damp_l * feedback, sat));
        self.right.push(soft_clip(self.damp_r * feedback, sat));
        [dl, dr]
    }

    /// `tone` は 0〜1(跳ね返るたびに高音を残す割合。小さいほど早く暗くなる)。
    pub fn process(&mut self, input: f32, delay: usize, feedback: f32, tone: f32) -> [f32; 2] {
        let dl = self.left.tap(delay);
        let dr = self.right.tap(delay);
        // 跳ね返るたびに少しずつ高音を落とす
        self.damp_l += (dr - self.damp_l) * tone;
        self.damp_r += (dl - self.damp_r) * tone;
        self.left.push(input + self.damp_l * feedback);
        self.right.push(self.damp_r * feedback);
        [dl, dr]
    }

    /// 状態の数値(遅延線 2 本と高音を落とす状態)を、尾の見張りに渡す。
    fn regions(&self, f: &mut dyn FnMut(&[f32])) {
        f(self.left.raw());
        f(self.right.raw());
        f(&[self.damp_l, self.damp_r]);
    }

    pub fn clear(&mut self) {
        self.left.clear();
        self.right.clear();
        self.damp_l = 0.0;
        self.damp_r = 0.0;
    }
}

/// 帰還の歪み。`amount`(0〜1)が 0 なら素通し、大きいほど大きな値を丸める(`x / (1 + a|x|)` に元の大きさを戻す形)。
fn soft_clip(x: f32, amount: f32) -> f32 {
    if amount <= 0.0 {
        return x;
    }
    let a = amount * 3.0;
    x * (1.0 + a) / (1.0 + a * x.abs())
}

/// 拍の割り方(`dly_feel`)を掛けた、左右の間隔(16 分音符の数)。`steps_r` が 0 なら右も左と同じ。
/// 付点は 1.5 倍、3 連は 2/3 倍。`feel` 0 は 1.0 倍で、間隔は今までと 1 サンプルも変わらない。
pub(crate) fn delay_steps(steps: f32, steps_r: f32, feel: f32) -> [f32; 2] {
    let k = match feel as u32 {
        1 => 1.5,
        2 => 2.0 / 3.0,
        _ => 1.0,
    };
    let r = if steps_r > 0.0 { steps_r } else { steps };
    [steps * k, r * k]
}

/// テープの揺れの速さ(Hz)と、最大の振れ幅(秒。`dly_wow` 100 のとき)。
const WOW_HZ: f32 = 0.6;
const WOW_SECS: f32 = 0.004;

/// ディレイの間隔(サンプル)。曲のテンポの 16 分音符 × `steps`。余韻の見積もりでも使う。
pub(crate) fn delay_samples(bpm: f32, steps: f32, sample_rate: f32) -> usize {
    let step = 60.0 / bpm / 4.0;
    (step * steps * sample_rate) as usize
}

/// センドのバスに入れるディレイ。送る音の低音を `dly_lowcut` のハイパスで削ってから遅らせる
/// (低音が何度も返って濁らないように)。
pub(crate) struct DelayFx {
    dsp: PingPong,
    /// テープの揺れの位相(0〜1)。
    wow_phase: f32,
    lowcut: Svf,
    /// ハイパスの係数を [`FILTER_UPDATE`] サンプルおきに求め直すための数え上げ。
    counter: u32,
    /// `clear` のあとに、一度でも 0 以外の音が入ったか。入るまでは遅延線も状態もすべて 0 なので、
    /// 入力に関係なく動く状態(ワウ・ローカット)を使っていなければ、処理を飛ばして無音を返す。
    active: bool,
    /// 入力が止まったあと、尾が聞こえないほど小さくなったかの見張り。
    watch: TailWatch,
}

impl Tail for DelayFx {
    fn regions(&self, f: &mut dyn FnMut(&[f32])) {
        self.dsp.regions(f);
        f(&[self.lowcut.max_abs()]);
    }
}

impl DelayFx {
    /// テスト用:飛ばす側(一度も音が入っていない、または尾を 0 にした状態)か。
    #[cfg(test)]
    pub(crate) fn is_idle(&self) -> bool {
        !self.active
    }

    /// テスト用:尾を 0 にしない側にする。
    #[cfg(test)]
    pub(crate) fn disable_tail_flush(&mut self) {
        self.watch.disable();
    }

    /// 尾が聞こえないほど小さくなったとき:状態を 0 にして、飛ばす側へ戻す。入力に関係なく動く
    /// 状態(周期の数え上げ・ワウの位相)は残す。
    fn flush_tail(&mut self) {
        self.dsp.clear();
        self.lowcut.clear();
        self.active = false;
    }
}

impl DelayFx {
    /// テスト用:飛ばさずに毎回処理する側にする。
    #[cfg(test)]
    pub(crate) fn force_active(&mut self) {
        self.active = true;
    }

    pub(crate) fn new(sample_rate: u32) -> Self {
        DelayFx {
            // 16分音符16個ぶん(最も遅い 40BPM)まで入る長さ
            // 付点(1.5 倍)と揺れの余白まで入る長さ
            dsp: PingPong::new(sample_rate as usize * 9 + 512),
            wow_phase: 0.0,
            lowcut: Svf::default(),
            counter: 0,
            active: false,
            watch: TailWatch::default(),
        }
    }

    /// 1 サンプルの処理本体(尾の見張りは [`SendFx::process`] が行う)。
    fn step(&mut self, p: &Params<'_>, input: f32, ctx: &SendCtx) -> [f32; 2] {
        let sr = ctx.sample_rate;
        let mode = p.get_hi(param::DLY_MODE) as u32;
        let sat = p.get_hi(param::DLY_SAT) / 100.0;
        let wow = p.get_hi(param::DLY_WOW) / 100.0;
        if input != 0.0 {
            self.active = true;
        } else if !self.active && wow <= 0.0 && mode != 2 && p.get(param::DLY_LOWCUT) <= 0.0 {
            // まだ一度も音が入っていない:状態はすべて 0 で、1 サンプル処理しても 0 のまま。
            // 周期を数える `counter` だけは、処理したときと同じに進める
            self.counter = self.counter.wrapping_add(1);
            return [0.0, 0.0];
        }
        let steps = delay_steps(
            p.get(param::DLY_STEPS),
            p.get_hi(param::DLY_STEPS_R),
            p.get_hi(param::DLY_FEEL),
        );
        let delay = delay_samples(ctx.bpm, steps[0], sr);
        let lowcut = p.get(param::DLY_LOWCUT);
        let input = if lowcut > 0.0 {
            let k = core::f32::consts::SQRT_2;
            if self.counter % FILTER_UPDATE == 0 {
                self.lowcut.set(cutoff_hz(lowcut), k, sr);
            }
            self.lowcut.process(input).hp
        } else {
            input
        };
        self.counter = self.counter.wrapping_add(1);
        let fb = p.get(param::DLY_FB) / 100.0;
        let tone = p.get(param::DLY_TONE) / 100.0;
        // 拡張を使わない(ピンポン・歪みなし・揺れなし・左右同じ・そのままの拍)ときは、今までの計算を通す
        if mode == 0
            && sat <= 0.0
            && wow <= 0.0
            && steps[0] == steps[1]
            && p.get_hi(param::DLY_FEEL) == 0.0
        {
            return self.dsp.process(input, delay, fb, tone);
        }
        let mut t = [delay as f32, delay_samples(ctx.bpm, steps[1], sr) as f32];
        if wow > 0.0 || mode == 2 {
            // テープの揺れ:左右で逆向きにゆっくり変える(モードがテープのときは `wow` が 0 でも少し揺らす)
            let depth = if mode == 2 { wow.max(0.15) } else { wow };
            let s = m::sin(self.wow_phase * core::f32::consts::TAU);
            self.wow_phase += WOW_HZ / sr;
            if self.wow_phase >= 1.0 {
                self.wow_phase -= self.wow_phase.floor();
            }
            let swing = s * depth * WOW_SECS * sr;
            t[0] += swing;
            t[1] -= swing;
        }
        // テープは暖かく:帰還を少し歪ませる(`dly_sat` 0 でもモードがテープなら 0.2)
        let sat = if mode == 2 { sat.max(0.2) } else { sat };
        if mode == 1 {
            self.dsp.process_free(input, t, fb, tone, sat)
        } else {
            self.dsp.process_pingpong_free(input, t, fb, tone, sat)
        }
    }
}

impl SendFx for DelayFx {
    fn process(&mut self, p: &Params<'_>, input: f32, ctx: &SendCtx) -> [f32; 2] {
        let out = self.step(p, input, ctx);
        if input != 0.0 || !self.active {
            self.watch.reset();
            return out;
        }
        // 帰還の利得が 1 以上(歪みで小さい音が大きくなる)ときは、尾が育ちうるので 0 にしない
        let mode = p.get_hi(param::DLY_MODE) as u32;
        let mut sat = p.get_hi(param::DLY_SAT) / 100.0;
        if mode == 2 {
            sat = sat.max(0.2);
        }
        if p.get(param::DLY_FB) / 100.0 * (1.0 + 3.0 * sat) >= 1.0 {
            self.watch.reset();
            return out;
        }
        let mut watch = core::mem::take(&mut self.watch);
        let flush = watch.tick(&*self, ctx.sample_rate);
        self.watch = watch;
        if flush {
            self.flush_tail();
        }
        out
    }

    fn clear(&mut self) {
        self.watch.reset();
        self.dsp.clear();
        self.lowcut.clear();
        self.counter = 0;
        self.wow_phase = 0.0;
        self.active = false;
    }
}