Skip to content

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

leftLeaderboard

juicewrld-desktopsrc-taurihostserver.rs

1.4.2Released Nov 21, 2026

server.rs

530 lines21.5 KBRust
//! The host's main thread, the one VST 3 calls the UI thread: it reads the app's requests, makes and drives the//! instances, owns their editor windows, and sends a heartbeat four times a second so the app can tell a hang from a//! slow plugin. A reader thread takes frames off the pipe and posts them to a message-only window, which also gets//! them while a plugin's window is being dragged (a modal loop that would drop thread messages).use crate::audio::{self, AudioThread, Job, Stream, View};use crate::proto::{self, Event, Frame, Opened, Reply, Request, KIND_EVENT, KIND_RESPONSE};use crate::ring::Ring;use crate::shim::{Callbacks, Module, Plugin};use serde_json::{json, Value};use std::cell::RefCell;use std::collections::HashMap;use std::ffi::c_void;use std::fs::File;use std::sync::atomic::{AtomicU32, Ordering};use std::sync::{mpsc, Arc, Mutex, OnceLock};use std::time::Duration;use windows::core::w;use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, WPARAM};use windows::Win32::System::LibraryLoader::GetModuleHandleW;use windows::Win32::System::Memory::{MapViewOfFile, FILE_MAP_ALL_ACCESS};use windows::Win32::UI::WindowsAndMessaging::{    CreateWindowExW, DefWindowProcW, DispatchMessageW, GetMessageW, PostMessageW, PostQuitMessage, RegisterClassW, SetTimer,    TranslateMessage, HWND_MESSAGE, MSG, WINDOW_EX_STYLE, WINDOW_STYLE, WM_APP, WM_TIMER, WNDCLASSW,};const WM_REQUEST: u32 = WM_APP + 1;const WM_RESTART: u32 = WM_APP + 2;const WM_GONE: u32 = WM_APP + 3;const TIMER_HEARTBEAT: usize = 1;const TIMER_IDLE: usize = 2;/// An audio call running longer than this is reported as stuck (the app decides when that's a hang).const STUCK_MS: u64 = 1500;/// restartComponent flags (ivsteditcontroller.h).const RESTART_RELOAD: i32 = 1;const RESTART_IO: i32 = 2;const RESTART_VALUES: i32 = 4;const RESTART_LATENCY: i32 = 8;const RESTART_TITLES: i32 = 16;/// The pipe to the app; frames are written whole under the lock, from any thread.pub struct Writer(Mutex<File>);impl Writer {    pub fn new(f: File) -> Writer {        Writer(Mutex::new(f))    }    pub fn send(&self, f: &Frame) {        let mut w = self.0.lock().unwrap_or_else(|e| e.into_inner());        let _ = proto::write_frame(&mut *w, f);    }    pub fn event(&self, e: &Event) {        self.send(&Frame::new(KIND_EVENT, 0, e, Vec::new()));    }    pub fn reply(&self, id: u32, r: Result<(Value, Vec<u8>), String>) {        match r {            Ok((v, bytes)) => self.send(&Frame::new(KIND_RESPONSE, id, &Reply::Ok(v), bytes)),            Err(e) => self.send(&Frame::new(KIND_RESPONSE, id, &Reply::Err(e), Vec::new())),        }    }}/// What the plugin callbacks and the heartbeat need, reachable without the server (which is busy while a request runs).struct Ctx {    writer: Arc<Writer>,    restarts: Mutex<HashMap<u32, i32>>,    /// Every instance's audio thread, for the heartbeat's stuck list; an instance whose close found its audio thread    /// stuck in the plugin stays here, so it's still reported and the app ends the host as for any hang.    audio: Mutex<HashMap<u32, Arc<audio::Shared>>>,    hwnd: Mutex<isize>,    /// Editor windows open, as the server last counted them (the heartbeat can't ask it: it may be busy).    editors: AtomicU32,}static CTX: OnceLock<Ctx> = OnceLock::new();fn ctx() -> &'static Ctx {    CTX.get().expect("host context")}struct Instance {    plugin: Plugin,    audio: AudioThread,    cid: String,    rate: f64,    block: u32,    latency: u32,    title: String,}struct Server {    rx: mpsc::Receiver<Frame>,    roots: Vec<String>,    owner: isize,    modules: HashMap<String, Module>,    instances: HashMap<u32, Instance>,    next: u32,}thread_local! {    static SERVER: RefCell<Option<Server>> = const { RefCell::new(None) };}fn post(msg: u32) {    let hwnd = *ctx().hwnd.lock().unwrap_or_else(|e| e.into_inner());    // SAFETY: our own message-only window, or nothing when it's gone.    unsafe {        let _ = PostMessageW(Some(HWND(hwnd as *mut c_void)), msg, WPARAM(0), LPARAM(0));    }}// ---- callbacks from the shim (any thread for restart; the main thread for the rest) ----unsafe extern "C" fn on_param_edit(_: *mut c_void, tag: u32, id: u32, value: f64, phase: i32) {    let _ = std::panic::catch_unwind(|| {        // An edit in the plugin's own editor: the processor gets it even while no audio flows.        if phase == 1 {            if let Some(a) = ctx().audio.lock().unwrap_or_else(|e| e.into_inner()).get(&tag) {                a.request_flush();            }        }        ctx().writer.event(&Event::Param { inst: tag, id, value, phase })    });}unsafe extern "C" fn on_restart(_: *mut c_void, tag: u32, flags: i32) {    let _ = std::panic::catch_unwind(|| {        *ctx().restarts.lock().unwrap_or_else(|e| e.into_inner()).entry(tag).or_insert(0) |= flags;        post(WM_RESTART);    });}unsafe extern "C" fn on_editor_closed(_: *mut c_void, tag: u32, x: i32, y: i32) {    let _ = std::panic::catch_unwind(|| ctx().writer.event(&Event::Editor { inst: tag, open: false, x, y }));}unsafe extern "C" fn on_editor_moved(_: *mut c_void, tag: u32, x: i32, y: i32, _w: i32, _h: i32) {    let _ = std::panic::catch_unwind(|| ctx().writer.event(&Event::Editor { inst: tag, open: true, x, y }));}unsafe extern "C" fn on_open_editor(_: *mut c_void, tag: u32) {    let _ = std::panic::catch_unwind(|| ctx().writer.event(&Event::OpenEditor { inst: tag }));}pub fn callbacks() -> Callbacks {    Callbacks {        ctx: std::ptr::null_mut(),        param_edit: Some(on_param_edit),        restart: Some(on_restart),        editor_closed: Some(on_editor_closed),        editor_moved: Some(on_editor_moved),        open_editor: Some(on_open_editor),    }}/// Runs the host until the app closes the pipe.pub fn run(input: File, writer: Arc<Writer>) {    let _ = CTX.set(Ctx {        writer,        restarts: Mutex::new(HashMap::new()),        audio: Mutex::new(HashMap::new()),        hwnd: Mutex::new(0),        editors: AtomicU32::new(0),    });    // SAFETY: plain Win32 window setup on this thread.    let hwnd = unsafe {        let instance = GetModuleHandleW(None).unwrap_or_default();        let class = w!("JuiceWRLDPluginHost");        RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(host_proc), hInstance: instance.into(), lpszClassName: class, ..Default::default() });        CreateWindowExW(WINDOW_EX_STYLE(0), class, w!(""), WINDOW_STYLE(0), 0, 0, 0, 0, Some(HWND_MESSAGE), None, Some(instance.into()), None)    };    let Ok(hwnd) = hwnd else {        log!("[host] couldn't make its message window");        return;    };    *ctx().hwnd.lock().unwrap_or_else(|e| e.into_inner()) = hwnd.0 as isize;    let (tx, rx) = mpsc::channel();    SERVER.with(|s| {        *s.borrow_mut() = Some(Server { rx, roots: Vec::new(), owner: 0, modules: HashMap::new(), instances: HashMap::new(), next: 1 })    });    let _ = std::thread::Builder::new().name("pipe".into()).spawn(move || {        let mut input = input;        loop {            match proto::read_frame(&mut input) {                Ok(Some(f)) => {                    if tx.send(f).is_err() {                        break;                    }                    post(WM_REQUEST);                }                Ok(None) | Err(_) => break,            }        }        post(WM_GONE);    });    // SAFETY: timers on our own window; the standard message loop.    unsafe {        SetTimer(Some(hwnd), TIMER_HEARTBEAT, 250, None);        SetTimer(Some(hwnd), TIMER_IDLE, 33, None);        let mut msg = MSG::default();        while GetMessageW(&mut msg, None, 0, 0).as_bool() {            let _ = TranslateMessage(&msg);            DispatchMessageW(&msg);        }    }}unsafe extern "system" fn host_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {    match msg {        WM_REQUEST => with_server(|s| s.drain()),        WM_RESTART => with_server(|s| s.restarts()),        WM_GONE => PostQuitMessage(0),        WM_TIMER if wparam.0 == TIMER_HEARTBEAT => heartbeat(),        WM_TIMER if wparam.0 == TIMER_IDLE => with_server(|s| s.idle()),        _ => return DefWindowProcW(hwnd, msg, wparam, lparam),    }    LRESULT(0)}/// Runs `f` on the server unless it's already busy further up this thread's stack (a plugin pumping messages inside a/// request): then the work waits for the request to finish, which drains again.fn with_server(f: impl FnOnce(&mut Server)) {    SERVER.with(|s| {        if let Ok(mut guard) = s.try_borrow_mut() {            if let Some(server) = guard.as_mut() {                f(server);            }        }    });}fn heartbeat() {    let now = audio::now_ms();    let stuck: Vec<u32> = ctx()        .audio        .lock()        .unwrap_or_else(|e| e.into_inner())        .iter()        .filter(|(_, a)| {            let since = a.busy_since.load(Ordering::Acquire);            since != 0 && now.saturating_sub(since) > STUCK_MS        })        .map(|(i, _)| *i)        .collect();    ctx().writer.event(&Event::Heartbeat { stuck, editors: ctx().editors.load(Ordering::Relaxed) });}fn hex_id(cid: &str) -> bool {    cid.len() == 32 && cid.bytes().all(|b| b.is_ascii_hexdigit())}impl Server {    fn drain(&mut self) {        while let Ok(f) = self.rx.try_recv() {            self.handle(f);        }        self.count_editors();    }    /// For the heartbeat: how many editor windows are open (the app watches the host more closely while there are).    fn count_editors(&self) {        let n = self.instances.values().filter(|i| i.plugin.editor_open()).count() as u32;        ctx().editors.store(n, Ordering::Relaxed);    }    fn handle(&mut self, f: Frame) {        let writer = ctx().writer.clone();        let req: Request = match serde_json::from_slice(&f.json) {            Ok(r) => r,            Err(e) => return writer.reply(f.id, Err(format!("bad request: {e}"))),        };        // Render answers from the audio thread, when it's done.        if let Request::Render { inst, frames } = req {            return match self.instances.get(&inst) {                Some(i) => {                    let id = f.id;                    let w = writer.clone();                    i.audio.shared.send(Job::Render {                        input: f.bytes,                        frames,                        reply: Box::new(move |r| w.reply(id, r.map(|bytes| (json!({ "frames": frames }), bytes)))),                    });                }                None => writer.reply(f.id, Err("no such instance".into())),            };        }        let r = self.request(req, f.bytes);        writer.reply(f.id, r);    }    fn instance(&self, inst: u32) -> Result<&Instance, String> {        self.instances.get(&inst).ok_or_else(|| "no such instance".to_string())    }    fn request(&mut self, req: Request, bytes: Vec<u8>) -> Result<(Value, Vec<u8>), String> {        let ok = |v: Value| Ok((v, Vec::new()));        match req {            Request::Hello { version, roots, owner } => {                if version != proto::VERSION {                    return Err(format!("the host speaks version {}, the app {version}", proto::VERSION));                }                self.roots = roots;                self.owner = owner as isize;                ok(json!({ "pid": std::process::id(), "version": proto::VERSION }))            }            Request::Ping {} => ok(json!({ "pid": std::process::id() })),            Request::Open { module, cid, rate, block, offline } => self.open(&module, &cid, rate, block, offline).map(|o| (json!(o), Vec::new())),            Request::Close { inst } => self.close(inst).map(|_| (json!({}), Vec::new())),            Request::Editor { inst, show, title, x, y } => {                let owner = self.owner;                let i = self.instances.get_mut(&inst).ok_or("no such instance")?;                if show {                    if i.plugin.editor_open() && i.title != title {                        i.plugin.set_title(&title);                    }                    i.title = title.clone();                    let at = x.zip(y);                    call(inst, || i.plugin.open_editor(owner, &title, at))?;                } else {                    i.plugin.close_editor();                }                ok(json!({ "open": i.plugin.editor_open() }))            }            Request::GetState { inst } => {                let i = self.instance(inst)?;                // Parameter changes made while no audio flowed reach the processor first, so the state saved is the                // one the controller shows (half a second at most: a stuck audio thread doesn't hold the save up).                i.audio.flush_now(Duration::from_millis(500));                let component = call(inst, || i.plugin.state(0))?;                let controller = call(inst, || i.plugin.state(1))?;                let blob = proto::state::pack(&i.cid, &component, &controller);                Ok((json!({ "bytes": blob.len(), "component": component.len(), "controller": controller.len() }), blob))            }            Request::SetState { inst } => {                let i = self.instance(inst)?;                let (cid, component, controller) = proto::state::unpack(&bytes)?;                if !cid.eq_ignore_ascii_case(&i.cid) {                    return Err("that state belongs to another plugin".into());                }                call(inst, || i.plugin.set_state(component, controller))?;                ok(json!({}))            }            Request::Params { inst } => {                let i = self.instance(inst)?;                ok(json!(call(inst, || i.plugin.params())))            }            Request::SetParam { inst, id, value } => {                let i = self.instance(inst)?;                if !value.is_finite() {                    return Err("not a value".into());                }                if !call(inst, || i.plugin.set_param(id, value)) {                    return Err("the plugin has too many parameters to take that one".into());                }                i.audio.shared.request_flush();                ok(json!({}))            }            Request::Reset { inst } => self.reactivate(inst).map(|latency| (json!({ "latency": latency }), Vec::new())),            Request::Bypass { inst, on } => {                let i = self.instance(inst)?;                let soft = call(inst, || i.plugin.set_bypass(on));                if soft {                    i.audio.shared.request_flush();                } else {                    i.audio.shared.send(Job::Bypass(on));                }                ok(json!({ "plugin": soft }))            }            Request::Attach { inst, handle, size } => {                let i = self.instance(inst)?;                let stream = map_ring(handle, size)?;                if stream.layout.rate != i.rate as u32 || stream.layout.max_block > i.block {                    return Err("the stream's rate or block size isn't the instance's".into());                }                i.audio.shared.send(Job::Attach(stream, i.latency));                ok(json!({}))            }            Request::Detach { inst } => {                self.instance(inst)?.audio.shared.send(Job::Detach);                ok(json!({}))            }            Request::Render { .. } => Err("render is handled apart".into()),        }    }    fn open(&mut self, module: &str, cid: &str, rate: f64, block: u32, offline: bool) -> Result<Opened, String> {        if !proto::module_allowed(module, &self.roots) {            return Err("that module isn't in one of the plugin folders".into());        }        if !hex_id(cid) {            return Err("not a class ID".into());        }        if !(8000.0..=384000.0).contains(&rate) || !(16..=8192).contains(&block) {            return Err("unsupported sample rate or block size".into());        }        if !self.modules.contains_key(module) {            crate::before_load(module, "host")?;            let m = call(0, || Module::load(module))?;            self.modules.insert(module.to_string(), m);        }        let m = &self.modules[module];        let inst = self.next;        self.next += 1;        let plugin = call(inst, || Plugin::create(m, cid, inst))?;        let info = match call(inst, || plugin.setup(rate, block, offline)) {            Ok(info) => info,            Err(e) => {                call(inst, || plugin.destroy());                return Err(e);            }        };        let latency = info.latency.max(0) as u32;        let audio = AudioThread::start(plugin, inst, block, latency);        ctx().audio.lock().unwrap_or_else(|e| e.into_inner()).insert(inst, audio.shared.clone());        let name = crate::shim::text(&info.name);        log!("[host] opened {name} as instance {inst} ({} in, {} out, latency {latency})", info.in_channels, info.out_channels);        self.instances.insert(inst, Instance { plugin, audio, cid: cid.to_ascii_uppercase(), rate, block, latency, title: String::new() });        Ok(Opened {            inst,            name,            inputs: info.in_channels.max(0) as u32,            outputs: info.out_channels.max(0) as u32,            in_buses: info.in_buses.max(0) as u32,            out_buses: info.out_buses.max(0) as u32,            latency,            tail: info.tail,            has_editor: info.has_editor != 0,            params: info.param_count.max(0) as u32,            bypass_param: info.bypass_param != 0,        })    }    fn close(&mut self, inst: u32) -> Result<(), String> {        let mut i = self.instances.remove(&inst).ok_or("no such instance")?;        ctx().restarts.lock().unwrap_or_else(|e| e.into_inner()).remove(&inst);        if !i.audio.stop(Duration::from_secs(2)) {            // Its audio thread is stuck inside the plugin: tearing it down now would pull memory out from under it.            // Its window goes (nothing may stay on the screen for an instance that's gone); the rest is left as it is,            // and the heartbeat keeps naming it as stuck (it stays in ctx().audio), so the app ends the host as for any            // hang, and the pages hear which of their plugins were lost.            call(inst, || i.plugin.close_editor());            std::mem::forget(i);            self.count_editors();            return Err("the plugin is stuck".into());        }        ctx().audio.lock().unwrap_or_else(|e| e.into_inner()).remove(&inst);        call(inst, || {            i.plugin.close_editor();            i.plugin.destroy();        });        Ok(())    }    /// setActive(false) and (true) with processing stopped around it; the latency it reports afterwards.    fn reactivate(&mut self, inst: u32) -> Result<u32, String> {        let i = self.instances.get_mut(&inst).ok_or("no such instance")?;        if !i.audio.suspend(Duration::from_secs(2)) {            // Its audio thread is in a slow (or stuck) plugin call. The Suspend stays queued; the Resume after it            // makes sure that, once the call returns, the instance plays on rather than staying suspended (silent)            // for good. One that stays stuck is the heartbeat's to report.            i.audio.shared.send(Job::Resume);            return Err("the plugin is stuck".into());        }        let r = call(inst, || i.plugin.reactivate());        i.audio.shared.send(Job::Resume);        let info = r?;        let latency = info.latency.max(0) as u32;        if latency != i.latency {            i.latency = latency;            i.audio.shared.send(Job::Latency(latency));            ctx().writer.event(&Event::Latency { inst, samples: latency });        }        Ok(latency)    }    fn restarts(&mut self) {        let pending: Vec<(u32, i32)> = ctx().restarts.lock().unwrap_or_else(|e| e.into_inner()).drain().collect();        for (inst, flags) in pending {            if !self.instances.contains_key(&inst) {                continue;            }            if flags & (RESTART_LATENCY | RESTART_IO | RESTART_RELOAD) != 0 {                if let Err(e) = self.reactivate(inst) {                    log!("[host] instance {inst} couldn't restart: {e}");                }            }            if flags & (RESTART_VALUES | RESTART_TITLES) != 0 {                ctx().writer.event(&Event::Changed { inst, flags });            }        }    }    fn idle(&mut self) {        for (inst, i) in &self.instances {            call(*inst, || i.plugin.idle());        }        // The user closes editors with their own close button: counted here too.        self.count_editors();    }}/// A call into a plugin on the main thread, marked for the crash report.fn call<T>(inst: u32, f: impl FnOnce() -> T) -> T {    audio::CURRENT.with(|c| c.set(inst));    let r = f();    audio::CURRENT.with(|c| c.set(0));    r}/// Maps a ring the app shared with this process (the handle is already ours) and checks its layout.fn map_ring(handle: u64, size: u64) -> Result<Stream, String> {    if !(256..=(64 << 20)).contains(&size) {        return Err("bad ring size".into());    }    let mapping = HANDLE(handle as usize as *mut c_void);    // SAFETY: a file mapping handle the app duplicated into this process for this purpose; size checked above.    let view = unsafe { MapViewOfFile(mapping, FILE_MAP_ALL_ACCESS, 0, 0, size as usize) };    if view.Value.is_null() {        return Err("couldn't map the stream's memory".into());    }    let view = View { base: view.Value as *mut u8, len: size as usize, mapping };    // SAFETY: the view is mapped for `len` bytes and lives in the Stream next to the ring.    let ring = unsafe { Ring::new(view.base, view.len) };    let layout = ring.layout()?;    Ok(Stream { view, ring, layout })}