Repository Public
1//! ORIX Sonata2//! File: crates/sonata-ffi/src/engine.rs3//! Description: C ABI of the real-time engine: process callback, transport, mixer, audition,4//! meters, scope tap and statistics.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use crate::compiler::SonataCompiler;10use crate::util::{error_json, give_json, guard, guard_json};11use sonata_ir::Strip;12use sonata_runtime::{engine, Controller, EngineConfig, Limits, PreparedProgram, Processor, TapPoint};13use std::cell::UnsafeCell;14use std::ffi::c_char;15use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering::Relaxed};16use std::sync::Mutex;1718/// Reader-side loudness state, fed from the master scope ring when statistics are requested.19struct Loudness {20 meter: crate::analysis::LiveLoudness,21 /// Scope frame counter up to which the meter has been fed.22 fed: u64,23 left: Vec<f32>,24 right: Vec<f32>,25}2627pub struct SonataEngine {28 controller: Controller,29 /// Touched only by the single real-time thread (contract of `sonata_engine_process`).30 processor: UnsafeCell<Processor>,31 sample_rate: u32,32 max_block: usize,33 next_note: AtomicU64,34 /// Monitor gain target (linear, f32 bits) and the value reached by the audio thread.35 monitor_target: AtomicU32,36 monitor_current: UnsafeCell<f32>,37 faulted: AtomicBool,38 peak_voices: AtomicU32,39 count_in_bars: AtomicU32,40 /// Samples clamped by the monitor stage.41 clamped: AtomicU64,42 /// Strip counts of the loaded program: (tracks, buses).43 strips: Mutex<(Vec<u32>, Vec<u32>)>,44 loudness: Mutex<Loudness>,45}4647// SAFETY: `processor` and `monitor_current` are only accessed from the one thread that calls48// `sonata_engine_process`; everything else is atomics, mutexes or the thread-safe Controller.49unsafe impl Sync for SonataEngine {}50unsafe impl Send for SonataEngine {}5152fn strip_of(kind: i32, id: u32) -> Strip {53 match kind {54 0 => Strip::Track(id),55 1 => Strip::Bus(id),56 _ => Strip::Master,57 }58}5960/// # Safety61/// The returned pointer must be released with `sonata_engine_free`.62#[no_mangle]63pub extern "C" fn sonata_engine_new(sample_rate: f64, max_block_frames: u32) -> *mut SonataEngine {64 let rate = if sample_rate.is_finite() { (sample_rate.round() as i64).clamp(8_000, 384_000) as u32 } else { 48_000 };65 let (controller, processor) = engine(EngineConfig::realtime(rate));66 let seconds = 12usize;67 Box::into_raw(Box::new(SonataEngine {68 controller,69 processor: UnsafeCell::new(processor),70 sample_rate: rate,71 max_block: (max_block_frames as usize).clamp(16, 1 << 16),72 next_note: AtomicU64::new(1 << 62),73 monitor_target: AtomicU32::new(1.0f32.to_bits()),74 monitor_current: UnsafeCell::new(1.0),75 faulted: AtomicBool::new(false),76 peak_voices: AtomicU32::new(0),77 count_in_bars: AtomicU32::new(0),78 clamped: AtomicU64::new(0),79 strips: Mutex::new((Vec::new(), Vec::new())),80 loudness: Mutex::new(Loudness {81 meter: crate::analysis::LiveLoudness::new(rate as f64),82 fed: 0,83 left: vec![0.0; rate as usize * seconds / 4],84 right: vec![0.0; rate as usize * seconds / 4],85 }),86 }))87}8889/// # Safety90/// `engine` must come from `sonata_engine_new`, no thread may be inside `sonata_engine_process`.91#[no_mangle]92pub unsafe extern "C" fn sonata_engine_free(engine: *mut SonataEngine) {93 if !engine.is_null() {94 drop(Box::from_raw(engine));95 }96}9798/// # Safety99/// Valid engine and compiler pointers; the compiler must not be used concurrently.100#[no_mangle]101pub unsafe extern "C" fn sonata_engine_load(engine: *mut SonataEngine, compiler: *mut SonataCompiler) -> *mut c_char {102 let (Some(e), Some(c)) = (engine.as_ref(), compiler.as_mut()) else { return error_json("null pointer") };103 guard_json(|| {104 let started = std::time::Instant::now();105 let Some(program) = c.program() else { return error_json("there is no compiled program to load") };106 let graph = match crate::compiler::build_graph(program, e.sample_rate) {107 Ok(g) => g,108 Err(m) => return error_json(m),109 };110 let assets = c.asset_provider();111 let prepared = match PreparedProgram::prepare(program, &graph, e.sample_rate, e.max_block, &assets, &Limits::default()) {112 Ok(p) => p,113 Err(m) => return error_json(m),114 };115 let info = prepared.info().clone();116 if e.controller.load(prepared).is_err() {117 return error_json("the engine is still swapping previous programs; try again in a moment");118 }119 if let Ok(mut s) = e.strips.lock() {120 s.0 = program.tracks.iter().map(|t| t.id).collect();121 s.1 = program.buses.iter().map(|b| b.id).collect();122 }123 give_json(&serde_json::json!({124 "ok": true,125 "prepare_us": started.elapsed().as_secs_f64() * 1e6,126 "voices": Limits::default().max_voices,127 "nodes": info.nodes,128 "latency_frames": info.total_latency,129 "estimated_bytes": info.estimated_bytes,130 }))131 })132}133134/// RT. Fills `frames` stereo frames.135///136/// # Safety137/// `left` and `right` must each be valid for `frames` floats; one thread at a time.138#[no_mangle]139pub unsafe extern "C" fn sonata_engine_process(engine: *mut SonataEngine, left: *mut f32, right: *mut f32, frames: u32) {140 if left.is_null() || right.is_null() || frames == 0 {141 return;142 }143 let l = std::slice::from_raw_parts_mut(left, frames as usize);144 let r = std::slice::from_raw_parts_mut(right, frames as usize);145 let Some(e) = engine.as_ref() else {146 l.fill(0.0);147 r.fill(0.0);148 return;149 };150 if e.faulted.load(Relaxed) {151 l.fill(0.0);152 r.fill(0.0);153 return;154 }155 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {156 let p = &mut *e.processor.get();157 p.process(l, r);158 }));159 if result.is_err() {160 // A bug in the engine must never become noise: silence from now on, reported in the stats.161 e.faulted.store(true, Relaxed);162 l.fill(0.0);163 r.fill(0.0);164 return;165 }166 // Monitor gain: linear ramp across the block to the target, then a final safety clamp.167 let target = f32::from_bits(e.monitor_target.load(Relaxed));168 let cur = &mut *e.monitor_current.get();169 let step = (target - *cur) / frames as f32;170 let mut g = *cur;171 let mut clamped = 0u64;172 if (target - 1.0).abs() > 1e-6 || step.abs() > 1e-9 {173 for i in 0..frames as usize {174 g += step;175 l[i] *= g;176 r[i] *= g;177 }178 }179 *cur = target;180 for i in 0..frames as usize {181 if l[i].abs() > 1.0 || r[i].abs() > 1.0 {182 clamped += 1;183 l[i] = l[i].clamp(-1.0, 1.0);184 r[i] = r[i].clamp(-1.0, 1.0);185 }186 }187 if clamped > 0 {188 e.clamped.fetch_add(clamped, Relaxed);189 }190 let v = e.controller.shared().active_voices();191 if v > e.peak_voices.load(Relaxed) {192 e.peak_voices.store(v, Relaxed);193 }194}195196macro_rules! with_engine {197 ($engine:expr, $e:ident => $body:expr) => {198 // SAFETY: the caller passes NULL or a live engine (header contract).199 if let Some($e) = unsafe { $engine.as_ref() } {200 guard((), || $body)201 }202 };203}204205#[no_mangle]206pub extern "C" fn sonata_engine_play(engine: *mut SonataEngine) {207 with_engine!(engine, e => {208 let bars = e.count_in_bars.load(Relaxed);209 if bars > 0 { e.controller.play_with_count_in(bars) } else { e.controller.play() }210 });211}212213#[no_mangle]214pub extern "C" fn sonata_engine_pause(engine: *mut SonataEngine) {215 with_engine!(engine, e => e.controller.pause());216}217218#[no_mangle]219pub extern "C" fn sonata_engine_stop(engine: *mut SonataEngine) {220 with_engine!(engine, e => e.controller.stop());221}222223#[no_mangle]224pub extern "C" fn sonata_engine_seek(engine: *mut SonataEngine, seconds: f64) {225 with_engine!(engine, e => e.controller.seek_seconds(if seconds.is_finite() { seconds.max(0.0) } else { 0.0 }));226}227228#[no_mangle]229pub extern "C" fn sonata_engine_set_loop(engine: *mut SonataEngine, enabled: bool, start_seconds: f64, end_seconds: f64) {230 with_engine!(engine, e => {231 let ok = enabled && start_seconds.is_finite() && end_seconds.is_finite() && end_seconds > start_seconds && start_seconds >= 0.0;232 let range = ok.then(|| (sonata_ir::seconds_to_samples(start_seconds, e.sample_rate), sonata_ir::seconds_to_samples(end_seconds, e.sample_rate))).filter(|(a, b)| b > a);233 e.controller.set_loop(range);234 });235}236237#[no_mangle]238pub extern "C" fn sonata_engine_set_metronome(engine: *mut SonataEngine, enabled: bool, gain_db: f32, count_in_bars: u32) {239 with_engine!(engine, e => {240 e.controller.set_metronome(enabled, if gain_db.is_finite() { gain_db.clamp(-60.0, 0.0) } else { -12.0 });241 e.count_in_bars.store(count_in_bars.min(8), Relaxed);242 });243}244245#[no_mangle]246pub extern "C" fn sonata_engine_position(engine: *const SonataEngine) -> f64 {247 // SAFETY: NULL or live engine.248 unsafe { engine.as_ref() }.map(|e| e.controller.shared().position_seconds()).unwrap_or(0.0)249}250251#[no_mangle]252pub extern "C" fn sonata_engine_state(engine: *const SonataEngine) -> i32 {253 // SAFETY: NULL or live engine.254 match unsafe { engine.as_ref() }.map(|e| e.controller.shared().transport_state()) {255 Some(sonata_runtime::TransportState::Playing) | Some(sonata_runtime::TransportState::CountIn) => 1,256 Some(sonata_runtime::TransportState::Paused) => 2,257 _ => 0,258 }259}260261#[no_mangle]262pub extern "C" fn sonata_engine_duration(engine: *const SonataEngine) -> f64 {263 // SAFETY: NULL or live engine.264 unsafe { engine.as_ref() }.map(|e| e.controller.shared().end_samples() as f64 / e.sample_rate as f64).unwrap_or(0.0)265}266267#[no_mangle]268pub extern "C" fn sonata_engine_set_strip(engine: *mut SonataEngine, strip_kind: i32, strip_id: u32, param: i32, value: f32) {269 with_engine!(engine, e => {270 if !value.is_finite() {271 return;272 }273 let s = strip_of(strip_kind, strip_id);274 match param {275 0 => e.controller.set_gain_db(s, Some(value.clamp(-144.0, 24.0))),276 1 => e.controller.set_pan(s, Some(value.clamp(-1.0, 1.0))),277 2 => e.controller.set_mute(s, Some(value >= 0.5)),278 3 => e.controller.set_solo(s, Some(value >= 0.5)),279 _ => {}280 }281 });282}283284#[no_mangle]285pub extern "C" fn sonata_engine_set_monitor_gain(engine: *mut SonataEngine, gain_db: f32) {286 with_engine!(engine, e => {287 let db = if gain_db.is_finite() { gain_db.clamp(-120.0, 0.0) } else { 0.0 };288 let lin = if db <= -119.9 { 0.0 } else { 10f32.powf(db / 20.0) };289 e.monitor_target.store(lin.to_bits(), Relaxed);290 });291}292293#[no_mangle]294pub extern "C" fn sonata_engine_note_on(engine: *mut SonataEngine, track_id: u32, midi_pitch: f32, velocity: f32) -> u64 {295 // SAFETY: NULL or live engine.296 let Some(e) = (unsafe { engine.as_ref() }) else { return 0 };297 guard(0, || {298 if !midi_pitch.is_finite() || !velocity.is_finite() {299 return 0;300 }301 let id = e.next_note.fetch_add(1, Relaxed);302 e.controller.note_on(track_id, id, midi_pitch.clamp(0.0, 127.0), velocity.clamp(0.0, 1.0));303 id304 })305}306307#[no_mangle]308pub extern "C" fn sonata_engine_note_off(engine: *mut SonataEngine, track_id: u32, note_id: u64) {309 with_engine!(engine, e => e.controller.note_off(track_id, note_id));310}311312#[no_mangle]313pub extern "C" fn sonata_engine_all_notes_off(engine: *mut SonataEngine) {314 with_engine!(engine, e => e.controller.all_notes_off());315}316317#[repr(C)]318#[derive(Clone, Copy, Default)]319pub struct SonataMeter {320 pub strip_kind: i32,321 pub strip_id: u32,322 pub peak_left: f32,323 pub peak_right: f32,324 pub rms_left: f32,325 pub rms_right: f32,326}327328/// # Safety329/// `meters` must be valid for `capacity` entries (or NULL with capacity 0).330#[no_mangle]331pub unsafe extern "C" fn sonata_engine_meters(engine: *mut SonataEngine, meters: *mut SonataMeter, capacity: usize) -> usize {332 let Some(e) = engine.as_ref() else { return 0 };333 guard(0, || {334 e.controller.collect_garbage();335 let (tracks, buses) = e.strips.lock().map(|s| s.clone()).unwrap_or_default();336 let total = tracks.len() + buses.len() + 1;337 if meters.is_null() || capacity < total {338 // Not enough room: report the size and leave the peaks unread.339 return total;340 }341 let out = std::slice::from_raw_parts_mut(meters, capacity);342 let strips =343 tracks.iter().map(|t| (0, *t, Strip::Track(*t))).chain(buses.iter().map(|b| (1, *b, Strip::Bus(*b)))).chain(std::iter::once((2, 0, Strip::Master)));344 for (slot, (kind, id, strip)) in out.iter_mut().zip(strips) {345 let m = e.controller.shared().meter(strip);346 *slot = SonataMeter { strip_kind: kind, strip_id: id, peak_left: m.peak_l, peak_right: m.peak_r, rms_left: m.rms_l, rms_right: m.rms_r };347 }348 total349 })350}351352#[no_mangle]353pub extern "C" fn sonata_engine_set_tap(engine: *mut SonataEngine, strip_kind: i32, strip_id: u32) {354 with_engine!(engine, e => e.controller.set_tap(match strip_kind {355 0 => TapPoint::Track(strip_id),356 1 => TapPoint::Bus(strip_id),357 3 => TapPoint::Instrument(strip_id),358 _ => TapPoint::Master,359 }));360}361362/// # Safety363/// `left` and `right` must be valid for `frames` floats.364#[no_mangle]365pub unsafe extern "C" fn sonata_engine_read_tap(engine: *mut SonataEngine, left: *mut f32, right: *mut f32, frames: usize) -> usize {366 let Some(e) = engine.as_ref() else { return 0 };367 if left.is_null() || right.is_null() || frames == 0 {368 return 0;369 }370 guard(0, || {371 let n = frames.min(sonata_runtime::SCOPE_FRAMES / 2);372 let l = std::slice::from_raw_parts_mut(left, n);373 let r = std::slice::from_raw_parts_mut(right, n);374 e.controller.shared().tap_scope().read_latest(l, r);375 n376 })377}378379#[no_mangle]380pub extern "C" fn sonata_engine_tap_frames(engine: *const SonataEngine) -> u64 {381 // SAFETY: NULL or live engine.382 unsafe { engine.as_ref() }.map(|e| e.controller.shared().tap_scope().frames_written()).unwrap_or(0)383}384385#[repr(C)]386#[derive(Clone, Copy, Default)]387pub struct SonataEngineStats {388 pub callbacks: u64,389 pub mean_us: f64,390 pub p50_us: f64,391 pub p95_us: f64,392 pub p99_us: f64,393 pub max_us: f64,394 pub overruns: u64,395 pub budget_us: f64,396 pub active_voices: u32,397 pub peak_voices: u32,398 pub lufs_momentary: f64,399 pub lufs_short_term: f64,400 pub lufs_integrated: f64,401 pub true_peak_db: f64,402 pub scrubbed_samples: u64,403 pub clamped_samples: u64,404}405406/// # Safety407/// `stats` must be valid for one `SonataEngineStats`.408#[no_mangle]409pub unsafe extern "C" fn sonata_engine_stats(engine: *mut SonataEngine, stats: *mut SonataEngineStats) {410 let (Some(e), Some(out)) = (engine.as_ref(), stats.as_mut()) else { return };411 guard((), || {412 let sh = e.controller.shared();413 let t = sh.timing();414 *out = SonataEngineStats {415 callbacks: t.callbacks,416 mean_us: t.mean_us,417 p50_us: t.p50_us,418 p95_us: t.p95_us,419 p99_us: t.p99_us,420 max_us: t.max_us,421 overruns: t.missed_deadlines + sh.underruns(),422 budget_us: 0.0,423 active_voices: sh.active_voices(),424 peak_voices: e.peak_voices.load(Relaxed),425 lufs_momentary: f64::NEG_INFINITY,426 lufs_short_term: f64::NEG_INFINITY,427 lufs_integrated: f64::NEG_INFINITY,428 true_peak_db: f64::NEG_INFINITY,429 scrubbed_samples: sh.scrubbed_samples() + if e.faulted.load(Relaxed) { 1 } else { 0 },430 clamped_samples: e.clamped.load(Relaxed),431 };432 // Feed the loudness meter with the master frames produced since the previous call.433 if let Ok(mut guard) = e.loudness.lock() {434 let lo = &mut *guard;435 let ring = sh.master_scope();436 let now = ring.frames_written();437 let fresh = (now.saturating_sub(lo.fed) as usize).min(lo.left.len());438 if fresh > 0 {439 let (l, r) = (&mut lo.left[..fresh], &mut lo.right[..fresh]);440 let end = ring.read_latest(l, r);441 lo.fed = end;442 lo.meter.push(&lo.left[..fresh], &lo.right[..fresh]);443 }444 let (m, s, i, tp) = lo.meter.read();445 out.lufs_momentary = m;446 out.lufs_short_term = s;447 out.lufs_integrated = i;448 out.true_peak_db = tp;449 }450 })451}452453#[no_mangle]454pub extern "C" fn sonata_engine_reset_stats(engine: *mut SonataEngine) {455 with_engine!(engine, e => {456 e.controller.shared().reset_timing();457 e.peak_voices.store(0, Relaxed);458 e.clamped.store(0, Relaxed);459 if let Ok(mut lo) = e.loudness.lock() {460 lo.meter = crate::analysis::LiveLoudness::new(e.sample_rate as f64);461 lo.fed = e.controller.shared().master_scope().frames_written();462 }463 });464}465