pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
//! コーラス(センド。`%cho` で送り、`%cho_rate`・`%cho_depth`)。少し遅らせた音を、左右で揺れ方を
//! ずらしながら重ねて広げる。
//!
//! 合成の部品 [`Chorus`] と、センドのバスに入れる [`ChorusFx`] を置く。

use crate::synth::va::dsp::DelayLine;
use crate::synth::va::engine::param;
use crate::synth::va::fx::send::{SendCtx, SendFx};
use crate::synth::va::fx::Params;
use crate::synth::va::m;

/// ステレオのコーラス。少し遅らせた音を、左右で揺れ方をずらしながら重ねる。
pub struct Chorus {
    line: DelayLine,
    phase: f32,
}

impl Chorus {
    /// 中心の遅れ(秒)と、揺れの最大の幅(秒)。
    const BASE: f32 = 0.012;
    const SWING: f32 = 0.006;
    /// 入った音が出きるまでの最も長い時間(秒)。余韻の見積もりに使う。
    pub const LONGEST_SECS: f32 = Self::BASE + Self::SWING;

    pub fn new(sample_rate: u32) -> Self {
        let len = ((Self::BASE + Self::SWING) * sample_rate as f32) as usize + 4;
        Chorus {
            line: DelayLine::new(len),
            phase: 0.0,
        }
    }

    /// `rate` は揺れの速さ(Hz)、`depth` は 0〜1。返すのは遅らせた音だけ(元の音は含まない)。
    pub fn process(&mut self, input: f32, rate: f32, depth: f32, sample_rate: f32) -> [f32; 2] {
        self.line.push(input);
        let base = Self::BASE * sample_rate;
        let swing = Self::SWING * sample_rate * depth;
        let tau = core::f32::consts::TAU;
        let l = self.line.tap_frac(base + swing * m::sin(self.phase * tau));
        let r = self
            .line
            .tap_frac(base + swing * m::sin((self.phase + 0.25) * tau));
        self.phase += rate / sample_rate;
        if self.phase >= 1.0 {
            self.phase -= self.phase.floor();
        }
        [l, r]
    }

    pub fn clear(&mut self) {
        self.line.clear();
        self.phase = 0.0;
    }
}

/// センドのバスに入れるコーラス。一度も音が送られていない間は計算を省き、無音を返す。
pub(crate) struct ChorusFx {
    dsp: Chorus,
    /// 一度でも音が入ったか。
    active: bool,
}

impl ChorusFx {
    pub(crate) fn new(sample_rate: u32) -> Self {
        ChorusFx {
            dsp: Chorus::new(sample_rate),
            active: false,
        }
    }
}

impl SendFx for ChorusFx {
    fn process(&mut self, p: &Params<'_>, input: f32, ctx: &SendCtx) -> [f32; 2] {
        if input != 0.0 || self.active {
            self.active = true;
            self.dsp.process(
                input,
                p.get(param::CHO_RATE) * 0.1,
                p.get(param::CHO_DEPTH) / 100.0,
                ctx.sample_rate,
            )
        } else {
            [0.0, 0.0]
        }
    }

    fn clear(&mut self) {
        self.dsp.clear();
        self.active = false;
    }
}