scsynth 0.1.0

A safe Rust wrapper for an embedded, in-process SuperCollider scsynth engine.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! A safe Rust wrapper for an embedded, in-process SuperCollider `scsynth` engine.
//!
//! The engine is created with [`World::new`] from a set of [`Options`]. Commands are sent as raw
//! OSC packets via [`World::send_packet`]; offline (device-free) rendering of a command file to a
//! soundfile is available via [`World::non_realtime_render`]. The engine is torn down on `Drop`.
//!
//! All `unsafe` FFI is confined to [`scsynth_sys`]; this crate exposes only safe abstractions.

use std::collections::VecDeque;
use std::ffi::CString;
use std::os::raw::{c_char, c_int, c_void};
use std::path::Path;
// `ptr` (NRT teardown) is unused on wasm, where there is no non-realtime soundfile path.
#[cfg(not(target_arch = "wasm32"))]
use std::ptr;
use std::sync::Mutex;

use scsynth_sys as sys;

pub use scsynth_sys;

/// Capturing scsynth's process-global diagnostic log output.
///
/// scsynth reports engine diagnostics - startup notices, command failures (the human-readable detail
/// behind a `/fail` reply), `Poll` UGen values, late/encoding warnings - through a single
/// process-global print function (`scprintf` -> `gPrint`). [`capture`](crate::log::capture)
/// redirects that function into an in-process buffer so the host can read those lines rather than
/// having them printed to stdout; this is especially useful on wasm, where stdout goes nowhere.
///
/// Because scsynth's print function is global and carries no per-call context (unlike the reply
/// context threaded through [`World::send_packet`]), capture is **process-wide**: it is shared by
/// every [`World`] and is independent of any one `World`'s lifetime. Enable it once with
/// [`capture`](crate::log::capture); lines accumulate until drained with [`poll`](crate::log::poll),
/// and [`release`](crate::log::release) restores the default (stdout).
pub mod log {
    use std::collections::VecDeque;
    use std::os::raw::{c_char, c_int, c_void};
    use std::sync::{LazyLock, Mutex};

    use super::sys;

    /// Captured log messages, oldest first. `'static`, so the engine's print function may reference
    /// it for the whole process lifetime with no risk of a dangling sink.
    static SINK: LazyLock<Mutex<VecDeque<String>>> = LazyLock::new(|| Mutex::new(VecDeque::new()));

    /// Start redirecting scsynth's log output into the capture buffer. Idempotent and process-wide;
    /// enable it before starting audio so no early messages are missed.
    pub fn capture() {
        // SAFETY: installs a `'static` callback over the `'static` `SINK`; `ctx` is unused (the sink
        // is a Rust global, not threaded through the C side).
        unsafe { sys::scsynth_set_log_func(Some(push), std::ptr::null_mut()) };
    }

    /// Stop capturing and restore scsynth's default (printing to stdout). Already-buffered lines
    /// remain drainable with [`poll`].
    pub fn release() {
        // SAFETY: clears the global print function back to the engine default.
        unsafe { sys::scsynth_set_log_func(None, std::ptr::null_mut()) };
    }

    /// Pop the oldest captured message (one engine `scprintf` call, trailing newlines trimmed), or
    /// `None` if the buffer is empty.
    pub fn poll() -> Option<String> {
        SINK.lock().unwrap().pop_front()
    }

    /// The engine print callback: copy one formatted message into [`SINK`].
    extern "C" fn push(_ctx: *mut c_void, text: *const c_char, len: c_int) {
        if text.is_null() || len <= 0 {
            return;
        }
        // SAFETY: `text` points at `len` bytes valid for this call (the C trampoline's scratchpad);
        // we copy them out before returning.
        let bytes = unsafe { std::slice::from_raw_parts(text as *const u8, len as usize) };
        let msg = String::from_utf8_lossy(bytes);
        SINK.lock()
            .unwrap()
            .push_back(msg.trim_end_matches('\n').to_string());
    }
}

/// Thread-safe queue of raw reply OSC packets captured from the engine.
///
/// A `Mutex` is sufficient: native replies arrive on scsynth's NRT helper thread (not the audio
/// thread), and wasm replies arrive inline on the caller's thread, so the lock is never contended
/// on the realtime path.
type ReplySink = Mutex<VecDeque<Vec<u8>>>;

