Skip to content

Node.js Native Mastering and Repair ​

This page covers the mastering, repair and assistant functions of @libraz/libsonare-native and its StreamingMasteringChain. The names, request shapes and results match the browser package, so Mastering API has the option-level reference and Mastering Processors the processor registry; this page lists what the Node package exports and where its calls differ. For conventions, errors and handle release see Node.js Native API.

Mastering API ​

The native addon and the WASM package expose the same mastering API; import it from @libraz/libsonare-native.

typescript
import {
  masterAudio,
  masterAudioStereo,
  masteringAnalyzePair,
  masteringAssistantSuggest,
  masteringAssistantSuggestStereo,
  masteringAudioProfile,
  masteringAudioProfileStereo,
  masteringChainConfigFromJson,
  masteringNormalizeLoudness,
  masteringPresetNames,
  masteringProcessorNames,
  masteringStreamingPreview,
  masteringStreamingPreviewStereo,
} from '@libraz/libsonare-native'

console.log(masteringProcessorNames())
console.log(masteringPresetNames())

const mastered = masterAudioStereo({
  left,
  right,
  sampleRate,
  overrides: {
    dynamics: {
      compressor: {
        thresholdDb: -18,
        ratio: 2.2,
        autoMakeup: true,
      },
    },
    loudness: {
      targetLufs: -14,
      ceilingDbtp: -1,
      truePeakOversample: 4,
    },
  },
})
console.log(mastered.outputLufs, mastered.stages)

const presetMaster = masterAudioStereo({
  left,
  right,
  sampleRate,
  preset: 'pop',
  overrides: { loudness: { targetLufs: -14 } },
})
console.log(presetMaster.outputLufs, presetMaster.stages)

// A chain configuration kept as a JSON document comes back as a typed config.
const stored = masteringChainConfigFromJson('{"loudness":{"targetLufs":-14}}')
const fromStored = masterAudio({ samples, sampleRate, overrides: stored })

const matchReport = masteringAnalyzePair({
  analysis: 'match.referenceLoudness',
  source,
  reference,
  sampleRate,
})

const masteredWithProgress = masterAudioStereo({
  left,
  right,
  sampleRate,
  overrides: { loudness: { targetLufs: -14, ceilingDbtp: -1, truePeakOversample: 4 } },
  onProgress: (progress, stage) => {
    console.log(`render ${(progress * 100).toFixed(0)}%: ${stage}`)
  },
})
console.log(masteredWithProgress.outputLufs)

const normalized = masteringNormalizeLoudness({ samples, sampleRate, targetLufs: -14 })

const profile = masteringAudioProfile({
  samples,
  sampleRate,
  nFft: 2048,
  hopLength: 512,
  truePeakOversample: 4,
})
const suggestions = masteringAssistantSuggest({
  samples,
  sampleRate,
  targetLufs: -14,
  ceilingDbtp: -1,
  preferStreamingSafe: true,
})
const deliveryPreview = masteringStreamingPreview({
  samples,
  sampleRate,
  platforms: [{ name: 'Streaming', targetLufs: -14, ceilingDbtp: -1 }],
})
console.log(profile, suggestions, deliveryPreview)

// The stereo entry points are request-object only — there is no positional
// overload, so a positional call throws.
const stereoProfile = masteringAudioProfileStereo({
  left,
  right,
  sampleRate,
  nFft: 2048,
  hopLength: 512,
  truePeakOversample: 4,
})
const stereoSuggestions = masteringAssistantSuggestStereo({
  left,
  right,
  sampleRate,
  targetLufs: -14,
  ceilingDbtp: -1,
  preferStreamingSafe: true,
})
// Omitting platforms uses the built-in Spotify / Apple Music / YouTube set.
const stereoPreview = masteringStreamingPreviewStereo({ left, right, sampleRate })
console.log(stereoProfile, stereoSuggestions, stereoPreview)

Note the calling-convention difference: the four stereo entry points take a single request object and nothing else. The metering sibling meteringCrestFactorDbStereo({ left, right, sampleRate }) follows the same request-object shape and returns a number, or undefined when both channels are silent. Node native and WASM declare the same request types, one per function (MasteringAudioProfileStereoRequest, MasteringAssistantSuggestStereoRequest, MasteringStreamingPreviewStereoRequest), and every result is a typed object rather than a JSON string.

The assistant/profile helpers accept the same option names as the WASM entry points. Profile options are nFft, hopLength (both in samples at 48 kHz, rescaled to the input rate), truePeakOversample and detectDefects; assistant options are targetLufs, ceilingDbtp, enableRepair, preferStreamingSafe, speechMonoAmount, targetPlatform and preset.

