SPB Git

Repository Public

compiler.rs 21.1 KB 462 lines rust

1//! ORIX Sonata2//! File: crates/sonata-ffi/src/compiler.rs3//! Description: C ABI of a compiler session: compile with overrides, keep the last valid program,4//! editor queries, JSON exports, MIDI/MusicXML export, MIDI import and offline rendering.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use crate::adapter::{self, ModuleSource, RenderRequest};10use crate::analysis::num;11use crate::timeline::timeline_json;12use crate::util::{error_json, give, give_json, guard_json, text};13use serde_json::{json, Value};14use sonata_ir::{Diagnostic, DspGraph, LineIndex, Overrides, Program, Registry, Severity, Span};15use sonata_runtime::{AssetProvider, AudioAsset};16use std::collections::BTreeMap;17use std::ffi::{c_char, c_void};18use std::path::{Path, PathBuf};19use std::sync::{Arc, Mutex};2021pub fn registry() -> &'static Registry {22    adapter::registry()23}2425pub fn build_graph(program: &Program, sample_rate: u32) -> Result<DspGraph, String> {26    adapter::build_graph(program, sample_rate)27}2829/// Loads the audio assets of a project from `<root>/assets`, decoded once and shared.30pub struct ProjectAssets {31    root: Option<PathBuf>,32    cache: Arc<Mutex<BTreeMap<String, Arc<AudioAsset>>>>,33}3435/// An asset name is a plain relative path: no absolute path, no `..`, no backslash.36pub fn safe_asset_name(name: &str) -> bool {37    !name.is_empty()38        && !name.starts_with('/')39        && !name.contains('\\')40        && !name.contains('\0')41        && name.split('/').all(|c| !c.is_empty() && c != "." && c != "..")42}4344impl ProjectAssets {45    pub fn new(root: Option<PathBuf>) -> ProjectAssets {46        ProjectAssets { root, cache: Arc::new(Mutex::new(BTreeMap::new())) }47    }48}4950impl AssetProvider for ProjectAssets {51    fn load(&self, asset: &str) -> Result<Arc<AudioAsset>, String> {52        let root = self.root.as_ref().ok_or_else(|| format!("asset '{asset}': the document is not in a project, so it has no assets folder"))?;53        if !safe_asset_name(asset) {54            return Err(format!("asset '{asset}': the path must stay inside the project's assets folder"));55        }56        if let Some(a) = self.cache.lock().ok().and_then(|c| c.get(asset).cloned()) {57            return Ok(a);58        }59        let dir = root.join("assets");60        let path = dir.join(asset);61        // Resolve symlinks and check the file is still under assets/.62        let real = path.canonicalize().map_err(|_| format!("asset '{asset}' is missing from the project"))?;63        let real_dir = dir.canonicalize().map_err(|_| "the project has no assets folder".to_string())?;64        if !real.starts_with(&real_dir) {65            return Err(format!("asset '{asset}' points outside the project"));66        }67        let (sample_rate, channels) = adapter::read_audio(&real).map_err(|e| format!("asset '{asset}': {e}"))?;68        let a = Arc::new(AudioAsset { sample_rate, channels });69        if let Ok(mut c) = self.cache.lock() {70            c.insert(asset.to_string(), a.clone());71        }72        Ok(a)73    }74}7576pub struct SonataCompiler {77    root: Option<PathBuf>,78    overlays: BTreeMap<String, String>,79    /// Last successfully compiled program (overrides applied) and what belongs to it.80    program: Option<Program>,81    sources: Vec<(String, String)>,82    ast_json: String,83    assets: Arc<Mutex<BTreeMap<String, Arc<AudioAsset>>>>,84    session: adapter::Session,85}8687impl SonataCompiler {88    pub fn program(&self) -> Option<&Program> {89        self.program.as_ref()90    }91    pub fn asset_provider(&self) -> ProjectAssets {92        ProjectAssets { root: self.root.clone(), cache: self.assets.clone() }93    }94    fn file_name(&self, span: Span) -> String {95        self.sources.get(span.file as usize).map(|s| s.0.clone()).unwrap_or_default()96    }97}9899/// A diagnostic with its file name and line/column resolved.100pub fn diagnostic_json(d: &Diagnostic, sources: &[(String, String)]) -> Value {101    let (name, src) = sources.get(d.span.file as usize).map(|s| (s.0.as_str(), s.1.as_str())).unwrap_or(("", ""));102    let idx = LineIndex::new(src);103    let a = idx.line_col(src, d.span.start);104    let b = idx.line_col(src, d.span.end.max(d.span.start));105    json!({106        "code": d.code,107        "severity": match d.severity { Severity::Error => "error", Severity::Warning => "warning", Severity::Info => "info", Severity::Hint => "hint" },108        "message": d.message,109        "suggestion": d.suggestion,110        "fix": d.fix.as_ref().map(|f| json!({ "title": f.title, "start": f.span.start, "end": f.span.end, "replacement": f.replacement })),111        "file": name,112        "start": d.span.start,113        "end": d.span.end.max(d.span.start),114        "line": a.line,115        "column": a.column,116        "end_line": b.line,117        "end_column": b.column,118    })119}120121#[no_mangle]122pub extern "C" fn sonata_compiler_new() -> *mut SonataCompiler {123    Box::into_raw(Box::new(SonataCompiler {124        root: None,125        overlays: BTreeMap::new(),126        program: None,127        sources: Vec::new(),128        ast_json: "null".into(),129        assets: Arc::new(Mutex::new(BTreeMap::new())),130        session: adapter::Session::default(),131    }))132}133134/// # Safety135/// `compiler` from `sonata_compiler_new`, not used afterwards.136#[no_mangle]137pub unsafe extern "C" fn sonata_compiler_free(compiler: *mut SonataCompiler) {138    if !compiler.is_null() {139        drop(Box::from_raw(compiler));140    }141}142143/// # Safety144/// Valid compiler; `project_root` NULL or NUL-terminated.145#[no_mangle]146pub unsafe extern "C" fn sonata_compiler_set_root(compiler: *mut SonataCompiler, project_root: *const c_char) {147    if let Some(c) = compiler.as_mut() {148        let new = text(project_root).filter(|s| !s.is_empty()).map(PathBuf::from);149        if new != c.root {150            if let Ok(mut a) = c.assets.lock() {151                a.clear();152            }153        }154        c.root = new;155    }156}157158/// # Safety159/// Valid compiler; strings NULL or NUL-terminated.160#[no_mangle]161pub unsafe extern "C" fn sonata_compiler_set_overlay(compiler: *mut SonataCompiler, relative_path: *const c_char, source: *const c_char) {162    let (Some(c), Some(path)) = (compiler.as_mut(), text(relative_path)) else { return };163    match text(source) {164        Some(s) => {165            c.overlays.insert(path.to_string(), s.to_string());166        }167        None => {168            c.overlays.remove(path);169        }170    }171}172173/// # Safety174/// Valid compiler; strings NUL-terminated (`options_json` may be NULL).175#[no_mangle]176pub unsafe extern "C" fn sonata_compiler_compile(177    compiler: *mut SonataCompiler,178    name: *const c_char,179    source: *const c_char,180    options_json: *const c_char,181) -> *mut c_char {182    let (Some(c), Some(source)) = (compiler.as_mut(), text(source)) else { return error_json("null pointer or invalid UTF-8") };183    let name = text(name).unwrap_or("main");184    let options: Value = text(options_json).and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null);185    guard_json(|| {186        let started = std::time::Instant::now();187        let composition = options.get("composition").and_then(|v| v.as_str());188        let modules = ModuleSource::new(c.root.as_ref(), &c.overlays, name);189        let compiled = adapter::compile(&mut c.session, name, source, &modules, composition);190        let mut diagnostics: Vec<Value> = compiled.diagnostics.iter().map(|d| diagnostic_json(d, &compiled.sources)).collect();191        let has_error = compiled.diagnostics.iter().any(|d| d.is_error());192        let mut conflicts = Vec::new();193        let mut graph_us = 0.0;194        let mut nodes = 0usize;195        let mut ok = false;196        if let (Some(mut program), false) = (compiled.program, has_error) {197            if let Some(rate) = options.get("sample_rate").and_then(|v| v.as_u64()).filter(|r| (8_000..=384_000).contains(r)) {198                program.master.sample_rate = rate as u32;199            }200            if let Some(o) = options.get("overrides") {201                match serde_json::from_value::<Overrides>(o.clone()) {202                    Ok(o) => conflicts = o.apply(&mut program),203                    Err(e) => diagnostics.push(json!({204                        "code": "X0002", "severity": "warning", "message": format!("the studio overrides could not be read and were ignored: {e}"),205                        "suggestion": Value::Null, "fix": Value::Null, "file": name, "start": 0, "end": 0, "line": 1, "column": 1, "end_line": 1, "end_column": 1,206                    })),207                }208            }209            // The graph is validated at the project rate now; the engine rebuilds it at its own rate.210            let t = std::time::Instant::now();211            match adapter::build_graph(&program, program.master.sample_rate) {212                Ok(g) => {213                    graph_us = t.elapsed().as_secs_f64() * 1e6;214                    nodes = g.nodes.len();215                    c.program = Some(program);216                    c.sources = compiled.sources;217                    c.ast_json = compiled.ast_json;218                    ok = true;219                }220                Err(m) => diagnostics.push(json!({221                    "code": "G5000", "severity": "error", "message": m, "suggestion": Value::Null, "fix": Value::Null,222                    "file": name, "start": 0, "end": 0, "line": 1, "column": 1, "end_line": 1, "end_column": 1,223                })),224            }225        }226        let (stats, timeline) = match (&c.program, ok) {227            (Some(p), true) => {228                // Rough working-set estimate: events, per-track voices and buffers (64 voices x ~64 KiB), graph buffers.229                let memory = p.stats.notes as usize * 96 + p.tracks.len() * 64 * 65_536 + nodes * 2 * 4096 * 4;230                (231                    json!({232                        "total_us": started.elapsed().as_secs_f64() * 1e6,233                        "lex_us": compiled.lex_us, "parse_us": compiled.parse_us, "sema_us": compiled.sema_us, "graph_us": graph_us,234                        "cache_hit": compiled.cache_hit,235                        "events": p.stats.notes, "tracks": p.stats.tracks, "max_polyphony": p.stats.max_polyphony,236                        "nodes": nodes, "estimated_memory_bytes": memory, "duration_sec": p.stats.duration_sec,237                    }),238                    timeline_json(p, &|s| c.file_name(s)),239                )240            }241            _ => (242                json!({243                    "total_us": started.elapsed().as_secs_f64() * 1e6,244                    "lex_us": compiled.lex_us, "parse_us": compiled.parse_us, "sema_us": compiled.sema_us, "graph_us": 0.0,245                    "cache_hit": compiled.cache_hit, "events": 0, "tracks": 0, "max_polyphony": 0, "nodes": 0, "estimated_memory_bytes": 0, "duration_sec": 0.0,246                }),247                Value::Null,248            ),249        };250        give_json(&json!({ "ok": ok, "diagnostics": diagnostics, "stats": stats, "conflicts": conflicts, "timeline": timeline }))251    })252}253254#[no_mangle]255pub extern "C" fn sonata_compiler_has_program(compiler: *const SonataCompiler) -> bool {256    // SAFETY: NULL or live handle.257    unsafe { compiler.as_ref() }.map(|c| c.program.is_some()).unwrap_or(false)258}259260/// # Safety261/// Valid compiler; `what` NUL-terminated.262#[no_mangle]263pub unsafe extern "C" fn sonata_compiler_export_json(compiler: *mut SonataCompiler, what: *const c_char) -> *mut c_char {264    let (Some(c), Some(what)) = (compiler.as_ref(), text(what)) else { return error_json("null pointer") };265    guard_json(|| {266        if what == "ast" {267            return give(c.ast_json.clone());268        }269        let Some(p) = &c.program else { return give_json(&json!({ "error": "there is no compiled program" })) };270        match what {271            "program" => give(serde_json::to_string_pretty(p).unwrap_or_else(|_| "null".into())),272            "graph" => match adapter::build_graph(p, p.master.sample_rate) {273                Ok(g) => give(serde_json::to_string_pretty(&g).unwrap_or_else(|_| "null".into())),274                Err(m) => give_json(&json!({ "error": m })),275            },276            "score" => give(serde_json::to_string(&sonata_interop::build_score(p)).unwrap_or_else(|_| "null".into())),277            "timeline" => give_json(&timeline_json(p, &|s| c.file_name(s))),278            other => give_json(&json!({ "error": format!("unknown export '{other}'") })),279        }280    })281}282283/// # Safety284/// Valid compiler; strings NUL-terminated.285#[no_mangle]286pub unsafe extern "C" fn sonata_compiler_query(compiler: *mut SonataCompiler, kind: *const c_char, source: *const c_char, offset: u32) -> *mut c_char {287    let (Some(c), Some(kind), Some(source)) = (compiler.as_mut(), text(kind), text(source)) else { return give("null".into()) };288    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {289        let root_name = c.sources.first().map(|s| s.0.clone()).unwrap_or_else(|| "main.sonata".into());290        let modules = ModuleSource::new(c.root.as_ref(), &c.overlays, &root_name);291        adapter::query(&mut c.session, kind, source, offset.min(source.len() as u32), &modules, &root_name)292    })) {293        Ok(s) => give(s),294        Err(_) => give("null".into()),295    }296}297298/// Writes `bytes` to `path` atomically (temporary file in the same directory, then rename).299pub fn write_atomic(path: &Path, bytes: &[u8], overwrite: bool) -> Result<(), String> {300    if path.exists() && !overwrite {301        return Err(format!("{} already exists", path.display()));302    }303    let dir = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));304    let name = path.file_name().ok_or("the path has no file name")?.to_string_lossy().to_string();305    let tmp = dir.join(format!(".{name}.{}.tmp", std::process::id()));306    std::fs::write(&tmp, bytes).map_err(|e| format!("cannot write {}: {e}", tmp.display()))?;307    std::fs::rename(&tmp, path).map_err(|e| {308        let _ = std::fs::remove_file(&tmp);309        format!("cannot replace {}: {e}", path.display())310    })311}312313/// # Safety314/// Valid compiler; strings NUL-terminated.315#[no_mangle]316pub unsafe extern "C" fn sonata_compiler_export_file(317    compiler: *mut SonataCompiler,318    format: *const c_char,319    path: *const c_char,320    overwrite: bool,321) -> *mut c_char {322    let (Some(c), Some(format), Some(path)) = (compiler.as_ref(), text(format), text(path)) else { return error_json("null pointer") };323    guard_json(|| {324        let Some(p) = &c.program else { return give_json(&json!({ "ok": false, "warnings": [], "error": "there is no compiled program" })) };325        let (bytes, warnings) = match format {326            "midi" => sonata_interop::program_to_midi(p),327            "musicxml" => {328                let (xml, w) = sonata_interop::program_to_musicxml(p);329                (xml.into_bytes(), w)330            }331            other => return give_json(&json!({ "ok": false, "warnings": [], "error": format!("unknown format '{other}'") })),332        };333        match write_atomic(Path::new(path), &bytes, overwrite) {334            Ok(()) => give_json(&json!({ "ok": true, "warnings": warnings, "error": Value::Null })),335            Err(m) => give_json(&json!({ "ok": false, "warnings": warnings, "error": m })),336        }337    })338}339340/// # Safety341/// Strings NUL-terminated (`instrument` may be NULL).342#[no_mangle]343pub unsafe extern "C" fn sonata_import_midi(path: *const c_char, instrument: *const c_char) -> *mut c_char {344    let Some(path) = text(path) else { return error_json("null pointer") };345    let instrument = text(instrument).filter(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')).unwrap_or("GrandPiano");346    guard_json(|| {347        let meta = match std::fs::metadata(path) {348            Ok(m) => m,349            Err(e) => return give_json(&json!({ "ok": false, "source": Value::Null, "error": format!("cannot read the file: {e}") })),350        };351        if meta.len() > sonata_interop::midi::MAX_MIDI_BYTES as u64 {352            return give_json(&json!({ "ok": false, "source": Value::Null, "error": "the file is too large to be a MIDI file this version accepts" }));353        }354        let data = match std::fs::read(path) {355            Ok(d) => d,356            Err(e) => return give_json(&json!({ "ok": false, "source": Value::Null, "error": format!("cannot read the file: {e}") })),357        };358        match sonata_interop::parse_midi(&data) {359            Ok(f) => give_json(&json!({ "ok": true, "source": sonata_interop::midi_to_sonata(&f, instrument), "error": Value::Null })),360            Err(m) => give_json(&json!({ "ok": false, "source": Value::Null, "error": m })),361        }362    })363}364365/// # Safety366/// `source` NUL-terminated.367#[no_mangle]368pub unsafe extern "C" fn sonata_format(source: *const c_char) -> *mut c_char {369    let Some(source) = text(source) else { return error_json("null pointer or invalid UTF-8") };370    guard_json(|| match adapter::format(source) {371        Ok(t) => give_json(&json!({ "ok": true, "text": t, "diagnostics": [] })),372        Err(ds) => {373            let sources = vec![("main".to_string(), source.to_string())];374            give_json(&json!({ "ok": false, "text": source, "diagnostics": ds.iter().map(|d| diagnostic_json(d, &sources)).collect::<Vec<_>>() }))375        }376    })377}378379/// # Safety380/// `source` NUL-terminated; `triples` valid for `3 * capacity` u32 (or NULL with capacity 0).381#[no_mangle]382pub unsafe extern "C" fn sonata_highlight(source: *const c_char, triples: *mut u32, capacity: usize) -> usize {383    let Some(source) = text(source) else { return 0 };384    let tokens = crate::util::guard(Vec::new(), || adapter::highlight(source));385    if !triples.is_null() && capacity > 0 {386        let out = std::slice::from_raw_parts_mut(triples, 3 * capacity);387        for (i, t) in tokens.iter().take(capacity).enumerate() {388            out[3 * i] = t.0;389            out[3 * i + 1] = t.1;390            out[3 * i + 2] = t.2;391        }392    }393    tokens.len()394}395396pub type SonataProgress = Option<unsafe extern "C" fn(context: *mut c_void, fraction: f64)>;397398/// # Safety399/// Valid compiler; `options_json` NUL-terminated; `cancel` NULL or valid for the whole call.400#[no_mangle]401pub unsafe extern "C" fn sonata_compiler_render(402    compiler: *mut SonataCompiler,403    options_json: *const c_char,404    progress: SonataProgress,405    context: *mut c_void,406    cancel: *const i32,407) -> *mut c_char {408    let (Some(c), Some(options)) = (compiler.as_ref(), text(options_json)) else { return error_json("null pointer") };409    let fail = |m: String| give_json(&json!({ "ok": false, "files": [], "seconds": 0.0, "realtime_factor": 0.0, "cancelled": false, "error": m }));410    let o: Value = match serde_json::from_str(options) {411        Ok(v) => v,412        Err(e) => return fail(format!("invalid render options: {e}")),413    };414    guard_json(|| {415        let Some(program) = &c.program else { return fail("there is no compiled program to render".into()) };416        let Some(path) = o.get("path").and_then(|v| v.as_str()).filter(|s| !s.is_empty()) else { return fail("no output path".into()) };417        let req = RenderRequest {418            path: PathBuf::from(path),419            format: o.get("format").and_then(|v| v.as_str()).unwrap_or("wav").to_string(),420            bit_depth: o.get("bit_depth").and_then(|v| v.as_u64()).unwrap_or(24) as u32,421            float: o.get("float").and_then(|v| v.as_bool()).unwrap_or(false),422            sample_rate: o.get("sample_rate").and_then(|v| v.as_u64()).map(|r| r as u32).unwrap_or(program.master.sample_rate),423            start_sec: o.get("start_sec").and_then(|v| v.as_f64()),424            end_sec: o.get("end_sec").and_then(|v| v.as_f64()),425            tail: o.get("tail").and_then(|v| v.as_bool()).unwrap_or(true),426            dither: o.get("dither").and_then(|v| v.as_bool()).unwrap_or(true),427            normalize: o.get("normalize").and_then(|v| v.as_str()).unwrap_or("none").to_string(),428            target: o.get("target").and_then(|v| v.as_f64()),429            stems: o.get("stems").and_then(|v| v.as_bool()).unwrap_or(false),430            overwrite: o.get("overwrite").and_then(|v| v.as_bool()).unwrap_or(false),431        };432        let started = std::time::Instant::now();433        let mut report = |f: f64| {434            if let Some(cb) = progress {435                cb(context, f.clamp(0.0, 1.0));436            }437        };438        let cancelled = || !cancel.is_null() && std::ptr::read_volatile(cancel) != 0;439        let assets = c.asset_provider();440        match adapter::render(program, &assets, &req, &mut report, &cancelled) {441            Ok(out) => {442                let seconds = started.elapsed().as_secs_f64();443                let audio: f64 = out.files.first().map(|f| f.frames as f64 / f.sample_rate.max(1) as f64).unwrap_or(0.0);444                let files: Vec<Value> = out445                    .files446                    .iter()447                    .map(|f| {448                        json!({449                            "path": f.path.to_string_lossy(), "frames": f.frames, "sample_rate": f.sample_rate, "channels": f.channels,450                            "peak_db": num(f.peak_db).as_f64().unwrap_or(-200.0), "true_peak_db": num(f.true_peak_db).as_f64().unwrap_or(-200.0), "lufs": num(f.lufs).as_f64().unwrap_or(-200.0),451                        })452                    })453                    .collect();454                give_json(455                    &json!({ "ok": !out.cancelled, "files": files, "seconds": seconds, "realtime_factor": if seconds > 0.0 { audio / seconds } else { 0.0 }, "cancelled": out.cancelled, "error": Value::Null }),456                )457            }458            Err(m) => fail(m),459        }460    })461}462
Files main
Menu

Theme