/// Errors that can arise when driving the engine.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// `World_New` returned a null pointer (e.g. allocation failed or options were invalid).
    #[error("World_New returned null - the engine could not be created")]
    WorldNew,
    /// A path contained an interior NUL byte and could not be passed to the C API.
    #[error("path contained an interior NUL byte")]
    Nul(#[from] std::ffi::NulError),
    /// The soundbuffer index passed to [`World::copy_buffer`] was out of range.
    #[error("soundbuffer index {0} is out of range")]
    BufferIndexOutOfRange(u32),
}

/// A snapshot of an engine soundbuffer's contents, read back by [`World::copy_buffer`].
pub struct Buffer {
    /// Interleaved samples, length `channels * frames`.
    pub data: Vec<f32>,
    /// Number of channels (the interleave stride of `data`).
    pub channels: usize,
    /// Number of frames (samples per channel).
    pub frames: usize,
}

/// Builder for the engine's [`sys::WorldOptions`].
///
/// Starts from the engine's own C++ defaults (via the `scsynth_sys` shim) so every field has a
/// sensible value; only the knobs we care about are exposed as setters.
///
/// Not `Clone`: the raw options hold `const char*` pointers into the owned `CString` fields, so a
/// shallow copy would dangle. [`World`] takes ownership to keep those backings alive.
pub struct Options {
    raw: sys::WorldOptions,
    // Owned C strings backing the `const char*` option fields, kept alive for as long as the
    // options (and any `World`/render driven from them) are in use.
    cmd_filename: Option<CString>,
    input_filename: Option<CString>,
    output_filename: Option<CString>,
    output_header_format: Option<CString>,
    output_sample_format: Option<CString>,
}

/// A handle to a running, in-process `scsynth` engine ("World").
pub struct World {
    inner: *mut sys::World,
    // Kept alive for the engine's lifetime: backs the options' `const char*` fields and is reused
    // by [`World::non_realtime_render`]. On wasm there is no NRT render and the shim does not retain
    // any option pointers, so this is read only to keep those backings owned for as long as the
    // world - hence the wasm-only `dead_code` allow.
    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
    options: Options,
    // Captured OSC replies (`/done`, `/fail`, `/n_end`, `/tr`, ...). `Box`ed for a stable address:
    // its pointer is handed to the engine as the reply context and read back in [`reply_to_sink`].
    replies: Box<ReplySink>,
}

impl Default for Options {
    fn default() -> Self {
        let mut raw = std::mem::MaybeUninit::<sys::WorldOptions>::uninit();
        // SAFETY: the shim fully initialises the struct via its C++ default constructor.
        let raw = unsafe {
            sys::scsynth_default_world_options(raw.as_mut_ptr());
            raw.assume_init()
        };
        Options {
            raw,
            cmd_filename: None,
            input_filename: None,
            output_filename: None,
            output_header_format: None,
            output_sample_format: None,
        }
    }
}

impl Options {
    /// Default options (the engine's own defaults).
    pub fn new() -> Self {
        Self::default()
    }

    /// Whether the engine runs in real time (`true`) or is driven offline (`false`).
    pub fn real_time(mut self, real_time: bool) -> Self {
        self.raw.mRealTime = real_time;
        self
    }

    /// Number of output bus channels (e.g. `1` for mono, `2` for stereo).
    pub fn output_channels(mut self, channels: u32) -> Self {
        self.raw.mNumOutputBusChannels = channels;
        self
    }

    /// Number of input bus channels.
    pub fn input_channels(mut self, channels: u32) -> Self {
        self.raw.mNumInputBusChannels = channels;
        self
    }

    /// The preferred sample rate in Hz (used directly for offline rendering).
    pub fn sample_rate(mut self, sample_rate: u32) -> Self {
        self.raw.mPreferredSampleRate = sample_rate;
        self
    }

    /// The control block size in frames (default 64).
    pub fn block_size(mut self, frames: u32) -> Self {
        self.raw.mBufLength = frames;
        self
    }