For long offline renders, pass onProgress (and optionally cancel) in the request of masterAudio(...) or masterAudioStereo(...) and update your Node UI from that callback; masterAudioAsync(...) and masterAudioStereoAsync(...) render on a worker thread without progress reporting.

The WASM package exposes the same camelCase mastering API names as the browser demo. The main groups are:

GroupAPI names
Presets and quick entry pointsmasteringPresetNames(), masteringPresetParams(), masteringPlatformNames(), masteringChainConfigFromJson(), masterAudio(), masterAudioStereo(), masteringNormalizeLoudness()
Offline dynamics (one-shot)masteringDynamicsCompressor(), masteringDynamicsGate(), masteringDynamicsTransientShaper()
Repair in one call (any channel count)masteringRepairAnalyze(), masteringRepairApply() — see Measure and repair in one call
Offline repair — monomasteringRepairDeclick(), masteringRepairDeclip(), masteringRepairDecrackle(), masteringRepairDehum(), masteringRepairDenoiseClassical(), masteringRepairDereverbClassical(), masteringRepairTrimSilence()
Offline repair — stereo pairmasteringRepairDeclickStereo(), masteringRepairDeclipStereo(), masteringRepairDecrackleStereo(), masteringRepairDehumStereo(), masteringRepairDenoiseClassicalStereo(), masteringRepairDereverbClassicalStereo(), masteringRepairTrimSilenceStereo()
Offline repair — channel-linked (any channel count)masteringRepairDenoiseClassicalLinked(), masteringRepairDereverbClassicalLinked()
Repair measurement (no audio returned)masteringRepairDetectClicks(), masteringRepairDetectClipping(), masteringRepairDetectCrackle(), masteringRepairDetectHum(), masteringRepairDetectNoiseFloor(), masteringRepairDetectReverb(), masteringRepairDetectTrimRange(), masteringRepairDetectTrimRangeStereo(), masteringRepairNoiseBandBins(), masteringRepairDereverbConfigForRoom()
Assistant and profilingmasteringAudioProfile(), masteringAssistantSuggest(), masteringStreamingPreview(), masteringAudioProfileStereo(), masteringAssistantSuggestStereo(), masteringStreamingPreviewStereo(), masteringAbMatchLoudness(), masteringAbMatchLoudnessStereo()
Named processorsmasteringProcessorNames(), masteringProcessorCatalog(), masteringAmpPresetCatalog(), masteringInsertNames(), masteringInsertParamNames(insert), masteringInsertParamInfo({ insert, sampleRate? }), masteringInsertTiming({ insert, params, sampleRate }), masteringApplyProcessor(), masteringApplyProcessorStereo()
Pair and stereo analysismasteringPairProcessorNames(), masteringApplyPairProcessor(), masteringApplyPairProcessorStereo(), masteringPairAnalysisNames(), masteringAnalyzePair(), masteringStereoAnalysisNames(), masteringAnalyzeStereo()
Streaming renderStreamingMasteringChain

The pair processors, pair analyses and both A/B loudness matches take referenceSampleRate in their request objects, as on WASM: the reference is resampled onto the source's rate. StreamingEqualizer.match takes it in its options and accepts buffers of different lengths.

Repair entry points ​

Every repair function takes a request object on both packages, and the mono ones also accept the positional form. The shape decides the input arity and what comes back:

ShapeCallReturns
MonomasteringRepairDeclick({ samples, sampleRate, ...options }){ samples, report }
Stereo pairmasteringRepairDeclickStereo({ left, right, sampleRate, ...options }){ channels, reports }
Channel-linkedmasteringRepairDenoiseClassicalLinked({ channels, sampleRate, ...config }){ channels, reports }, one output per input channel in input order
MeasurementmasteringRepairDetectClicks({ samples, sampleRate, ...options })a detection report; no audio

A stereo repair is not two mono calls: the decision that would move the stereo image is shared across the pair. Report-field shapes, the measurement helpers, and masteringAbMatchLoudness are in the JavaScript mastering reference; the stages and their fixed order are in Audio Repair.

Order a repair pass applies its stages
declipdeclickdecrackledehumdenoisedereverb
masteringRepairApply runs the stages you list in this fixed order, whatever order the array gives.

Mastering Analysis Functions ​

The explainable-mastering helpers return typed result objects; see Mastering Assistant for their shapes. Each stereo entry point below is request-only — it takes a single request object and has no positional overload, so a positional call throws a TypeError naming the request object.

FunctionReturn TypeDescription
masteringAudioProfileStereo(request)MasteringAudioProfileMastering-assistant profile of a channel pair. Takes MasteringAudioProfileStereoRequest
masteringAssistantSuggestStereo(request)MasteringAssistantResultSuggested mastering moves for a channel pair. Takes MasteringAssistantSuggestStereoRequest
masteringStreamingPreviewStereo(request)MasteringStreamingPreviewResultDelivery-platform loudness preview for a channel pair. Takes MasteringStreamingPreviewStereoRequest; omitting platforms selects the built-in Spotify / Apple Music / YouTube set (three rows)

