Repository Public
1/*2 * ORIX Sonata3 * File: crates/sonata-ffi/include/sonata.h4 * Description: Stable C ABI of the Sonata compiler, runtime and analysis library, consumed by5 * the Swift package SonataBridge. Hand-written; a Rust test checks every symbol is exported.6 *7 * Author: Simon-Pierre Boucher8 * Contact: contact@spboucher.ai9 *10 * Conventions11 * - Strings are NUL-terminated UTF-8. A `char *` RETURNED by the library is owned by the caller12 * and must be released with sonata_string_free; it is never NULL unless stated.13 * - Cold data crosses as JSON. Hot data (audio, meters, scopes) crosses as plain memory.14 * - Thread safety: a SonataCompiler must be used from one thread at a time. A SonataEngine may be15 * controlled from any thread while exactly one real-time thread calls sonata_engine_process.16 * - Functions marked RT are real-time safe: no allocation, lock, I/O or logging.17 * - No function unwinds across this boundary: internal panics are caught in every exported18 * function and reported as SONATA_ERR_PANIC (functions returning a status), as19 * {"ok":false,"error":...} (functions returning JSON), as the neutral value documented for the20 * function (0, false, NULL), or as silence plus a latched fault (sonata_engine_process).21 *22 * Ownership and lifetime of every pointer23 * - Handles (SonataCompiler *, SonataEngine *, SonataAudio *) are created by their _new/_open24 * function, owned by the caller, and released exactly once with their _free function. The25 * library keeps a table of the handles it has given out: every function checks its handle26 * against it before use. NULL gives SONATA_ERR_NULL; a pointer that was already freed or never27 * came from this library gives SONATA_ERR_STALE (or the neutral value / an error JSON) and is28 * not dereferenced; a second _free of the same pointer is refused with SONATA_ERR_STALE.29 * This defines sequential misuse. It cannot make a race safe: freeing a handle while another30 * thread is inside a call on it is undefined, as is using an address the allocator has since31 * given to a newer handle. In particular the host must stop its audio callback BEFORE32 * sonata_engine_free.33 * - `const char *` arguments are borrowed for the duration of the call and never kept.34 * - `char *` results are owned by the caller (sonata_string_free, exactly once).35 * - Buffer arguments (`float *`, `SonataMeter *`, `uint32_t *`, structs) are borrowed for the36 * call; the caller guarantees the stated capacity. The library never keeps them.37 * - sonata_audio_channel returns a pointer INTO the SonataAudio: valid until sonata_audio_free.38 * - `context` of a progress callback is passed back untouched and never dereferenced; `cancel`39 * is read (never written) until the render call returns.40 */41#ifndef ORIX_SONATA_H42#define ORIX_SONATA_H4344#include <stdbool.h>45#include <stddef.h>46#include <stdint.h>4748#ifdef __cplusplus49extern "C" {50#endif5152#define SONATA_ABI_VERSION 15354typedef struct SonataCompiler SonataCompiler;55typedef struct SonataEngine SonataEngine;56typedef struct SonataAudio SonataAudio;57typedef struct SonataStudio SonataStudio;58typedef struct SonataRecorder SonataRecorder;59typedef struct SonataMidiCapture SonataMidiCapture;6061/** Status of control functions. Callers may ignore it; nothing is left half done on an error. */62enum {63 SONATA_OK = 0,64 SONATA_ERR_NULL = -1, /* a required pointer was NULL */65 SONATA_ERR_STALE = -2, /* the handle is not live: already freed, or not from this library */66 SONATA_ERR_PANIC = -3, /* internal error, contained; the call had no effect */67 SONATA_ERR_ARGUMENT = -4 /* a value was out of its domain (non-finite, unknown selector) */68};6970/* ── General ─────────────────────────────────────────────────────────────── */7172/** ABI version of the loaded library; must equal SONATA_ABI_VERSION. */73uint32_t sonata_abi_version(void);74/** JSON: {"version","language_version","ir_version","build"} */75char *sonata_version_json(void);76void sonata_string_free(char *s);77/** JSON of the registry: engines, effects and patch nodes with parameters, units, ranges, presets. */78char *sonata_registry_json(void);7980/* ── Language services (stateless) ───────────────────────────────────────── */8182/** Canonical formatting. JSON: {"ok":bool,"text":string,"diagnostics":[Diagnostic]} */83char *sonata_format(const char *source);84/**85 * Syntax classes for highlighting. Writes up to `capacity` triples (byte start, byte length,86 * class) and returns the number of triples available. Classes: 0 keyword, 1 identifier,87 * 2 number, 3 unit, 4 note, 5 string, 6 comment, 7 operator, 8 punctuation, 9 type,88 * 10 function, 11 parameter, 12 instrument, 13 error.89 */90size_t sonata_highlight(const char *source, uint32_t *triples, size_t capacity);9192/* ── Compiler session ────────────────────────────────────────────────────── */9394SonataCompiler *sonata_compiler_new(void);95int32_t sonata_compiler_free(SonataCompiler *compiler);96/** Directory used to resolve non-std imports and assets; NULL forbids both. */97int32_t sonata_compiler_set_root(SonataCompiler *compiler, const char *project_root);98/**99 * Supplies the unsaved text of a module (path relative to the root, e.g. "src/motifs.sonata");100 * NULL text removes the overlay. Lets the editor compile what is on screen, not what is on disk.101 */102int32_t sonata_compiler_set_overlay(SonataCompiler *compiler, const char *relative_path, const char *text);103/**104 * Compiles. `options_json` may be NULL or {"overrides":Overrides,"sample_rate":u32,"composition":string}.105 * Returns JSON {"ok","diagnostics","stats","conflicts","timeline"}. When ok, the compiled program106 * becomes the session's current program; when not, the previous valid program is kept.107 */108char *sonata_compiler_compile(SonataCompiler *compiler, const char *name, const char *source, const char *options_json);109bool sonata_compiler_has_program(const SonataCompiler *compiler);110/** `what`: "ast" | "program" | "graph" | "score" | "timeline". JSON, or {"error":...}. */111char *sonata_compiler_export_json(SonataCompiler *compiler, const char *what);112/**113 * Editor queries on `source` at byte `offset`. `kind`: "completions" | "hover" | "definition" |114 * "references" | "symbols" | "signature". Returns JSON.115 */116char *sonata_compiler_query(SonataCompiler *compiler, const char *kind, const char *source, uint32_t offset);117118/* ---- Language services ------------------------------------------------------------------119 * For the editor. Every function here follows the rules of the compiler section: the handle120 * comes from sonata_compiler_new, a returned string is owned by the caller and released with121 * sonata_string_free, a panic is contained and answers "null", an invalid handle answers122 * "null". Offsets are UTF-8 byte offsets into `source`. Not real-time safe.123 */124/**125 * sonata_compiler_compile that can be given up. `cancel` is NULL or points to an int32_t the126 * caller owns and keeps valid for the whole call; storing a non-zero value in it from another127 * thread makes the compilation return early (it is read between modules, phases and tracks128 * and every 256 evaluation steps). A cancelled call returns {"ok":false,"cancelled":true,129 * "diagnostics":[],"stats":null,"conflicts":[],"timeline":null} and leaves the current130 * program and the session as they were.131 */132char *sonata_compiler_compile_cancellable(SonataCompiler *compiler, const char *name, const char *source, const char *options_json, const int32_t *cancel);133/**134 * One entry for every editor service. `file` names the file whose text is `source` (NULL:135 * the root of the last compilation); `start`/`end` delimit a position (start == end) or a136 * range; `arg` may be NULL. Kinds and results (JSON):137 * "completion" [{label,kind,detail,doc,insert,replace_start,replace_end}]138 * "hover" {start,end,markdown} | null139 * "signature" {label,doc,parameters:[string],active_parameter} | null140 * "definition" {file,start,end,line,column} | null141 * "references" [{file,start,end,line,column}]142 * "outline" [{name,kind,detail,start,end,children}]143 * "prepare_rename" {start,end,name,kind} | {"error":reason}144 * "rename" arg = new name; [{file,file_id,start,end,new_text}] | {"error":reason}145 * "code_actions" [{title,kind,diagnostic,edits:[edit]}]146 * "folding" [{start,end,kind}]147 * "format_range" [{file,file_id,start,end,new_text}]148 * "semantic_tokens" {legend:[string],tokens:[start,length,class,...]} (whole file when start == end)149 * "legend" [string]150 * "workspace_symbols" arg = query; [{name,kind,detail,location}]151 * "events_at" [{id,track,start_beats,duration_beats,start_sec,end_sec,pitch,hz,velocity,location}]152 * "span_of" arg = event id in decimal; location | null153 * "trace" {schema,events:[...]} of the compiled piece, null when it does not compile154 * "imports" [{module,imports:[string]}]155 * "dependents" arg = module; [string]156 * An unknown kind answers "null". `location` is {file,file_id,start,end,line,column,end_line,end_column}.157 */158char *sonata_services_query(SonataCompiler *compiler, const char *kind, const char *file, const char *source, uint32_t start, uint32_t end, const char *arg);159/**160 * Writes the current program as a file. `format`: "midi" | "musicxml". Atomic write; refuses to161 * replace an existing file unless `overwrite`. JSON {"ok","warnings":[string],"error"}.162 */163char *sonata_compiler_export_file(SonataCompiler *compiler, const char *format, const char *path, bool overwrite);164/** Reads a Standard MIDI File and returns Sonata source. JSON {"ok","source","error"}. */165char *sonata_import_midi(const char *path, const char *instrument);166167typedef void (*SonataProgress)(void *context, double fraction);168/**169 * Offline render of the current program. `options_json`:170 * {"path","format":"wav|aiff|flac","bit_depth":16|24|32,"float":bool,"sample_rate":u32,171 * "start_sec","end_sec","tail":bool,"dither":bool,"normalize":"none|peak|lufs","target":f64,172 * "stems":bool,"overwrite":bool}173 * `cancel` may be NULL; when it becomes non-zero the render stops and the partial file is removed.174 * JSON {"ok","files":[{"path","frames","sample_rate","channels","peak_db","true_peak_db","lufs"}],175 * "seconds","realtime_factor","cancelled","error"}176 */177char *sonata_compiler_render(SonataCompiler *compiler, const char *options_json, SonataProgress progress, void *context, const volatile int32_t *cancel);178179/* ── Real-time engine ────────────────────────────────────────────────────── */180181/**182 * Creates an engine at `sample_rate` (8 000 – 384 000 Hz, rounded). NULL when 256 engines are183 * already alive. The monitor gain of a new engine is 0 dB: a host that drives a device sets its184 * own prudent level before starting the callback (SonataBridge's AudioHost uses -12 dB).185 */186SonataEngine *sonata_engine_new(double sample_rate, uint32_t max_block_frames);187/** The audio callback must have stopped calling sonata_engine_process for this engine. */188int32_t sonata_engine_free(SonataEngine *engine);189/**190 * Prepares the compiler's current program for this engine (off the audio thread) and hands it to191 * the audio thread, which swaps at a block boundary with a short crossfade and keeps the192 * transport position. JSON {"ok","error","prepare_us","voices","nodes","latency_frames"}.193 */194char *sonata_engine_load(SonataEngine *engine, SonataCompiler *compiler);195/**196 * RT. Fills `frames` stereo frames (any count; the result does not depend on how time is cut197 * into blocks). The output is already protected: monitor gain, mute and fade-in ramps, silence198 * while a fault is latched, clamp to [-1, 1]. A NULL or stale engine gives silence.199 */200void sonata_engine_process(SonataEngine *engine, float *left, float *right, uint32_t frames);201202int32_t sonata_engine_play(SonataEngine *engine);203int32_t sonata_engine_pause(SonataEngine *engine);204/** Stops and returns to the start (or to the loop start when cycling). */205int32_t sonata_engine_stop(SonataEngine *engine);206int32_t sonata_engine_seek(SonataEngine *engine, double seconds);207int32_t sonata_engine_set_loop(SonataEngine *engine, bool enabled, double start_seconds, double end_seconds);208int32_t sonata_engine_set_metronome(SonataEngine *engine, bool enabled, float gain_db, uint32_t count_in_bars);209/** RT-safe reads (0 for a NULL or stale engine). Position in seconds of program time. State: 0 stopped, 1 playing, 2 paused. */210double sonata_engine_position(const SonataEngine *engine);211int32_t sonata_engine_state(const SonataEngine *engine);212/** Length in seconds of the loaded program, release and effect tails excluded. */213double sonata_engine_duration(const SonataEngine *engine);214215enum { SONATA_STRIP_TRACK = 0, SONATA_STRIP_BUS = 1, SONATA_STRIP_MASTER = 2 };216enum { SONATA_PARAM_GAIN_DB = 0, SONATA_PARAM_PAN = 1, SONATA_PARAM_MUTE = 2, SONATA_PARAM_SOLO = 3 };217/** Live mixer control (smoothed on the audio thread). Lost at the next load unless also stored as an override. */218int32_t sonata_engine_set_strip(SonataEngine *engine, int32_t strip_kind, uint32_t strip_id, int32_t param, float value);219/**220 * Output gain applied after the master, in dB, clamped to [-120, 0] (-120 = silence; a221 * non-finite value is taken as silence). Monitor level only: never part of renders. Reaches the222 * audio thread through an atomic (works even when the command queue is full), 20 ms ramp.223 */224int32_t sonata_engine_set_monitor_gain(SonataEngine *engine, float gain_db);225/** Mutes or unmutes the device output with a 20 ms ramp. Meters keep reading the programme. */226int32_t sonata_engine_set_mute(SonataEngine *engine, bool muted);227/** The output restarts from silence and ramps up over 20 ms. Call before (re)starting a device. */228int32_t sonata_engine_fade_in(SonataEngine *engine);229230/**231 * Output faults. When a non-finite sample or a runaway level (above +18 dBFS after the limiter)232 * reaches the master, the engine latches a fault: the chunk that contained it and everything233 * after it is exact silence, instruments and effects are reset, and the bits below are set.234 * The output stays silent until sonata_engine_rearm, whatever else is done.235 */236enum {237 SONATA_FAULT_NON_FINITE = 1,238 SONATA_FAULT_OVERLOAD = 2,239 SONATA_FAULT_PANIC = 4 /* the engine itself failed: it stays silent and must be replaced */240};241/**242 * The host reports a fault it observed itself (SONATA_FAULT_NON_FINITE and/or243 * SONATA_FAULT_OVERLOAD; other bits are refused): same silence, same re-arm.244 */245int32_t sonata_engine_latch_fault(SonataEngine *engine, uint32_t bits);246/** RT-safe read of the latched fault bits; 0 when healthy. */247uint32_t sonata_engine_fault(const SonataEngine *engine);248/**249 * Clears a latched fault: components are reset, notes held at the transport position are250 * restarted and the output fades back in. SONATA_ERR_PANIC when the fault is SONATA_FAULT_PANIC251 * (that engine cannot be re-armed).252 */253int32_t sonata_engine_rearm(SonataEngine *engine);254255typedef struct {256 uint32_t fault; /* SONATA_FAULT_* bits, latched */257 uint32_t muted; /* 1 when sonata_engine_set_mute(true) is in effect */258 uint64_t fault_events; /* faults latched since creation */259 float monitor_gain; /* linear target set by sonata_engine_set_monitor_gain */260 float output_gain; /* linear gain applied at the end of the last callback */261 uint64_t scrubbed_samples; /* non-finite samples replaced by silence */262 uint64_t clamped_samples; /* samples the final clamp brought back to [-1, 1] */263 uint64_t dropped_commands; /* control changes lost because the command queue was full */264 uint64_t deferred_command_chunks; /* chunks that left commands for the next one (control flood) */265 uint64_t underruns; /* reported by the host */266} SonataEngineHealth;267int32_t sonata_engine_health(const SonataEngine *engine, SonataEngineHealth *health);268269/** Auditions a note on a track of the loaded program. Returns the note id for sonata_engine_note_off. */270uint64_t sonata_engine_note_on(SonataEngine *engine, uint32_t track_id, float midi_pitch, float velocity);271int32_t sonata_engine_note_off(SonataEngine *engine, uint32_t track_id, uint64_t note_id);272int32_t sonata_engine_all_notes_off(SonataEngine *engine);273274typedef struct {275 int32_t strip_kind;276 uint32_t strip_id;277 /** Linear sample peaks and RMS since the previous call (peak) / over the meter window (RMS). */278 float peak_left, peak_right, rms_left, rms_right;279} SonataMeter;280/** Copies up to `capacity` meters (tracks, buses, then master) and returns how many exist. */281size_t sonata_engine_meters(SonataEngine *engine, SonataMeter *meters, size_t capacity);282283/** Chooses what the scope tap observes (default: master, post limiter). */284int32_t sonata_engine_set_tap(SonataEngine *engine, int32_t strip_kind, uint32_t strip_id);285/**286 * Copies the most recent `frames` stereo frames seen by the tap (oldest first) and returns the287 * number written (less when fewer were produced). Never blocks the audio thread.288 */289size_t sonata_engine_read_tap(SonataEngine *engine, float *left, float *right, size_t frames);290/** Total frames the tap has produced since the engine started (to detect new data). */291uint64_t sonata_engine_tap_frames(const SonataEngine *engine);292293typedef struct {294 uint64_t callbacks;295 double mean_us, p50_us, p95_us, p99_us, max_us;296 /** Callbacks that took longer than their buffer duration. */297 uint64_t overruns;298 /** Buffer duration of the last callback, microseconds. */299 double budget_us;300 uint32_t active_voices;301 uint32_t peak_voices;302 /** Loudness of the master: momentary, short-term, integrated (LUFS) and true peak (dBTP). */303 double lufs_momentary, lufs_short_term, lufs_integrated, true_peak_db;304 /** Non-finite samples scrubbed and samples clamped by the safety stage since start. */305 uint64_t scrubbed_samples, clamped_samples;306} SonataEngineStats;307int32_t sonata_engine_stats(SonataEngine *engine, SonataEngineStats *stats);308int32_t sonata_engine_reset_stats(SonataEngine *engine);309310/* ── Analysis (stateless, not real-time) ─────────────────────────────────── */311312enum { SONATA_WINDOW_RECTANGULAR = 0, SONATA_WINDOW_HANN = 1, SONATA_WINDOW_BLACKMAN = 2, SONATA_WINDOW_BLACKMAN_HARRIS = 3 };313/**314 * Magnitude spectrum in dBFS of `size` samples (`size` a power of two in 256..32768) written to315 * `out_db[0 .. size/2]` (size/2 + 1 values). Calibrated so a full-scale sine reads 0 dBFS at its316 * bin whatever the window. Returns false for an unsupported size.317 */318bool sonata_spectrum(const float *samples, uint32_t size, int32_t window, float *out_db);319/**320 * Measurements of a mono signal. JSON {"fundamental_hz","confidence","peak_db","rms_db","dc",321 * "thd_percent","harmonics":[{"n","hz","db"}],"inharmonicity","noise_db","crest_db"}.322 */323char *sonata_measure(const float *samples, size_t count, double sample_rate);324/** Stereo measurements. JSON {"correlation","balance","width","mid_rms_db","side_rms_db"}. */325char *sonata_measure_stereo(const float *left, const float *right, size_t count);326/** Loudness of a stereo buffer. JSON {"integrated","short_term_max","momentary_max","range","true_peak_db","sample_peak_db"}. */327char *sonata_loudness(const float *left, const float *right, size_t count, double sample_rate);328329/* ── WaveLab measurements ────────────────────────────────────────────────── */330331/**332 * An analysis running on its own thread. Create with sonata_analysis_start, poll its state and333 * progress from any thread, read its result once done, free with sonata_analysis_free. The334 * handle is checked like every other: NULL, stale and foreign pointers are refused.335 */336typedef struct SonataAnalysis SonataAnalysis;337338enum { SONATA_ANALYSIS_RUNNING = 0, SONATA_ANALYSIS_DONE = 1, SONATA_ANALYSIS_FAILED = 2, SONATA_ANALYSIS_CANCELLED = 3 };339340/**341 * The measurements, the options of a request with their defaults, and the limits.342 * JSON {"schema":1,"measures":[{"name","needs_reference","description"}],"options":{...},343 * "limits":{"max_samples"}}. Caller frees with sonata_string_free.344 */345char *sonata_analysis_measures_json(void);346/**347 * Runs measurements on the calling thread and returns their tables. For the quick ones only348 * (spectrum, loudness, thd, ...): the constant-Q transform of a long file takes seconds; use a349 * job for it.350 *351 * `request_json`: {"measures":["spectrum","thd"],"sample_rate":48000,"options":{"range":[a,b],352 * "at_s":t,"at_hz":f,"fft_size":4096,...}}; an unknown option or measure is an error, not ignored.353 * `left` is the signal (`count` floats); `right` is NULL for mono or `count` floats;354 * `ref_left` / `ref_right` are the reference of the comparing measures (`ref_count` floats), or355 * NULL. The buffers are only read during the call.356 *357 * Returns {"ok":true,"schema":1,"tables":[{"name","title","columns":[{"name","unit"}],358 * "rows":[[...]],"summary":[{"name","value","unit"}],"notes":[...],"matrix":bool}]} or359 * {"ok":false,"error"}. A value that does not exist (level of silence, pitch of noise) is null.360 * Units are exact: dBFS, dBTP, dB, dBc, LUFS, LU, Hz, cents, s, samples, degrees, %, count,361 * dB/s, or "" for a pure number. In a matrix table the first column is time and every other362 * column is one frequency, named by its value in Hz.363 */364char *sonata_analyze(const char *request_json, const float *left, const float *right, size_t count, const float *ref_left, const float *ref_right, size_t ref_count);365/**366 * Starts the same work on a thread of its own. The signals are copied: they may be freed as367 * soon as the call returns. NULL on error with `*error` set (caller frees; `error` may be NULL).368 */369SonataAnalysis *sonata_analysis_start(const char *request_json, const float *left, const float *right, size_t count, const float *ref_left, const float *ref_right, size_t ref_count, char **error);370/** SONATA_ANALYSIS_*; a negative status for a bad handle. Never blocks. */371int32_t sonata_analysis_state(const SonataAnalysis *analysis);372/** Progress from 0 to 1 (-1 for a bad handle). Never blocks. */373double sonata_analysis_progress(const SonataAnalysis *analysis);374/** Asks the job to stop; it ends at its next poll (once per constant-Q frame, between measures). */375int32_t sonata_analysis_cancel(const SonataAnalysis *analysis);376/**377 * The tables of a finished job, as sonata_analyze returns them except that a matrix table has378 * "rows":null and instead "dimensions":{"rows","columns"}, "times_s":[...] and379 * "frequencies_hz":[...]; its levels are read with sonata_analysis_matrix. While the job runs,380 * after a failure or a cancellation: {"ok":false,"error","state"}.381 */382char *sonata_analysis_result(const SonataAnalysis *analysis);383/**384 * Levels of matrix table number `table` (its index in "tables"), row-major: `rows * columns`385 * floats in dBFS, one row per time of "times_s", one column per frequency of "frequencies_hz";386 * -240 means no energy. Returns that number of floats; writes them only if `out` is not NULL387 * and `capacity` (in floats) is large enough, so call once with NULL to size the buffer.388 * Negative for a bad handle, an unfinished job, or a table that is not a matrix.389 */390int64_t sonata_analysis_matrix(const SonataAnalysis *analysis, uint32_t table, float *out, size_t capacity);391/** Frees a job. A running job is cancelled and ends by itself: the call does not wait. */392int32_t sonata_analysis_free(SonataAnalysis *analysis);393/**394 * Routing of a DSP graph for drawing. `graph_json` is what sonata_compiler_export_json(c,395 * "graph") returns. JSON {"schema":1,"sample_rate","nodes":[{"id","kind","label","strip",396 * "latency_samples","latency_s","total_latency_samples","total_latency_s"}],397 * "edges":[{"from","to","kind":"audio"|"sidechain"}],398 * "compensation":[{"node","samples","seconds","after","before"}],"order","output",399 * "total_latency_samples","total_latency_s"}; node kinds: instrument, audio_clips, effect,400 * fader, send, sum, compensation, limiter, output. {"ok":false,"error"} if it is not a graph.401 */402char *sonata_routing_json(const char *graph_json);403404/* ── Audio files ─────────────────────────────────────────────────────────── */405406/** Opens and fully decodes a WAV/AIFF/FLAC file (validated sizes and formats). NULL on error, with `*error` set (caller frees). */407SonataAudio *sonata_audio_open(const char *path, char **error);408int32_t sonata_audio_free(SonataAudio *audio);409uint64_t sonata_audio_frames(const SonataAudio *audio);410uint32_t sonata_audio_channels(const SonataAudio *audio);411double sonata_audio_sample_rate(const SonataAudio *audio);412/** Pointer to the samples of one channel (valid until sonata_audio_free); NULL if out of range. */413const float *sonata_audio_channel(const SonataAudio *audio, uint32_t channel);414/**415 * Waveform overview computed from the real PCM: for each of `buckets` consecutive windows of416 * `frames_per_bucket` frames starting at `start_frame`, the minimum, maximum and RMS.417 * Uses a cached multi-resolution pyramid. Returns the number of buckets written.418 */419size_t sonata_audio_overview(SonataAudio *audio, uint32_t channel, uint64_t start_frame, double frames_per_bucket, size_t buckets, float *out_min, float *out_max, float *out_rms);420421/* ── Lab (WaveLab and Instrument Lab; stateless, not real-time) ──────────── */422423/**424 * Measured response of a registry effect to an impulse of `amplitude` (fully wet, as the runtime425 * runs it). `params_json` may be NULL or {"name": number | "choice", ...}; other parameters keep426 * the descriptor defaults. `fft_size` is a power of two in 256..65536. For a non-linear effect427 * the result describes that impulse only. JSON {"ok","sample_rate","fft_size","amplitude",428 * "latency","bin_hz","impulse":[..],"magnitude_db":[..],"phase":[..],"group_delay_ms":[..]}429 * (fft_size/2 + 1 bins; phase unwrapped in radians with the latency removed) or {"ok":false,"error"}.430 */431char *sonata_effect_response(const char *kind, const char *params_json, double sample_rate, uint32_t fft_size, float amplitude);432/**433 * Peak envelope of a recorded note (one value per `hop` samples) and the times measured on it,434 * `gate_off_sec` being the note-off time. JSON {"ok","hop","hop_sec","envelope":[..],"peak",435 * "peak_time_sec","attack_10_90_sec","sustain_level","decay_sec","release_t60_sec"}; measured436 * fields are null when they cannot be measured.437 */438char *sonata_envelope(const float *samples, size_t count, double sample_rate, double gate_off_sec, uint32_t hop);439/**440 * Writes PCM to a .wav, .aiff or .flac file atomically. `right` may be NULL (mono). `bits` 16, 24441 * or 32; `is_float` selects 32-bit float. Refuses to replace a file unless `overwrite`.442 * JSON {"ok","frames","bytes","clipped_samples","error"}.443 */444char *sonata_write_audio(const char *path, const float *left, const float *right, size_t frames, double sample_rate, uint32_t bits, bool is_float, bool dither, bool overwrite);445446/* ── Studio layer (ADR 0011; not real-time unless marked RT) ─────────────── */447448/*449 * The studio layer is the session stored in studio.json under "overrides"."session": tracks,450 * audio regions, MIDI regions, takes, automation lanes, folders, groups, markers. It is edited451 * through a SonataStudio handle by commands, saved as JSON, and given to452 * sonata_compiler_compile inside options.overrides ({"strips","notes","added","session"}); the453 * compile result's "conflicts" lists what could not be applied. Shapes and examples:454 * Documentation/manual/studio.md, "For the interface".455 *456 * Ownership: every char* returned is owned by the caller and freed with sonata_string_free.457 * Handles are owned by the caller and freed with their _free (or _finish) function; a NULL,458 * stale or foreign handle is refused. One thread at a time per handle.459 */460461/**462 * Opens a session from its JSON (NULL or "null": an empty session). NULL on a document that463 * cannot be read or was written by a later version; `*error` then receives the reason.464 */465SonataStudio *sonata_studio_new(const char *session_json, char **error);466int32_t sonata_studio_free(SonataStudio *studio);467/** The session as JSON, to store in studio.json and to pass to the compiler. */468char *sonata_studio_json(const SonataStudio *studio);469/** JSON {"can_undo","can_redo","undo_depth","redo_depth","journal_error","tracks","next_id"}. */470char *sonata_studio_state(const SonataStudio *studio);471/**472 * Applies one command ({"op": "...", ...}). JSON {"ok":true,"state":{...}} or473 * {"ok":false,"error"}; a refused command leaves the session exactly as it was.474 */475char *sonata_studio_command(SonataStudio *studio, const char *command_json);476/** 1 when a step was undone (redone), 0 when there was none, negative on a bad handle. */477int32_t sonata_studio_undo(SonataStudio *studio);478int32_t sonata_studio_redo(SonataStudio *studio);479/**480 * Call right after saving the session: starts the edit journal at `journal_path` from the481 * current state, keeping the undoable steps. Every later command is appended and synced.482 */483char *sonata_studio_checkpoint(SonataStudio *studio, const char *journal_path);484/**485 * Rebuilds a session and its undo stack from the last saved session and its journal (after a486 * crash, or at launch to keep undo). `*report_json` receives {"replayed","truncated",487 * "undo_depth"}. NULL with `*error` when the journal belongs to another session or is damaged.488 */489SonataStudio *sonata_studio_recover(const char *saved_session_json, const char *journal_path, char **report_json, char **error);490/** JSON [{"id","title","description"}] of the session templates. */491char *sonata_studio_templates(void);492/** Session JSON of a template, or NULL for an unknown identifier. */493char *sonata_studio_template(const char *id);494/**495 * Proposes Sonata source for the studio tracks the language can express, against the last496 * compilation of `compiler`. Nothing is written. JSON {"ok","insert","new_source","diff",497 * "converted":[names],"kept":[reasons],"remaining":session} or {"ok":false,"error"}.498 */499char *sonata_studio_to_code(const SonataStudio *studio, const SonataCompiler *compiler);500/**501 * Renders one track after its inserts and before its fader into a 32-bit float WAV at502 * `out_path` (the last compilation and its overrides are used). Blocks; call it off the main503 * thread. `progress` may be NULL; `cancel` NULL or a flag read during the render. JSON504 * {"ok","fingerprint","file":{"path","asset","sha256","frames","sample_rate","channels",505 * "length_ticks"}} or {"ok":false,"error","cancelled"}. Store the result with the command506 * set_track {"frozen":{"asset","fingerprint"}}.507 */508char *sonata_studio_freeze(const SonataCompiler *compiler, const char *track, const char *out_path, SonataProgress progress, void *context, const volatile int32_t *cancel);509/** Records what a bus puts out into a file (internal resampling). JSON {"ok","file"} as above. */510char *sonata_studio_bounce_bus(const SonataCompiler *compiler, const char *bus, const char *out_path);511/** Mixes `regions_json` (array of regions) over [from, to) ticks into one file. JSON {"ok","file"}. */512char *sonata_studio_consolidate(const SonataCompiler *compiler, const char *regions_json, int64_t from, int64_t to, const char *out_path);513/**514 * Renders the warp of a region into the project's assets (cache/warp-<key>.wav) unless it is515 * already there. JSON {"ok","cache","cache_key","frames"}; store both in the region's warp.516 */517char *sonata_studio_warp(const SonataCompiler *compiler, const char *region_json, const char *asset_sha256, const char *context);518/** Sample positions of the attacks found in `samples`; returns how many were written to `out`. */519size_t sonata_studio_transients(const float *samples, size_t count, double sample_rate, uint64_t *out, size_t capacity);520521/**522 * Starts a recording into `folder` (files take-<stamp>-<pass>.wav, 32-bit float stereo).523 * `options_json` may be NULL or {"sample_rate","latency_samples","ring_seconds","punch_in",524 * "punch_out"} (samples). Nothing is recorded until sonata_recorder_arm.525 */526SonataRecorder *sonata_recorder_start(const char *folder, const char *stamp, const char *options_json, char **error);527/**528 * RT. One input block and the timeline sample of its first frame. No allocation, lock or529 * system call. Input that does not fit in the ring is counted as dropped, never waited for.530 */531void sonata_recorder_push(const SonataRecorder *recorder, uint64_t position, const float *left, const float *right, uint32_t frames);532/** RT. Adds the input to the output at `gain` (linear, 0 = off), ramped over 10 ms. */533void sonata_recorder_monitor(const SonataRecorder *recorder, float gain, const float *in_left, const float *in_right, float *out_left, float *out_right, uint32_t frames);534int32_t sonata_recorder_arm(const SonataRecorder *recorder, bool armed);535int32_t sonata_recorder_set_punch(const SonataRecorder *recorder, bool enabled, uint64_t punch_in, uint64_t punch_out);536/** JSON {"ok","recording","pushed","written","dropped","failed","takes":[...]}. */537char *sonata_recorder_status(const SonataRecorder *recorder);538/**539 * Stops, writes what is left, completes the files and frees the recorder; the audio callback540 * must have stopped pushing to it. JSON {"ok","takes":[{"name","path","pass","error",541 * "position_samples","frames","sample_rate","position_ticks","length_ticks"}]}.542 */543char *sonata_recorder_finish(SonataRecorder *recorder);544/** Completes a take file left by a crash. JSON {"ok","frames","sample_rate","repaired","length_ticks"}. */545char *sonata_take_recover(const char *path);546/**547 * Loopback latency: lag in samples at which `received` best matches `sent`, -1 when nothing548 * correlates; `*confidence` (may be NULL) receives the correlation there.549 */550int64_t sonata_measure_latency(const float *sent, size_t sent_count, const float *received, size_t received_count, size_t max_lag, float *confidence);551552/** Collects incoming MIDI; always keeps the last `keep_seconds` for retrospective capture. */553SonataMidiCapture *sonata_midi_capture_new(double keep_seconds);554int32_t sonata_midi_capture_free(SonataMidiCapture *capture);555/**556 * Not RT (takes a lock): call from the MIDI thread. `kind`: 0 note off, 1 note on,557 * 2 controller, 3 pitch bend (`value` in semitones), 4 channel pressure, 5 polyphonic pressure;558 * `number` is the key or the controller; other values are 0..1.559 */560int32_t sonata_midi_capture_push(const SonataMidiCapture *capture, double time_seconds, uint8_t channel, int32_t kind, uint8_t number, float value);561int32_t sonata_midi_capture_start(const SonataMidiCapture *capture, double time_seconds);562/**563 * Ends the recording and turns it into the content of a MIDI region starting at564 * `origin_seconds`, placed with the tempo map of the last compilation. `options_json` may be565 * NULL or {"apply_sustain","mpe","quantise":{"grid","strength","swing","ends"}}. JSON {"ok",566 * "events","position","length","notes":[...],"controllers":[...]}.567 */568char *sonata_midi_capture_stop(const SonataMidiCapture *capture, const SonataCompiler *compiler, double origin_seconds, const char *options_json);569/** The same for what was played during the last `seconds` before `now_seconds`, recording or not. */570char *sonata_midi_capture_retrospective(const SonataMidiCapture *capture, const SonataCompiler *compiler, double now_seconds, double seconds, const char *options_json);571572#ifdef __cplusplus573}574#endif575#endif /* ORIX_SONATA_H */576