    /// Verbosity of the engine's logging (`-1` silences it).
    pub fn verbosity(mut self, verbosity: i32) -> Self {
        self.raw.mVerbosity = verbosity;
        self
    }

    /// Whether to scan for and load synthdefs from disk on startup (default `true`).
    pub fn load_synthdefs(mut self, load: bool) -> Self {
        self.raw.mLoadGraphDefs = u32::from(load);
        self
    }

    /// The non-realtime OSC command file to read (`[u32 BE len][OSC bundle]` records).
    pub fn nrt_command_file(mut self, path: impl AsRef<Path>) -> Result<Self, Error> {
        let s = path_to_cstring(path)?;
        self.raw.mNonRealTimeCmdFilename = s.as_ptr();
        self.cmd_filename = Some(s);
        Ok(self)
    }

    /// The non-realtime input soundfile (optional).
    pub fn nrt_input_file(mut self, path: impl AsRef<Path>) -> Result<Self, Error> {
        let s = path_to_cstring(path)?;
        self.raw.mNonRealTimeInputFilename = s.as_ptr();
        self.input_filename = Some(s);
        Ok(self)
    }

    /// The non-realtime output soundfile, with libsndfile header and sample formats
    /// (e.g. `"WAV"` and `"int16"`).
    pub fn nrt_output_file(
        mut self,
        path: impl AsRef<Path>,
        header_format: &str,
        sample_format: &str,
    ) -> Result<Self, Error> {
        let path = path_to_cstring(path)?;
        let header = CString::new(header_format)?;
        let sample = CString::new(sample_format)?;
        self.raw.mNonRealTimeOutputFilename = path.as_ptr();
        self.raw.mNonRealTimeOutputHeaderFormat = header.as_ptr();
        self.raw.mNonRealTimeOutputSampleFormat = sample.as_ptr();
        self.output_filename = Some(path);
        self.output_header_format = Some(header);
        self.output_sample_format = Some(sample);
        Ok(self)
    }
}

impl World {
    /// Create a new engine from the given options. The engine takes ownership of the options so
    /// the `CString` backings for any non-realtime filenames stay valid for rendering.
    ///
    /// Plugin registration (the static UGen `*_Load` functions) runs inside `World_New`.
    ///
    /// On wasm the engine has no audio device or threads, so it runs driverless: the shim forces
    /// `real_time` to `false` (and `load_synthdefs` to `false`) regardless of the options, and
    /// starts the world for synchronous, host-pumped rendering.
    pub fn new(mut options: Options) -> Result<Self, Error> {
        // SAFETY: `options.raw` is fully initialised; the constructor copies what it needs.
        // Native builds a realtime/NRT world directly; wasm routes through the driverless shim.
        #[cfg(not(target_arch = "wasm32"))]
        let inner = unsafe { sys::World_New(&mut options.raw) };
        #[cfg(target_arch = "wasm32")]
        let inner = unsafe { sys::scsynth_wasm_new(&mut options.raw) };
        if inner.is_null() {
            return Err(Error::WorldNew);
        }
        let replies = Box::new(ReplySink::default());
        Ok(World {
            inner,
            options,
            replies,
        })
    }

    /// Send a raw OSC packet to the engine in-process (no socket).
    ///
    /// Any replies the engine emits in response (`/done`, `/fail`, node notifications like
    /// `/n_end`, trigger messages `/tr`, ...) are captured and can be drained with
    /// [`World::poll_reply`].
    ///
    /// On native the packet is queued to the engine's command FIFO and processed on its NRT helper
    /// thread (driven by [`World::process`]), so replies arrive asynchronously - pump and poll until
    /// the reply you want appears. On wasm the packet is dispatched synchronously: `/d_recv`,
    /// `/s_new` etc. complete in full (and any replies are already queued) before this returns.
    pub fn send_packet(&self, packet: &[u8]) {
        let len = c_int::try_from(packet.len()).expect("packet too large");
        let ctx = &*self.replies as *const ReplySink as *mut c_void;
        // SAFETY: `inner` is a valid world; the buffer lives for the duration of the call, and
        // `ctx` points at `self.replies`, which (being `Box`ed and owned by `self`) outlives every
        // reply the engine will deliver against this world. `reply_to_sink` reads `ctx` back as a
        // `&ReplySink`.
        //
        // Native: `World_SendPacketWithContext` takes a mutable `char*` and copies it into the
        // command FIFO, so we hand it an owned copy. Wasm: the shim copies internally, so the slice
        // goes directly.
        #[cfg(not(target_arch = "wasm32"))]
        {
            let mut buf = packet.to_vec();
            unsafe {
                sys::World_SendPacketWithContext(
                    self.inner,
                    len,
                    buf.as_mut_ptr() as *mut c_char,
                    Some(reply_to_sink),
                    ctx,
                );
            }
        }
        #[cfg(target_arch = "wasm32")]
        unsafe {
            sys::scsynth_wasm_perform(self.inner, packet.as_ptr(), len, Some(reply_to_sink), ctx);
        }
    }

