Skip to content

Reworked AudioBuffer, removed memory allocations in the audio thread,… #32

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,6 @@ num-traits = "0.1"
libc = "0.2"
bitflags = "0.8"
libloading = "0.4"

[features]
nightly = []
4 changes: 2 additions & 2 deletions examples/dimension_expander/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ version = "0.1.0"
authors = ["Marko Mijalkovic <[email protected]>"]

[dependencies]
vst2 = { git = "https://github.com/overdrivenpotato/rust-vst2" }
vst2 = { path = "../.." }
time = "0.1"

[lib]
name = "dimension_expander"
crate-type = ["dylib"]
crate-type = ["cdylib"]
13 changes: 5 additions & 8 deletions examples/dimension_expander/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,7 @@ impl Plugin for DimensionExpander {
_ => (),
}
}

fn process(&mut self, buffer: AudioBuffer<f32>) {
fn process(&mut self, buffer: &mut AudioBuffer<f32>) {
let (inputs, mut outputs) = buffer.split();

// Assume 2 channels
Expand All @@ -149,14 +148,12 @@ impl Plugin for DimensionExpander {
}

// Iterate over inputs as (&f32, &f32)
let stereo_in = match inputs.split_at(1) {
(l, r) => l[0].iter().zip(r[0].iter())
};
let (l, r) = inputs.split_at(1);
let stereo_in = l[0].iter().zip(r[0].iter());

// Iterate over outputs as (&mut f32, &mut f32)
let stereo_out = match outputs.split_at_mut(1) {
(l, r) => l[0].iter_mut().zip(r[0].iter_mut())
};
let (mut l, mut r) = outputs.split_at_mut(1);
let stereo_out = l[0].iter_mut().zip(r[0].iter_mut());

// Zip and process
for ((left_in, right_in), (left_out, right_out)) in stereo_in.zip(stereo_out) {
Expand Down
2 changes: 1 addition & 1 deletion examples/sine_synth/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ version = "0.1.0"
authors = ["Rob Saunders <[email protected]>"]

[dependencies]
vst2 = { git = "https://github.com/overdrivenpotato/rust-vst2" }
vst2 = { path = "../.." }

[lib]
name = "sine_synth"
Expand Down
38 changes: 22 additions & 16 deletions examples/sine_synth/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@
use vst2::buffer::AudioBuffer;
use vst2::plugin::{Category, Plugin, Info, CanDo};
use vst2::event::Event;
use vst2::api::Supported;
use vst2::api::{Supported, Events};

use std::f64::consts::PI;

/// Convert the midi note into the equivalent frequency.
/// Convert the midi note's pitch into the equivalent frequency.
///
/// This function assumes A4 is 440hz.
fn midi_note_to_hz(note: u8) -> f64 {
const A4: f64 = 440.0;
fn midi_pitch_to_freq(pitch: u8) -> f64 {
const A4_PITCH: u8 = 69;
const A4_FREQ: f64 = 440.0;

(A4 / 32.0) * ((note as f64 - 9.0) / 12.0).exp2()
(((pitch - A4_PITCH) as f64) / 12.).exp2() * A4_FREQ
}

struct SineSynth {
Expand Down Expand Up @@ -87,36 +88,41 @@ impl Plugin for SineSynth {
}

#[allow(unused_variables)]
fn process_events(&mut self, events: Vec<Event>) {
for event in events {
fn process_events(&mut self, events: &Events) {
for &e in events.events_raw() {
let event: Event = Event::from(unsafe { *e });
match event {
Event::Midi(ev) => self.process_midi_event(ev.data),
// More events can be handled here.
_ => ()
}
}
/* on nightly you can just enable the "nightly" feature and then do:
for event in events.events() {
match event {
Event::Midi { data, .. } => self.process_midi_event(data),
// More events can be handled here.
_ => {}
}
}
*/
}

fn set_sample_rate(&mut self, rate: f32) {
self.sample_rate = rate as f64;
}

fn process(&mut self, buffer: AudioBuffer<f32>) {
let (inputs, outputs) = buffer.split();

let samples = inputs
.first()
.map(|channel| channel.len())
.unwrap_or(0);
fn process(&mut self, buffer: &mut AudioBuffer<f32>) {
let samples = buffer.samples();

let per_sample = self.time_per_sample();

for (input_buffer, output_buffer) in inputs.iter().zip(outputs) {
for (input_buffer, output_buffer) in buffer.zip() {
let mut t = self.time;

for (_, output_sample) in input_buffer.iter().zip(output_buffer) {
if let Some(current_note) = self.note {
let signal = (t * midi_note_to_hz(current_note) * TAU).sin();
let signal = (t * midi_pitch_to_freq(current_note) * TAU).sin();

// Apply a quick envelope to the attack of the signal to avoid popping.
let attack = 0.5;
Expand Down
87 changes: 81 additions & 6 deletions src/api.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
//! Structures and types for interfacing with the VST 2.4 API.
use std::mem;

use std::os::raw::c_void;

Expand Down Expand Up @@ -34,10 +33,10 @@ pub type HostCallbackProc = fn(effect: *mut AEffect, opcode: i32, index: i32, va
pub type DispatcherProc = fn(effect: *mut AEffect, opcode: i32, index: i32, value: isize, ptr: *mut c_void, opt: f32) -> isize;

/// Process function used to process 32 bit floating point samples. Called by host.
pub type ProcessProc = fn(effect: *mut AEffect, inputs: *mut *mut f32, outputs: *mut *mut f32, sample_frames: i32);
pub type ProcessProc = fn(effect: *mut AEffect, inputs: *const *const f32, outputs: *mut *mut f32, sample_frames: i32);

/// Process function used to process 64 bit floating point samples. Called by host.
pub type ProcessProcF64 = fn(effect: *mut AEffect, inputs: *mut *mut f64, outputs: *mut *mut f64, sample_frames: i32);
pub type ProcessProcF64 = fn(effect: *mut AEffect, inputs: *const *const f64, outputs: *mut *mut f64, sample_frames: i32);

/// Callback function used to set parameter values. Called by host.
pub type SetParameterProc = fn(effect: *mut AEffect, index: i32, parameter: f32);
Expand Down Expand Up @@ -135,13 +134,17 @@ pub struct AEffect {
impl AEffect {
/// Return handle to Plugin object. Only works for plugins created using this library.
pub unsafe fn get_plugin(&mut self) -> &mut Box<Plugin> {
mem::transmute::<_, &mut Box<Plugin>>(self.object)
&mut *(self.object as *mut Box<Plugin>)
}

/// Drop the Plugin object. Only works for plugins created using this library.
pub unsafe fn drop_plugin(&mut self) {
// Possibly a simpler way of doing this..?
drop(mem::transmute::<_, Box<Box<Plugin>>>(self.object))
drop(Box::from_raw(self.object as *mut Box<Plugin>));
drop(Box::from_raw(self.user as *mut super::PluginCache));
}

pub(crate) unsafe fn get_cache(&mut self) -> &mut super::PluginCache {
&mut *(self.user as *mut _)
}
}

Expand Down Expand Up @@ -399,6 +402,77 @@ pub struct Events {
pub events: [*mut Event; 2],
}

impl Events {
/// Use this in your impl of process_events() to process the incoming midi events (on stable).
///
/// # Example
/// ```no_run
/// # use vst2::plugin::{Info, Plugin, HostCallback};
/// # use vst2::buffer::{AudioBuffer, SendEventBuffer};
/// # use vst2::host::Host;
/// # use vst2::api;
/// # use vst2::event::Event;
/// # struct ExamplePlugin { host: HostCallback, send_buf: SendEventBuffer }
/// # impl Plugin for ExamplePlugin {
/// # fn get_info(&self) -> Info { Default::default() }
/// #
/// fn process_events(&mut self, events: &api::Events) {
/// for &e in events.events_raw() {
/// let event: Event = Event::from(unsafe { *e });
/// match event {
/// Event::Midi(ev) => {
/// // ...
/// }
/// _ => ()
/// }
/// }
/// }
/// # }
/// ```
#[inline(always)]
pub fn events_raw(&self) -> &[*const Event] {
use std::slice;
unsafe { slice::from_raw_parts(&self.events[0] as *const *mut _ as *const *const _, self.num_events as usize) }
}

#[inline(always)]
pub(crate) fn events_raw_mut(&mut self) -> &mut [*const SysExEvent] {
use std::slice;
unsafe { slice::from_raw_parts_mut(&mut self.events[0] as *mut *mut _ as *mut *const _, self.num_events as usize) }
}

/// Use this in your impl of process_events() to process the incoming midi events (on nightly).
///
/// # Example
/// ```no_run
/// # use vst2::plugin::{Info, Plugin, HostCallback};
/// # use vst2::buffer::{AudioBuffer, SendEventBuffer};
/// # use vst2::host::Host;
/// # use vst2::api;
/// # use vst2::event::Event;
/// # struct ExamplePlugin { host: HostCallback, send_buf: SendEventBuffer }
/// # impl Plugin for ExamplePlugin {
/// # fn get_info(&self) -> Info { Default::default() }
/// #
/// fn process_events(&mut self, events: &api::Events) {
/// for e in events.events() {
/// match e {
/// Event::Midi { data, .. } => {
/// // ...
/// }
/// _ => ()
/// }
/// }
/// }
/// # }
/// ```
#[cfg(feature = "nightly")]
#[inline(always)]
pub fn events<'a>(&'a self) -> impl Iterator<Item = ::event::Event> + 'a {
self.events_raw().into_iter().map(|&e| ::event::Event::from(unsafe { *e }))
}
}

/// The type of event that has occured. See `api::Event.event_type`.
#[repr(i32)]
#[derive(Copy, Clone, Debug)]
Expand Down Expand Up @@ -533,6 +607,7 @@ pub struct MidiEvent {
/// `plugin::CanDo` has a `ReceiveSysExEvent` variant which lets the host query the plugin as to
/// whether this event is supported.
#[repr(C)]
#[derive(Clone)]
pub struct SysExEvent {
/// Should be `EventType::SysEx`.
pub event_type: EventType,
Expand Down
Loading