Node.js Native API
@libraz/libsonare-native is libsonare's Node.js binding: a native addon that calls the C++ library directly, with no WebAssembly layer. This page is its landing page. It covers what the addon is, how to build and load it, the conventions every call shares (request objects, errors, releasing handles), the ABI check, and the mixing, project and streaming classes. The function-by-function listings are on the Node pages below. Examples use the native package unless an import path is explicitly @libraz/libsonare.
What are N-API and a "native addon"?
A native addon is a compiled C/C++ module that Node loads like a normal package. It runs real machine code instead of JavaScript or WebAssembly.
N-API (Node-API) is the stable interface Node provides for building these addons. It shields the addon from V8 engine internals, so one compiled binary can keep working across Node versions without recompiling.
The practical upside is native speed and direct file decoding from Node. The cost is that the addon must be built for your platform, instead of running everywhere like the WASM package.
What You Will Learn
By the end of this page you should be able to:
- decide between browser WASM, Python, and Node native without treating them as interchangeable packages;
- build and import the Node N-API addon, and tell which examples use
@libraz/libsonareand which use@libraz/libsonare-native; - release native handles, catch errors, and recognize an ABI mismatch;
- map native addon functions back to the broader JavaScript, Python, mastering, and mixing docs;
- find the Node page that lists a function.
Comparison
| WebAssembly | Python | Node.js (N-API) | |
|---|---|---|---|
| Platform | Browser | Desktop | Desktop |
| Initialization | await init() | None | None |
| Distribution | npm (@libraz/libsonare) | PyPI (pip install libsonare) | Source (bindings/node) |
| Build | Emscripten | Pre-built wheels (or CMake + pip) | CMake + cmake-js |
| Performance | Near-native | Native | Native |
| Handle release | destroy(), or using where the runtime supports it | with / close() | destroy(), or using where the runtime supports it |
| File I/O | Sample-based APIs; Audio.fromMemory(...) decodes WAV/MP3 bytes, and the browser decode path can read additional supported formats | WAV/MP3 by default; FFmpeg formats in FFmpeg builds | WAV/MP3 by default; FFmpeg formats in FFmpeg builds |
| Ordinary analysis, effects, features, conversions, mastering, mixing, streaming | Same feature set | Same feature set | Same feature set |
Use Python for scripts and notebooks, WASM for browser apps, and Node native only when you specifically need native file decoding or native runtime performance from Node.js. Python is covered by the Python API; Installation compares the two Node packages.
What Differs From WASM
The function names, request shapes and results are shared with the browser package, so the JavaScript reference is the option-level reference for both. What changes on Node:
| WASM | Node native | |
|---|---|---|
| Start-up | await init() before any call | None; the addon checks its ABI when the package is required |
| Files | Decoded samples, or Audio.fromMemory(...) bytes | Audio.fromFile(path) and Audio.fileNumChannels(path) as well |
| Off-thread work | OfflineWorkerClient | The *Async variants of the analysis calls (Asynchronous variants) |
| Browser helpers | bindWebMidi, bindMicrophoneInput, OPFS clip streams, the worklet facade | Not part of the addon; RealtimeEngine is used directly |
| Strip references | StripRef: index or scene id | The same |
Node Pages
| Page | Covers |
|---|---|
| This page | Loading, request objects, errors, Audio, handle release, ABI versions, mixing, projects and the streaming classes |
| Analysis, Effects and Utilities | Analysis, effects, conversions, metering, scale quantization and the stateful class methods |
| Feature Extraction | Spectrograms, mel, MFCC, chroma, pitch and spectral features, inverse reconstruction and the librosa-compatible helpers |
| Mastering, Repair and Assistant | masterAudio, the named processors, the repair functions, the mastering assistant and StreamingMasteringChain |
| Editing and Retune | Vocal edit sessions, StreamingRetune and the note-editing helpers |
| Types | The exported TypeScript types |
Building and Loading
Requirements
- Node.js 22.12+
- CMake 3.16+
- C++17 compiler
- Yarn 4+
Installation
@libraz/libsonare-native is not published to npm; the published artifacts are the WASM npm package, the Python package and the native CLI release assets. Build it from bindings/node in the source tree; to use it from another project, reference the built local package through your workspace or a file: dependency.
git clone https://github.com/libraz/libsonare.git
cd libsonare/bindings/node
yarn install
yarn buildThe native build auto-detects FFmpeg development libraries via pkg-config. Without FFmpeg it decodes WAV and MP3. To require or disable FFmpeg explicitly:
SONARE_FFMPEG=1 yarn build # require FFmpeg-backed decoding
SONARE_FFMPEG=0 yarn build # force WAV/MP3-only decodingUsage
import {
Audio, analyze, detectBpm, detectKey, detectBeats, version
} from '@libraz/libsonare-native';
// Load audio
const audio = Audio.fromFile('music.mp3');
const samples = audio.data;
const sampleRate = audio.sampleRate;
// Individual analysis
const bpm = detectBpm({ samples, sampleRate });
const key = detectKey({ samples, sampleRate }); // key.root: pitch class 0..11 (C = 0); key.mode: 'major', 'minor', ...
const beats = detectBeats({ samples, sampleRate });
// All-in-one analysis
const result = analyze({ samples, sampleRate });
console.log(`BPM: ${result.bpm}`);
console.log(`Key: ${result.key.name}`); // "C major"
console.log(`Beats: ${result.beats.length}`);Each detect* call computes its own spectrogram from the samples, the transform this demo walks through. analyze() computes it once for the whole pipeline, so prefer it when you want several results from one buffer.
Calling Conventions
One-shot request objects
Top-level one-shot analysis, effects, mastering, metering, feature, mixer, and voice-changer functions take a named request object. Many mono entry points also accept (samples, sampleRate, options?), which normalizes to the same validation, defaults, results, errors, and progress behavior; the stereo, multichannel and matrix-input functions are request-only. A *Request type is exported for each.
const bpm = detectBpm({ samples, sampleRate });
const result = masterAudio({ samples, sampleRate, preset: 'pop' });Errors
Library failures arrive as SonareError — a standard Error whose name is 'SonareError', augmented with a numeric code (an ErrorCode value) and its canonical codeName, for example 'InvalidParameter'. Both packages export ErrorCode, SonareError and the isSonareError(value) type guard, and the same failure reports the same numeric code on every binding.
SonareError is a runtime class, not a type-only declaration, so importing the name by value gives a real binding on this package and on the WASM one alike: a shared TypeScript module can import it from either surface and get the same kind of thing at run time.
instanceof SonareError is brand-based rather than prototype-based — it checks the shape. That means it narrows an error raised by the addon, which carries the shape but never constructs the class, and one that lost its prototype crossing a worker or structuredClone boundary. isSonareError(value) is the same check written as a type guard, and the two are wired to each other so they never disagree; either one is fine. Constructing a SonareError directly is supported for re-raising a native failure across a boundary that does not preserve prototypes.
import { Audio, ErrorCode, isSonareError } from '@libraz/libsonare-native';
try {
const audio = Audio.fromFile('missing.wav');
audio.destroy();
} catch (err) {
if (isSonareError(err)) {
console.error(err.codeName, err.code === ErrorCode.FileNotFound);
}
}Argument problems are raised as native RangeError (a value that is out of range, non-finite, or an unknown id or name) or TypeError (the wrong type), which isSonareError does not match, and they name the function and the argument (<function>: request must be an object, detectBpm: samples must be a Float32Array, detectBpm: sampleRate out of supported range [8000, 384000]). Every call scans its sample and matrix inputs for NaN and infinity and refuses one with a RangeError naming the call and the index; there is no per-call switch that skips the scan. Which failure takes which class and code, here and on every other runtime, is in the error contract, and Error Handling has the ErrorCode enum and a usage example; an addon built from a different tree than the package throws AbiMismatch (code 10) when the package is required, and Installation covers the fix.
Four more refusals are worth knowing:
- A string with an embedded NUL (names, ids, keys, JSON text, file paths) is a
RangeErrornaming the field. - Any call on a handle after
destroy()throwsSonareErrorInvalidState, as does a destroyedHrtfSet,ProjectTimelineorSampleBankpassed as an argument. Destroying twice is a no-op. - A failure caused by earlier configuration rather than by the argument itself (a full insert-automation, strip, MIDI CC, external-destination, controller-binding or sidechain table, a bus or lane change that earlier routing forbids) is
SonareErrorInvalidState. - On
RealtimeEngine, every trailingrenderFrameis optional: omit it to apply at once. A negative value,-1included, is aRangeError.
Audio
| Method | Description |
|---|---|
Audio.fromFile(path, channelIndex?) | Load WAV/MP3 from disk; also FFmpeg-supported formats when capabilities().features.ffmpeg is true. Without channelIndex a multichannel source is downmixed to mono; with it, that one zero-based channel is loaded (a RangeError for a negative or missing channel). Each call decodes the file once |
Audio.fileNumChannels(path) | Channel count of the source file, without loading it as an Audio |
Audio.fromBuffer(samples, sampleRate) | Wrap a mono Float32Array; sampleRate is required |
Audio.fromMemory(data) | Decode encoded audio bytes with the same format support as fromFile |
audio.data | The samples as a Float32Array |
audio.sampleRate | Sample rate (Hz) |
audio.durationSec | Duration (seconds) |
audio.length | Number of samples |
audio.destroy() | Release the native handle; later reads throw SonareError InvalidState, and a second call does nothing. Also [Symbol.dispose] for using |
The Audio instance also exposes the common analysis, effects, feature, loudness, and mastering helpers as methods. For example, use audio.detectBpm() or audio.masterAudio({ preset: 'pop' }) when you already have an Audio object.
A few focused helpers remain standalone functions, including analyzeSections(...), analyzeMelody(...), cqt(...), and vqt(...). For those, pass audio.data and audio.sampleRate explicitly.
data is shared, not a copy
The first read of audio.data copies the samples out of the native handle once; every later read returns that same array, which the instance's own methods also read, so writing into it changes what a later audio.detectBpm() or audio.masterAudio(...) sees. Copy it with slice() before editing, and build a new instance with Audio.fromBuffer(edited, sampleRate) to process the edited samples.
Decoding Every Channel
Audio.fromMemory(data) and Audio.fromFile(path) fold a multichannel source to mono. decodeChannels(data) decodes bytes once and keeps every channel: it returns { sampleRate, channels }, one Float32Array per channel in the source's own order (5.1 is L R C LFE Ls Rs). downmix(channels, targetLayout) folds channels to a narrower layout, named by targetLayout as 'mono', 'stereo', '5.1' or '7.1' (a number is a TypeError), with the ITU-R BS.775 rule the decoders use: centre and surround at -3 dB, LFE dropped. It cannot upmix; the result is one Float32Array per output channel. The optional third argument { normalize, includeLfe } scales the fold so the worst case stays at or below full scale (normalize, default false) and folds the LFE plane into the front pair at -3 dB instead of dropping it (includeLfe, default false); without normalize the fold can pass full scale.
import { decodeChannels, downmix } from '@libraz/libsonare-native';
const { sampleRate, channels } = decodeChannels(fs.readFileSync('surround.wav'));
const stereo = channels.length > 2 ? downmix(channels, 'stereo') : channels;Audio Method Differences
The Audio method set is the same on Node and WASM. analyzeBpm, analyzeRhythm, analyzeDynamics, analyzeTimbre and analyzeImpulseResponse are instance methods on both, next to the detection, effects, feature, loudness and mastering helpers. analyzeSections, analyzeMelody and the room functions estimateRoom, synthesizeRir and roomMorph stay standalone on both. The one method Node adds is detectAcoustic(options?); on WASM it is a free function only.
| Capability | Node native | WASM |
|---|---|---|
| File construction | Audio.fromFile(path, channelIndex?), Audio.fromBuffer(...), Audio.fromMemory(...) | Audio.fromBuffer(...), Audio.fromMemory(...), Audio.fromMemoryWithBrowserFallback(...) |
| Sample access | audio.data returns one array that is shared with the instance | Same: audio.data returns one shared array |
| Release | destroy() or using; later reads throw InvalidState | Same |
Lifecycle and Release
Cleanup with using
Every native handle class — Audio, RealtimeEngine, Project, Mixer, and ClipPageProvider — implements [Symbol.dispose], so you can use the using declaration for automatic, throw-safe cleanup at scope exit:
import { RealtimeEngine } from '@libraz/libsonare-native';
function render() {
using engine = new RealtimeEngine({ sampleRate: 48000, maxBlockSize: 128 });
engine.setTempo(120);
// ... the handle is released when this scope ends, even on an exception.
}The using syntax needs TypeScript 5.2 or later (or another tool that lowers it) or a runtime that parses it natively; Node 22 does not, so there call destroy() in a try/finally. destroy() is the release method on every handle class, ProjectTimeline included. GC also reclaims handles eventually, but using/explicit release gives deterministic cleanup that long-lived processes should prefer.
RealtimeVoiceChanger also implements [Symbol.dispose] alongside an explicit destroy(), so it supports using as well. StreamingMasteringChain, StreamingEqualizer, and StreamAnalyzer likewise expose idempotent destroy() and [Symbol.dispose] for deterministic release.
ABI Versions
A binding and the shared library it loads must come from the same tree. The C ABI carries a version per subsystem, each one guarding the exact size and member offsets of that subsystem's flat POD structs, and a binding compares them on load so a layout mismatch is caught before a single byte is exchanged. The practical rule: rebuild the library whenever you rebuild the binding, and never point a binding at a shared library from another checkout.
| ABI | Current | Covers |
|---|---|---|
| Feature | 8 | the flat analysis and feature-result structs plus the shipped general C function contracts — SonareKey, SonareChordDetectionOptions, and their neighbors |
| Project | 3 | the headless-DAW project and arrangement structs. Reports 0 in a build without arrangement support |
| Voice changer | 4 | the realtime voice-changer configuration struct |
| Acoustic | 6 | the room-acoustics structs |
| Engine | 4 | the realtime command queue |
sonare_abi_version() packs the first four into one uint32_t (feature in bits 0-7, project in 8-15, voice changer in 16-23, acoustic in 24-31, aggregate 0x06040308), so one comparison covers all of them. The engine ABI is deliberately excluded and keeps its own accessor, sonare_engine_abi_version(), because it versions a SharedArrayBuffer record layout rather than a POD struct. Each subsystem's header owns its macro (SONARE_FEATURE_ABI_VERSION, SONARE_PROJECT_ABI_VERSION, SONARE_VOICE_CHANGER_ABI_VERSION, SONARE_ACOUSTIC_ABI_VERSION). The feature macro also covers shipped general C function contracts, so a signature change such as the note APIs' voiced argument moves it; the other macros move on layout changes to the structs they guard. The project version moves once per release that changes its layout. Equal values therefore mean identical layout and covered contracts, and a field appended to a guarded struct is a bump, not an additive change.
What each binding does with the number differs, and it decides where a stale library shows up (the error contract puts it beside every other failure, and Installation covers the fix):
- Python compares the packed value against the one it was built for when the library first loads, before configuring a single symbol, and raises a
SonareErrorwithErrorCode.ABI_MISMATCH(10) and a message beginninglibsonare ABI mismatch— a shared library from another checkout fails on first library use, never partway through a call. ItsRealtimeEngineandProjectconstructors, andProject.from_json, check the engine and project versions the same way. The Python CLI exits with 13. - Node native and WASM make the same comparison themselves and throw a
SonareErrorwithErrorCode.AbiMismatch(10): Node when the addon is required, WASM ininit(). Both export the query functionsabiVersion(),projectAbiVersion(),engineAbiVersion()andvoiceChangerAbiVersion(); the Node addon checks the engine ABI when aRealtimeEngineis constructed.projectAbiVersion()isundefinedwhen the build has no project subsystem, andcapabilities().abireports the loadedprojectandengineversions. The engine ABI is outside the packed value, so eachRealtimeEngineconstructor compares it separately and throwsAbiMismatchbefore creating the engine; Node'sProjectconstructor andProject.fromJsondo the same with the project version. - A C caller compares
sonare_abi_version()with its compile-timeSONARE_ABI_VERSIONonce; the JSON entry points (the voice changer's JSON configuration, the capability catalog) tolerate layout drift and need no gate. See C ABI versions.
Every C struct a caller fills leads with struct_size, written by its *_init function, so a struct built against an older layout is refused by name instead of read at the wrong offsets. The version the library reports moves with those layouts, which is why the library has to be rebuilt alongside the binding even when your own code is untouched.
Mastering API
The mastering, repair and assistant functions, with their request shapes, are on Node.js Native Mastering, Repair and Assistant.
Mixing API
The native addon and the WASM package both expose the mixing API: mixStereo(...), mixingScenePresetNames(), mixingScenePreset(name), and the persistent Mixer class.
Use it for channel-strip processing, scene presets, sends, buses, automation, meters, and offline stem rendering. See Mixing Engine for the cross-runtime guide.
For persistent mixers, Node native and WASM both accept a StripRef (number | string: a 0-based strip index or a scene strip id) for the strip control methods; stripById(id) looks an index up by id. An id that names no strip is a RangeError.
Node stripMeter(strip, tap?) reads the post-fader meter by default; pass 'preFader' or 'postFader' as tap when you need an explicit tap. mixer.sceneWarnings() reports recoverable diagnostics such as a send to an undeclared bus; an insert param the processor does not read refuses the scene load with its indexed path and sorted accepted keys.
Projects, Instruments & Live MIDI
The Node native addon exposes the same headless-DAW API as WASM and Python: the Project class (tracks, clips, tempo, undo/redo, SMF/MIDI 2.0 interchange), instrument-bound bounces (Project.bounce with instruments, builtinInstruments, synthInstruments or sf2Instruments, SoundFont loading), the NativeSynth preset catalog (synthPresetNames() / synthPresetPatch() / SynthPatch), chordFunctionalAnalysis(...), and the RealtimeEngine with live MIDI input.
The engine carries the same lane mixer and MIDI clip schedule as the other bindings — setTrackLanes (at most MAX_TRACK_LANES, 32, lanes) / setTrackBuses, strip JSON and insert controls for tracks, the master, and buses, insert automation-id resolvers (each throws a RangeError for an unknown track, bus, insert, destination or parameter), setParamSmoothingMs, wide/scope telemetry, setMidiClips, and sampleAtPpq — with the same camelCase names as WASM. It also exposes external-device routing through setMidiDestinationExternal, setExternalMidiClockEnabled, drainExternalMidi, and externalMidiDroppedCount (see Realtime Engine). The browser-only helpers (bindWebMidi, bindMicrophoneInput) are WASM-specific and not part of the native addon.
The vocal edit session family and the note-editing helpers are on Node.js Native Editing and Retune. The guides carry the depth: Project Editing, Bouncing Projects, Built-in Synthesizer, SoundFont Player, and MIDI Input.
Audio, project and live-device examples
Phase, tags and stereo analysis
Capture phase with stft to reconstruct the original sample length with istft. Pass one equally sized sample array per channel to the encoder. The tag reader takes the encoded bytes. Stereo pair analysis takes a left and a right plane for both inputs.
import { encodeAudio, istft, masteringAnalyzePair, readAudioTags, stft }
from '@libraz/libsonare-native';
const sampleRate = 16000;
const mono = Float32Array.from(
{ length: sampleRate }, (_, i) => 0.2 * Math.sin(2 * Math.PI * 440 * i / sampleRate),
);
const stereo = [mono, mono];
const { magnitude, phase } = stft({ samples: mono, sampleRate, nFft: 256, hopLength: 64, phase: true });
if (!phase) throw new Error('STFT phase is unavailable');
const reconstructed = istft({ magnitude, phase, nFft: 256, hopLength: 64, lengthSamples: mono.length });
const wav = encodeAudio({ channels: stereo, sampleRate, format: 'wav', tags: { title: '440 Hz' } });
console.log(readAudioTags({ data: wav }).title);
const quieter = mono.map(sample => sample * 0.5);
console.log(masteringAnalyzePair({
analysis: 'match.referenceLoudness', source: stereo, reference: [quieter, quieter], sampleRate,
}));Project readers
Tempo and time-signature readers return stored segments. The position reader reports the effective tempo, bar and beat at a PPQ position. Annotation readers preserve the stored order, including overlapping sections. Each automation lane has a project-assigned ID.
import { Project } from '@libraz/libsonare-native';
const project = new Project();
try {
project.setTempoSegments([{ startPpq: 0, bpm: 120 }]);
project.setTimeSignatures([{ startPpq: 0, numerator: 3, denominator: 4 }]);
console.log(project.tempoSegments(), project.timeSignatures());
const ppq = project.barStartPpq(1);
console.log(project.positionAtPpq(ppq), project.secToPpq(project.ppqToSec(ppq)));
project.annotateKeys([{ startPpq: 0, endPpq: 6, tonicPc: 0, mode: 'major' }]);
project.annotateChords([{ startPpq: 0, endPpq: 3, rootPc: 0, quality: 'major' }]);
project.annotateSections([
{ startPpq: 0, endPpq: 4, label: 'Verse' },
{ startPpq: 3, endPpq: 6, label: 'Chorus' },
]);
console.log(project.keyAnnotations(), project.chordAnnotations(), project.sectionAnnotations());
console.log(project.mixerScene(), project.unresolvedSoundFontUris());
const trackId = project.addTrack({ kind: 'audio', name: 'Voice' });
const laneId = project.addAutomationLane(trackId, {
targetKind: 'trackFaderDb',
points: [{ ppq: 0, value: -3 }],
});
console.log(laneId, project.automationLanes());
} finally {
project.destroy();
}MIDI CC bindings
Set consume to route matching controller messages to the parameter and suppress their delivery to the instrument. It defaults to false. The reader returns a snapshot whose order is unspecified.
import { RealtimeEngine } from '@libraz/libsonare-native';
const engine = new RealtimeEngine({ sampleRate: 48000 });
try {
engine.bindMidiCc({ ccNumber: 1, paramId: 42, consume: true });
console.log(engine.midiCcBindings());
} finally {
engine.destroy();
}Live devices
This package reports features.liveDevices as false. LiveSession and its enumeration methods throw a coded NotSupported error with reason notCompiledIn.
import { capabilities, isSonareError, LiveSession } from '@libraz/libsonare-native';
console.log(capabilities().features.liveDevices); // false
try {
LiveSession.audioDevices();
} catch (error) {
if (!isSonareError(error)) throw error;
console.log(error.codeName, error.reason); // NotSupported, notCompiledIn
}Streaming and Realtime Classes
Beyond the one-shot functions, the native addon exposes the same streaming and realtime classes as the WASM build:
| Class | Purpose |
|---|---|
StreamAnalyzer | Block-by-block analysis with BPM/key estimates that update over time and readFrames/readFramesI16/readFramesU8. See Realtime Streaming. |
StreamingEqualizer | Real-time-safe block EQ. A fractional, NaN or oversized maxBlockSize or slope throws a RangeError. |
StreamingMasteringChain | Incremental mastering render (see StreamingMasteringChain). |
RealtimeVoiceChanger | Preset-based live voice chain for block processing. |
Mixer | Persistent multi-strip mixer from a JSON scene. See Mixing Engine. |
RealtimeEngine | Transport/clip/automation engine for DAW-style hosting. |
import { StreamAnalyzer } from '@libraz/libsonare-native';
const analyzer = new StreamAnalyzer({ sampleRate: 48000, computeMel: true, computeOnset: true });
analyzer.process(block); // pass a Float32Array block
const frames = analyzer.readFrames(analyzer.availableFrames);
const stats = analyzer.stats(); // stats.estimate.key (a Key or absent), .key.name ("C major"), .chordreadFrames(maxFrames) returns the float Structure-of-Arrays StreamFrames, with band-major Matrix2D mel and chroma and an array absent for a feature the config did not compute; availableFrames is a getter. setReferenceHz(referenceHz) changes the A4 tuning reference in Hz after construction.
RealtimeVoiceChanger in Node native is constructed with { sampleRate, maxBlockSize?, numChannels, config? }, where config is a preset id ('brightIdol'), a preset object or a full config. Use it with processMono(...), processMonoInto(...), processPlanar(...) or processInterleavedInto(...); latencySamples is a getter. For offline convenience, realtimeVoiceChangerRender({ channels, sampleRate, config? }) runs whole planar channels through the same chain.
import {
RealtimeVoiceChanger,
realtimeVoiceChangerPresetConfig,
realtimeVoiceChangerPresetNames,
realtimeVoiceChangerRender,
voiceCharacterPresetId,
} from '@libraz/libsonare-native';
const changer = new RealtimeVoiceChanger({
sampleRate: 48000,
maxBlockSize: 128,
numChannels: 1,
config: 'brightIdol',
});
const blockOut = changer.processMono(inputBlock);
const [rendered] = realtimeVoiceChangerRender({ channels: [vocal], sampleRate: 48000, config: 'softWhisper' });
const presetConfig = realtimeVoiceChangerPresetConfig('brightIdol');
console.log(
voiceCharacterPresetId(1),
realtimeVoiceChangerPresetNames(),
presetConfig,
changer.latencySamples,
blockOut,
rendered,
);
changer.destroy();RealtimeEngine is constructed with { sampleRate, maxBlockSize?, commandCapacity?, telemetryCapacity?, maxChannels? }. It is shared at the class level with the WASM package, and a few runtime details differ.
| Detail | WASM | Node native |
|---|---|---|
| ABI check | init() compares the loaded module's ABI with the package's (AbiMismatch) | Checks the packed ABI when the package loads and the engine ABI at construction (AbiMismatch) |
Project is constructed with new Project(), or loaded with Project.fromJson(json). Its setAssistSidecar(...) and assistSidecars() methods preserve opaque module metadata, while ProjectAutomationTargetKind and targetKind classify automation lanes. RealtimeEngine.setTrackMonitorMode(trackId, mode, renderFrame?) accepts 'off', 'pfl' (pre-fader listen), or 'afl' (after-fader listen); omit renderFrame to apply immediately. process() and processPrepared() fold an armed cue into their single output, so the tapped lane is counted twice there; offline renders, bounces, stem bounces and freezes carry the program output only, whatever the monitor or solo state. Track and mixer pan law setters take a PanLaw ('const3Db', 'const4.5Db', 'const6Db' or 'linear0Db').
StreamingMasteringChain
The streaming chain, the streaming loudness gain and the streaming repair calls are on Node.js Native Mastering, Repair and Assistant.
StreamingEqualizer
StreamingEqualizer is available in Node native, Python, and WASM. A fractional, NaN or oversized maxBlockSize or slope throws a RangeError on Node native.
It is useful when you need an EQ that keeps state across processMono / processStereo calls. It can also publish a spectrum snapshot and configure bands from a reference match: match(source, reference, { sampleRate?, referenceSampleRate?, maxBands? }) takes buffers of any lengths, and the reference may be at its own rate.
Node native and WASM accept the same phase mode values; Python additionally supports context-manager usage:
| Runtime | Phase mode values |
|---|---|
| Node native | 'zero', 'natural', 'linear' |
| WASM | 'zero', 'natural', 'linear' (same as Node native) |
| Python | See the Python API; also supports with StreamingEqualizer(...) as eq: / eq.close() |
import { StreamingEqualizer } from '@libraz/libsonare-native';
const eq = new StreamingEqualizer({ sampleRate: 48000, maxBlockSize: 512 });
eq.setBand(0, { type: 'highShelf', frequencyHz: 8000, gainDb: 4, enabled: true });
eq.setPhaseMode('natural');
eq.setAutoGain({ enabled: true });
const { left, right } = eq.processStereo(leftBlock, rightBlock);
console.log(eq.spectrum(), eq.latencySamples, left, right);