Skip to content

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

leftLeaderboard

juicewrld-desktopsrc-taurisrcpluginsproto.rs

1.4.2Released Nov 21, 2026

proto.rs

352 lines15.2 KBRust
//! The pipe between the app and its plugin host (juicewrld-plugins.exe, host/main.rs), in both of them: the host's stdin//! carries requests, its stdout responses and events, as frames//!//! ```text//! u32 length (of the rest) | u8 kind | u32 id | u32 json length | json | bytes//! ```//!//! little-endian, the JSON a [`Request`], a [`Reply`] or an [`Event`], the bytes a plugin's state or audio when the//! message carries some. A response has its request's id; events have 0. Nothing else is written to the pipe: the host//! moves the process's standard output elsewhere before any plugin loads, so a plugin's printf can't corrupt it.use serde::{Deserialize, Serialize};use std::io::{self, Read, Write};pub const KIND_REQUEST: u8 = 1;pub const KIND_RESPONSE: u8 = 2;pub const KIND_EVENT: u8 = 3;/// The largest frame either side accepts: a long render's audio or a big plugin's state (a sampler with its/// samples), and well short of what a 32-bit length could claim.pub const MAX_FRAME: usize = 512 << 20;/// The protocol's version; the app and the host ship together, so they only ever differ in a broken install.pub const VERSION: u32 = 1;#[derive(Debug, Clone, PartialEq)]pub struct Frame {    pub kind: u8,    pub id: u32,    pub json: Vec<u8>,    pub bytes: Vec<u8>,}impl Frame {    pub fn new(kind: u8, id: u32, json: &impl Serialize, bytes: Vec<u8>) -> Frame {        Frame { kind, id, json: serde_json::to_vec(json).unwrap_or_else(|_| b"null".to_vec()), bytes }    }}/// Writes one frame (a single write of the whole frame, so frames from two threads never interleave mid-frame).pub fn write_frame(w: &mut impl Write, f: &Frame) -> io::Result<()> {    let len = 1 + 4 + 4 + f.json.len() + f.bytes.len();    if len > MAX_FRAME {        return Err(io::Error::new(io::ErrorKind::InvalidInput, "frame too large"));    }    let mut buf = Vec::with_capacity(4 + len);    buf.extend_from_slice(&(len as u32).to_le_bytes());    buf.push(f.kind);    buf.extend_from_slice(&f.id.to_le_bytes());    buf.extend_from_slice(&(f.json.len() as u32).to_le_bytes());    buf.extend_from_slice(&f.json);    buf.extend_from_slice(&f.bytes);    w.write_all(&buf)?;    w.flush()}/// Reads one frame; None when the other side closed the pipe between frames.pub fn read_frame(r: &mut impl Read) -> io::Result<Option<Frame>> {    let mut len = [0u8; 4];    match r.read_exact(&mut len) {        Ok(()) => {}        Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),        Err(e) => return Err(e),    }    let len = u32::from_le_bytes(len) as usize;    if !(9..=MAX_FRAME).contains(&len) {        return Err(io::Error::new(io::ErrorKind::InvalidData, format!("bad frame length {len}")));    }    let mut body = vec![0u8; len];    r.read_exact(&mut body)?;    let kind = body[0];    let id = u32::from_le_bytes([body[1], body[2], body[3], body[4]]);    let json_len = u32::from_le_bytes([body[5], body[6], body[7], body[8]]) as usize;    if json_len > len - 9 {        return Err(io::Error::new(io::ErrorKind::InvalidData, "bad json length"));    }    let bytes = body.split_off(9 + json_len);    let json = body.split_off(9);    Ok(Some(Frame { kind, id, json, bytes }))}/// Whether `module` (a path the app found scanning) lies inside one of `roots`: compared without case, with either/// slash, no "." or ".." anywhere, no colon past the drive letter, and ending in ".vst3". The host loads nothing else,/// whatever it's asked; the app checks the same before it asks.pub fn module_allowed(module: &str, roots: &[String]) -> bool {    let norm = |p: &str| p.replace('\\', "/").trim_end_matches('/').to_lowercase();    let m = norm(module);    let colons = m.match_indices(':').map(|(i, _)| i).collect::<Vec<_>>();    if m.split('/').any(|c| c == "." || c == "..") || !m.ends_with(".vst3") || m.contains('\0') || colons.iter().any(|&i| i != 1) {        return false;    }    roots.iter().any(|r| {        let r = norm(r);        !r.is_empty() && m.len() > r.len() + 1 && m.starts_with(&r) && m.as_bytes()[r.len()] == b'/'    })}/// What the app asks of the host. Instances are the host's own numbers (the app maps the page's to them).#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]#[serde(tag = "op", rename_all = "camelCase")]pub enum Request {    /// First thing: the folders modules may come from (nothing else is ever loaded), and the app's window, which owns    /// the editors.    #[serde(rename_all = "camelCase")]    Hello { version: u32, roots: Vec<String>, owner: u64 },    /// A new instance of class `cid` from the module at `module`, set up for `rate` and blocks of up to `block` frames.    #[serde(rename_all = "camelCase")]    Open { module: String, cid: String, rate: f64, block: u32, offline: bool },    Close { inst: u32 },    /// Shows the editor (titled `title`, at x/y when given) or hides it.    #[serde(rename_all = "camelCase")]    Editor { inst: u32, show: bool, title: String, x: Option<i32>, y: Option<i32> },    GetState { inst: u32 },    /// The state is the frame's bytes.    SetState { inst: u32 },    Params { inst: u32 },    SetParam { inst: u32, id: u32, value: f64 },    /// Flush: setActive(false) and (true), clearing tails and delay lines.    Reset { inst: u32 },    Bypass { inst: u32, on: bool },    /// Serve the ring in this file mapping (a handle already duplicated into the host) to the instance.    #[serde(rename_all = "camelCase")]    Attach { inst: u32, handle: u64, size: u64 },    Detach { inst: u32 },    /// Process `frames` frames of planar stereo f32 (the frame's bytes) and answer with as many.    Render { inst: u32, frames: u32 },    Ping {},}/// The host's answer: `{"ok": ...}` or `{"err": "..."}`.#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]#[serde(rename_all = "camelCase")]pub enum Reply {    Ok(serde_json::Value),    Err(String),}/// What an open instance is like.#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]#[serde(rename_all = "camelCase")]pub struct Opened {    pub inst: u32,    pub name: String,    /// Channels of the plugin's main input and output buses (the page always gets stereo: a mono plugin's input is    /// downmixed and its output doubled).    pub inputs: u32,    pub outputs: u32,    /// Audio buses in all (a side chain is one more input).    pub in_buses: u32,    pub out_buses: u32,    /// IAudioProcessor::getLatencySamples.    pub latency: u32,    pub tail: u32,    pub has_editor: bool,    pub params: u32,    /// The plugin has its own bypass parameter (else bypass is the host's, the dry signal delayed by the latency).    pub bypass_param: bool,}/// One parameter, as the controller describes it.#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]#[serde(rename_all = "camelCase")]pub struct Param {    pub id: u32,    pub title: String,    pub short_title: String,    pub units: String,    pub steps: i32,    pub default: f64,    pub value: f64,    pub display: String,    pub automatable: bool,    pub read_only: bool,    pub hidden: bool,    pub list: bool,    pub bypass: bool,}/// What the host tells the app on its own.#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]#[serde(tag = "ev", rename_all = "camelCase")]pub enum Event {    /// Four times a second from the main thread; `stuck` lists instances whose audio call has run past the limit, and    /// `editors` says how many editor windows are open (the app watches the host more closely while there are some).    Heartbeat {        stuck: Vec<u32>,        #[serde(default)]        editors: u32,    },    /// The plugin's latency changed (restartComponent): it was reactivated and reports this now.    Latency { inst: u32, samples: u32 },    /// An edit in the plugin's own editor (phase 0 begin, 1 value, 2 end).    Param { inst: u32, id: u32, value: f64, phase: i32 },    /// The editor window closed (at x, y) or was moved there.    Editor { inst: u32, open: bool, x: i32, y: i32 },    /// The plugin asked for something to be reread (restartComponent other than latency): parameter values or titles.    Changed { inst: u32, flags: i32 },    /// The plugin asked to have its editor shown.    OpenEditor { inst: u32 },}/// The bytes of a plugin's state as the page keeps them: the component's and the controller's, each with its length,/// after a short header naming the format and the class, so state is never handed to another plugin.////// ```text/// "JWV3" | u32 version 1 | 32 bytes class ID (ASCII hex) | u32 component length | component | u32 controller length | controller/// ```pub mod state {    pub const MAGIC: &[u8; 4] = b"JWV3";    pub fn pack(cid: &str, component: &[u8], controller: &[u8]) -> Vec<u8> {        let mut out = Vec::with_capacity(48 + component.len() + controller.len());        out.extend_from_slice(MAGIC);        out.extend_from_slice(&1u32.to_le_bytes());        let mut id = [b'0'; 32];        for (d, s) in id.iter_mut().zip(cid.bytes()) {            *d = s.to_ascii_uppercase();        }        out.extend_from_slice(&id);        out.extend_from_slice(&(component.len() as u32).to_le_bytes());        out.extend_from_slice(component);        out.extend_from_slice(&(controller.len() as u32).to_le_bytes());        out.extend_from_slice(controller);        out    }    /// The class ID and the two states, if the bytes are a state blob.    pub fn unpack(bytes: &[u8]) -> Result<(String, &[u8], &[u8]), String> {        let bad = || "that isn't a plugin state".to_string();        if bytes.len() < 44 || &bytes[..4] != MAGIC {            return Err(bad());        }        if u32::from_le_bytes(bytes[4..8].try_into().map_err(|_| bad())?) != 1 {            return Err("a plugin state of a newer version".into());        }        let cid = std::str::from_utf8(&bytes[8..40]).map_err(|_| bad())?.to_string();        let mut at = 40;        let mut take = || -> Result<&[u8], String> {            let len = u32::from_le_bytes(bytes.get(at..at + 4).ok_or_else(bad)?.try_into().map_err(|_| bad())?) as usize;            at += 4;            let part = bytes.get(at..at + len).ok_or_else(bad)?;            at += len;            Ok(part)        };        let component = take()?;        let controller = take()?;        Ok((cid, component, controller))    }}#[cfg(test)]mod tests {    use super::*;    #[test]    fn frames_round_trip() {        let frames = [            Frame::new(KIND_REQUEST, 7, &Request::Ping {}, vec![]),            Frame::new(KIND_REQUEST, 8, &Request::Render { inst: 3, frames: 2 }, vec![1, 2, 3, 4, 5, 6, 7, 8]),            Frame::new(KIND_RESPONSE, 8, &Reply::Ok(serde_json::json!({"a": 1})), (0..=255).collect()),            Frame::new(KIND_EVENT, 0, &Event::Heartbeat { stuck: vec![], editors: 1 }, vec![]),        ];        let mut pipe = Vec::new();        for f in &frames {            write_frame(&mut pipe, f).unwrap();        }        let mut r = &pipe[..];        for f in &frames {            assert_eq!(read_frame(&mut r).unwrap().as_ref(), Some(f));        }        // The other side closed between frames: a clean end.        assert_eq!(read_frame(&mut r).unwrap(), None);    }    #[test]    fn a_broken_frame_is_an_error_not_a_guess() {        let mut pipe = Vec::new();        write_frame(&mut pipe, &Frame::new(KIND_REQUEST, 1, &Request::Ping {}, vec![9; 16])).unwrap();        // Cut short: the pipe broke mid-frame.        assert!(read_frame(&mut &pipe[..pipe.len() - 3]).is_err());        // A length past the limit, or too short to hold the header, is refused before anything is allocated.        let mut huge = (MAX_FRAME as u32 + 1).to_le_bytes().to_vec();        huge.extend_from_slice(&[0; 16]);        assert!(read_frame(&mut &huge[..]).is_err());        assert!(read_frame(&mut &[3u8, 0, 0, 0, 1, 1, 1][..]).is_err());        // A JSON length longer than the frame.        let mut lying = Vec::new();        lying.extend_from_slice(&9u32.to_le_bytes());        lying.push(KIND_EVENT);        lying.extend_from_slice(&0u32.to_le_bytes());        lying.extend_from_slice(&100u32.to_le_bytes());        assert!(read_frame(&mut &lying[..]).is_err());    }    #[test]    fn messages_read_as_the_other_side_writes_them() {        let open = Request::Open { module: "C:/x.vst3".into(), cid: "AB".into(), rate: 48000.0, block: 128, offline: false };        let text = serde_json::to_string(&open).unwrap();        assert_eq!(text, r#"{"op":"open","module":"C:/x.vst3","cid":"AB","rate":48000.0,"block":128,"offline":false}"#);        assert_eq!(serde_json::from_str::<Request>(&text).unwrap(), open);        assert_eq!(serde_json::to_string(&Reply::Err("no".into())).unwrap(), r#"{"err":"no"}"#);        assert_eq!(serde_json::from_str::<Reply>(r#"{"ok":{"inst":1}}"#).unwrap(), Reply::Ok(serde_json::json!({"inst": 1})));        let ev = Event::Param { inst: 2, id: 5, value: 0.25, phase: 1 };        assert_eq!(serde_json::to_string(&ev).unwrap(), r#"{"ev":"param","inst":2,"id":5,"value":0.25,"phase":1}"#);        // A heartbeat from a host that doesn't count editors reads as none open.        assert_eq!(serde_json::from_str::<Event>(r#"{"ev":"heartbeat","stuck":[2]}"#).unwrap(), Event::Heartbeat { stuck: vec![2], editors: 0 });        // Unknown operations are refused, not mistaken for another.        assert!(serde_json::from_str::<Request>(r#"{"op":"loadDll","path":"C:/evil.dll"}"#).is_err());    }    #[test]    fn only_modules_inside_the_plugin_folders_load() {        // Made-up folders and modules: the rule is about paths, nothing here touches a disk.        let roots = vec![r"E:\Audio\VST3".to_string(), "D:/Plugins/".to_string()];        for ok in [r"E:\Audio\VST3\Example Audio\Example EQ.vst3", "e:/audio/vst3/Example Tune.vst3", r"D:\Plugins\Some Bundle.vst3"] {            assert!(module_allowed(ok, &roots), "{ok}");        }        for bad in [            r"C:\Windows\System32\evil.vst3",            r"E:\Audio\VST3",            r"E:\Audio\VST3.vst3",            r"E:\Audio\VST3x\a.vst3",            r"E:\Audio\VST3\..\..\x.vst3",            r"E:\Audio\VST3\.\x.vst3",            r"E:\Audio\VST3\x.dll",            r"E:\Audio\VST3\x.vst3:stream.vst3",            "D:/Plugins",            "",        ] {            assert!(!module_allowed(bad, &roots), "{bad}");        }        assert!(!module_allowed("C:/a/b.vst3", &[]), "no folders, nothing loads");        assert!(!module_allowed("C:/a/b.vst3", &["".to_string()]));    }    #[test]    fn state_blobs_name_their_plugin() {        let blob = state::pack("abcdef0123456789abcdef0123456789", b"component", b"ctl");        let (cid, c, t) = state::unpack(&blob).unwrap();        assert_eq!(cid, "ABCDEF0123456789ABCDEF0123456789");        assert_eq!((c, t), (&b"component"[..], &b"ctl"[..]));        // Empty states pack and unpack too.        let empty = state::pack("00", b"", b"");        let (_, c, t) = state::unpack(&empty).unwrap();        assert!(c.is_empty() && t.is_empty());        // Anything else is refused: other bytes, a cut blob, a length running past the end.        assert!(state::unpack(b"not a state at all, not even close to one").is_err());        assert!(state::unpack(&blob[..blob.len() - 1]).is_err());        let mut long = blob.clone();        long[40] = 0xff;        assert!(state::unpack(&long).is_err());    }}