SPB Git

Repository Public

voice.rs 7.4 KB 188 lines rust

1//! ORIX Sonata2//! File: crates/sonata-instruments/src/engines/voice.rs3//! Description: Sung vowel — source-filter synthesis: a glottal pulse train and breath noise4//! through five parallel formant resonators interpolated between vowels.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use super::bowed::semitones_to_ratio_fast;10use super::common::{vibrato_params, EnvSettings, Vibrato};11use crate::instrument::{Instrument, NoteOn};12use crate::params::{choice, envelope_params, num, preset, resolve, Resolved};13use crate::poly::{Engine, Poly};14use sonata_dsp::core::{db_to_lin, semitones_to_ratio, Rng};15use sonata_dsp::env::Adsr;16use sonata_dsp::filter::{Biquad, BiquadCoefs, BiquadKind, OnePole};17use sonata_dsp::osc::{Oscillator, Waveform};18use sonata_ir::{EngineDesc, InstrumentSpec, Unit};1920/// Formant frequencies (Hz), levels (dB) and bandwidths (Hz) of a tenor for a, e, i, o, u.21const FREQ: [[f32; 5]; 5] = [22    [650.0, 1080.0, 2650.0, 2900.0, 3250.0],23    [400.0, 1700.0, 2600.0, 3200.0, 3580.0],24    [290.0, 1870.0, 2800.0, 3250.0, 3540.0],25    [400.0, 800.0, 2600.0, 2800.0, 3000.0],26    [350.0, 600.0, 2700.0, 2900.0, 3300.0],27];28const GAIN: [[f32; 5]; 5] = [29    [0.0, -6.0, -7.0, -8.0, -22.0],30    [0.0, -14.0, -12.0, -14.0, -20.0],31    [0.0, -15.0, -18.0, -20.0, -30.0],32    [0.0, -10.0, -12.0, -12.0, -26.0],33    [0.0, -20.0, -32.0, -28.0, -36.0],34];35const BW: [f32; 5] = [80.0, 90.0, 120.0, 130.0, 140.0];36/// Vocal-tract length scaling per voice type (soprano, alto, tenor, bass).37const TRACT: [f32; 4] = [1.22, 1.12, 1.0, 0.9];3839pub fn desc() -> EngineDesc {40    let mut params = vec![41        num("vowel", Unit::Scalar, 0.0, 4.0, 0.0, true, "Vowel position, continuous: 0 = a, 1 = e, 2 = i, 3 = o, 4 = u."),42        choice("voice", &["soprano", "alto", "tenor", "bass"], "tenor", "Voice type: scales the formants for the size of the vocal tract."),43        num("breath", Unit::Ratio, 0.0, 1.0, 0.1, true, "Aspiration noise mixed into the glottal source."),44        num("tension", Unit::Ratio, 0.0, 1.0, 0.5, true, "Vocal effort: a pressed voice has a brighter source spectrum."),45    ];46    params.extend(vibrato_params(5.5, 0.25, 0.35));47    params.extend(envelope_params(false, 0.08, 0.1, 0.9, 0.16));48    EngineDesc {49        model: "voice".into(),50        title: "Formant Voice".into(),51        family: "voice".into(),52        method: "Source-filter synthesis: band-limited glottal pulse train with spectral tilt and aspiration noise, five parallel two-pole formant filters"53            .into(),54        doc:55            "Sustained sung vowels. It synthesises vowel colour from published average formant tables; it does not sing words and does not imitate any person."56                .into(),57        range: (36, 84),58        params,59        presets: vec![60            preset("aah", "Open 'a'.", &[], &[]),61            preset("ooh", "Rounded 'u', soft.", &[("vowel", 4.0), ("tension", 0.35), ("breath", 0.15)], &[]),62            preset("eeh", "Bright 'i'.", &[("vowel", 2.0), ("tension", 0.6)], &[]),63            preset("soprano", "Soprano 'a' with wide vibrato.", &[("vibrato.depth", 0.35), ("vibrato.rate", 5.9)], &[("voice", "soprano")]),64            preset("bass_ooh", "Low 'o'.", &[("vowel", 3.0), ("tension", 0.45), ("vibrato.depth", 0.15)], &[("voice", "bass")]),65            preset("whisper", "Mostly breath.", &[("breath", 0.9), ("tension", 0.2), ("vibrato.depth", 0.0)], &[]),66        ],67        articulations: vec!["normal".into(), "legato".into(), "staccato".into(), "accent".into()],68        pitched: true,69    }70}7172const LEVEL: f32 = 0.9;7374pub struct Formant {75    sr: f32,76    r: Resolved,77    env: EnvSettings,78    i_vowel: usize,79}8081pub struct Voice {82    osc: Oscillator,83    tilt: OnePole,84    filters: [Biquad; 5],85    gains: [f32; 5],86    last_vowel: f32,87    env: Adsr,88    vib: Vibrato,89    rng: Rng,90    freq: f32,91    bend: f32,92    vel: f32,93}9495impl Formant {96    fn set_formants(&self, v: &mut Voice, vowel: f32, smooth: u32) {97        let x = vowel.clamp(0.0, 4.0);98        let i = (x as usize).min(3);99        let t = x - i as f32;100        let scale = TRACT[self.r.pick("voice").min(3)];101        for k in 0..5 {102            let f = (FREQ[i][k] + (FREQ[i + 1][k] - FREQ[i][k]) * t) * scale;103            let g = GAIN[i][k] + (GAIN[i + 1][k] - GAIN[i][k]) * t;104            let f = f.min(0.45 * self.sr);105            v.filters[k].set_smoothed(BiquadCoefs::design(BiquadKind::Bandpass, f, f / BW[k], 0.0, self.sr), smooth);106            v.gains[k] = db_to_lin(g);107        }108        v.last_vowel = vowel;109    }110}111112impl Engine for Formant {113    type Voice = Voice;114    fn prepare(&mut self, sample_rate: f32, _max_block: usize) {115        self.sr = sample_rate;116    }117    fn make_voice(&self, sr: f32) -> Voice {118        let mut osc = Oscillator::new(sr);119        osc.waveform = Waveform::Saw;120        Voice {121            osc,122            tilt: OnePole::new(2000.0, sr),123            filters: [Biquad::default(); 5],124            gains: [0.0; 5],125            last_vowel: -1.0,126            env: Adsr::new(sr),127            vib: Vibrato::default(),128            rng: Rng::new(1),129            freq: 220.0,130            bend: 1.0,131            vel: 0.0,132        }133    }134    fn start(&self, v: &mut Voice, note: &NoteOn, seed: u64) {135        v.rng = Rng::new(seed);136        v.osc.set_phase(0.0);137        v.tilt.reset();138        v.filters.iter_mut().for_each(|f| f.reset());139        self.set_formants(v, self.r.v[self.i_vowel], 0);140        v.freq = note.freq;141        v.bend = 1.0;142        v.vel = note.velocity.clamp(0.0, 1.0);143        v.vib.start(self.r.get("vibrato.rate") * (1.0 + 0.05 * v.rng.bipolar()), 1.0, self.r.get("vibrato.delay"), self.sr, v.rng.unipolar());144        self.env.start(&mut v.env);145    }146    fn release(&self, v: &mut Voice) {147        v.env.gate_off();148    }149    fn bend(&self, v: &mut Voice, semitones: f32) {150        v.bend = semitones_to_ratio(semitones);151    }152    fn render(&self, v: &mut Voice, left: &mut [f32], right: &mut [f32]) -> bool {153        let vowel = self.r.v[self.i_vowel];154        if vowel != v.last_vowel {155            self.set_formants(v, vowel, left.len() as u32);156        }157        let breath = self.r.get("breath");158        let tension = self.r.get("tension") * (0.6 + 0.4 * v.vel);159        v.tilt.set(500.0 + 5500.0 * tension * tension, self.sr);160        let vdepth = self.r.get("vibrato.depth");161        let level = LEVEL * (0.25 + 0.75 * v.vel);162        for i in 0..left.len() {163            v.osc.set_freq(v.freq * v.bend * semitones_to_ratio_fast(v.vib.tick() * vdepth));164            // Glottal source: a sawtooth (-6 dB/octave) through a tilt filter gives the -12 dB/octave165            // of a relaxed voice; aspiration noise is added in proportion to `breath`.166            let src = v.tilt.lowpass(v.osc.tick()) * (1.0 - 0.6 * breath) + v.rng.bipolar() * breath * 0.35;167            let mut y = 0.0;168            for k in 0..5 {169                y += v.filters[k].tick(src) * v.gains[k];170            }171            let y = y * level * v.env.tick();172            left[i] = y;173            right[i] = y;174        }175        !v.env.is_idle()176    }177    fn set_param(&mut self, index: usize, value: f32) {178        if index < self.r.v.len() {179            self.r.v[index] = value;180        }181    }182}183184pub fn build(spec: &InstrumentSpec, _tuning: f64, seed: u64) -> Result<Box<dyn Instrument>, String> {185    let r = resolve(&desc(), spec)?;186    Ok(Box::new(Poly::new(Formant { sr: 48_000.0, env: EnvSettings::read(&r, false), i_vowel: r.idx("vowel"), r }, seed)))187}188
Files main
Menu

Theme