    /// Pop the next captured reply OSC packet, or `None` if none are queued.
    ///
    /// Returns the raw OSC bytes exactly as the engine emitted them (a `/done`, `/fail`, `/n_end`,
    /// `/tr`, ...); decode them with an OSC library such as `rosc`. Replies are queued in arrival
    /// order by the reply path set up in [`World::send_packet`].
    ///
    /// On native, replies are produced on scsynth's NRT helper thread, so a reply for a command may
    /// not be queued until one or more [`World::process`] calls have driven that thread; loop
    /// pump-then-poll until the expected reply arrives. On wasm, replies are queued synchronously
    /// during `send_packet`.
    pub fn poll_reply(&self) -> Option<Vec<u8>> {
        self.replies.lock().unwrap().pop_front()
    }

    /// Pump `output.len() / output_channels` frames of synthesis through the engine, reading
    /// interleaved `input` (use `&[]` with `input_channels = 0` for none) and writing interleaved
    /// `output`. This is the host-driven realtime path: call it from any audio loop (a `cpal`
    /// callback, JACK, a test, ...). Requires the engine to have been created with
    /// [`Options::real_time`]`(true)`.
    ///
    /// For sample-accurate behaviour `output.len() / output_channels` should be a whole multiple
    /// of the world's block size (default 64); any trailing frames are zeroed.
    pub fn process(
        &mut self,
        input: &[f32],
        input_channels: usize,
        output: &mut [f32],
        output_channels: usize,
    ) {
        let num_frames = output.len().checked_div(output_channels).unwrap_or(0);
        // SAFETY: `inner` is a valid world; the slices outlive the call and the channel
        // counts/length describe the interleaved buffers. Native uses the host-pumped external
        // driver; wasm uses the driverless pump shim - same signature and semantics.
        #[cfg(not(target_arch = "wasm32"))]
        unsafe {
            sys::scsynth_pump(
                self.inner,
                input.as_ptr(),
                input_channels as c_int,
                output.as_mut_ptr(),
                output_channels as c_int,
                num_frames as c_int,
            );
        }
        #[cfg(target_arch = "wasm32")]
        unsafe {
            sys::scsynth_wasm_pump(
                self.inner,
                input.as_ptr(),
                input_channels as c_int,
                output.as_mut_ptr(),
                output_channels as c_int,
                num_frames as c_int,
            );
        }
    }

    /// Read back the current contents of soundbuffer `index` (allocated with `/b_alloc`, filled by
    /// `/b_gen`, `/b_setn`, recording, ...).
    ///
    /// Returns the interleaved samples plus the channel and frame counts. The snapshot is taken via
    /// `World_CopySndBuf`: on native under the engine's NRT lock (consistent with the audio thread);
    /// on wasm the single-threaded engine is read directly. An out-of-range `index` yields
    /// [`Error::BufferIndexOutOfRange`]; an allocated-but-empty buffer yields an empty [`Buffer`].
    pub fn copy_buffer(&self, index: u32) -> Result<Buffer, Error> {
        let mut out: Option<Buffer> = None;
        let ctx = &mut out as *mut Option<Buffer> as *mut c_void;
        // SAFETY: `inner` is a valid world; `copy_buffer_to` writes only through `ctx` (a live
        // `&mut Option<Buffer>`) for the duration of the call, copying the engine-owned samples out
        // before the shim frees them. A non-zero return means the copy did not happen.
        let err = unsafe { sys::scsynth_copy_buffer(self.inner, index, Some(copy_buffer_to), ctx) };
        if err != 0 {
            return Err(Error::BufferIndexOutOfRange(index));
        }
        Ok(out.unwrap_or(Buffer {
            data: Vec::new(),
            channels: 0,
            frames: 0,
        }))
    }

