SPB Git

Repository Public

piano.rs 11.2 KB 286 lines rust

1//! ORIX Sonata2//! File: crates/sonata-instruments/src/engines/piano.rs3//! Description: Piano — modal synthesis of stiff strings (inharmonic partials, two-stage decay,4//! unison beating), hammer spectrum and noise, soundboard and sympathetic resonance, pedal.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use super::common::{pan_gains, EnvSettings};10use crate::instrument::{Instrument, NoteOn};11use crate::params::{envelope_params, num, preset, resolve, Resolved};12use crate::poly::{Engine, Poly};13use sonata_dsp::core::{semitones_to_ratio, Rng};14use sonata_dsp::env::Adsr;15use sonata_dsp::filter::{Biquad, BiquadCoefs, OnePole};16use sonata_dsp::osc::AdditiveBank;17use sonata_ir::{Articulation, EngineDesc, InstrumentSpec, Unit};1819pub fn desc() -> EngineDesc {20    let mut params = vec![21        num("brightness", Unit::Ratio, 0.0, 1.0, 0.5, false, "Overall spectral tilt of the strings."),22        num("hammer.hardness", Unit::Ratio, 0.0, 1.0, 0.5, false, "Felt hardness: a harder hammer excites more partials, more so at high velocity."),23        num("hammer.noise", Unit::Ratio, 0.0, 1.0, 0.3, false, "Level of the hammer's knock."),24        num(25            "strike_position",26            Unit::Ratio,27            0.05,28            0.3,29            0.125,30            false,31            "Hammer strike point as a fraction of the string length; partials with a node there are weak (1/8 removes every 8th).",32        ),33        num("inharmonicity", Unit::Scalar, 0.0, 4.0, 1.0, false, "Multiplier of the string stiffness coefficient B (1 = a typical grand)."),34        num(35            "unison_detune",36            Unit::Semitones,37            0.0,38            0.3,39            0.012,40            false,41            "Mistuning between the strings of one note, which creates the slow beating and the two-stage decay.",42        ),43        num("decay", Unit::Scalar, 0.2, 3.0, 1.0, false, "Multiplier of every partial's decay time."),44        num("resonance", Unit::Ratio, 0.0, 1.0, 0.25, true, "Soundboard and sympathetic string resonance; rings much longer while the sustain pedal is down."),45        num("width", Unit::Ratio, 0.0, 1.0, 0.6, false, "Stereo spread from bass (left) to treble (right)."),46    ];47    params.extend(envelope_params(true, 0.0, 1.0, 1.0, 0.18));48    EngineDesc {49        model: "piano".into(),50        title: "Piano".into(),51        family: "keyboard".into(),52        method: "Modal synthesis: up to 36 inharmonic partials per note, each as two detuned decaying sinusoids (prompt sound and aftersound), amplitudes from a struck-string spectrum; filtered-noise hammer knock; resonator bank for the soundboard".into(),53        doc: "A synthesised acoustic piano. It models the stretched partials of stiff strings, the dependence of brightness on velocity, the double decay of unison strings and the sustain pedal. It is a physically informed approximation, not a sampled instrument.".into(),54        range: (21, 108),55        params,56        presets: vec![57            preset("grand", "Concert grand: balanced, long sustain.", &[], &[]),58            preset("upright", "Upright: shorter strings, more inharmonic, shorter decay, narrower.", &[("inharmonicity", 2.2), ("decay", 0.6), ("brightness", 0.42), ("width", 0.3), ("resonance", 0.35), ("hammer.noise", 0.4)], &[]),59            preset("bright", "Hard hammers for pop and rock.", &[("brightness", 0.8), ("hammer.hardness", 0.85), ("decay", 0.9)], &[]),60            preset("felt", "Soft felt strip: dark, intimate, audible action.", &[("brightness", 0.2), ("hammer.hardness", 0.12), ("hammer.noise", 0.7), ("decay", 0.7), ("resonance", 0.4)], &[]),61            preset("honky_tonk", "Deliberately mistuned unisons.", &[("unison_detune", 0.14), ("brightness", 0.65), ("hammer.hardness", 0.7), ("decay", 0.7)], &[]),62        ],63        articulations: vec!["normal".into(), "staccato".into(), "legato".into(), "accent".into(), "marcato".into()],64        pitched: true,65    }66}6768const MAX_PARTIALS: usize = 36;69const LEVEL: f32 = 0.5;70const BOARD_MODES: usize = 14;7172pub struct Piano {73    sr: f32,74    r: Resolved,75    env: EnvSettings,76    i_res: usize,77    board: Vec<Biquad>,78    board_freqs: Vec<f32>,79    pedal_state: bool,80}8182pub struct Voice {83    bank: AdditiveBank,84    env: Adsr,85    rng: Rng,86    noise_lp: OnePole,87    noise_hp: OnePole,88    noise_env: f32,89    noise_decay: f32,90    noise_amp: f32,91    attack: f32,92    attack_step: f32,93    gl: f32,94    gr: f32,95    pitch: f32,96    has_damper: bool,97}9899impl Piano {100    fn set_board(&mut self, pedal: bool) {101        let t60 = if pedal { 3.5 } else { 0.35 };102        for (b, f) in self.board.iter_mut().zip(&self.board_freqs) {103            let c = BiquadCoefs::resonator(*f, t60 * (200.0 / f).sqrt().clamp(0.3, 1.5), self.sr);104            b.set_smoothed(c, 256);105        }106        self.pedal_state = pedal;107    }108}109110impl Engine for Piano {111    type Voice = Voice;112113    fn prepare(&mut self, sample_rate: f32, _max_block: usize) {114        self.sr = sample_rate;115        // Soundboard / sympathetic modes: log-spaced from 55 Hz to 2.6 kHz with a fixed irregularity.116        self.board_freqs = (0..BOARD_MODES).map(|i| 55.0 * 2f32.powf(i as f32 * 0.43 + 0.07 * ((i * 7) % 5) as f32)).collect();117        self.board = self.board_freqs.iter().map(|_| Biquad::default()).collect();118        self.set_board(false);119        for b in &mut self.board {120            let c = b.coefs();121            b.set(c);122        }123    }124125    fn make_voice(&self, sr: f32) -> Voice {126        Voice {127            bank: AdditiveBank::new(MAX_PARTIALS * 2),128            env: Adsr::new(sr),129            rng: Rng::new(1),130            noise_lp: OnePole::new(900.0, sr),131            noise_hp: OnePole::new(150.0, sr),132            noise_env: 0.0,133            noise_decay: 0.99,134            noise_amp: 0.0,135            attack: 0.0,136            attack_step: 1.0,137            gl: 1.0,138            gr: 1.0,139            pitch: 60.0,140            has_damper: true,141        }142    }143144    fn start(&self, v: &mut Voice, note: &NoteOn, seed: u64) {145        let sr = self.sr;146        let vel = note.velocity.clamp(0.0, 1.0) * if matches!(note.articulation, Articulation::Accent | Articulation::Marcato) { 1.1 } else { 1.0 };147        let vel = vel.min(1.0);148        let midi = note.pitch;149        v.pitch = midi;150        v.has_damper = midi < 90.0;151        v.rng = Rng::new(seed);152        v.bank.clear();153        // Stiffness coefficient B of f_n = n f0 sqrt(1 + B n^2): about 1e-4 in the bass, 3e-4 at154        // middle C, above 1e-2 in the top octave.155        let b = self.r.get("inharmonicity") * (3.0e-4 * ((midi - 60.0) * 0.085).exp()).max(8.0e-5);156        let f0 = note.freq / (1.0 + b).sqrt();157        let bright = self.r.get("brightness");158        let hard = self.r.get("hammer.hardness");159        // Hammer low-pass: the contact gets shorter (brighter) with velocity and hardness.160        let fc = (300.0 + 11_000.0 * vel * vel * (0.25 + 1.5 * bright)) * (0.5 + hard) + 1.5 * f0;161        let p = self.r.get("strike_position");162        let t1 = self.r.get("decay") * 12.0 * 2f32.powf(-(midi - 21.0) / 20.0);163        let detune = self.r.get("unison_detune") * if midi < 34.0 { 0.3 } else { 1.0 };164        let mut norm = 0.0;165        let mut amps = [0.0f32; MAX_PARTIALS];166        let mut count = 0;167        for n in 1..=MAX_PARTIALS {168            let nf = n as f32;169            let f = nf * f0 * (1.0 + b * nf * nf).sqrt();170            if f > 0.45 * sr {171                break;172            }173            let a = (std::f32::consts::PI * nf * p).sin() / nf / (1.0 + (f / fc).powi(2));174            amps[n - 1] = a;175            norm += a.abs();176            count = n;177        }178        let gain = LEVEL * (0.08 + 0.92 * vel.powf(1.6)) / norm.max(1e-6);179        for n in 1..=count {180            let nf = n as f32;181            let f = nf * f0 * (1.0 + b * nf * nf).sqrt();182            let a = amps[n - 1] * gain;183            let t60 = (t1 / (1.0 + 0.05 * nf.powf(1.4))).max(0.05);184            let d1 = semitones_to_ratio(detune * (0.3 + 0.7 * v.rng.unipolar()));185            let d2 = semitones_to_ratio(-detune * (0.3 + 0.7 * v.rng.unipolar()));186            // Prompt sound: most of the energy, fast decay. Aftersound: weaker, slow decay, detuned.187            v.bank.push(f * d1, a * 0.72, 0.0, t60 * 0.45, sr);188            v.bank.push(f * d2, a * 0.28, 0.0, t60 * 1.7, sr);189        }190        v.attack = 0.0;191        v.attack_step = 1.0 / ((0.0035 - 0.0028 * vel) * (1.3 - hard * 0.6) * sr).max(8.0);192        v.noise_env = 1.0;193        v.noise_decay = (-1.0 / (0.012 * sr)).exp();194        v.noise_amp = self.r.get("hammer.noise") * 0.5 * LEVEL * vel * vel;195        v.noise_lp.reset();196        v.noise_hp.reset();197        v.noise_lp.set(600.0 + 2500.0 * hard + 6.0 * note.freq.min(800.0), sr);198        let (gl, gr) = pan_gains(((midi - 64.0) / 44.0).clamp(-1.0, 1.0) * self.r.get("width"));199        v.gl = gl;200        v.gr = gr;201        self.env.start(&mut v.env);202    }203204    fn release(&self, v: &mut Voice) {205        // The top octave and a half has no dampers: those strings ring out.206        if v.has_damper {207            v.env.gate_off();208        }209    }210211    fn bend(&self, _v: &mut Voice, _semitones: f32) {}212213    fn render(&self, v: &mut Voice, left: &mut [f32], right: &mut [f32]) -> bool {214        for i in 0..left.len() {215            if v.attack < 1.0 {216                v.attack = (v.attack + v.attack_step).min(1.0);217            }218            let mut y = v.bank.tick() * v.attack;219            if v.noise_env > 1e-4 {220                let nz = v.noise_hp.highpass(v.noise_lp.lowpass(v.rng.bipolar()));221                y += nz * v.noise_env * v.noise_amp;222                v.noise_env *= v.noise_decay;223            }224            y *= v.env.tick();225            left[i] = y * v.gl;226            right[i] = y * v.gr;227        }228        !v.env.is_idle()229    }230231    fn set_param(&mut self, index: usize, value: f32) {232        if index < self.r.v.len() {233            self.r.v[index] = value;234        }235    }236237    fn post(&mut self, left: &mut [f32], right: &mut [f32], pedal: bool) {238        if pedal != self.pedal_state {239            self.set_board(pedal);240        }241        let mix = self.r.v[self.i_res] * 0.35;242        if mix <= 0.0 {243            return;244        }245        for i in 0..left.len() {246            let x = 0.5 * (left[i] + right[i]);247            let (mut a, mut b) = (0.0, 0.0);248            for (k, m) in self.board.iter_mut().enumerate() {249                let y = m.tick(x);250                if k % 2 == 0 {251                    a += y;252                } else {253                    b += y;254                }255            }256            left[i] += (a + 0.4 * b) * mix;257            right[i] += (b + 0.4 * a) * mix;258        }259    }260261    fn reset_shared(&mut self) {262        self.board.iter_mut().for_each(|b| b.reset());263    }264265    fn tail_seconds(&self) -> f32 {266        // Soundboard resonators: 3.5 s (pedal down) times the 1.5 low-mode factor.267        if self.r.v[self.i_res] > 0.0 {268            5.5269        } else {270            0.0271        }272    }273274    fn decays_naturally(&self) -> bool {275        true276    }277}278279pub fn build(spec: &InstrumentSpec, _tuning: f64, seed: u64) -> Result<Box<dyn Instrument>, String> {280    let d = desc();281    let r = resolve(&d, spec)?;282    let e =283        Piano { sr: 48_000.0, env: EnvSettings::read(&r, true), i_res: r.idx("resonance"), board: Vec::new(), board_freqs: Vec::new(), pedal_state: false, r };284    Ok(Box::new(Poly::new(e, seed)))285}286
Files main
Menu

Theme