Skip to content

XP event5x XPListening, games, ratings, comments and chat earn five times the XP

leftLeaderboard

juicewrld-desktopsrc-taurihostshim.rs

1.4.2Released Nov 21, 2026

shim.rs

326 lines12.1 KBRust
//! The C++ shim (host/shim/jwvst3.h) as Rust: raw declarations, and thin wrappers that turn its error buffers into//! Results. The instance pointer is shared between the main thread and the instance's audio thread exactly as VST 3//! shares a plugin between its UI and audio threads; which calls belong to which thread is written on each.use std::ffi::{c_char, c_void, CStr, CString};#[repr(C)]pub struct JwModule {    _private: [u8; 0],}#[repr(C)]pub struct JwPlugin {    _private: [u8; 0],}#[repr(C)]pub struct FactoryInfo {    pub vendor: [c_char; 256],    pub url: [c_char; 256],    pub email: [c_char; 256],    pub flags: i32,}#[repr(C)]pub struct ClassInfo {    pub cid: [c_char; 33],    pub category: [c_char; 128],    pub name: [c_char; 256],    pub vendor: [c_char; 256],    pub version: [c_char; 128],    pub sdk_version: [c_char; 128],    pub sub_categories: [c_char; 512],    pub class_flags: u32,    pub cardinality: i32,}#[repr(C)]#[derive(Clone, Copy)]pub struct PluginInfo {    pub in_channels: i32,    pub out_channels: i32,    pub in_buses: i32,    pub out_buses: i32,    pub latency: i32,    pub tail: u32,    pub has_editor: i32,    pub param_count: i32,    pub single: i32,    pub bypass_param: i32,    pub name: [c_char; 256],}#[repr(C)]pub struct ParamInfo {    pub id: u32,    pub title: [c_char; 256],    pub short_title: [c_char; 128],    pub units: [c_char; 64],    pub step_count: i32,    pub default_value: f64,    pub value: f64,    pub flags: i32,    pub display: [c_char; 128],}#[repr(C)]pub struct Transport {    pub tempo: f64,    pub playing: i32,    pub position: i64,}#[repr(C)]pub struct Callbacks {    pub ctx: *mut c_void,    pub param_edit: Option<unsafe extern "C" fn(*mut c_void, u32, u32, f64, i32)>,    pub restart: Option<unsafe extern "C" fn(*mut c_void, u32, i32)>,    pub editor_closed: Option<unsafe extern "C" fn(*mut c_void, u32, i32, i32)>,    pub editor_moved: Option<unsafe extern "C" fn(*mut c_void, u32, i32, i32, i32, i32)>,    pub open_editor: Option<unsafe extern "C" fn(*mut c_void, u32)>,}extern "C" {    pub fn jw_init(callbacks: *const Callbacks);    pub fn jw_set_quiet_windows(on: i32);    pub fn jw_set_log(handle: *mut c_void);    pub fn jw_set_stages(on: i32);    pub fn jw_module_load(path: *const c_char, err: *mut c_char, err_len: usize) -> *mut JwModule;    pub fn jw_module_factory_info(m: *mut JwModule, out: *mut FactoryInfo) -> i32;    pub fn jw_module_class_count(m: *mut JwModule) -> i32;    pub fn jw_module_class_info(m: *mut JwModule, index: i32, out: *mut ClassInfo) -> i32;    pub fn jw_plugin_create(m: *mut JwModule, cid: *const c_char, tag: u32, err: *mut c_char, err_len: usize) -> *mut JwPlugin;    pub fn jw_plugin_setup(p: *mut JwPlugin, rate: f64, max_block: i32, offline: i32, out: *mut PluginInfo, err: *mut c_char, err_len: usize) -> i32;    pub fn jw_plugin_reactivate(p: *mut JwPlugin, out: *mut PluginInfo) -> i32;    pub fn jw_plugin_set_processing(p: *mut JwPlugin, on: i32) -> i32;    pub fn jw_plugin_process(p: *mut JwPlugin, in_l: *const f32, in_r: *const f32, out_l: *mut f32, out_r: *mut f32, frames: i32, t: *const Transport) -> i32;    pub fn jw_plugin_params_pending(p: *mut JwPlugin) -> i32;    pub fn jw_plugin_flush(p: *mut JwPlugin) -> i32;    pub fn jw_plugin_get_state(p: *mut JwPlugin, which: i32, data: *mut *mut u8, len: *mut i64, err: *mut c_char, err_len: usize) -> i32;    pub fn jw_plugin_set_state(p: *mut JwPlugin, comp: *const u8, comp_len: i64, ctrl: *const u8, ctrl_len: i64, err: *mut c_char, err_len: usize) -> i32;    pub fn jw_plugin_param_count(p: *mut JwPlugin) -> i32;    pub fn jw_plugin_param_info(p: *mut JwPlugin, index: i32, out: *mut ParamInfo) -> i32;    pub fn jw_plugin_set_param(p: *mut JwPlugin, id: u32, value: f64) -> i32;    pub fn jw_plugin_set_bypass(p: *mut JwPlugin, on: i32) -> i32;    pub fn jw_plugin_idle(p: *mut JwPlugin);    pub fn jw_plugin_destroy(p: *mut JwPlugin);    pub fn jw_editor_open(p: *mut JwPlugin, owner: isize, title: *const c_char, x: i32, y: i32, use_pos: i32, err: *mut c_char, err_len: usize) -> i32;    pub fn jw_editor_close(p: *mut JwPlugin);    pub fn jw_editor_is_open(p: *mut JwPlugin) -> i32;    pub fn jw_editor_set_title(p: *mut JwPlugin, title: *const c_char);    pub fn jw_free(data: *mut c_void);    pub fn jw_redirect_stdio();}/// A fixed C string field as Rust.pub fn text(field: &[c_char]) -> String {    // SAFETY: the shim always terminates its fields.    let bytes: Vec<u8> = field.iter().take_while(|&&c| c != 0).map(|&c| c as u8).collect();    String::from_utf8_lossy(&bytes).into_owned()}fn cstring(s: &str) -> CString {    CString::new(s.replace('\0', "")).unwrap_or_default()}/// Runs a shim call that reports failure in an error buffer.fn with_err<T>(f: impl FnOnce(*mut c_char, usize) -> Option<T>) -> Result<T, String> {    let mut err = [0 as c_char; 512];    match f(err.as_mut_ptr(), err.len()) {        Some(v) => Ok(v),        None => {            // SAFETY: zero-initialized and the shim terminates what it writes.            let msg = unsafe { CStr::from_ptr(err.as_ptr()) }.to_string_lossy().into_owned();            Err(if msg.is_empty() { "the plugin failed".into() } else { msg })        }    }}/// A loaded module. Never unloaded: some plugins leave threads behind, and the host process ends soon enough.pub struct Module(pub *mut JwModule);unsafe impl Send for Module {}pub struct Class {    pub cid: String,    pub category: String,    pub name: String,    pub vendor: String,    pub version: String,    pub sdk_version: String,    pub sub_categories: String,    pub class_flags: u32,    pub cardinality: i32,}impl Module {    pub fn load(path: &str) -> Result<Module, String> {        let c = cstring(path);        with_err(|e, n| {            // SAFETY: valid C string and error buffer.            let m = unsafe { jw_module_load(c.as_ptr(), e, n) };            (!m.is_null()).then_some(Module(m))        })    }    pub fn vendor(&self) -> String {        // SAFETY: zeroed out-struct the shim fills.        let mut info: FactoryInfo = unsafe { std::mem::zeroed() };        unsafe { jw_module_factory_info(self.0, &mut info) };        text(&info.vendor)    }    pub fn classes(&self) -> Vec<Class> {        let n = unsafe { jw_module_class_count(self.0) };        (0..n)            .filter_map(|i| {                let mut c: ClassInfo = unsafe { std::mem::zeroed() };                (unsafe { jw_module_class_info(self.0, i, &mut c) } == 0).then(|| Class {                    cid: text(&c.cid),                    category: text(&c.category),                    name: text(&c.name),                    vendor: text(&c.vendor),                    version: text(&c.version),                    sdk_version: text(&c.sdk_version),                    sub_categories: text(&c.sub_categories),                    class_flags: c.class_flags,                    cardinality: c.cardinality,                })            })            .collect()    }}/// An instance. Main-thread calls take `&self`; the two audio-thread calls are marked.#[derive(Clone, Copy)]pub struct Plugin(pub *mut JwPlugin);// SAFETY: shared with the instance's audio thread for process/set_processing only, as VST 3 allows.unsafe impl Send for Plugin {}unsafe impl Sync for Plugin {}impl Plugin {    pub fn create(m: &Module, cid: &str, tag: u32) -> Result<Plugin, String> {        let c = cstring(cid);        with_err(|e, n| {            let p = unsafe { jw_plugin_create(m.0, c.as_ptr(), tag, e, n) };            (!p.is_null()).then_some(Plugin(p))        })    }    pub fn setup(&self, rate: f64, max_block: u32, offline: bool) -> Result<PluginInfo, String> {        let mut info: PluginInfo = unsafe { std::mem::zeroed() };        with_err(|e, n| (unsafe { jw_plugin_setup(self.0, rate, max_block as i32, offline as i32, &mut info, e, n) } == 0).then_some(info))    }    pub fn reactivate(&self) -> Result<PluginInfo, String> {        let mut info: PluginInfo = unsafe { std::mem::zeroed() };        if unsafe { jw_plugin_reactivate(self.0, &mut info) } == 0 {            Ok(info)        } else {            Err("the plugin wouldn't switch on again".into())        }    }    /// Audio thread.    pub fn set_processing(&self, on: bool) {        unsafe { jw_plugin_set_processing(self.0, on as i32) };    }    /// Audio thread: one block, at most the max block size.    pub fn process(&self, in_l: &[f32], in_r: &[f32], out_l: &mut [f32], out_r: &mut [f32], t: &Transport) -> i32 {        let n = in_l.len().min(in_r.len()).min(out_l.len()).min(out_r.len());        unsafe { jw_plugin_process(self.0, in_l.as_ptr(), in_r.as_ptr(), out_l.as_mut_ptr(), out_r.as_mut_ptr(), n as i32, t) }    }    /// Whether parameter changes are waiting for the processor (any thread).    pub fn params_pending(&self) -> bool {        unsafe { jw_plugin_params_pending(self.0) != 0 }    }    /// Audio thread, while processing: hands the processor the parameter changes waiting, with no audio (a parameter    /// flush).    pub fn flush(&self) -> i32 {        unsafe { jw_plugin_flush(self.0) }    }    /// The component's (0) or the controller's (1) state.    pub fn state(&self, which: i32) -> Result<Vec<u8>, String> {        let mut data: *mut u8 = std::ptr::null_mut();        let mut len = 0i64;        with_err(|e, n| (unsafe { jw_plugin_get_state(self.0, which, &mut data, &mut len, e, n) } == 0).then_some(()))?;        if data.is_null() || len <= 0 {            return Ok(Vec::new());        }        // SAFETY: the shim malloc'd `len` bytes for us.        let bytes = unsafe { std::slice::from_raw_parts(data, len as usize) }.to_vec();        unsafe { jw_free(data as *mut c_void) };        Ok(bytes)    }    pub fn set_state(&self, component: &[u8], controller: &[u8]) -> Result<(), String> {        with_err(|e, n| {            (unsafe { jw_plugin_set_state(self.0, component.as_ptr(), component.len() as i64, controller.as_ptr(), controller.len() as i64, e, n) } == 0)                .then_some(())        })    }    pub fn params(&self) -> Vec<crate::proto::Param> {        let n = unsafe { jw_plugin_param_count(self.0) };        (0..n)            .filter_map(|i| {                let mut p: ParamInfo = unsafe { std::mem::zeroed() };                (unsafe { jw_plugin_param_info(self.0, i, &mut p) } == 0).then(|| crate::proto::Param {                    id: p.id,                    title: text(&p.title),                    short_title: text(&p.short_title),                    units: text(&p.units),                    steps: p.step_count,                    default: p.default_value,                    value: p.value,                    display: text(&p.display),                    automatable: p.flags & 1 != 0,                    read_only: p.flags & 2 != 0,                    list: p.flags & 8 != 0,                    hidden: p.flags & 16 != 0,                    bypass: p.flags & 65536 != 0,                })            })            .collect()    }    pub fn set_param(&self, id: u32, value: f64) -> bool {        unsafe { jw_plugin_set_param(self.0, id, value) == 0 }    }    /// The plugin's own bypass; false when it has none.    pub fn set_bypass(&self, on: bool) -> bool {        unsafe { jw_plugin_set_bypass(self.0, on as i32) == 0 }    }    pub fn idle(&self) {        unsafe { jw_plugin_idle(self.0) }    }    /// Main thread, after the audio thread has stopped.    pub fn destroy(self) {        unsafe { jw_plugin_destroy(self.0) }    }    pub fn open_editor(&self, owner: isize, title: &str, at: Option<(i32, i32)>) -> Result<(), String> {        let t = cstring(title);        let (x, y) = at.unwrap_or((0, 0));        with_err(|e, n| (unsafe { jw_editor_open(self.0, owner, t.as_ptr(), x, y, at.is_some() as i32, e, n) } == 0).then_some(()))    }    pub fn close_editor(&self) {        unsafe { jw_editor_close(self.0) }    }    pub fn editor_open(&self) -> bool {        unsafe { jw_editor_is_open(self.0) != 0 }    }    pub fn set_title(&self, title: &str) {        let t = cstring(title);        unsafe { jw_editor_set_title(self.0, t.as_ptr()) }    }}