commit b5a035f1d5e1ea47f30b047040c21d1db389c26b Author: annieversary Date: Sat Jul 24 18:40:59 2021 +0200 restart history diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1e13b45 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/target +Cargo.lock +.DS_Store +build diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..75d1f30 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "unnieversal" +version = "0.1.0" +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[workspace] +members =[ + "crates/*", +] + +[dependencies] diff --git a/README.md b/README.md new file mode 100644 index 0000000..63c2960 --- /dev/null +++ b/README.md @@ -0,0 +1,137 @@ +# unnieversal + +some VST plugins made in Rust using `baseplug` + +source for the plugins are inside the `crates` folder + +the compiled plugins live inside `build`. all plugins have only been tested on macos with reaper + +disclaimer: i am not responsible for loss of work, time, sanity, or anything else if you decide to use this plugins + +## building a plugin + +### macos + +to build a plugin, first run: + +```bash +cargo b --package package_name --release +``` + +Then make the generated dylib file into a VST plugin: + +```bash +./osx_vst_bundler.sh PluginName target/release/libpackage_name.dylib +``` + +this will create `PluginName.vst` in the `build` folder. You can copy it into `/Library/Audio/Plug-Ins/VST` and use it in your daw + +alternatively, you can run: + +```bash +./macos.sh packagename +``` + +this will generate `Packagename.vst` in `build` and copy it directly for you + +### other platforms + +no idea what you have to do for other platforms, refer to the `vst-rs` [docs](https://github.com/rustaudio/vst-rs). i think you can just build and take the `.so` or `.dll`, but don't quote me on that + +PRs are welcome for more build instructions + +i also might delete the `build` folder from the repo, + +## plugin list + +the following is the current list of plugins. you can find the code in the `crates` folder + +- basic_gain: simple gain plugin +- noted: output midi at regular intervals +- sosten: granular sustain plugin +- quinoa: [WIP] granular synthesis plugin +- XLowpass: reimplementation of [Airwindows XLowpass](http://www.airwindows.com/xlowpass/) +- multidim: randomized midi note generator +- robotuna: automatic pitch correction +- hysteria: hysteresis nonlinear effect +- threebandeq: [WIP] 3 band eq + +### basic_gain + +simple gain plugin, used as a template for starting new projects + +### noted + +midi retriggerer + +parameters: +- `tempo`: how often to retrigger a note + +it listens for incoming midi, and while a note is on, it triggers it every `tempo` beats. if `tempo` is one, it will trigger once per beat + +it's useful when you want to play a note super fast (over 1/64 tempo) but don't want to have a section full of tiny midi notes. just add the plugin, set the tempo to how often you want it to play, and add a midi note that lasts however long you want the notes to play for + +### sosten + +sustains a sound by replaying a grain of sound on loop + +parameters: +- `length`: length of the grain in samples. maximum is 48000 cause i said so +- `mix`: dry/wet knob +- `enable`: will enable the sustain if it's over 0.5 + +to use this plugin, add an automation for `enable` and set the value to `1.0` wherever you want the sustain to happen + +### quinoa [WIP] + +nothing implemented yet, but it's supposed to be a granular synthesis plugin that does stuff with an audio file + +since this needs a ui so we can select a file to play, and i still don't know how to do that, it's kinda stuck + +### XLowpass + +XLowpass just reimplements [Airwindows XLowpass](http://www.airwindows.com/xlowpass/) in rust. it's a lowpass distortion filter + +parameters: +- `gain` +- `frequency`: cutoff frequency. it's not in hz, so move it around until it does what you want it to +- `nuke`: amount of distortion + +i haven't checked correctly, but there's probably some mistakes and it might not sound exactly the same. it does what i want it to, so that's good enough for me. also i have absolutely no idea what the code does, it's just a direct translation + +you might need to play with the parameters around a bit to get it to sound good + +### multidim + +multidim simulates a ball bouncing around in a 16-dimensional cube. each time the ball bounces off of a wall, a midi note is sent out + +parameters: +- `speed`: speed at which the ball moves. around 1 should cause approximately one bounce per beat +- `root`: the lowest note that will be generated (in midi number). the rest of the notes will be from `root` to `root + 16` +- `note_length`: length of each note in beats +- `enable`: enables the generation if over 0.5 + +since some daws keep the plugins running all the time (whether the song is playing or not), this plugin will generate notes constantly even if the song is paused. since this gets annoying fast, i added an `enable` param. set it to 1 to make the plugin generate notes + +### robotuna + +WIP automatic pitch correction and pitch shifting. the intention is to use it to make hyperpop-style high-pitched vocals + +it kinda works, but not really. since the pitch shifting part is too slow using a phase vocoder, it doesn't run in real time, and there's some clicking noises. i need to rework that whole thing so it can run in real time. i'll probably change the whole thing completely instead of optimizing it cause yeah + +### hysteria + +hysteria is a hysteresis nonlinear effect, which compresses and distorts the input audio + +parameters: +- `drive` +- `saturation` +- `width`: width of the hysteresis loop + +original source [here](https://ccrma.stanford.edu/~jatin/ComplexNonlinearities/Hysteresis.html) + +turn the values up for loud and distorted. don't set them all to the max at once though, that doesn't sound as interesting + +### threebandeq [WIP] + +wip, there's nothing yet diff --git a/crates/basic_gain/Cargo.toml b/crates/basic_gain/Cargo.toml new file mode 100644 index 0000000..480a8eb --- /dev/null +++ b/crates/basic_gain/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "basic_gain" +version = "0.1.0" +edition = "2018" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +baseplug = { git = "https://github.com/wrl/baseplug.git", rev = "9cec68f31cca9c0c7a1448379f75d92bbbc782a8" } +serde = "1.0.126" diff --git a/crates/basic_gain/src/lib.rs b/crates/basic_gain/src/lib.rs new file mode 100644 index 0000000..08d585d --- /dev/null +++ b/crates/basic_gain/src/lib.rs @@ -0,0 +1,57 @@ +#![allow(incomplete_features)] +#![feature(generic_associated_types)] + +use baseplug::{Plugin, ProcessContext}; +use serde::{Deserialize, Serialize}; + +baseplug::model! { + #[derive(Debug, Serialize, Deserialize)] + struct GainModel { + #[model(min = -90.0, max = 3.0)] + #[parameter(name = "gain", unit = "Decibels", + gradient = "Power(0.15)")] + gain: f32 + } +} + +impl Default for GainModel { + fn default() -> Self { + Self { + // "gain" is converted from dB to coefficient in the parameter handling code, + // so in the model here it's a coeff. + // -0dB == 1.0 + gain: 1.0, + } + } +} + +struct Gain; + +impl Plugin for Gain { + const NAME: &'static str = "basic gain"; + const PRODUCT: &'static str = "basic gain"; + const VENDOR: &'static str = "unnieversal"; + + const INPUT_CHANNELS: usize = 2; + const OUTPUT_CHANNELS: usize = 2; + + type Model = GainModel; + + #[inline] + fn new(_sample_rate: f32, _model: &GainModel) -> Self { + Self + } + + #[inline] + fn process(&mut self, model: &GainModelProcess, ctx: &mut ProcessContext) { + let input = &ctx.inputs[0].buffers; + let output = &mut ctx.outputs[0].buffers; + + for i in 0..ctx.nframes { + output[0][i] = input[0][i] * model.gain[i]; + output[1][i] = input[1][i] * model.gain[i]; + } + } +} + +baseplug::vst2!(Gain, b"tAnE"); diff --git a/crates/hysteria/Cargo.toml b/crates/hysteria/Cargo.toml new file mode 100644 index 0000000..f9b8e06 --- /dev/null +++ b/crates/hysteria/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "hysteria" +version = "0.1.0" +edition = "2018" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +baseplug = { git = "https://github.com/wrl/baseplug.git", rev = "9cec68f31cca9c0c7a1448379f75d92bbbc782a8" } +serde = "1.0.126" diff --git a/crates/hysteria/src/hysteresis.rs b/crates/hysteria/src/hysteresis.rs new file mode 100644 index 0000000..75214ad --- /dev/null +++ b/crates/hysteria/src/hysteresis.rs @@ -0,0 +1,142 @@ +pub struct Hysteresis { + fs: f32, + t: f32, + + m_s: f32, + a: f32, + c: f32, + + // Save calculations + nc: f32, + m_s_oa: f32, + m_s_oa_tc: f32, + m_s_oa_tc_talpha: f32, + + // state variables + m_n1: f32, + h_n1: f32, + h_d_n1: f32, +} + +impl Hysteresis { + const ALPHA: f32 = 1.6e-3; + const D_ALPHA: f32 = 0.9; + const UPPER_LIM: f32 = 20.0; + const K: f32 = 0.47875; + + pub fn new() -> Self { + let m_s = 1.0; + let a = m_s / 4.0; + let c = 1.7e-1; + + let fs = 48000.0; + let t = 1.0 / fs; + Self { + fs, + t, + + m_s, + a, + c, + + // Save calculations + nc: 1.0 - c, + m_s_oa: m_s / a, + m_s_oa_tc: c * m_s / a, + m_s_oa_tc_talpha: Self::ALPHA * c * m_s / a, + + // state variables + m_n1: 0.0, + h_n1: 0.0, + h_d_n1: 0.0, + } + } + + pub fn set_sample_rate(&mut self, sample_rate: f32) { + // Sample rate + self.fs = sample_rate; + self.t = 1.0 / self.fs; + } + + pub fn process(&mut self, drive: f32, width: f32, sat: f32, h: f32) -> f32 { + self.m_s = 0.5 + 1.5 * (1.0 - sat); + self.a = self.m_s / (0.01 + 6.0 * drive); + self.c = (1.0 - width).sqrt() - 0.01; + + self.nc = 1.0 - self.c; + self.m_s_oa = self.m_s / self.a; + self.m_s_oa_tc = self.c * self.m_s_oa; + self.m_s_oa_tc_talpha = Self::ALPHA * self.m_s_oa_tc; + + let h_d = self.deriv(h, self.h_n1, self.h_d_n1); + let mut m = self.solver(h, h_d); + + if m.is_nan() || m > Self::UPPER_LIM { + m = 0.0; + } + + self.m_n1 = m; + self.m_n1 = h; + self.h_d_n1 = h_d; + + m + } + + fn deriv(&self, x_n: f32, x_n1: f32, x_d_n1: f32) -> f32 { + (((1.0 + Self::D_ALPHA) / self.t) * (x_n - x_n1)) - Self::D_ALPHA * x_d_n1 + } + + fn solver(&self, h: f32, h_d: f32) -> f32 { + // Corresponds to RK2 + let k1 = self.t * self.hysteresis_func(self.m_n1, self.h_n1, self.h_d_n1); + let k2 = self.t + * self.hysteresis_func( + self.m_n1 + (k1 / 2.0), + (h + self.h_n1) / 2.0, + (h_d + self.h_d_n1) / 2.0, + ); + + self.m_n1 + k2 + } + + fn hysteresis_func(&self, m: f32, h: f32, h_d: f32) -> f32 { + let q = (h + Self::ALPHA * m) / self.a; + let coth = 1.0 / q.tanh(); + let near_zero = q.abs() < 0.001; + + let m_diff = self.m_s * langevin(coth, q, near_zero) - m; + + let delta: f32 = if h_d >= 0.0 { 1.0 } else { -1.0 }; + let delta_m = if delta.signum() == m_diff.signum() { + 1.0 + } else { + 0.0 + }; + + let l_prime = langevin_d(coth, q, near_zero); + + let kap1 = self.nc * delta_m; + let f1_denom = self.nc * delta * Self::K - Self::ALPHA * m_diff; + let f1 = kap1 * m_diff / f1_denom; + let f2 = self.m_s_oa_tc * l_prime; + let f3 = 1.0 - (self.m_s_oa_tc_talpha * l_prime); + + h_d * (f1 + f2) / f3 + } +} + +fn langevin(coth: f32, x: f32, near_zero: bool) -> f32 { + if near_zero { + x / 3.0 + } else { + coth - (1.0 / x) + } +} + +fn langevin_d(coth: f32, x: f32, near_zero: bool) -> f32 { + if near_zero { + 1.0 / 3.0 + } else { + (1.0 / (x * x)) - (coth * coth) + 1.0 + } +} diff --git a/crates/hysteria/src/lib.rs b/crates/hysteria/src/lib.rs new file mode 100644 index 0000000..663998d --- /dev/null +++ b/crates/hysteria/src/lib.rs @@ -0,0 +1,92 @@ +#![allow(incomplete_features)] +#![feature(generic_associated_types)] + +use baseplug::{Plugin, ProcessContext}; +use serde::{Deserialize, Serialize}; + +mod hysteresis; +use hysteresis::*; + +baseplug::model! { + #[derive(Debug, Serialize, Deserialize)] + struct HysteriaModel { + #[model(min = 0.0, max = 10.0)] + #[parameter(name = "drive")] + drive: f32, + #[model(min = 0.0, max = 1.0)] + #[parameter(name = "saturation")] + sat: f32, + #[model(min = 0.0, max = 1.0)] + #[parameter(name = "width")] + width: f32, + } +} + +impl Default for HysteriaModel { + fn default() -> Self { + Self { + drive: 1., + sat: 0.5, + width: 0.5, + } + } +} + +struct Hysteria { + hysteresis_l: Hysteresis, + hysteresis_r: Hysteresis, +} + +impl Plugin for Hysteria { + const NAME: &'static str = "hysteria"; + const PRODUCT: &'static str = "hysteria"; + const VENDOR: &'static str = "unnieversal"; + + const INPUT_CHANNELS: usize = 2; + const OUTPUT_CHANNELS: usize = 2; + + type Model = HysteriaModel; + + #[inline] + fn new(_sample_rate: f32, _model: &HysteriaModel) -> Self { + Self { + hysteresis_l: Hysteresis::new(), + hysteresis_r: Hysteresis::new(), + } + } + + #[inline] + fn process(&mut self, model: &HysteriaModelProcess, ctx: &mut ProcessContext) { + let input = &ctx.inputs[0].buffers; + let output = &mut ctx.outputs[0].buffers; + + // Update sample rate + let sample_rate = ctx.sample_rate; + self.hysteresis_l.set_sample_rate(sample_rate); + self.hysteresis_r.set_sample_rate(sample_rate); + + for i in 0..ctx.nframes { + // Makeup is an added extra to make it work similarly with all params + let makeup = calc_makeup(model.width[i], model.sat[i]); + + output[0][i] = self.hysteresis_l.process( + model.drive[i], + model.width[i], + model.sat[i], + input[0][i], + ) * makeup; + output[1][i] = self.hysteresis_r.process( + model.drive[i], + model.width[i], + model.sat[i], + input[1][i], + ) * makeup; + } + } +} + +fn calc_makeup(width: f32, sat: f32) -> f32 { + (1.0 + 0.6 * width) / (0.5 + 1.5 * (1.0 - sat)) +} + +baseplug::vst2!(Hysteria, b"hyst"); diff --git a/crates/multidim/Cargo.toml b/crates/multidim/Cargo.toml new file mode 100644 index 0000000..85a11f4 --- /dev/null +++ b/crates/multidim/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "multidim" +version = "0.1.0" +edition = "2018" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +baseplug = { git = "https://github.com/wrl/baseplug.git", rev = "9cec68f31cca9c0c7a1448379f75d92bbbc782a8" } +serde = "1.0.126" +log = "0.4.14" + +utils = { path = "../utils" } +rand = "0.8.4" diff --git a/crates/multidim/src/lib.rs b/crates/multidim/src/lib.rs new file mode 100644 index 0000000..5c0dbb1 --- /dev/null +++ b/crates/multidim/src/lib.rs @@ -0,0 +1,155 @@ +#![allow(incomplete_features)] +#![feature(generic_associated_types)] +#![feature(drain_filter)] + +use baseplug::{event::Data, Event, Plugin, ProcessContext}; +use rand::{thread_rng, Rng}; +use serde::{Deserialize, Serialize}; + +use utils::logs::*; + +mod maths; +use maths::*; + +baseplug::model! { + #[derive(Debug, Serialize, Deserialize)] + struct MultidimModel { + /// Speed at which the ball moves + /// Around 1 should cause aprox. one bounce per beat + #[model(min = 0.0, max = 10.0)] + #[parameter(name = "speed")] + speed: f32, + /// Root note + /// Notes will be generated from `root` to `root + DIM` + #[model(min = 0.0, max = 111.0)] + #[parameter(name = "root note")] + root: f32, + /// How many beats each note lasts + #[model(min = 0.0, max = 4.0)] + #[parameter(name = "note length")] + note_length: f32, + /// Enable if over 0.5 + #[model(min = 0.0, max = 1.0)] + #[parameter(name = "enable")] + enable: f32, + } +} + +impl Default for MultidimModel { + fn default() -> Self { + Self { + speed: 1.0, + root: 64.0, + note_length: 0.25, + enable: 0.0, + } + } +} + +const DIM: usize = 16; + +struct Multidim { + position: [f32; DIM], + velocity: [f32; DIM], + + frame: usize, + pending_note_offs: Vec<(u8, usize)>, +} + +impl Plugin for Multidim { + const NAME: &'static str = "multidim"; + const PRODUCT: &'static str = "multidim"; + const VENDOR: &'static str = "unnieversal"; + + const INPUT_CHANNELS: usize = 2; + const OUTPUT_CHANNELS: usize = 2; + + type Model = MultidimModel; + + #[inline] + fn new(_sample_rate: f32, _model: &MultidimModel) -> Self { + setup_logging("multidim.log"); + + // Randomize direction, normalize + let mut velocity = [0.0; DIM]; + let mut rng = thread_rng(); + for v in &mut velocity { + *v = rng.gen_range(-1.0..1.0); + } + velocity = normalize(velocity); + + log::info!("finished init"); + + Self { + position: [0.0; DIM], + velocity, + frame: 0, + pending_note_offs: Vec::with_capacity(100), + } + } + + #[inline] + fn process(&mut self, model: &MultidimModelProcess, ctx: &mut ProcessContext) { + let output = &mut ctx.outputs[0].buffers; + let enqueue_midi = &mut ctx.enqueue_event; + + let curr_bpm = ctx.musical_time.bpm as f32; + let beat_in_seconds = 60.0 / curr_bpm; + let samples_per_beat = beat_in_seconds * ctx.sample_rate as f32; + + // Check for pending note offs + let n = ctx.nframes; + let f = self.frame; + for (note, end) in self.pending_note_offs.drain_filter(|(_, end)| *end < f + n) { + // Send note off + let note_on = Event:: { + frame: end - self.frame, + data: Data::Midi([0x80, note, 120]), + }; + enqueue_midi(note_on); + } + self.frame += ctx.nframes; + + for i in 0..ctx.nframes { + // write silence + output[0][i] = 0.0; + output[1][i] = 0.0; + + // If we're not playing, we skip advancing the ball + // We don't want to 1) waste cpu 2) send note ons + if model.enable[i] < 0.5 { + continue; + } + + // Advance ball and get list of collisions + let collisions = advance( + model.speed[i] / samples_per_beat, + &mut self.position, + &mut self.velocity, + ); + + let root = model.root[i].floor() as u8; + // Go through the list of possible collisions, and if any happened, send midi + for (idx, collision) in collisions.iter().enumerate() { + if !collision { + continue; + } + + let note = idx as u8 + root; + + // Send note on + let note_on = Event:: { + frame: i, + data: Data::Midi([0x90, note, 120]), + }; + enqueue_midi(note_on); + + // Add note off + let end = self.frame + (samples_per_beat * model.note_length[i]) as usize; + self.pending_note_offs.push((note, end)) + } + } + } +} + +baseplug::vst2!(Multidim, b"mdim"); diff --git a/crates/multidim/src/maths.rs b/crates/multidim/src/maths.rs new file mode 100644 index 0000000..fed4e55 --- /dev/null +++ b/crates/multidim/src/maths.rs @@ -0,0 +1,45 @@ +/// Returns a vector's magnitude +fn magnitude(vec: &[f32; DIM]) -> f32 { + let mut a = 0.; + for x in vec { + a += x * x; + } + a +} + +/// Normalizes a vector +pub fn normalize(mut vec: [f32; DIM]) -> [f32; DIM] { + let mag = magnitude(&vec); + + for x in &mut vec { + *x /= mag; + } + + vec +} + +/// Advances position +/// Deals with bounces on the box +/// Returns an array of bools, one per dimension, where true indicates a collision in that dim +pub fn advance( + speed: f32, + position: &mut [f32; DIM], + velocity: &mut [f32; DIM], +) -> [bool; DIM] { + let mut res = [false; DIM]; + + for (i, (x, v)) in position.iter_mut().zip(velocity.iter_mut()).enumerate() { + // Advance position in this axis + *x += *v * speed; + + // If we're out of bounds in this coordinate, change velocity + if x.abs() > 1.0 { + *v = -*v; + + // Mark as collision + res[i] = true; + } + } + + res +} diff --git a/crates/noted/Cargo.toml b/crates/noted/Cargo.toml new file mode 100644 index 0000000..f8d7fbf --- /dev/null +++ b/crates/noted/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "noted" +version = "0.1.0" +edition = "2018" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +baseplug = { git = "https://github.com/wrl/baseplug.git", rev = "9cec68f31cca9c0c7a1448379f75d92bbbc782a8" } +serde = "1.0.126" diff --git a/crates/noted/src/lib.rs b/crates/noted/src/lib.rs new file mode 100644 index 0000000..32849b2 --- /dev/null +++ b/crates/noted/src/lib.rs @@ -0,0 +1,126 @@ +/*! +Noted listens for incoming midi notes, and replaces them +*/ + +#![allow(incomplete_features)] +#![feature(generic_associated_types)] + +use baseplug::{event::Data, Event, MidiReceiver, Plugin, ProcessContext}; +use serde::{Deserialize, Serialize}; + +baseplug::model! { + #[derive(Debug, Serialize, Deserialize)] + struct NotedModel { + #[model(min = 0.001, max = 4.0)] + #[parameter(name = "tempo", gradient = "Exponential")] + tempo: f32, + } +} + +impl Default for NotedModel { + fn default() -> Self { + Self { tempo: 1.0 } + } +} + +struct Noted { + notes: [bool; 128], + frame_count: u64, + + note_off_buffer: Vec, +} + +impl Plugin for Noted { + const NAME: &'static str = "noted"; + const PRODUCT: &'static str = "noted"; + const VENDOR: &'static str = "unnieversal"; + + const INPUT_CHANNELS: usize = 2; + const OUTPUT_CHANNELS: usize = 2; + + type Model = NotedModel; + + #[inline] + fn new(_sample_rate: f32, _model: &NotedModel) -> Self { + Self { + notes: [false; 128], + frame_count: 0, + note_off_buffer: Vec::with_capacity(200), + } + } + + #[inline] + fn process(&mut self, model: &NotedModelProcess, ctx: &mut ProcessContext) { + let output = &mut ctx.outputs[0].buffers; + let enqueue_midi = &mut ctx.enqueue_event; + + let is_playing = ctx.musical_time.is_playing; + let curr_bpm = ctx.musical_time.bpm; + let beat_in_seconds = 60.0 / curr_bpm; + let smth = beat_in_seconds * ctx.sample_rate as f64; + + while let Some(note) = self.note_off_buffer.pop() { + let note_off = Event:: { + frame: 0, + data: Data::Midi([0x80, note as u8, 0]), + }; + enqueue_midi(note_off); + } + + for i in 0..ctx.nframes { + // write silence + output[0][i] = 0.0; + output[1][i] = 0.0; + + if is_playing { + let tempo_in_samples = model.tempo[i] as f64 * smth; + let tempo_in_samples = tempo_in_samples.round() as u64; + + self.frame_count += 1; + + // Send note ons for active notes + if self.frame_count >= tempo_in_samples { + for (note, is_on) in self.notes.iter().enumerate() { + if *is_on { + // Send note off + let note_off = Event:: { + frame: i, + data: Data::Midi([0x80, note as u8, 0]), + }; + enqueue_midi(note_off); + + // Send note on + let note_on = Event:: { + frame: i, + data: Data::Midi([0x90, note as u8, 120]), + }; + enqueue_midi(note_on); + } + } + self.frame_count = 0; + } + } else { + self.frame_count = 0; + } + } + } +} +impl MidiReceiver for Noted { + fn midi_input(&mut self, _model: &NotedModelProcess, data: [u8; 3]) { + match data[0] { + // note on + 0x90 => { + self.notes[data[1] as usize] = true; + } + // note off + 0x80 => { + self.notes[data[1] as usize] = false; + self.note_off_buffer.push(data[1]); + } + + _ => (), + } + } +} + +baseplug::vst2!(Noted, b"NoTe"); diff --git a/crates/pvoc-rs/.gitignore b/crates/pvoc-rs/.gitignore new file mode 100644 index 0000000..d4f917d --- /dev/null +++ b/crates/pvoc-rs/.gitignore @@ -0,0 +1,3 @@ +target +Cargo.lock +*.swp diff --git a/crates/pvoc-rs/Cargo.toml b/crates/pvoc-rs/Cargo.toml new file mode 100644 index 0000000..a2cf323 --- /dev/null +++ b/crates/pvoc-rs/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "pvoc" +version = "0.1.7" +authors = ["Noah Weninger "] +description = "A phase vocoder for making audio effects" +repository = "https://github.com/nwoeanhinnogaehr/pvoc-rs" +readme = "README.md" +keywords = ["audio", "fft", "dsp", "fourier"] +license = "GPL-3.0" + +[dependencies] +rustfft = "5.0.1" +apodize = "1.0.0" + +[dev-dependencies] +approx = "0.3.2" + +[dev-dependencies.rand] +version = "0.8.3" +features = ["small_rng"] diff --git a/crates/pvoc-rs/LICENSE b/crates/pvoc-rs/LICENSE new file mode 100644 index 0000000..9cecc1d --- /dev/null +++ b/crates/pvoc-rs/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/crates/pvoc-rs/README.md b/crates/pvoc-rs/README.md new file mode 100644 index 0000000..fa821ee --- /dev/null +++ b/crates/pvoc-rs/README.md @@ -0,0 +1,28 @@ +# fork + +this is a minor fork that adds a `set_sample_rate` method. i'm too lazy to open a pr and stuff + +upstream at https://github.com/nwoeanhinnogaehr/pvoc-rs + +# pvoc-rs + +A phase vocoder written in Rust. + +### Example usage +```rust +use pvoc::{PhaseVocoder, Bin}; + +let mut pvoc = PhaseVocoder::new(1, 44100.0, 256, 4); +pvoc.process(&input_samples, + &mut output_samples, + |channels: usize, bins: usize, input: &[Vec], output: &mut [Vec]| { + for i in 0..channels { + for j in 0..bins { + output[i][j] = input[i][j]; // change this! + } + } +}); + +``` + +Check out [pvoc-plugins](https://github.com/nwoeanhinnogaehr/pvoc-plugins) for some LADSPA plugins that use this library. diff --git a/crates/pvoc-rs/src/lib.rs b/crates/pvoc-rs/src/lib.rs new file mode 100644 index 0000000..0ed5d94 --- /dev/null +++ b/crates/pvoc-rs/src/lib.rs @@ -0,0 +1,398 @@ +extern crate apodize; +extern crate rustfft; +#[cfg(test)] +#[macro_use] +extern crate approx; +#[cfg(test)] +extern crate rand; + +use rustfft::num_complex::Complex; +use rustfft::num_traits::{Float, FromPrimitive, ToPrimitive}; +use std::collections::VecDeque; +use std::f64::consts::PI; +use std::sync::Arc; + +#[allow(non_camel_case_types)] +type c64 = Complex; + +/// Represents a component of the spectrum, composed of a frequency and amplitude. +#[derive(Copy, Clone)] +pub struct Bin { + pub freq: f64, + pub amp: f64, +} + +impl Bin { + pub fn new(freq: f64, amp: f64) -> Bin { + Bin { + freq: freq, + amp: amp, + } + } + pub fn empty() -> Bin { + Bin { + freq: 0.0, + amp: 0.0, + } + } +} + +/// A phase vocoder. +/// +/// Roughly translated from http://blogs.zynaptiq.com/bernsee/pitch-shifting-using-the-ft/ +pub struct PhaseVocoder { + channels: usize, + sample_rate: f64, + frame_size: usize, + time_res: usize, + + samples_waiting: usize, + in_buf: Vec>, + out_buf: Vec>, + last_phase: Vec>, + sum_phase: Vec>, + output_accum: Vec>, + + forward_fft: Arc>, + backward_fft: Arc>, + + window: Vec, + + fft_in: Vec, + fft_out: Vec, + fft_scratch: Vec, + analysis_out: Vec>, + synthesis_in: Vec>, +} + +impl PhaseVocoder { + /// Constructs a new phase vocoder. + /// + /// `channels` is the number of channels of audio. + /// + /// `sample_rate` is the sample rate. + /// + /// `frame_size` is the fourier transform size. It must be `> 1`. + /// For optimal computation speed, this should be a power of 2. + /// Will be rounded to a multiple of `time_res`. + /// + /// `time_res` is the number of frames to overlap. + /// + /// # Panics + /// Panics if `frame_size` is `<= 1` after rounding. + pub fn new( + channels: usize, + sample_rate: f64, + frame_size: usize, + time_res: usize, + ) -> PhaseVocoder { + let mut frame_size = frame_size / time_res * time_res; + if frame_size == 0 { + frame_size = time_res; + } + + // If `frame_size == 1`, computing the window would panic. + assert!(frame_size > 1); + + let mut fft_planner = rustfft::FftPlanner::new(); + + let mut pv = PhaseVocoder { + channels, + sample_rate, + frame_size, + time_res, + + samples_waiting: 0, + in_buf: vec![VecDeque::new(); channels], + out_buf: vec![VecDeque::new(); channels], + last_phase: vec![vec![0.0; frame_size]; channels], + sum_phase: vec![vec![0.0; frame_size]; channels], + output_accum: vec![VecDeque::new(); channels], + + forward_fft: fft_planner.plan_fft(frame_size, rustfft::FftDirection::Forward), + backward_fft: fft_planner.plan_fft(frame_size, rustfft::FftDirection::Inverse), + + window: apodize::hanning_iter(frame_size) + .map(|x| x.sqrt()) + .collect(), + + fft_in: vec![c64::new(0.0, 0.0); frame_size], + fft_out: vec![c64::new(0.0, 0.0); frame_size], + fft_scratch: vec![], + analysis_out: vec![vec![Bin::empty(); frame_size]; channels], + synthesis_in: vec![vec![Bin::empty(); frame_size]; channels], + }; + pv.fft_scratch = vec![ + c64::new(0.0, 0.0); + pv.forward_fft + .get_outofplace_scratch_len() + .max(pv.backward_fft.get_outofplace_scratch_len()) + ]; + pv + } + + pub fn num_channels(&self) -> usize { + self.channels + } + + pub fn num_bins(&self) -> usize { + self.frame_size + } + + pub fn time_res(&self) -> usize { + self.time_res + } + + pub fn sample_rate(&self) -> f64 { + self.sample_rate + } + + pub fn set_sample_rate(&mut self, sample_rate: f64) { + self.sample_rate = sample_rate; + } + + /// Reads samples from `input`, processes the samples, then resynthesizes as many samples as + /// possible into `output`. Returns the number of frames written to `output`. + /// + /// `processor` is a function to manipulate the spectrum before it is resynthesized. Its + /// arguments are respectively `num_channels`, `num_bins`, `analysis_output` and + /// `synthesis_input`. + /// + /// Samples are expected to be normalized to the range [-1, 1]. + /// + /// This method can be called multiple times on the same `PhaseVocoder`. + /// If this happens, in the analysis step, it will be assumed that the `input` is a continuation + /// of the `input` that was passed during the previous call. + /// + /// It is possible that not enough data is available yet to fill `output` completely. + /// In that case, only the first frames of `output` will be written to. + /// Conversely, if there is more data available than `output` can hold, the remaining + /// output is kept in the `PhaseVocoder` and can be retrieved with another call to + /// `process` when more input data is available. + /// + /// # Remark + /// The `synthesis_input` passed to the `processor_function` is currently initialised to empty + /// bins. This behaviour may change in a future release, so make sure that your implementation + /// does not rely on it. + pub fn process( + &mut self, + input: &[&[S]], + output: &mut [&mut [S]], + mut processor: F, + ) -> usize + where + S: Float + ToPrimitive + FromPrimitive, + F: FnMut(usize, usize, &[Vec], &mut [Vec]), + { + assert_eq!(input.len(), self.channels); + assert_eq!(output.len(), self.channels); + + // push samples to input queue + for chan in 0..input.len() { + for sample in input[chan].iter() { + self.in_buf[chan].push_back(sample.to_f64().unwrap()); + self.samples_waiting += 1; + } + } + + while self.samples_waiting >= 2 * self.frame_size * self.channels { + let frame_sizef = self.frame_size as f64; + let time_resf = self.time_res as f64; + let step_size = frame_sizef / time_resf; + + for _ in 0..self.time_res { + // Initialise the synthesis bins to empty bins. + // This may be removed in a future release. + for synthesis_channel in self.synthesis_in.iter_mut() { + for bin in synthesis_channel.iter_mut() { + *bin = Bin::empty(); + } + } + + // ANALYSIS + for chan in 0..self.channels { + // read in + for i in 0..self.frame_size { + self.fft_in[i] = c64::new(self.in_buf[chan][i] * self.window[i], 0.0); + } + + self.forward_fft.process_outofplace_with_scratch( + &mut self.fft_in, + &mut self.fft_out, + &mut self.fft_scratch, + ); + + for i in 0..self.frame_size { + let x = self.fft_out[i]; + let (amp, phase) = x.to_polar(); + let freq = self.phase_to_frequency(i, phase - self.last_phase[chan][i]); + self.last_phase[chan][i] = phase; + + self.analysis_out[chan][i] = Bin::new(freq, amp * 2.0); + } + } + + // PROCESSING + processor( + self.channels, + self.frame_size, + &self.analysis_out, + &mut self.synthesis_in, + ); + + // SYNTHESIS + for chan in 0..self.channels { + for i in 0..self.frame_size { + let amp = self.synthesis_in[chan][i].amp; + let freq = self.synthesis_in[chan][i].freq; + let phase = self.frequency_to_phase(freq); + self.sum_phase[chan][i] += phase; + let phase = self.sum_phase[chan][i]; + + self.fft_in[i] = c64::from_polar(amp, phase); + } + + self.backward_fft.process_outofplace_with_scratch( + &mut self.fft_in, + &mut self.fft_out, + &mut self.fft_scratch, + ); + + // accumulate + for i in 0..self.frame_size { + if i == self.output_accum[chan].len() { + self.output_accum[chan].push_back(0.0); + } + self.output_accum[chan][i] += + self.window[i] * self.fft_out[i].re / (frame_sizef * time_resf); + } + + // write out + for _ in 0..step_size as usize { + self.out_buf[chan].push_back(self.output_accum[chan].pop_front().unwrap()); + self.in_buf[chan].pop_front(); + } + } + } + self.samples_waiting -= self.frame_size * self.channels; + } + + // pop samples from output queue + let mut n_written = 0; + for chan in 0..self.channels { + for samp in 0..output[chan].len() { + output[chan][samp] = match self.out_buf[chan].pop_front() { + Some(x) => FromPrimitive::from_f64(x).unwrap(), + None => break, + }; + n_written += 1; + } + } + n_written / self.channels + } + + pub fn phase_to_frequency(&self, bin: usize, phase: f64) -> f64 { + let frame_sizef = self.frame_size as f64; + let freq_per_bin = self.sample_rate / frame_sizef; + let time_resf = self.time_res as f64; + let step_size = frame_sizef / time_resf; + let expect = 2.0 * PI * step_size / frame_sizef; + let mut tmp = phase; + tmp -= (bin as f64) * expect; + let mut qpd = (tmp / PI) as i32; + if qpd >= 0 { + qpd += qpd & 1; + } else { + qpd -= qpd & 1; + } + tmp -= PI * (qpd as f64); + tmp = time_resf * tmp / (2.0 * PI); + tmp = (bin as f64) * freq_per_bin + tmp * freq_per_bin; + tmp + } + + pub fn frequency_to_phase(&self, freq: f64) -> f64 { + let step_size = self.frame_size as f64 / self.time_res as f64; + 2.0 * PI * freq / self.sample_rate * step_size + } +} + +#[cfg(test)] +fn identity(channels: usize, bins: usize, input: &[Vec], output: &mut [Vec]) { + for i in 0..channels { + for j in 0..bins { + output[i][j] = input[i][j]; + } + } +} + +#[cfg(test)] +fn test_data_is_reconstructed(mut pvoc: PhaseVocoder, input_samples: &[f32]) { + let mut output_samples = vec![0.0; input_samples.len()]; + let frame_size = pvoc.num_bins(); + // Pre-padding, not collecting any output. + pvoc.process(&[&vec![0.0; frame_size]], &mut [&mut Vec::new()], identity); + // The data-itself, collecting some output that we will discard + let mut scratch = vec![0.0; frame_size]; + pvoc.process(&[&input_samples], &mut [&mut scratch], identity); + // Post-padding and collecting all output + pvoc.process( + &[&vec![0.0; frame_size]], + &mut [&mut output_samples], + identity, + ); + + assert_ulps_eq!(input_samples, output_samples.as_slice(), epsilon = 1e-2); +} + +#[test] +fn identity_transform_reconstructs_original_data_hat_function() { + let window_len = 256; + let pvoc = PhaseVocoder::new(1, 44100.0, window_len, window_len / 4); + let input_len = 1024; + let mut input_samples = vec![0.0; input_len]; + for i in 0..input_len { + if i < input_len / 2 { + input_samples[i] = (i as f32) / ((input_len / 2) as f32) + } else { + input_samples[i] = 2.0 - (i as f32) / ((input_len / 2) as f32); + } + } + + test_data_is_reconstructed(pvoc, input_samples.as_slice()); +} + +#[test] +fn identity_transform_reconstructs_original_data_random_data() { + use rand::rngs::SmallRng; + use rand::{Rng, SeedableRng}; + let mut rng = SmallRng::seed_from_u64(1); + let mut input_samples = [0.0; 16384]; + rng.fill(&mut input_samples[..]); + let pvoc = PhaseVocoder::new(1, 44100.0, 256, 256 / 4); + test_data_is_reconstructed(pvoc, &input_samples); +} + +#[test] +fn process_works_with_sample_res_equal_to_window() { + let mut pvoc = PhaseVocoder::new(1, 44100.0, 256, 256); + let input_len = 1024; + let input_samples = vec![0.0; input_len]; + let mut output_samples = vec![0.0; input_len]; + pvoc.process(&[&input_samples], &mut [&mut output_samples], identity); +} + +#[test] +fn process_works_when_reading_sample_by_sample() { + let mut pvoc = PhaseVocoder::new(1, 44100.0, 8, 2); + let input_len = 32; + let input_samples = vec![0.0; input_len]; + let mut output_samples = vec![0.0; input_len]; + for i in 0..input_samples.len() { + pvoc.process( + &[&input_samples[dbg!(i)..i + 1]], + &mut [&mut output_samples], + identity, + ); + } +} diff --git a/crates/quinoa/Cargo.toml b/crates/quinoa/Cargo.toml new file mode 100644 index 0000000..a5842b7 --- /dev/null +++ b/crates/quinoa/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "quinoa" +version = "0.1.0" +edition = "2018" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +baseplug = { git = "https://github.com/wrl/baseplug.git", rev = "9cec68f31cca9c0c7a1448379f75d92bbbc782a8" } +serde = "1.0.126" diff --git a/crates/quinoa/src/lib.rs b/crates/quinoa/src/lib.rs new file mode 100644 index 0000000..e377023 --- /dev/null +++ b/crates/quinoa/src/lib.rs @@ -0,0 +1,59 @@ +#![allow(incomplete_features)] +#![feature(generic_associated_types)] + +use baseplug::{Plugin, ProcessContext}; +use serde::{Deserialize, Serialize}; + +// TODO Everything + +baseplug::model! { + #[derive(Debug, Serialize, Deserialize)] + struct QuinoaModel { + #[model(min = -90.0, max = 3.0)] + #[parameter(name = "gain", unit = "Decibels", + gradient = "Power(0.15)")] + gain: f32 + } +} + +impl Default for QuinoaModel { + fn default() -> Self { + Self { + // "gain" is converted from dB to coefficient in the parameter handling code, + // so in the model here it's a coeff. + // -0dB == 1.0 + gain: 1.0, + } + } +} + +struct Quinoa; + +impl Plugin for Quinoa { + const NAME: &'static str = "basic gain plug"; + const PRODUCT: &'static str = "basic gain plug"; + const VENDOR: &'static str = "spicy plugins & co"; + + const INPUT_CHANNELS: usize = 2; + const OUTPUT_CHANNELS: usize = 2; + + type Model = QuinoaModel; + + #[inline] + fn new(_sample_rate: f32, _model: &QuinoaModel) -> Self { + Self + } + + #[inline] + fn process(&mut self, model: &QuinoaModelProcess, ctx: &mut ProcessContext) { + let input = &ctx.inputs[0].buffers; + let output = &mut ctx.outputs[0].buffers; + + for i in 0..ctx.nframes { + output[0][i] = input[0][i] * model.gain[i]; + output[1][i] = input[1][i] * model.gain[i]; + } + } +} + +baseplug::vst2!(Quinoa, b"tAnE"); diff --git a/crates/robotuna/Cargo.toml b/crates/robotuna/Cargo.toml new file mode 100644 index 0000000..78345a6 --- /dev/null +++ b/crates/robotuna/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "robotuna" +version = "0.1.0" +edition = "2018" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +baseplug = { git = "https://github.com/wrl/baseplug.git", rev = "9cec68f31cca9c0c7a1448379f75d92bbbc782a8" } +ringbuf = "0.2.5" +serde = "1.0.126" +log = "0.4.14" + +utils = { path = "../utils" } diff --git a/crates/robotuna/src/lib.rs b/crates/robotuna/src/lib.rs new file mode 100644 index 0000000..883d084 --- /dev/null +++ b/crates/robotuna/src/lib.rs @@ -0,0 +1,224 @@ +#![allow(incomplete_features)] +#![feature(generic_associated_types)] + +use std::time::Duration; + +use baseplug::{MidiReceiver, Plugin, ProcessContext}; +use ringbuf::{Consumer, Producer, RingBuffer}; +use serde::{Deserialize, Serialize}; + +use utils::buffers::*; +use utils::logs::*; + +mod tuna; + +const BUFFER_LEN: usize = 2 << 10; +const OVERLAP: usize = BUFFER_LEN / 3; + +baseplug::model! { + #[derive(Debug, Serialize, Deserialize)] + struct RoboTunaModel { + #[model(min = 0.0, max = 1.0)] + #[parameter(name = "manual/snap")] + manual: f32, + #[model(min = 0.1, max = 2.0)] + #[parameter(name = "frequency gain")] + freq_gain: f32, + } +} + +impl Default for RoboTunaModel { + fn default() -> Self { + Self { + manual: 1.0, + freq_gain: 1.0, + } + } +} + +struct RoboTuna { + /// Current midi note + note: Option, + + /// Current recording buffer + /// Input goes here + recording_buffer: Buffers, + /// The next recording buffer we'll use. It gets a bit of the end of the `recording_buffer` + /// so we can do overlap + next_recording_buffer: Buffers, + /// Current playing buffer + /// Output comes from here + playing_buffer: Buffers, + /// Next playing buffer we'll use + /// We start using it at the end of the previous buffer so we can overlap + next_playing_buffer: Buffers, + + /// Ringbuf producer so we can send audio chunks to the processing thread + recordings: Producer, + /// Ringbuf consumer so we can receive processed buffers from the processing threads + processed: Consumer>, + + /// Contains some empty buffers so we can reuse them instead of doing allocations + /// Buffers here are not actually empty, since we don't spend any time clearing them + /// But since they will be overwritten, this isn't an issue + empty_buffers: Vec>, +} + +// LMAO let's go, i think this works + +impl Plugin for RoboTuna { + const NAME: &'static str = "robotuna"; + const PRODUCT: &'static str = "robotuna"; + const VENDOR: &'static str = "unnieversal"; + + const INPUT_CHANNELS: usize = 2; + const OUTPUT_CHANNELS: usize = 2; + + type Model = RoboTunaModel; + + #[inline] + fn new(_sample_rate: f32, _model: &RoboTunaModel) -> Self { + setup_logging("robotuna.log"); + + let (recordings, recording_rx) = RingBuffer::::new(10).split(); + let (processed_tx, processed) = RingBuffer::>::new(10).split(); + + // Spawn analysis thread + std::thread::spawn(move || { + tuna::tuna(recording_rx, processed_tx); + }); + + // keep some empty buffer around so we can swap them + let mut empty_buffers = Vec::with_capacity(50); + const BUF: Buffers = Buffers::new(); + empty_buffers.append(&mut vec![BUF; 30]); + + log::info!("finished init"); + + Self { + note: None, + recording_buffer: Buffers::new(), + next_recording_buffer: Buffers::new(), + playing_buffer: Buffers::new(), + next_playing_buffer: Buffers::new(), + recordings, + processed, + empty_buffers, + } + } + + #[inline] + fn process(&mut self, model: &RoboTunaModelProcess, ctx: &mut ProcessContext) { + let input = &ctx.inputs[0].buffers; + let output = &mut ctx.outputs[0].buffers; + + for i in 0..ctx.nframes { + // Record + + // Add to main buffer + let full = self + .recording_buffer + .write_advance(input[0][i], input[1][i]); + // If we're in overlap section, also add to next buffer + if self.recording_buffer.idx > BUFFER_LEN - OVERLAP { + self.next_recording_buffer + .write_advance(input[0][i], input[1][i]); + } + // If we finish the buffer, switch them + if full { + // get the empty buffer from unused buffer list + let mut buf = self + .empty_buffers + .pop() + .expect("should have an empty buffer"); + buf.reset(); + std::mem::swap(&mut buf, &mut self.recording_buffer); + buf.reset(); + + std::mem::swap(&mut self.next_recording_buffer, &mut self.recording_buffer); + + let _ = self.recordings.push(tuna::ProcessChunk { + buffers: buf, + sample_rate: ctx.sample_rate as u32, + note: self.note, + manual: model.manual[i] <= 0.5, + freq_gain: model.freq_gain[i], + }); + } + + // Play + + // Get values from main buffer + let (mut l, mut r, full) = self.playing_buffer.read_advance(); + // If we're in overlap section, also play from next buffer + if self.playing_buffer.idx > BUFFER_LEN - OVERLAP { + let (l1, r1, _) = self.next_playing_buffer.read_advance(); + + // How much into overlap we are, from 0 to 1 + let overlap = + (OVERLAP - (BUFFER_LEN - self.playing_buffer.idx)) as f32 / OVERLAP as f32; + + // Linearly crossfade + // lineal crossfade works well for two waves that are highly correlated + l *= 1. - overlap; + r *= 1. - overlap; + l += overlap * l1; + r += overlap * r1; + } + // If we finish the buffer, switch them + if full { + // We try to switch like with the recording buffer, but since there might not be a processed + // buffer yet, we do it in a loop and retry every 1 millisecond + // After 10 iterations we give up. Since we didn't swap the buffer, we're gonna play the last one + // again. This isn't ideal, but it's better than silence ig (it might not be, idk) + + // The 10 iterations is arbitrary, as is the 1 millisecond wait time + + for _ in 0..10 { + if let Some(mut buf) = self.processed.pop() { + buf.reset(); + std::mem::swap(&mut buf, &mut self.playing_buffer); + buf.reset(); + + std::mem::swap(&mut self.next_playing_buffer, &mut self.playing_buffer); + + // Stick buf in unused buffer list + self.empty_buffers.push(buf); + + // Exit loop + break; + } else { + log::info!("didn't have a processed buffer to swap to, retrying"); + } + std::thread::sleep(Duration::from_millis(1)); + } + } + + output[0][i] = l; + output[1][i] = r; + } + } +} +impl MidiReceiver for RoboTuna { + fn midi_input(&mut self, _model: &RoboTunaModelProcess, data: [u8; 3]) { + match data[0] { + // note on + 0x90 => { + self.note = Some(data[1]); + } + // note off + 0x80 => { + // only set note to None if it's the same one we currently have + if let Some(n) = self.note { + if n == data[1] { + self.note = None; + } + } + } + + _ => (), + } + } +} + +baseplug::vst2!(RoboTuna, b"tuna"); diff --git a/crates/robotuna/src/tuna.rs b/crates/robotuna/src/tuna.rs new file mode 100644 index 0000000..93e8bb0 --- /dev/null +++ b/crates/robotuna/src/tuna.rs @@ -0,0 +1,131 @@ +use ringbuf::{Consumer, Producer}; + +use utils::buffers::*; +use utils::pitch::*; + +use crate::BUFFER_LEN; + +type SampleRate = u32; + +pub struct ProcessChunk { + pub(crate) buffers: Buffers, + pub(crate) sample_rate: SampleRate, + /// Midi note number to shift frequency to + pub(crate) note: Option, + /// If true, will listen to note + /// If false, will snap to closest note + pub(crate) manual: bool, + /// Extra frequency shifting to do + pub(crate) freq_gain: f32, +} + +pub fn tuna(mut inputs: Consumer, mut outputs: Producer>) { + // Keep track of last detected note, and use it in case of not detecting a new one + let mut prev_l_freq: Option = None; + let mut prev_r_freq: Option = None; + + let mut detector_l = generate_pitch_detector(BUFFER_LEN); + let mut detector_r = generate_pitch_detector(BUFFER_LEN); + + // Sample rates get overriden on first iteration, so we just set 48k + let mut shifter_l = generate_vocoder(48000); + let mut shifter_r = generate_vocoder(48000); + + loop { + if let Some(ProcessChunk { + buffers: recording, + sample_rate, + note, + manual, + freq_gain, + }) = inputs.pop() + { + log::info!("got a buffer to process"); + + // If we're on manual mode, and we don't have a note, just pass through + if manual && note.is_none() { + let _ = outputs.push(recording); + continue; + } + + // TODO It does weird stereo things + + // Update sample rate + shifter_l.set_sample_rate(sample_rate as f64); + shifter_r.set_sample_rate(sample_rate as f64); + + // Left + let l = recording.l; + // Try detecting note + let l = if let Some((actual, _clarity)) = pitch_detect(&mut detector_l, &l, sample_rate) + { + log::info!("L: detected actual pitch: {}", actual); + + // If note is found, set it as previous, and pitch shift + prev_l_freq = Some(actual); + + // If it's on manual mode, convert midi note to pitch + // If not, snap to closest frequency + let expected = if manual { + midi_note_to_pitch(note.expect("We wouldn't be here if note is None")) + } else { + closest_note_freq(actual) + }; + + // Perform pitch shift + // `expected / actual` is how much to shift the pitch + // If the actual pitch is 400, and expected is 800, we want to shift by 2 + pitch_shift(&mut shifter_l, &l, freq_gain * expected / actual) + } else if let Some(actual) = prev_l_freq { + log::info!("L: reusing actual pitch: {}", actual); + + let expected = if manual { + midi_note_to_pitch(note.expect("We wouldn't be here if note is None")) + } else { + closest_note_freq(actual) + }; + + pitch_shift(&mut shifter_l, &l, freq_gain * expected / actual) + } else { + log::info!("L: no actual pitch"); + + // If there's nothing, leave it as is + l + }; + + // Same thing for the right side + let r = recording.r; + let r = if let Some((actual, _clarity)) = pitch_detect(&mut detector_r, &r, sample_rate) + { + log::info!("R: detected actual pitch: {}", actual); + + prev_r_freq = Some(actual); + + let expected = if manual { + midi_note_to_pitch(note.expect("We wouldn't be here if note is None")) + } else { + closest_note_freq(actual) + }; + + pitch_shift(&mut shifter_r, &l, freq_gain * expected / actual) + } else if let Some(actual) = prev_r_freq { + log::info!("R: reusing actual pitch: {}", actual); + + let expected = if manual { + midi_note_to_pitch(note.expect("We wouldn't be here if note is None")) + } else { + closest_note_freq(actual) + }; + + pitch_shift(&mut shifter_r, &l, freq_gain * expected / actual) + } else { + log::info!("R: no actual pitch"); + + r + }; + + let _ = outputs.push(Buffers::from(l, r)); + log::info!("finished processing a buffer"); + } + } +} diff --git a/crates/sosten/Cargo.toml b/crates/sosten/Cargo.toml new file mode 100644 index 0000000..61b85df --- /dev/null +++ b/crates/sosten/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "sosten" +version = "0.1.0" +edition = "2018" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +baseplug = { git = "https://github.com/wrl/baseplug.git", rev = "9cec68f31cca9c0c7a1448379f75d92bbbc782a8" } +serde = "1.0.126" diff --git a/crates/sosten/src/delay.rs b/crates/sosten/src/delay.rs new file mode 100644 index 0000000..7c66eaf --- /dev/null +++ b/crates/sosten/src/delay.rs @@ -0,0 +1,30 @@ +pub struct DelayLine { + buffer: [f32; LEN], + index: usize, +} + +impl DelayLine { + pub fn new() -> Self { + Self { + buffer: [0.0; LEN], + index: 0, + } + } + + pub fn read_slice(&self, slice: &mut [f32]) { + // Copy values in order + for i in 0..LEN { + slice[i] = self.buffer[(self.index + i - LEN) % LEN]; + } + } + + pub fn write_and_advance(&mut self, value: f32) { + self.buffer[self.index] = value; + + if self.index == LEN - 1 { + self.index = 0; + } else { + self.index += 1; + } + } +} diff --git a/crates/sosten/src/lib.rs b/crates/sosten/src/lib.rs new file mode 100644 index 0000000..094d61c --- /dev/null +++ b/crates/sosten/src/lib.rs @@ -0,0 +1,126 @@ +#![allow(incomplete_features)] +#![feature(generic_associated_types)] + +use baseplug::{Plugin, ProcessContext}; +use serde::{Deserialize, Serialize}; + +mod delay; +use delay::DelayLine; + +// If you change this remember to change the max on the model +const LEN: usize = 48000; + +baseplug::model! { + #[derive(Debug, Serialize, Deserialize)] + struct SostenModel { + #[model(min = 10.0, max = 48000.0)] + #[parameter(name = "length")] + length: f32, + #[model(min = 0.0, max = 1.0)] + #[parameter(name = "mix")] + mix: f32, + #[model(min = 0.0, max = 1.0)] + #[parameter(name = "enable")] + enable: f32, + } +} + +impl Default for SostenModel { + fn default() -> Self { + Self { + length: 1000.0, + mix: 1.0, + enable: 0.0, + } + } +} + +struct Sosten { + delay_l: DelayLine, + delay_r: DelayLine, + buffer_l: [f32; LEN], + buffer_r: [f32; LEN], + + playing: bool, + idx: usize, +} + +impl Plugin for Sosten { + const NAME: &'static str = "sosten"; + const PRODUCT: &'static str = "sosten"; + const VENDOR: &'static str = "unnieversal"; + + const INPUT_CHANNELS: usize = 2; + const OUTPUT_CHANNELS: usize = 2; + + type Model = SostenModel; + + #[inline] + fn new(_sample_rate: f32, _model: &SostenModel) -> Self { + Self { + delay_l: DelayLine::::new(), + delay_r: DelayLine::::new(), + buffer_l: [0.; LEN], + buffer_r: [0.; LEN], + + playing: false, + idx: 0, + } + } + + #[inline] + fn process(&mut self, model: &SostenModelProcess, ctx: &mut ProcessContext) { + let input = &ctx.inputs[0].buffers; + let output = &mut ctx.outputs[0].buffers; + + for i in 0..ctx.nframes { + // Update delays + self.delay_l.write_and_advance(input[0][i]); + self.delay_r.write_and_advance(input[1][i]); + + // Toggle playing according to `enable` + if model.enable[i] >= 0.5 { + // If it wasn't playing before this, reload buffer + if !self.playing { + self.delay_l.read_slice(&mut self.buffer_l); + self.delay_r.read_slice(&mut self.buffer_r); + self.idx = 0; + + self.playing = true; + } + } else { + self.playing = false; + } + + // Play the repeating part + if self.playing { + // Length of section to play + let len = model.length[i].trunc() as usize; + + // Pass through input + let mix_inv = 1. - model.mix[i]; + output[0][i] = mix_inv * input[0][i]; + output[1][i] = mix_inv * input[1][i]; + + // If len has changed, idx may have not, so we do the min so we don't go out of bounds + let idx = self.idx.min(len - 1); + + // Play from Buffer + output[0][i] += model.mix[i] * self.buffer_l[(LEN - len) + idx]; + output[1][i] += model.mix[i] * self.buffer_r[(LEN - len) + idx]; + + // Loop index after we finish playing a section + self.idx += 1; + if self.idx >= len { + self.idx = 0; + } + } else { + // If it's not on a repeat section, pass all the audio fully + output[0][i] = input[0][i]; + output[1][i] = input[1][i]; + } + } + } +} + +baseplug::vst2!(Sosten, b"sost"); diff --git a/crates/threebandeq/Cargo.toml b/crates/threebandeq/Cargo.toml new file mode 100644 index 0000000..cc28ad5 --- /dev/null +++ b/crates/threebandeq/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "threebandeq" +version = "0.1.0" +edition = "2018" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +baseplug = { git = "https://github.com/wrl/baseplug.git", rev = "9cec68f31cca9c0c7a1448379f75d92bbbc782a8" } +serde = "1.0.126" diff --git a/crates/threebandeq/src/lib.rs b/crates/threebandeq/src/lib.rs new file mode 100644 index 0000000..85fa9ea --- /dev/null +++ b/crates/threebandeq/src/lib.rs @@ -0,0 +1,57 @@ +#![allow(incomplete_features)] +#![feature(generic_associated_types)] + +use baseplug::{Plugin, ProcessContext}; +use serde::{Deserialize, Serialize}; + +baseplug::model! { + #[derive(Debug, Serialize, Deserialize)] + struct ThreeBandEqModel { + #[model(min = -90.0, max = 3.0)] + #[parameter(name = "gain", unit = "Decibels", + gradient = "Power(0.15)")] + gain: f32 + } +} + +impl Default for ThreeBandEqModel { + fn default() -> Self { + Self { + // "gain" is converted from dB to coefficient in the parameter handling code, + // so in the model here it's a coeff. + // -0dB == 1.0 + gain: 1.0, + } + } +} + +struct ThreeBandEq; + +impl Plugin for ThreeBandEq { + const NAME: &'static str = "basic gain"; + const PRODUCT: &'static str = "basic gain"; + const VENDOR: &'static str = "unnieversal"; + + const INPUT_CHANNELS: usize = 2; + const OUTPUT_CHANNELS: usize = 2; + + type Model = ThreeBandEqModel; + + #[inline] + fn new(_sample_rate: f32, _model: &ThreeBandEqModel) -> Self { + Self + } + + #[inline] + fn process(&mut self, model: &ThreeBandEqModelProcess, ctx: &mut ProcessContext) { + let input = &ctx.inputs[0].buffers; + let output = &mut ctx.outputs[0].buffers; + + for i in 0..ctx.nframes { + output[0][i] = input[0][i] * model.gain[i]; + output[1][i] = input[1][i] * model.gain[i]; + } + } +} + +baseplug::vst2!(ThreeBandEq, b"tAnE"); diff --git a/crates/utils/Cargo.toml b/crates/utils/Cargo.toml new file mode 100644 index 0000000..25f5841 --- /dev/null +++ b/crates/utils/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "utils" +version = "0.1.0" +edition = "2018" + +[dependencies] +pitch-detection = { git = "https://github.com/alesgenova/pitch-detection", rev = "774d8ab2e6cdf8ff22a4c9b2f0a4a900b971c635" } +simplelog = "0.10.0" +log = "0.4.14" +log-panics = "2.0.0" +dirs = "3.0.2" +pvoc = { path = "../pvoc-rs" } diff --git a/crates/utils/src/buffers.rs b/crates/utils/src/buffers.rs new file mode 100644 index 0000000..925e942 --- /dev/null +++ b/crates/utils/src/buffers.rs @@ -0,0 +1,53 @@ +#[derive(Clone)] +pub struct Buffers { + pub r: [f32; LEN], + pub l: [f32; LEN], + pub idx: usize, +} +// unsafe impl Sync for Buffers {} +// unsafe impl Send for Buffers {} + +impl Buffers { + pub const fn new() -> Self { + Self { + l: [0.; LEN], + r: [0.; LEN], + idx: 0, + } + } + + pub const fn from(l: [f32; LEN], r: [f32; LEN]) -> Self { + Self { l, r, idx: 0 } + } + + /// Writes to buffer, advances idx, returns true if buffer is full + pub fn write_advance(&mut self, l: f32, r: f32) -> bool { + self.l[self.idx] = l; + self.r[self.idx] = r; + + self.idx += 1; + if self.idx >= LEN { + self.idx = 0; + true + } else { + false + } + } + + /// Reads buffer, advances idx, returns true if buffer is full + pub fn read_advance(&mut self) -> (f32, f32, bool) { + (self.l[self.idx], self.r[self.idx], { + self.idx += 1; + if self.idx >= LEN { + self.idx = 0; + true + } else { + false + } + }) + } + + pub fn reset(&mut self) { + self.idx = 0; + } +} diff --git a/crates/utils/src/lib.rs b/crates/utils/src/lib.rs new file mode 100644 index 0000000..c5ccea0 --- /dev/null +++ b/crates/utils/src/lib.rs @@ -0,0 +1,3 @@ +pub mod buffers; +pub mod logs; +pub mod pitch; diff --git a/crates/utils/src/logs.rs b/crates/utils/src/logs.rs new file mode 100644 index 0000000..52fb0b9 --- /dev/null +++ b/crates/utils/src/logs.rs @@ -0,0 +1,17 @@ +pub fn setup_logging(path: &str) { + let log_folder = ::dirs::home_dir().unwrap().join("tmp"); + + let _ = ::std::fs::create_dir(log_folder.clone()); + + let log_file = ::std::fs::File::create(log_folder.join(path)).unwrap(); + + let log_config = ::simplelog::ConfigBuilder::new() + .set_time_to_local(true) + .build(); + + let _ = ::simplelog::WriteLogger::init(simplelog::LevelFilter::Info, log_config, log_file); + + ::log_panics::init(); + + ::log::info!("init"); +} diff --git a/crates/utils/src/pitch.rs b/crates/utils/src/pitch.rs new file mode 100644 index 0000000..779934e --- /dev/null +++ b/crates/utils/src/pitch.rs @@ -0,0 +1,77 @@ +use pitch_detection::detector::yin::YINDetector; +use pitch_detection::detector::PitchDetector; + +pub fn generate_pitch_detector(size: usize) -> impl PitchDetector { + let padding = size / 2; + + YINDetector::new(size, padding) +} + +/// Returns an option with (Frequency, Clarity) +pub fn pitch_detect( + detector: &mut dyn PitchDetector, + signal: &[f32], + sample_rate: u32, +) -> Option<(f32, f32)> { + const POWER_THRESHOLD: f32 = 0.15; + const CLARITY_THRESHOLD: f32 = 0.5; + + let pitch = detector.get_pitch( + &signal, + sample_rate as usize, + POWER_THRESHOLD, + CLARITY_THRESHOLD, + ); + + pitch.map(|a| (a.frequency, a.clarity)) +} + +pub fn generate_vocoder(sample_rate: u32) -> PhaseVocoder { + PhaseVocoder::new(1, sample_rate as f64, 256, 4) +} + +// From https://github.com/nwoeanhinnogaehr/pvoc-plugins/blob/master/src/plugins/pitchshifter.rs +use pvoc::{Bin, PhaseVocoder}; +pub fn pitch_shift( + pvoc: &mut PhaseVocoder, + input: &[f32], + shift: f32, +) -> [f32; LEN] { + let shift = shift as f64; + let mut output = [0.0; LEN]; + + pvoc.process( + &[&input], + &mut [&mut output], + |channels: usize, bins: usize, input: &[Vec], output: &mut [Vec]| { + for i in 0..channels { + for j in 0..bins / 2 { + let index = ((j as f64) * shift) as usize; + if index < bins / 2 { + output[i][index].freq = input[i][j].freq * shift; + output[i][index].amp += input[i][j].amp; + } + } + } + }, + ); + + output +} + +/// Returns closest midi note to `pitch` +pub fn pitch_to_midi_note(pitch: f32) -> u8 { + // With the frequency, check the closest note + let note = 69 + (12. * (pitch / 440.).log2()).round() as i16; + note.clamp(0, 127) as u8 +} + +/// Returns a midi note's pitch +pub fn midi_note_to_pitch(note: u8) -> f32 { + 440.0f32 * 2.0f32.powf((note as f32 - 69.) / 12.) +} + +/// Returns the closest note frequency +pub fn closest_note_freq(freq: f32) -> f32 { + midi_note_to_pitch(pitch_to_midi_note(freq)) +} diff --git a/crates/xlowpass/Cargo.toml b/crates/xlowpass/Cargo.toml new file mode 100644 index 0000000..98cfe4e --- /dev/null +++ b/crates/xlowpass/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "xlowpass" +version = "0.1.0" +edition = "2018" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +baseplug = { git = "https://github.com/wrl/baseplug.git", rev = "9cec68f31cca9c0c7a1448379f75d92bbbc782a8" } +libc = "0.2.97" +serde = "1.0.126" diff --git a/crates/xlowpass/src/lib.rs b/crates/xlowpass/src/lib.rs new file mode 100644 index 0000000..432f555 --- /dev/null +++ b/crates/xlowpass/src/lib.rs @@ -0,0 +1,315 @@ +#![allow(incomplete_features)] +#![feature(generic_associated_types)] + +use baseplug::{Plugin, ProcessContext}; +use serde::{Deserialize, Serialize}; +use std::f32::consts::PI; + +use std::f32::consts::{FRAC_1_SQRT_2, FRAC_PI_2}; + +const EPS: f32 = 1.18e-37; + +baseplug::model! { + #[derive(Debug, Serialize, Deserialize)] + struct XLowpassModel { + #[model(min = 0.0, max = 1.0)] + #[parameter(name = "gain")] + gain: f32, + #[model(min = 0.5, max = 1.0)] + #[parameter(name = "freq")] + freq: f32, + #[model(min = 0.0, max = 0.5)] + #[parameter(name = "nuke")] + nuke: f32, + } +} + +impl Default for XLowpassModel { + fn default() -> Self { + Self { + gain: 0.5, + freq: 1.0, + nuke: 0.0, + } + } +} + +struct XLowpass { + biquad: [f32; 15], + biquad_a: [f32; 15], + biquad_b: [f32; 15], + biquad_c: [f32; 15], + biquad_d: [f32; 15], + + fpd_l: u32, + fpd_r: u32, +} + +impl Plugin for XLowpass { + const NAME: &'static str = "XLowpass"; + const PRODUCT: &'static str = "XLowpass"; + const VENDOR: &'static str = "unnieversal"; + + const INPUT_CHANNELS: usize = 2; + const OUTPUT_CHANNELS: usize = 2; + + type Model = XLowpassModel; + + #[inline] + fn new(_sample_rate: f32, _model: &XLowpassModel) -> Self { + Self { + biquad: [0.0; 15], + biquad_a: [0.0; 15], + biquad_b: [0.0; 15], + biquad_c: [0.0; 15], + biquad_d: [0.0; 15], + fpd_l: 8638612, + fpd_r: 5638657, + } + } + + #[inline] + fn process(&mut self, model: &XLowpassModelProcess, ctx: &mut ProcessContext) { + let input = &ctx.inputs[0].buffers; + let output = &mut ctx.outputs[0].buffers; + + for i in 0..ctx.nframes { + let gain = (model.gain[i] + 0.5).powi(4); + + self.biquad_a[0] = (model.freq[i].powi(2) * 20000.0) / ctx.sample_rate; + if self.biquad_a[0] < 0.001 { + self.biquad_a[0] = 0.001; + } + + let compensation = self.biquad_a[0].sqrt() * 6.4; + let clip_factor = 1.0 + (self.biquad_a[0].powi(2) * model.nuke[i] * 32.0); + + let k = (PI * self.biquad_a[0]).tan(); + let norm = 1.0 / (1.0 + k / FRAC_1_SQRT_2 + k * k); + self.biquad_a[2] = k * k * norm; + self.biquad_a[3] = 2.0 * self.biquad_a[2]; + self.biquad_a[4] = self.biquad_a[2]; + self.biquad_a[5] = 2.0 * (k * k - 1.0) * norm; + self.biquad_a[6] = (1.0 - k / FRAC_1_SQRT_2 + k * k) * norm; + + for j in 0..7 { + self.biquad[j] = self.biquad_a[j]; + self.biquad_b[j] = self.biquad_a[j]; + self.biquad_c[j] = self.biquad_a[j]; + self.biquad_d[j] = self.biquad_a[j]; + } + + let mut a_wet = 1.0; + let mut b_wet = 1.0; + let mut c_wet = 1.0; + let mut d_wet = model.nuke[i] * 4.0; + + //four-stage wet/dry control using progressive stages that bypass when not engaged + if d_wet < 1.0 { + a_wet = d_wet; + b_wet = 0.0; + c_wet = 0.0; + d_wet = 0.0; + } else if d_wet < 2.0 { + b_wet = d_wet - 1.0; + c_wet = 0.0; + d_wet = 0.0; + } else if d_wet < 3.0 { + c_wet = d_wet - 2.0; + d_wet = 0.0; + } else { + d_wet -= 3.0; + } + //this is one way to make a little set of dry/wet stages that are successively added to the + //output as the control is turned up. Each one independently goes from 0-1 and stays at 1 + //beyond that point: this is a way to progressively add a 'black box' sound processing + //which lets you fall through to simpler processing at lower settings. + + // Begin processing + + let mut in_l = input[0][i]; + let mut in_r = input[1][i]; + if in_l.abs() < EPS { + in_l = self.fpd_l as f32 * EPS; + } + if in_r.abs() < EPS { + in_r = self.fpd_r as f32 * EPS; + } + + in_l *= gain; + in_r *= gain; + + let mut nuke_level_l = in_l; + let mut nuke_level_r = in_r; + + self.set_initial(&mut in_l, &mut nuke_level_l, clip_factor, compensation); + self.set_initial(&mut in_r, &mut nuke_level_r, clip_factor, compensation); + + if a_wet > 0. { + self.calc( + &mut in_l, + Biquad::A, + &mut &mut nuke_level_l, + clip_factor, + compensation, + a_wet, + ); + self.calc( + &mut in_r, + Biquad::A, + &mut &mut nuke_level_r, + clip_factor, + compensation, + a_wet, + ); + } + if b_wet > 0. { + self.calc( + &mut in_l, + Biquad::B, + &mut &mut nuke_level_l, + clip_factor, + compensation, + b_wet, + ); + self.calc( + &mut in_r, + Biquad::B, + &mut &mut nuke_level_r, + clip_factor, + compensation, + b_wet, + ); + } + if c_wet > 0. { + self.calc( + &mut in_l, + Biquad::C, + &mut &mut nuke_level_l, + clip_factor, + compensation, + c_wet, + ); + self.calc( + &mut in_r, + Biquad::C, + &mut &mut nuke_level_r, + clip_factor, + compensation, + c_wet, + ); + } + if d_wet > 0. { + self.calc( + &mut in_l, + Biquad::D, + &mut &mut nuke_level_l, + clip_factor, + compensation, + d_wet, + ); + self.calc( + &mut in_r, + Biquad::D, + &mut &mut nuke_level_r, + clip_factor, + compensation, + d_wet, + ); + } + + //begin 32 bit stereo floating point dither + let expon = frexp(in_l); + self.fpd_l ^= self.fpd_l << 13; + self.fpd_l ^= self.fpd_l >> 17; + self.fpd_l ^= self.fpd_l << 5; + in_l += (self.fpd_l as f32 - 0x7fffffff_i32 as f32) * 5.5e-36 * 2f32.powi(expon + 62); + let expon = frexp(in_r); + self.fpd_r ^= self.fpd_r << 13; + self.fpd_r ^= self.fpd_r >> 17; + self.fpd_r ^= self.fpd_r << 5; + in_l += (self.fpd_r as f32 - 0x7fffffff_i32 as f32) * 5.5e-36 * 2f32.powi(expon + 62); + //end 32 bit stereo floating point dither + + output[0][i] = in_l; + output[1][i] = in_r; + } + } +} + +fn frexp(val: f32) -> i32 { + let mut a = 0; + unsafe { + frexpf(val, &mut a as *mut i32); + a + } +} + +extern "C" { + fn frexpf(_: libc::c_float, _: *mut libc::c_int) -> libc::c_float; +} + +enum Biquad { + A, + B, + C, + D, +} +impl XLowpass { + fn get_biquad(&mut self, b: Biquad) -> &mut [f32] { + match b { + Biquad::A => &mut self.biquad_a, + Biquad::B => &mut self.biquad_b, + Biquad::C => &mut self.biquad_c, + Biquad::D => &mut self.biquad_d, + } + } + fn calc( + &mut self, + in_l: &mut f32, + b: Biquad, + nuke_level_l: &mut f32, + clip_factor: f32, + compensation: f32, + a_wet: f32, + ) { + let biquad = self.get_biquad(b); + let mut out_sample = biquad[2] * *in_l + biquad[3] * biquad[7] + biquad[4] * biquad[8] + - biquad[5] * biquad[9] + - biquad[6] * biquad[10]; + biquad[8] = biquad[7]; + biquad[7] = *in_l; + biquad[10] = biquad[9]; + out_sample *= clip_factor; + out_sample = out_sample.clamp(-FRAC_PI_2, FRAC_PI_2); + self.biquad[9] = out_sample.sin(); + *in_l = out_sample / compensation; + *nuke_level_l = *in_l; + *in_l = (*in_l * a_wet) + (*nuke_level_l * (1.0 - a_wet)); + *nuke_level_l = *in_l; + } + + fn set_initial( + &mut self, + in_l: &mut f32, + nuke_level_l: &mut f32, + clip_factor: f32, + compensation: f32, + ) { + let mut out_sample = self.biquad[2] * *in_l + + self.biquad[3] * self.biquad[7] + + self.biquad[4] * self.biquad[8] + - self.biquad[5] * self.biquad[9] + - self.biquad[6] * self.biquad[10]; + self.biquad[8] = self.biquad[7]; + self.biquad[7] = *in_l; + self.biquad[10] = self.biquad[9]; + out_sample *= clip_factor; + out_sample = out_sample.clamp(-FRAC_PI_2, FRAC_PI_2); + self.biquad[9] = out_sample.sin(); + *in_l = out_sample / compensation; + *nuke_level_l = *in_l; + } +} + +baseplug::vst2!(XLowpass, b"xlow"); diff --git a/macos.sh b/macos.sh new file mode 100755 index 0000000..a601719 --- /dev/null +++ b/macos.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +# Make sure we have the arguments we need +if [[ -z $1 ]]; then + echo "Builds, bundles and copies to /Library/Audio/Plug-Ins/VST a package" + echo "Example:" + echo -e "\t$0 packagename" +else + cargo b --package "$1" --release + echo "Built" + package="$1" + upPackage="$(tr '[:lower:]' '[:upper:]' <<< ${package:0:1})${package:1}" + ./osx_vst_bundler.sh "$upPackage" "target/release/lib$1.dylib" + echo "Bundled" + sudo cp -r "build/$upPackage.vst" /Library/Audio/Plug-Ins/VST + echo "Copied" +fi diff --git a/osx_vst_bundler.sh b/osx_vst_bundler.sh new file mode 100755 index 0000000..fd60daa --- /dev/null +++ b/osx_vst_bundler.sh @@ -0,0 +1,61 @@ +#!/bin/bash + +# Make sure we have the arguments we need +if [[ -z $1 || -z $2 ]]; then + echo "Generates a macOS bundle from a compiled dylib file" + echo "Example:" + echo -e "\t$0 Plugin target/release/plugin.dylib" + echo -e "\tCreates a Plugin.vst bundle" +else + # Make the bundle folder + mkdir -p "build/$1.vst/Contents/MacOS" + + # Create the PkgInfo + echo "BNDL????" > "build/$1.vst/Contents/PkgInfo" + + #build the Info.Plist + echo " + + + + CFBundleDevelopmentRegion + English + + CFBundleExecutable + $1 + + CFBundleGetInfoString + vst + + CFBundleIconFile + + + CFBundleIdentifier + com.unnieversal.$1 + + CFBundleInfoDictionaryVersion + 6.0 + + CFBundleName + $1 + + CFBundlePackageType + BNDL + + CFBundleVersion + 1.0 + + CFBundleSignature + $((RANDOM % 9999)) + + CSResourcesFileMapped + + + +" > "build/$1.vst/Contents/Info.plist" + + # move the provided library to the correct location + cp "$2" "build/$1.vst/Contents/MacOS/$1" + + echo "Created bundle build/$1.vst" +fi diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..31e1bb2 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,7 @@ +#[cfg(test)] +mod tests { + #[test] + fn it_works() { + assert_eq!(2 + 2, 4); + } +}