1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
// Copyright (c) 2021 Weird Constructor <weirdconstructor@gmail.com>
// This file is a part of HexoDSP. Released under GPL-3.0-or-later.
// See README.md and COPYING for details.

use crate::dsp::{
    denorm, denorm_offs, inp, out, DspNode, GraphFun, LedPhaseVals, NodeContext, NodeGlobalRef,
    NodeId, ProcBuf, SAtom,
};
use crate::nodes::{NodeAudioContext, NodeExecContext};
use synfx_dsp::{Biquad, DelayBuffer, FixedOnePole};

// Bowed String instrument oscillator
// Bowed string model, a la Smith (1986),
// after McIntyre, Schumacher, Woodhouse (1983).
//
// This is a digital waveguide model, making its use possibly subject to
// patents held by Stanford University, Yamaha, and others.
//
// Implementation taken from tubonitaub / alec-deason
// from https://github.com/alec-deason/virtual_modular/blob/4025f1ef343c2eb9cd74eac07b5350c1e7ec9c09/src/simd_graph.rs#L3926
// or
// under MIT License
//
// Which is a reimplementation of this implementation:
// https://github.com/thestk/stk/blob/38970124ecda9d78a74a375426ed5fb9c09840a2/src/Bowed.cpp#L32
// By Perry R. Cook and Gary P. Scavone, 1995--2019.
// Contributions by Esteban Maestre, 2011.
#[derive(Debug, Clone)]
struct BowedString {
    srate: f32,
    nut_to_bow: DelayBuffer<f32>,
    bow_to_bridge: DelayBuffer<f32>,
    string_filter: FixedOnePole,
    body_filters: [Biquad; 6],
}

impl BowedString {
    pub fn new() -> Self {
        let mut s = Self {
            srate: 44100.0,
            nut_to_bow: DelayBuffer::new(),
            bow_to_bridge: DelayBuffer::new(),
            string_filter: FixedOnePole::new(0.0, 0.0),
            body_filters: [
                Biquad::new_with(1.0, 1.5667, 0.3133, -0.5509, -0.3925),
                Biquad::new_with(1.0, -1.9537, 0.9542, -1.6357, 0.8697),
                Biquad::new_with(1.0, -1.6683, 0.8852, -1.7674, 0.8735),
                Biquad::new_with(1.0, -1.8585, 0.9653, -1.8498, 0.9516),
                Biquad::new_with(1.0, -1.9299, 0.9621, -1.9354, 0.9590),
                Biquad::new_with(1.0, -1.9800, 0.9888, -1.9867, 0.9923),
            ],
        };
        s.set_sample_rate(s.srate);
        s
    }

    pub fn set_sample_rate(&mut self, sample_rate: f32) {
        self.srate = sample_rate;
        self.string_filter = FixedOnePole::new(0.75 - (0.2 * (22050.0 / sample_rate)), 0.9);
    }

    pub fn reset(&mut self) {
        self.nut_to_bow.reset();
        self.bow_to_bridge.reset();
        self.string_filter.reset();

        for f in self.body_filters.iter_mut() {
            f.reset();
        }
    }

    #[inline]
    pub fn process(&mut self, freq: f32, bow_velocity: f32, bow_force: f32, pos: f32) -> f32 {
        let total_l = self.srate / freq.max(20.0);
        let total_l = if total_l <= 0.0 { 0.3 } else { total_l };
        let bow_position = ((pos + 1.0) / 2.0).clamp(0.01, 0.99);

        let bow_nut_l = total_l * (1.0 - bow_position);
        let bow_bridge_l = total_l * bow_position;

        let nut = -self.nut_to_bow.cubic_interpolate_at_s(bow_nut_l);
        let brid = self.bow_to_bridge.cubic_interpolate_at_s(bow_bridge_l);
        let bridge = -self.string_filter.process(brid);

        let dv = 0.25 * bow_velocity - (nut + bridge);

        let phat = ((dv + 0.001) * bow_force + 0.75).abs().powf(-4.0).clamp(0.01, 0.98);
        let phat = phat * dv;

        self.bow_to_bridge.feed(nut + phat);
        self.nut_to_bow.feed(bridge + phat);

        let mut output = bridge;
        for f in self.body_filters.iter_mut() {
            output = f.tick(output);
        }

        output
    }
}

/// A bowed string simulation oscillator
#[derive(Debug, Clone)]
pub struct BowStri {
    bstr: Box<BowedString>,
}

impl BowStri {
    pub fn new(_nid: &NodeId, _node_global: &NodeGlobalRef) -> Self {
        Self { bstr: Box::new(BowedString::new()) }
    }
    pub const freq: &'static str = "Frequency of the bowed string oscillator.\n";
    pub const det: &'static str = "Detune the oscillator in semitones and cents. \
         the input of this value is rounded to semitones on coarse input. \
         Fine input lets you detune in cents (rounded). \
         A signal sent to this port is not rounded.\n\
         Note: The signal input allows detune +-10 octaves.";
    pub const vel: &'static str = "Velocity of the bow";
    pub const force: &'static str = "Force of the bow";
    pub const pos: &'static str = "Position of the bow";
    pub const sig: &'static str = "Oscillator signal output.\n";

    pub const DESC: &'static str = r#"Bowed String Oscillator

This is an oscillator that simulates a bowed string.
"#;

    pub const HELP: &'static str = r#"A Bowed String Simulation Oscillator

This is an oscillator that simulates a bowed string.
It's a bit wonky, so play around with the parameters and see what
works and what doesn't. It plays find in the area from **~55Hz** up to
**~1760Hz**, beyond that it might not produce a sound.

I can recommend to apply an envelope to the ~~vel~~ parameter,
which is basically the bow's velocity.
"#;

    pub fn graph_fun() -> Option<GraphFun> {
        None
    }
}

impl DspNode for BowStri {
    fn set_sample_rate(&mut self, srate: f32) {
        self.bstr.set_sample_rate(srate);
    }

    fn reset(&mut self) {
        self.bstr.reset();
    }

    #[inline]
    fn process(
        &mut self,
        ctx: &mut dyn NodeAudioContext,
        _ectx: &mut NodeExecContext,
        _nctx: &NodeContext,
        _atoms: &[SAtom],
        inputs: &[ProcBuf],
        outputs: &mut [ProcBuf],
        ctx_vals: LedPhaseVals,
    ) {
        let o = out::BowStri::sig(outputs);
        let freq = inp::BowStri::freq(inputs);
        let det = inp::BowStri::det(inputs);
        let vel = inp::BowStri::vel(inputs);
        let force = inp::BowStri::force(inputs);
        let pos = inp::BowStri::pos(inputs);

        let mut last_val = 0.0;
        for frame in 0..ctx.nframes() {
            // The BowStri oscillator is usually off by ~30 cent per octave,
            // that makes it off by 1 semitone at about 1760Hz and off by ~30c
            // at 440 Hz.
            // Calculate some tune correction here based on the
            // normalized value (-0.2 is 110Hz, 0.0 is 440Hz, ...):
            let tune_correction = (freq.read(frame).clamp(-0.2, 1.0) + 0.2) * 10.0 * 0.0012;

            let freq = denorm_offs::BowStri::freq(freq, tune_correction + det.read(frame), frame);

            let out = self.bstr.process(
                freq,
                denorm::BowStri::vel(vel, frame),
                denorm::BowStri::force(force, frame),
                denorm::BowStri::pos(pos, frame),
            );
            last_val = out;
            o.write(frame, out);
        }

        ctx_vals[0].set(last_val);
    }
}