    /// Run offline (non-realtime) synthesis, reading the command file and rendering to the output
    /// soundfile configured on the options this engine was created with. Requires options built
    /// with [`Options::real_time`]`(false)` and [`Options::nrt_command_file`] /
    /// [`Options::nrt_output_file`].
    ///
    /// This consumes the engine: `World_NonRealTimeSynthesis` tears the world down internally
    /// (it calls `World_Cleanup`), so the handle must not be reused or cleaned up again.
    ///
    /// Not available on wasm: it renders to a soundfile via libsndfile, which is not built for that
    /// target. Use [`World::process`] to render audio on wasm.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn non_realtime_render(mut self) {
        // SAFETY: `inner` is a valid world and `self.options` (with its live C strings) outlives
        // the call.
        unsafe { sys::World_NonRealTimeSynthesis(self.inner, &mut self.options.raw) };
        // The engine already freed the world; null it so our `Drop` does not free it again.
        self.inner = ptr::null_mut();
    }
}

impl Drop for World {
    fn drop(&mut self) {
        if self.inner.is_null() {
            return;
        }
        // SAFETY: `inner` was returned by `World_New` and is dropped exactly once. Pass
        // `unload_plugins = false` (the C++ default) for a normal teardown.
        unsafe { sys::World_Cleanup(self.inner, false) };
    }
}

/// The engine's reply callback: copy each reply OSC packet into the [`ReplySink`] carried as the
/// reply address's context. Used as the `ReplyFunc` on both targets.
extern "C" fn reply_to_sink(addr: *mut sys::ReplyAddress, buf: *mut c_char, size: c_int) {
    // SAFETY: `addr` is a valid `ReplyAddress` whose `mReplyData` we set (in `send_packet`) to a
    // pointer to a live `ReplySink`. `scsynth_reply_context` reads that pointer back without Rust
    // naming the opaque struct's fields.
    let ctx = unsafe { sys::scsynth_reply_context(addr) };
    if ctx.is_null() || buf.is_null() || size <= 0 {
        return;
    }
    // SAFETY: `ctx` is the `&ReplySink` we handed the engine, which outlives every reply (it is
    // owned, boxed, by the `World`). `buf`/`size` describe a valid OSC packet the engine owns for
    // the duration of this call; we copy it out before returning.
    let sink = unsafe { &*(ctx as *const ReplySink) };
    let bytes = unsafe { std::slice::from_raw_parts(buf as *const u8, size as usize) }.to_vec();
    sink.lock().unwrap().push_back(bytes);
}

/// Collect a copied soundbuffer's samples into the `Option<Buffer>` carried as `ctx`. Used as the
/// `ScBufferFunc` for [`World::copy_buffer`] on both targets.
extern "C" fn copy_buffer_to(
    ctx: *mut c_void,
    data: *const f32,
    num_samples: c_int,
    num_channels: c_int,
    num_frames: c_int,
) {
    if ctx.is_null() {
        return;
    }
    // SAFETY: `ctx` is the `&mut Option<Buffer>` `copy_buffer` handed the shim, live for the call.
    let out = unsafe { &mut *(ctx as *mut Option<Buffer>) };
    let samples = num_samples.max(0) as usize;
    let data = if data.is_null() || samples == 0 {
        Vec::new()
    } else {
        // SAFETY: `data` points at `samples` engine-owned floats, valid until this call returns.
        unsafe { std::slice::from_raw_parts(data, samples) }.to_vec()
    };
    *out = Some(Buffer {
        data,
        channels: num_channels.max(0) as usize,
        frames: num_frames.max(0) as usize,
    });
}

/// Convert a path to a `CString`, erroring on interior NUL bytes.
fn path_to_cstring(path: impl AsRef<Path>) -> Result<CString, Error> {
    Ok(CString::new(path.as_ref().to_string_lossy().into_owned())?)
}