Use the stereo entry points whenever you have two channels. The measured comparison and the demo are under Stereo profiling, assistant, and preview, and the readings are in LUFS (LUFS). The mono helpers measure a 0.5 * (left + right) downmix, and on decorrelated material that reads about 6 dB low, so the integrated loudness, the normalization gain derived from it, and the ceiling-risk judgment are all under-reported by the same amount. Measured on a decorrelated pink-noise pair (48 kHz, 4 s), the downmix path reported -22.55 LUFS against the stereo path's -16.44 LUFS — a 6.11 dB gap — and Spotify normalizationGainDb came out at +8.55 through the downmix versus +2.44 through the stereo path.

Only the loudness block of the stereo profile is measured from both channels: integrated LUFS and LRA come from the channel-summed program, and the true peak is the larger of the two. The spectral, dynamics, and tempo fields stay measured on the downmix, so they remain comparable with masteringAudioProfile.

StreamingMasteringChain ​

The native addon (and the WASM package) exposes a StreamingMasteringChain class for incremental rendering, for example when bridging an Electron app, worker, or audio capture pipeline. Its config is the same nested config as masterAudio's overrides, plus sampleRate, numChannels, the optional maxBlockSize, loudnessStaticGainDb and the optional loudnessStaticGainPeakDbtp, and it renders one block at a time.

typescript
import { StreamingMasteringChain } from '@libraz/libsonare-native';

const chain = new StreamingMasteringChain({
  sampleRate: 48000,
  maxBlockSize: 512,
  numChannels: 2,
  eq: { tilt: { tiltDb: 0.5 } },
  dynamics: { compressor: { thresholdDb: -20 } },
  maximizer: { truePeakLimiter: { ceilingDbtp: -1, oversampleFactor: 4 } },
});

// processMono needs a chain built with numChannels = 1
const { left, right } = chain.processStereo(leftBlock, rightBlock);

console.log(chain.stageNames(), chain.latencySamples);
chain.setParameter('eq.tilt.tiltDb', 1.0); // realtime-safe update at a block boundary
chain.reset();   // clear state without rebuilding

setParameter(key, value) changes one realtime-safe full-chain parameter at a serialized block boundary. The native chain keeps its processor instances, audio history, and latency. Use the full dotted key (for example, eq.tilt.tiltDb); structural keys, keys from disabled stages, and unknown keys are rejected. Serialize this call with process*(), flush*(), and reset(). Changes take effect at the boundary and are not smoothed automatically.

Stereo-only stages are skipped when numChannels === 1. The streaming chain rejects offline-only repair stages. A loudness stage requires a precomputed static gain in loudnessStaticGainDb; optionally pass the source true-peak in loudnessStaticGainPeakDbtp so the gain is clamped against the configured ceiling. Both builds release the underlying handle with an idempotent destroy(), and [Symbol.dispose] does the same. using releases it when the code is compiled by TypeScript 5.2+ or runs on a runtime with explicit resource management (Node 22 itself does not parse using). GC eventually reclaims a native handle, but a long-lived process that builds one chain per request must release it explicitly or native memory accumulates.

Related mastering guides: Browser local processing, Reference match, Quality checklist.

Streaming Loudness Gain and Repair ​

streamingLoudnessGain({ samples, sampleRate, config }) (and streamingLoudnessGainStereo({ left, right, ... })) measure the loudness numbers a StreamingMasteringChain is built with, at the loudness stage's input where the offline chain measures them. The result is { loudnessStaticGainDb, truePeakDbtp, integratedLufs }; the gain equals the one the offline chain applies, ceiling clamp included, and is 0 dB for silence. Pass loudnessStaticGainDb and truePeakDbtp (as loudnessStaticGainPeakDbtp) to the chain's constructor.

masteringRepairAnalyze({ channels, sampleRate, preferStreamingSafe? }) measures the repair defects of any number of channels and recommends stages with their settings; masteringRepairApply({ channels, sampleRate, stages, onProgress?, cancel? }) applies stages (each at most once, an unknown setting refused) in the fixed order declip, declick, decrackle, dehum, denoise, dereverb whatever order the array gives. Declip, declick, and dehum decide over the whole channel set and report per channel; decrackle runs each channel alone; denoise and dereverb apply one linked mask and report once.

typescript
const analysis = masteringRepairAnalyze({ channels: [left, right], sampleRate: 48000 });
const { channels, reports } = masteringRepairApply({
  channels: [left, right],
  sampleRate: 48000,
  stages: analysis.recommended,
});