SPB Git

Repository Public

adapter.rs 18.2 KB 411 lines rust

1//! ORIX Sonata2//! File: crates/sonata-ffi/src/adapter.rs3//! Description: The only place where the C ABI touches the compiler, renderer and file readers.4//! Keeps the rest of the crate independent of their exact signatures.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use sonata_compiler::{CompileOptions, Compiler};10use sonata_ir::{Diagnostic, DspGraph, Program, Registry};11use sonata_render::file::{read_audio_file, write_audio_file, AudioData, Dither, FileFormat, FileSpec, ReadLimits, SampleFormat};12use sonata_render::render::{measure_levels, normalize, render as render_program, Normalize, RenderError, RenderOptions, Tail};13use sonata_semantics::modules::SourceLoader;14use std::collections::BTreeMap;15use std::path::{Path, PathBuf};16use std::sync::atomic::{AtomicBool, Ordering};17use std::sync::Arc;1819/// What a compilation gives back to the session.20pub struct Compiled {21    pub program: Option<Program>,22    pub diagnostics: Vec<Diagnostic>,23    /// Module name and text by `FileId`.24    pub sources: Vec<(String, String)>,25    pub lex_us: f64,26    pub parse_us: f64,27    pub sema_us: f64,28    pub cache_hit: bool,29    pub ast_json: String,30}3132/// Where non-std modules come from: unsaved overlays first, then files under the root directory.33/// A module path is relative to the directory of the root source: from `src/main.sonata`,34/// `import motifs` reads `src/motifs.sonata` and `import lib.arp` reads `src/lib/arp.sonata`.35pub struct ModuleSource<'a> {36    /// Directory the root source's name is relative to (the project, or the folder of a lone file).37    pub root: Option<&'a PathBuf>,38    /// Unsaved texts by path relative to `root`.39    pub overlays: &'a BTreeMap<String, String>,40    /// Directory of the root source relative to `root` (`src`, or empty).41    pub base: String,42}4344impl<'a> ModuleSource<'a> {45    /// `name` is the root source's path relative to `root` (`src/main.sonata`, `piece.sonata`).46    pub fn new(root: Option<&'a PathBuf>, overlays: &'a BTreeMap<String, String>, name: &str) -> ModuleSource<'a> {47        let base = match name.rfind('/') {48            Some(i) if !name.starts_with('/') => name[..i].to_string(),49            _ => String::new(),50        };51        ModuleSource { root, overlays, base }52    }5354    /// Relative path of a module, or `None` when the name is not a plain dotted identifier path.55    pub fn module_path(&self, module: &str) -> Option<String> {56        let ok = !module.is_empty() && module.split('.').all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'));57        let file = format!("{}.sonata", module.replace('.', "/"));58        ok.then(|| if self.base.is_empty() { file } else { format!("{}/{file}", self.base) })59    }60}6162impl SourceLoader for ModuleSource<'_> {63    /// A tuning file under `<root>/assets`, refused when it resolves outside that folder.64    fn load_asset(&self, path: &str) -> Option<String> {65        if let Some(text) = self.overlays.get(&format!("assets/{path}")) {66            return Some(text.clone());67        }68        if sonata_semantics::asset_path_problem(path).is_some() {69            return None;70        }71        let dir = self.root?.join("assets");72        let real = dir.join(path).canonicalize().ok()?;73        if !real.starts_with(dir.canonicalize().ok()?) || std::fs::metadata(&real).ok()?.len() > sonata_semantics::tuning::MAX_TUNING_BYTES as u64 {74            return None;75        }76        std::fs::read_to_string(real).ok()77    }78    fn load(&self, module: &str) -> Option<String> {79        let rel = self.module_path(module)?;80        if let Some(text) = self.overlays.get(&rel) {81            return Some(text.clone());82        }83        let root = self.root?;84        let path = root.join(&rel);85        // The module must really be inside the root (no symlink escape) and of a sane size.86        let own = path.canonicalize().ok().zip(root.canonicalize().ok()).filter(|(real, real_root)| real.starts_with(real_root)).map(|(real, _)| real);87        // The project's own modules come first; then `import package.module` reads an installed88        // package (`<root>/packages/<package>/src/<module>.sonata`).89        let file = own.or_else(|| module.split_once('.').and_then(|(package, rest)| sonata_pkg::module_file(root, package, rest)))?;90        if std::fs::metadata(&file).ok()?.len() > 4 * 1024 * 1024 {91            return None;92        }93        std::fs::read_to_string(file).ok()94    }95}9697/// Per-session compiler state (content-hash cache, incremental module reuse).98#[derive(Default)]99pub struct Session {100    compiler: Compiler,101}102103pub fn registry() -> &'static Registry {104    sonata_compiler::registry()105}106107/// Name shown for a module: project modules use their path so the editor can open them.108fn display_name(name: &str, is_std: bool, root_name: &str, modules: &ModuleSource<'_>) -> String {109    if is_std || name == root_name || name.ends_with(".sonata") {110        return name.to_string();111    }112    modules.module_path(name).unwrap_or_else(|| name.to_string())113}114115pub fn compile(session: &mut Session, name: &str, source: &str, modules: &ModuleSource<'_>, composition: Option<&str>) -> Compiled {116    let options = CompileOptions { composition: composition.map(|s| s.to_string()), ..CompileOptions::default() };117    let out = session.compiler.compile(name, source, modules, &options);118    Compiled {119        program: out.program.as_deref().cloned(),120        diagnostics: out.diagnostics.to_vec(),121        sources: out.sources.files.iter().map(|f| (display_name(&f.name, f.is_std, name, modules), f.text.to_string())).collect(),122        lex_us: out.stats.lex_us,123        parse_us: out.stats.parse_us,124        sema_us: out.stats.sema_us,125        cache_hit: out.stats.cache_hit,126        ast_json: out.ast_json(),127    }128}129130/// [`compile`] that gives up when `cancel` answers true (asked between modules, phases and131/// tracks and every 256 evaluation steps). `None` means cancelled; the session stays sound.132pub fn compile_cancellable(133    session: &mut Session,134    name: &str,135    source: &str,136    modules: &ModuleSource<'_>,137    composition: Option<&str>,138    cancel: &(dyn Fn() -> bool + Sync),139) -> Option<Compiled> {140    let options = CompileOptions { composition: composition.map(|s| s.to_string()), ..CompileOptions::default() };141    let out = session.compiler.compile_cancellable_with(name, source, modules, &options, cancel)?;142    Some(Compiled {143        program: out.program.as_deref().cloned(),144        diagnostics: out.diagnostics.to_vec(),145        sources: out.sources.files.iter().map(|f| (display_name(&f.name, f.is_std, name, modules), f.text.to_string())).collect(),146        lex_us: out.stats.lex_us,147        parse_us: out.stats.parse_us,148        sema_us: out.stats.sema_us,149        cache_hit: out.stats.cache_hit,150        ast_json: out.ast_json(),151    })152}153154/// Every editor service behind one entry: `file` is the name of the file whose text is155/// `source`. Kinds and JSON shapes are listed in sonata.h (`sonata_services_query`).156#[allow(clippy::too_many_arguments)]157pub fn services_query(session: &mut Session, kind: &str, file: &str, source: &str, start: u32, end: u32, arg: &str, modules: &ModuleSource<'_>) -> String {158    use serde_json::json;159    let len = source.len() as u32;160    let (start, end) = (start.min(len), end.min(len).max(start.min(len)));161    match kind {162        "completion" | "completions" => query(session, "completions", source, start, modules, file),163        "hover" | "definition" | "references" | "signature" => query(session, kind, source, start, modules, file),164        "outline" | "symbols" => query(session, "symbols", source, start, modules, file),165        "semantic_tokens" => {166            // Flat triples (byte start, byte length, class index in the legend), inside the range when one is given.167            let all = start == end;168            let flat: Vec<u32> = highlight(source).into_iter().filter(|(s, l, _)| all || (*s < end && s + l > start)).flat_map(|(s, l, c)| [s, l, c]).collect();169            json!({ "legend": sonata_compiler::services::more::SEMANTIC_LEGEND, "tokens": flat }).to_string()170        }171        "trace" | "imports" | "dependents" => {172            let out = session.compiler.compile(file, source, modules, &CompileOptions::default());173            match kind {174                "trace" => sonata_compiler::trace::trace_json(&out).map(|v| v.to_string()).unwrap_or_else(|| "null".into()),175                "imports" => json!(out.imports().into_iter().map(|(m, i)| json!({ "module": m, "imports": i })).collect::<Vec<_>>()).to_string(),176                _ => json!(out.dependents_of(arg)).to_string(),177            }178        }179        _ => sonata_compiler::services::Services::new().query_range(kind, file, source, start, end, arg, modules),180    }181}182183pub fn build_graph(program: &Program, sample_rate: u32) -> Result<DspGraph, String> {184    sonata_compiler::build_graph(program, sample_rate).map_err(|ds| ds.iter().map(|d| format!("{}: {}", d.code, d.message)).collect::<Vec<_>>().join("; "))185}186187pub fn format(source: &str) -> Result<String, Vec<Diagnostic>> {188    sonata_parser::format::format(source)189}190191/// (byte start, byte length, class) triples; classes as documented in sonata.h.192pub fn highlight(source: &str) -> Vec<(u32, u32, u32)> {193    sonata_compiler::services::highlight(source)194}195196/// Editor query; returns JSON text in the shapes documented for `sonata_compiler_query`.197pub fn query(_session: &mut Session, kind: &str, source: &str, offset: u32, modules: &ModuleSource<'_>, root_name: &str) -> String {198    use serde_json::{json, Value};199    let services = sonata_compiler::services::Services::new();200    let name_of = |file: &str| -> String {201        if file == root_name || file.starts_with("std.") || file.ends_with(".sonata") {202            file.to_string()203        } else {204            modules.module_path(file).unwrap_or_else(|| file.to_string())205        }206    };207    let location = |l: &sonata_compiler::Location| json!({ "file": name_of(&l.file), "start": l.start, "end": l.end, "line": l.line, "column": l.column });208    let value: Value = match kind {209        "completions" => {210            // The word being typed is replaced by the chosen item.211            let bytes = source.as_bytes();212            let end = (offset as usize).min(bytes.len());213            let mut start = end;214            while start > 0 && (bytes[start - 1].is_ascii_alphanumeric() || bytes[start - 1] == b'_' || bytes[start - 1] == b'#') {215                start -= 1;216            }217            Value::Array(218                services219                    .completions(root_name, source, offset, modules)220                    .into_iter()221                    .map(|c| json!({ "label": c.label, "kind": c.kind, "detail": if c.detail.is_empty() { Value::Null } else { json!(c.detail) }, "doc": Value::Null, "insert": c.insert, "replace_start": start, "replace_end": end }))222                    .collect(),223            )224        }225        "hover" => services.hover(root_name, source, offset, modules).map(|h| json!({ "start": h.start, "end": h.end, "markdown": h.text })).unwrap_or(Value::Null),226        "definition" => services.definition(root_name, source, offset, modules).map(|l| location(&l)).unwrap_or(Value::Null),227        "references" => Value::Array(services.references(root_name, source, offset, modules).iter().map(location).collect()),228        "symbols" => {229            fn symbol(s: &sonata_compiler::services::DocumentSymbol) -> Value {230                let kind = serde_json::to_value(s.kind).ok().and_then(|v| v.as_str().map(|x| x.to_string())).unwrap_or_else(|| format!("{:?}", s.kind).to_lowercase());231                json!({ "name": s.name, "kind": kind, "detail": if s.detail.is_empty() { Value::Null } else { json!(s.detail) }, "start": s.range.start, "end": s.range.end, "children": s.children.iter().map(symbol).collect::<Vec<_>>() })232            }233            Value::Array(services.document_symbols(root_name, source, modules).iter().map(symbol).collect())234        }235        "signature" => services236            .signature_help(root_name, source, offset, modules)237            .map(|h| json!({ "label": h.label, "doc": if h.doc.is_empty() { Value::Null } else { json!(h.doc) }, "parameters": h.parameters.iter().map(|p| p.label.clone()).collect::<Vec<_>>(), "active_parameter": h.active_parameter }))238            .unwrap_or(Value::Null),239        _ => Value::Null,240    };241    value.to_string()242}243244/// Decoded audio: sample rate and one vector per channel.245pub fn read_audio(path: &Path) -> Result<(u32, Vec<Vec<f32>>), String> {246    let (audio, _info) = read_audio_file(path, &ReadLimits::default())?;247    Ok((audio.sample_rate, audio.channels))248}249250pub struct RenderRequest {251    pub path: PathBuf,252    pub format: String,253    pub bit_depth: u32,254    pub float: bool,255    pub sample_rate: u32,256    pub start_sec: Option<f64>,257    pub end_sec: Option<f64>,258    pub tail: bool,259    pub dither: bool,260    pub normalize: String,261    pub target: Option<f64>,262    pub stems: bool,263    pub overwrite: bool,264}265266pub struct RenderedFile {267    pub path: PathBuf,268    pub frames: u64,269    pub sample_rate: u32,270    pub channels: u32,271    pub peak_db: f64,272    pub true_peak_db: f64,273    pub lufs: f64,274}275276pub struct RenderOutcome {277    pub files: Vec<RenderedFile>,278    pub cancelled: bool,279}280281fn file_spec(req: &RenderRequest) -> Result<FileSpec, String> {282    let format = match req.format.as_str() {283        "wav" => FileFormat::Wav,284        "aiff" | "aif" => FileFormat::Aiff,285        "flac" => FileFormat::Flac,286        other => return Err(format!("unknown audio format '{other}' (wav, aiff, flac)")),287    };288    let samples = match (req.float, req.bit_depth) {289        (true, 64) => SampleFormat::Float64,290        (true, _) => SampleFormat::Float32,291        (false, 16) => SampleFormat::Pcm16,292        (false, 24) => SampleFormat::Pcm24,293        (false, 32) => SampleFormat::Pcm32,294        (false, other) => return Err(format!("unsupported bit depth {other} (16, 24, 32)")),295    };296    if format == FileFormat::Flac && (samples.is_float() || samples.bits() > 24) {297        return Err("FLAC stores 16 or 24-bit integer samples".into());298    }299    let mut spec = FileSpec::new(format, samples);300    spec.dither = if req.dither && !samples.is_float() && samples.bits() < 32 { Dither::Tpdf } else { Dither::None };301    spec.overwrite = req.overwrite;302    Ok(spec)303}304305fn safe_file_stem(name: &str) -> String {306    let s: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();307    if s.is_empty() {308        "stem".into()309    } else {310        s311    }312}313314pub fn render(315    program: &Program,316    assets: &dyn sonata_runtime::AssetProvider,317    req: &RenderRequest,318    progress: &mut dyn FnMut(f64),319    cancel: &dyn Fn() -> bool,320) -> Result<RenderOutcome, String> {321    if ![44_100, 48_000, 88_200, 96_000, 176_400, 192_000].contains(&req.sample_rate) {322        return Err(format!("unsupported sample rate {} Hz", req.sample_rate));323    }324    let spec = file_spec(req)?;325    if req.path.exists() && !req.overwrite {326        return Err(format!("{} already exists", req.path.display()));327    }328    let graph = build_graph(program, req.sample_rate)?;329    let mut options = RenderOptions::default();330    options.range = match (req.start_sec, req.end_sec) {331        (None, None) => None,332        (a, b) => Some((a.unwrap_or(0.0).max(0.0), b.unwrap_or(program.end_sec))),333    };334    if !req.tail {335        options.tail = Tail { max_sec: 0.0, ..Tail::default() };336    }337    options.stems = req.stems;338    // The renderer polls an AtomicBool; mirror the caller's flag into it from the progress callback.339    let flag = Arc::new(AtomicBool::new(false));340    let f2 = flag.clone();341    let mut report = |fraction: f64| {342        if cancel() {343            f2.store(true, Ordering::Relaxed);344        }345        progress(fraction);346    };347    let mut output = match render_program(program, &graph, assets, &options, &mut report, &flag) {348        Ok(o) => o,349        Err(RenderError::Cancelled) => return Ok(RenderOutcome { files: Vec::new(), cancelled: true }),350        Err(e) => return Err(e.to_string()),351    };352    if cancel() {353        return Ok(RenderOutcome { files: Vec::new(), cancelled: true });354    }355    match req.normalize.as_str() {356        "none" => {}357        "peak" => {358            // The same gain goes to the stems so they still sum to the master.359            let gain_db = normalize(&mut output.audio, Normalize::TruePeak(req.target.unwrap_or(-1.0).clamp(-60.0, 0.0)))?;360            scale_stems(&mut output.stems, gain_db);361        }362        "lufs" => {363            let gain_db =364                normalize(&mut output.audio, Normalize::Loudness { target_lufs: req.target.unwrap_or(-16.0).clamp(-60.0, -5.0), max_true_peak_dbtp: -1.0 })?;365            scale_stems(&mut output.stems, gain_db);366        }367        other => return Err(format!("unknown normalisation '{other}' (none, peak, lufs)")),368    }369    let mut files = Vec::new();370    let mut write = |path: &Path, audio: &AudioData| -> Result<(), String> {371        let report = write_audio_file(path, audio, &spec)?;372        let lv = measure_levels(audio);373        files.push(RenderedFile {374            path: path.to_path_buf(),375            frames: report.frames,376            sample_rate: audio.sample_rate,377            channels: audio.channels.len() as u32,378            peak_db: lv.sample_peak_db as f64,379            true_peak_db: lv.true_peak_dbtp as f64,380            lufs: lv.integrated_lufs,381        });382        Ok(())383    };384    write(&req.path, &output.audio)?;385    if req.stems {386        let base = req.path.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| "render".into());387        let ext = req.path.extension().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| req.format.clone());388        let dir = req.path.parent().map(|p| p.to_path_buf()).unwrap_or_default();389        for stem in &output.stems {390            let path = dir.join(format!("{base} - {}.{ext}", safe_file_stem(&stem.name)));391            if path.exists() && !req.overwrite {392                return Err(format!("{} already exists", path.display()));393            }394            write(&path, &stem.audio)?;395        }396    }397    progress(1.0);398    Ok(RenderOutcome { files, cancelled: false })399}400401fn scale_stems(stems: &mut [sonata_render::render::Stem], gain_db: f64) {402    let g = 10f64.powf(gain_db / 20.0) as f32;403    for s in stems {404        for c in &mut s.audio.channels {405            for v in c.iter_mut() {406                *v *= g;407            }408        }409    }410}411
Files main
Menu

Theme