Skip to content

JavaScript/TypeScript Mastering API ​

This page covers the offline mastering entry points of the libsonare JavaScript/TypeScript package: the chain and preset calls, the explainable-mastering helpers, the one-shot dynamics and repair processors. Two related references live alongside it: Streaming and Realtime API covers StreamingEqualizer, StreamingRetune, RealtimeVoiceChanger, realtimeVoiceChangerRender(...), and StreamingMasteringChain, and the MasteringChainConfig schema with its result types is on Types and Enumerations.

Mastering API ​

The browser package includes the same named mastering processors that the /mastering demo runs as inserts on the realtime engine. Decode audio with the Web Audio API, pass Float32Array channel buffers to libsonare, then export the returned samples as WAV in your application.

This section lists the JS entry points and their result/config types. For what each processor does, the preset list, and the analysis/assistant JSON, see Mastering Processors and Mastering Assistant.

Which entry point ​

You haveUse
One named processor to runmasteringApplyProcessor()
A preset, with optional overridesmasterAudio() / masterAudioStereo()
A full stage configmasterAudio({ overrides }) / masterAudioStereo({ overrides })
Loudness to a target, nothing elsemasteringNormalizeLoudness()
Audio arriving block by blockStreamingMasteringChain, with streamingLoudnessGain() for its loudness stage
No idea where to startmasteringAssistantSuggest(), then masterAudio({ overrides: suggestion.chainConfig })

Named functions ​

PurposeFunction
Normalize loudness to a target under a true-peak ceilingmasteringNormalizeLoudness()
List built-in mastering presetsmasteringPresetNames()
Expand one preset into its nested chain configmasteringPresetParams(preset)
Read a serialized chain config documentmasteringChainConfigFromJson(document)
Apply a preset, or a chain config, to mono audiomasterAudio()
Apply a preset, or a chain config, to stereo audiomasterAudioStereo()
Run block-by-block EQStreamingEqualizer
Run a streaming chain (block-by-block)StreamingMasteringChain
Measure the loudness numbers a streaming chain is built withstreamingLoudnessGain() / streamingLoudnessGainStereo()
Summarize source audio for mastering decisionsmasteringAudioProfile()
Summarize a stereo pair for mastering decisionsmasteringAudioProfileStereo()
Suggest mastering moves from source analysismasteringAssistantSuggest()
Suggest mastering moves from a stereo pairmasteringAssistantSuggestStereo()
Take just the suggested chain, ready to use as overrideschainConfig of the masteringAssistantSuggest() / masteringAssistantSuggestStereo() result
Preview loudness targets for delivery platformsmasteringStreamingPreview()
Preview delivery loudness for a stereo pairmasteringStreamingPreviewStereo()
List mono/stereo processorsmasteringProcessorNames()
Get machine-readable processor classificationsmasteringProcessorCatalog()
List chain insert processorsmasteringInsertNames()
List the parameter keys an insert acceptsmasteringInsertParamNames(name)
Describe construction keys and realtime insert parametersmasteringInsertParamInfo({ insert, sampleRate? })
Measure configured insert latency and tailmasteringInsertTiming({ insert, params, sampleRate })
Process mono audiomasteringApplyProcessor()
Process stereo audiomasteringApplyProcessorStereo()
List pair processorsmasteringPairProcessorNames()
Process source/reference pairmasteringApplyPairProcessor() / masteringApplyPairProcessorStereo()
List pair analysesmasteringPairAnalysisNames()
Analyze source/reference pairmasteringAnalyzePair()
List stereo analysesmasteringStereoAnalysisNames()
Analyze stereo channelsmasteringAnalyzeStereo()
Analyze and repair any channel count in one callmasteringRepairAnalyze() / masteringRepairApply() — see Audio Repair Workflow
typescript
import { init, masterAudioStereo } from '@libraz/libsonare'

await init()

// Full chain with explicit stage config
const result = masterAudioStereo({
  left,
  right,
  sampleRate,
  overrides: {
    spectral: { airBand: { amount: 0.35, shelfFrequencyHz: 14000 } },
    maximizer: { truePeakLimiter: { ceilingDbtp: -1, oversampleFactor: 4 } },
    loudness: { enabled: true, targetLufs: -14, ceilingDbtp: -1, truePeakOversample: 4 },
  },
  onProgress: (progress, stage) => console.log(stage, progress),
})
console.log(result.outputLufs, result.outputTruePeakDbtp, result.outputLoudnessRangeLu)
if (result.loudnessTargetLimited) {
  console.warn('The true-peak ceiling prevented the requested LUFS target.')
}
console.log(result.stageGainReductions)

// Preset with nested overrides (the typed MasteringChainConfig shape)
const presetResult = masterAudioStereo({
  left,
  right,
  sampleRate,
  preset: 'pop',
  overrides: {
    loudness: { targetLufs: -14 },
    maximizer: { truePeakLimiter: { releaseMs: 50 } },
  },
})

Stage config sits under overrides

masterAudio({ samples, sampleRate, overrides: { loudness: { targetLufs: -14 } } }) applies the target. A loudness key written beside samples throws a TypeError that names the key and lists the keys the request accepts, and a call with neither preset nor overrides throws a TypeError too. masterAudioStereo behaves the same. An explicit overrides: {} without a preset runs an empty chain and returns the input unchanged.

Both calls take an onProgress(progress, stage) callback, called between chain stages, and a cancel() callback polled between stages: returning true stops the call with a SonareError whose code is Cancelled. masteringApplyProcessor(...) / masteringApplyProcessorStereo(...) run one named processor, and masteringAnalyzeStereo(...) returns the analysis object. A named processor refuses a parameter it does not read, naming it (utility.gain reads levelDb, so gainDb throws a TypeError, unknown key params.gainDb (expected levelDb), rather than passing through silently).

Offline chain and preset results include outputTruePeakDbtp, outputLoudnessRangeLu, loudnessTargetLimited, and stageGainReductions.

When loudnessTargetLimited is true, the true-peak ceiling prevented the requested LUFS target. Report outputLufs, not the requested target. Each StageGainReduction gives the most recent gain reduction for one dynamics or maximizer stage.

report — before and after in one object ​

Every offline chain result also carries a report, which is the "what did this actually do" summary you would otherwise assemble by measuring the input yourself:

typescript
interface MasteringReport {
  before: MasteringLoudnessSummary;
  after: MasteringLoudnessSummary;
  appliedGainDb: number;
  maxGainReductionDb: number;
  loudnessTargetLimited: boolean;
  /** 32 logarithmically spaced after-minus-before energy deltas, in dB. */
  bandEnergyDeltaDb: Float32Array;
}

interface MasteringLoudnessSummary {
  integratedLufs: number;
  maxMomentaryLufs?: number;  // Absent when the signal is shorter than one momentary window.
  maxShortTermLufs?: number;  // Absent when the signal is shorter than one short-term window.
  truePeakDbtp: number;
  loudnessRangeLu?: number;  // Absent for silence or when no 3 s block passes the gates.
}
typescript
const { report } = masterAudioStereo({ left, right, sampleRate, overrides: config });
console.log(report.before.integratedLufs, '→', report.after.integratedLufs);
const beforeLra = report.before.loudnessRangeLu;
const afterLra = report.after.loudnessRangeLu;
if (typeof beforeLra === 'number' && Number.isFinite(beforeLra) &&
    typeof afterLra === 'number' && Number.isFinite(afterLra)) {
  console.log(afterLra - beforeLra, 'LU of range change');
} else {
  console.log('Loudness range change was not measured');
}
drawTiltCurve(report.bandEnergyDeltaDb);   // 32 bands, positive = brighter after

The same object is mirrored on the C ABI, ctypes, Node, Python, and both CLI report files, so a report exported from the CLI and one read in the browser have the same shape.

The explainable-mastering helpers — masteringAudioProfile(...), masteringAssistantSuggest(...), and masteringStreamingPreview(...) — return objects typed MasteringAudioProfile, MasteringAssistantResult, and MasteringStreamingPreviewResult; see Mastering Assistant for their exact shapes, accepted options, and how to turn a suggestion into a rendered master. Reference-track workflows use masteringPairProcessorNames() and masteringAnalyzePair(); the source and the reference may differ in length and in sample rate. masteringApplyPairProcessor() runs a mono two-input match.* processor; its stereo counterpart masteringApplyPairProcessorStereo() is described below.

Stereo entry points for the explainable helpers ​

Each of the three has a stereo counterpart that measures the channel pair directly. They are request-object only — there is no positional overload, and a positional call throws a TypeError. sampleRate is required.

typescript
function masteringAudioProfileStereo(request: MasteringAudioProfileStereoRequest): MasteringAudioProfile
function masteringAssistantSuggestStereo(request: MasteringAssistantSuggestStereoRequest): MasteringAssistantResult
function masteringStreamingPreviewStereo(request: MasteringStreamingPreviewStereoRequest): MasteringStreamingPreviewResult

interface MasteringStreamingPreviewStereoRequest {
  left: Float32Array;
  right: Float32Array;
  sampleRate: number;
  platforms?: StreamingPlatform[];   // { name, targetLufs, ceilingDbtp }
}

The profile request adds nFft, hopLength, truePeakOversample and detectDefects; the suggestion request takes the assistant settings (targetLufs, ceilingDbtp, targetPlatform, preset, and so on) beside the channels.

typescript
const profile = masteringAudioProfileStereo({ left, right, sampleRate });
const suggestion = masteringAssistantSuggestStereo({ left, right, sampleRate });
const preview = masteringStreamingPreviewStereo({
  left,
  right,
  sampleRate,
  platforms: [{ name: 'Spotify', targetLufs: -14, ceilingDbtp: -1 }],
});

Use them for anything stereo. The mono helpers measure a 0.5 * (left + right) downmix, and on decorrelated material that downmix 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 -18.45 LUFS against the stereo path's -12.43 LUFS, a 6.03 dB gap, and a -14 LUFS target's normalizationGainDb came out at +4.45 through the downmix versus -1.57 through the stereo path. On a correlated pair the gap shrinks to 3.01 dB, which is just the halving; the remaining ~3 dB is the decorrelation.

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 describe shape and timing rather than absolute level, so they stay measured on the downmix and remain directly comparable with masteringAudioProfile.

Taking the chain without the rest ​

masteringAssistantSuggest(...) answers with an object holding chainConfig, one explanation line per decision (explanation) and the measured profile. The chainConfig is already the nested MasteringChainConfig that masterAudio(...) and masterAudioStereo(...) take as overrides, so the suggestion can be applied without a translation step:

typescript
const { chainConfig } = masteringAssistantSuggestStereo({ left, right, sampleRate });
const mastered = masterAudioStereo({ left, right, sampleRate, overrides: chainConfig });

The stereo form measures the pair directly for the same reason the other stereo entry points do.

streamingLoudnessGain(request) ​

A StreamingMasteringChain cannot measure whole-signal loudness, so its loudness stage needs a precomputed static gain. streamingLoudnessGain runs the offline chain described by config up to the loudness stage and measures there, so the gain it returns is the one masterAudio applies, ceiling clamp included.

typescript
function streamingLoudnessGain(request: StreamingLoudnessGainRequest): StreamingLoudnessGainResult
function streamingLoudnessGainStereo(request: StreamingLoudnessGainStereoRequest): StreamingLoudnessGainResult
// request: { samples | left + right: Float32Array; sampleRate: number; config?: MasteringChainConfig }

interface StreamingLoudnessGainResult {
  loudnessStaticGainDb: number;  // the gain the offline loudness stage applies
  truePeakDbtp: number;          // dBTP of the loudness stage's input; -120 for digital silence
  integratedLufs: number;        // LUFS of that input; -Infinity below the absolute gate
}
typescript
const config = { loudness: { enabled: true, targetLufs: -14, ceilingDbtp: -1 } };
const { loudnessStaticGainDb, truePeakDbtp } = streamingLoudnessGain({ samples, sampleRate, config });
const chain = new StreamingMasteringChain({
  ...config,
  sampleRate,
  numChannels: 1,
  loudnessStaticGainDb,
  loudnessStaticGainPeakDbtp: truePeakDbtp,
});

The measurement is taken at the loudness stage's input, where the offline chain measures it, not on the source. The gain is computed from config.loudness whether or not the stage is enabled, and a silent or below-gate input yields 0 dB. On a soft-clipped synthetic loop at -9.47 LUFS with a -14 LUFS target and -1 dBTP ceiling the gain was -4.53 dB, equal to the chain's report.appliedGainDb. The stereo form sums the two channels with BS.1770 weights. Python spells them streaming_loudness_gain and streaming_loudness_gain_stereo and returns a StreamingLoudnessGain with loudness_static_gain_db, true_peak_dbtp, and integrated_lufs.

masteringPlatformNames() ​

typescript
function masteringPlatformNames(): MasteringPlatform[]

The delivery targets accepted as targetPlatform, in index order — 'streaming', 'broadcast', 'club' and whatever else the loaded build carries. It is read from the library rather than hardcoded in the binding, so a target added to the core shows up here without a binding change. Populate a picker from it instead of shipping your own list.

masteringAbMatchLoudness(request) ​

Gain-match one take to another's loudness so an A/B comparison is about tone, not level.

typescript
function masteringAbMatchLoudness(request: MasteringAbMatchLoudnessRequest): LoudnessMatchResult

interface MasteringAbMatchLoudnessRequest {
  source: Float32Array;      // the take that gets the gain
  reference: Float32Array;   // returned untouched
  sampleRate: number;        // required: the rate of both buffers, unless referenceSampleRate says otherwise
  referenceSampleRate?: number; // default: sampleRate; resampled onto sampleRate before it is measured
}

interface LoudnessMatchResult {
  samples: Float32Array;        // source, at reference's loudness
  sampleRate: number;
  referenceLufs: number;        // BS.1770 integrated
  sourceLufs: number;           // before the gain
  appliedGainDb: number;        // the gain that lands the remeasured source on referenceLufs
  matchedTruePeakDbtp: number;  // true peak after the gain
}

Request-object only. The two buffers may differ in length — each is measured on its own program — and the reference may be recorded at its own rate through referenceSampleRate.

The gain is uncapped, and the result can exceed 0 dBTP

appliedGainDb is the gain that lands the remeasured source on referenceLufs: it equals referenceLufs - sourceLufs unless the gain moves blocks across the absolute gate, in which case it is solved for the target. It has no upper bound and no headroom clamp is applied, so matchedTruePeakDbtp can come back above 0. That is deliberate: clamping for headroom would silently no-op the match for any source already near full scale, which is exactly the case an A/B is most often set up to examine. Check matchedTruePeakDbtp yourself and attenuate the pair together if you are about to render rather than audition.

When either take is silent or sits below the measurement gate, its LUFS field is non-finite and appliedGainDb is 0 — the source comes back unchanged. Test Number.isFinite(result.sourceLufs) before presenting a figure.

masteringStreamingPreviewStereo treats platforms exactly as the mono helper does: omit it and the preview falls back to the built-in Spotify / Apple Music / YouTube set, returning three rows. An empty array is refused with a RangeError.

masteringAbMatchLoudnessStereo(request) ​

typescript
function masteringAbMatchLoudnessStereo(request: MasteringAbMatchLoudnessStereoRequest): LoudnessMatchStereoResult
// request: { sourceLeft, sourceRight, referenceLeft, referenceRight: Float32Array; sampleRate: number; referenceSampleRate?: number } -> { left, right, sampleRate, referenceLufs, sourceLufs, appliedGainDb, matchedTruePeakDbtp }

The stereo form of masteringAbMatchLoudness: one gain, measured on the stereo program, goes to both source channels, so the left/right balance is unchanged. Request-object only; each pair's two channels must be equal in length or the call throws a RangeError, and the source and reference pairs may differ. Measured on decorrelated pink noise: -12.43 LUFS matched to -1.99 LUFS applied 10.44 dB, and both channels came back at 3.3256 times their input RMS. matchedTruePeakDbtp is the maximum over both channels. The uncapped gain and the non-finite LUFS of a silent take behave as in the mono call: a silent source gave sourceLufs of -Infinity, appliedGainDb of 0, and unchanged samples.

masteringApplyPairProcessor, masteringApplyPairProcessorStereo, masteringAnalyzePair and masteringAnalyzeStereo refuse undeclared parameters with a TypeError that names params.<key> and lists the accepted keys.

masteringApplyPairProcessorStereo(request) ​

typescript
function masteringApplyPairProcessorStereo(request: MasteringApplyPairProcessorStereoRequest): MasteringStereoResult
// request: { processor: 'match.abCrossfade', sourceLeft, sourceRight, referenceLeft, referenceRight, sampleRate, referenceSampleRate?, params? }

Only match.abCrossfade supports stereo pairs. An unknown processor name raises RangeError. A registered processor without stereo support raises SonareError with code NotSupported. The result is a static linear blend, (1 - mix) * source + mix * reference, as long as the shorter pair. mix defaults to 0.5 and must lie in [0, 1] (outside it the call throws a RangeError); 0 returns the source and 1 the reference. Measured on in-phase tones (source RMS 0.0707, reference RMS 0.2828): the default gave 0.1768, mix: 0.25 gave 0.1237, a 4 s source against a 2 s reference returned 2 s, and latencySamples was 0.

A reference at its own sample rate ​

masteringApplyPairProcessor, masteringApplyPairProcessorStereo, masteringAnalyzePair, masteringAbMatchLoudness, masteringAbMatchLoudnessStereo and the options of StreamingEqualizer.match (EqMatchOptions) take referenceSampleRate. Omitted, the reference is at sampleRate. A reference at another rate is resampled onto the source's rate before it is processed or measured; equal rates are processed untouched. A delay estimate (match.estimateReferenceDelaySamples) is reported in source-rate samples. StreamingEqualizer.match needs no equal-length buffers.

lufsSeriesMultichannel(...) ​

Momentary (400 ms) and short-term (3 s) LUFS series over a multichannel program, with the BS.1770-4 channel sum. The mono momentaryLufs / shortTermLufs on Features measure one channel each; this is their multichannel counterpart.

typescript
function lufsSeriesMultichannel(request: LufsSeriesMultichannelRequest): LufsSeriesResult

interface LufsSeriesMultichannelRequest {
  channels: Float32Array[];  // one array per channel, equal lengths
  sampleRate: number;        // required: pass the buffer's real rate
}

interface LufsSeriesResult {
  momentaryLufs: Float32Array;  // 400 ms series
  shortTermLufs: Float32Array;  // 3 s series
}

The channels are planar, one Float32Array per channel, as AudioBuffer.getChannelData hands them out, so nothing has to be de-interleaved before measuring. Channels of different lengths throw a RangeError.

It exists because a multichannel series cannot be assembled from mono ones. BS.1770 sums the K-weighted per-channel block energies and only then converts to LUFS, so running momentaryLufs per channel and combining in dB gives a different number, and a 0.5 * (left + right) downmix reads low on decorrelated material, the same trap the stereo helpers above exist to avoid. Both series fall out of one K-weighting pass, which is why the result always carries both; there is nothing to save by asking for one. With channels: 1 the two series match the mono meters element for element.

sampleRate has to be the buffer's actual rate: K-weighting is sample-rate dependent, so a wrong rate gives a wrong answer rather than an error. A call without sampleRate throws a TypeError. A signal shorter than the 400 ms window yields an empty momentaryLufs rather than an error (0.1 s at 48 kHz gave 0 entries).

Amp preset catalog ​

masteringAmpPresetCatalog() returns the built-in amp-sim rigs as { index, name, params } objects. index selects the rig through saturation.ampSim's presetIndex; params contains its resolved numeric and boolean controls before user overrides. Save the index and explicit overrides in a project so the engine can supply the rig's defaults when it is loaded.

Preset parameters and configured insert timing ​

masteringPresetNames() is the compact name list. capabilityCatalog().masteringPresets adds one metadata object per name: kind is mastering or restoration, and restoration entries leave targetLufs, truePeakCeilingDbtp, and maxLimiterGainReductionDb absent.

typescript
function masteringPresetParams(preset: MasteringPreset): MasteringChainConfig

masteringPresetParams returns the nested MasteringChainConfig of the preset's built-in chain, the same shape the assistant's chainConfig has; passing it as overrides to masterAudio or masterAudioStereo reproduces the preset. An unknown preset name throws a RangeError (unknown mastering preset: nope), and a preset, processor, analysis or platform name with an embedded NUL is refused with a RangeError naming the field.

The catalog's latencySamples and tailSamples values are representative defaults. Query a prepared configuration when those values matter for routing or scheduling:

typescript
function masteringInsertTiming(request: {
  insert: MasteringInsertName;
  params?: Record<string, number | boolean | string | number[]>;
  sampleRate: number;
}): { latencySamples: number; tailSamples: number }

masteringInsertTiming applies the supplied construction parameters and returns the exact latency and tail for that sample rate. It accepts every value type the insert's parameter descriptor declares — numbers, booleans, enum names, and the string and array keys such as the amp-sim preset and cabIrF32Base64, the convolution irF32Base64 and the room-morph bandAbsorption / bandScattering — checked against the descriptor's type, so the query reproduces the insert a scene or strip builds. A value of the wrong type or an unknown key is a TypeError (the message lists the keys the insert reads); a non-finite number, an unknown insert, a sample rate outside [8000, 384000] or a value the insert refuses is a RangeError. Passing {} at 48 kHz gives the default configuration represented by the processor catalog; use the actual insert parameters when a topology or slot changes the timing.

Related mastering guides: Processing chain, Tone and air, Dynamics, Stereo, limiter, and loudness, Reference match.

Standalone dynamics and repair processors ​

Every named stage is also a one-shot function, so you can run a single processor without assembling a chain. The dynamics processors return a DynamicsProcessorResult (the processed samples plus latencySamples, the processor's lookahead latency in samples); the repair processors return { samples, report }, the repaired audio and what the pass found and did. Each also takes a request object ({ samples, sampleRate, ...options }), and sampleRate is required in both forms.

typescript
// Offline dynamics
function masteringDynamicsCompressor(samples: Float32Array, sampleRate: number, options?: CompressorOptions): DynamicsProcessorResult
function masteringDynamicsGate(samples: Float32Array, sampleRate: number, options?: GateOptions): DynamicsProcessorResult
function masteringDynamicsTransientShaper(samples: Float32Array, sampleRate: number, options?: TransientShaperOptions): DynamicsProcessorResult

// Offline repair
function masteringRepairDeclick(samples: Float32Array, sampleRate: number, options?: DeclickOptions): DeclickResult
function masteringRepairDeclip(samples: Float32Array, sampleRate: number, options?: DeclipOptions): DeclipResult
function masteringRepairDecrackle(samples: Float32Array, sampleRate: number, options?: DecrackleOptions): DecrackleResult
function masteringRepairDehum(samples: Float32Array, sampleRate: number, options?: DehumOptions): DehumResult
function masteringRepairDenoiseClassical(samples: Float32Array, sampleRate: number, options?: DenoiseClassicalOptions): DenoiseResult
function masteringRepairDereverbClassical(samples: Float32Array, sampleRate: number, options?: DereverbClassicalOptions): DereverbResult
function masteringRepairTrimSilence(samples: Float32Array, sampleRate: number, options?: TrimSilenceOptions): TrimSilenceResult
DYNAMICS · COMPRESSORIDLE
Compression — threshold, ratio, knee, attack, release

The left panel is the transfer curve — input level in, output level out — with the threshold and the soft knee marked; raise the ratio and it bends harder past the threshold. The right panel runs a fixed program (a steady bed with transient hits) through the compressor: the shaded gap is the gain reduction, and attack and release decide how fast it clamps down and lets go. Press play to hear the same program — the pumping you see is the pumping you hear.

Threshold
-18 dB
Ratio
4 :1
Knee
6 dB
Attack
15 ms
Release
160 ms

The one-shot repair helpers and the chain-config repair stages are offline. StreamingMasteringChain rejects repair.declick, repair.declip, repair.decrackle, repair.dehum, and repair.dereverb, and accepts repair.denoise with a causal noise estimator (mcra, imcra, or the default spp); quantile is refused by name. Four of the repair processors — repair.decrackle, repair.dehum, repair.denoiseClassical, and repair.dereverbClassical — are also causal realtime inserts under those ids; see Audio Repair Workflow. See Dynamics and Repair.

A/B PROCESS · DENOISEIDLE
Denoise repair — damaged vs repaired

Broadband hiss is added to a clean chord. Compare the noisy and denoised signals and their spectra, then choose a denoising algorithm. Both retain their processed levels without extra loudness matching. Noise reduction can also change musical transients and timbre. FLOOR shows the average high-band reduction in dB.

Compare
Algorithm

Stereo and linked repair ​

Each repair processor has a stereo counterpart that takes the channel pair together. They exist because repair decisions are not always per-channel: a click is one physical event on both channels, and a denoiser that builds a different mask per channel moves the stereo image while it works. Every entry below takes a request object only ({ left, right, sampleRate, ...options }; a positional call throws a TypeError), sampleRate is required, and the channels must be the same length (otherwise a RangeError). Each takes the same options interface as its mono form and returns { channels, reports }, with channels as [left, right].

typescript
function masteringRepairDeclickStereo(request: MasteringRepairDeclickStereoRequest): MasteringRepairDeclickResult
function masteringRepairDeclipStereo(request: MasteringRepairDeclipStereoRequest): MasteringRepairDeclipResult
function masteringRepairDecrackleStereo(request: MasteringRepairDecrackleStereoRequest): MasteringRepairDecrackleResult
function masteringRepairDehumStereo(request: MasteringRepairDehumStereoRequest): MasteringRepairDehumResult
function masteringRepairDenoiseClassicalStereo(request: MasteringRepairDenoiseClassicalStereoRequest): MasteringRepairDenoiseClassicalResult
function masteringRepairDereverbClassicalStereo(request: MasteringRepairDereverbClassicalStereoRequest): MasteringRepairDereverbClassicalResult
function masteringRepairTrimSilenceStereo(request: MasteringRepairTrimSilenceStereoRequest): MasteringRepairTrimSilenceResult

// N-channel forms of the two fully linked processors
function masteringRepairDenoiseClassicalLinked(request: MasteringRepairDenoiseClassicalLinkedRequest): MasteringRepairDenoiseClassicalResult
function masteringRepairDereverbClassicalLinked(request: MasteringRepairDereverbClassicalLinkedRequest): MasteringRepairDereverbClassicalResult

The length of reports tells you how much was linked: two reports mean the channels were processed separately enough to need them, one report means one decision covered both channels.

ProcessorWhat is sharedResult shapeNotes
declickThe selection: a run either channel detects is repaired in both, each channel filling from its own samples and AR model{ channels, reports }, two reportsThe two reports genuinely differ. A merged run can exceed maxClickSamples
declipEach channel’s clipped runs independently by default; linkChannels: true uses their union{ channels, reports }, two reportslinkedRuns is 0 by default. Runs longer than 512 samples stay clipped and count in unreconstructedRuns; the cap is independent of lpcOrder and the sample rate
decrackleNothing: crackle is surface damage with no common event{ channels, reports }, two reportsThe entry centralizes the reports and the channel-length contract. Fields of the mode you did not choose read 0
dehumOnly with adaptive set: the tracker reads the channel mean and both cascades follow one frequency{ channels, reports }, two reportsappliedFundamentalHz and fundamentalDriftHz are identical in both reports, while each detected measures its own channel. With adaptive clear (the default) the channels are independent
denoise, dereverbEverything: the gain mask is built from channel-summed power and applied unchanged to every channel{ channels, reports }, one reportInterchannel level and phase cannot move. The Linked variants take channels: Float32Array[]; one channel reproduces the mono entry bit for bit, two reproduce the stereo entry
trim silenceThe union of the per-channel keep ranges, erring toward keeping because trimming is destructive; never a downmix{ channels, reports, ranges }, one reportranges holds each channel's own detected range, [leftRange, rightRange], for inspection

Every repair processor and detector pads an input shorter than nFft instead of refusing it.

Comparing reports across channel counts

DenoiseReport.detected is absolute and measured on the summed set, so N identical channels read 10*log10(N) above one: about +3.01 dB at two, +4.77 dB at three. A stereo floorDbfs is not comparable with a mono one. DereverbReport is made of ratios and fractions, so it is channel-count invariant and compares directly.

masteringRepairTrimSilenceStereo is the only repair entry point that shortens its input: result.channels[0].length is the output length and both channels come back equal. A pair in which neither channel carries signal returns two empty arrays and succeeds — no throw, no null. reports[0].range is then (inputLength, inputLength), which makes removedHeadSamples the whole input and removedTailSamples zero; the two still sum correctly, only the split is arbitrary. Option liveness follows mode: thresholdDb acts only in 'peak', gateLufs and windowMs only in 'lufsGated', and setting an inert option is silent rather than an error. Gated mode compares an unweighted RMS over a windowMs window against gateLufs, so the gated quantity is dBFS and not BS.1770 loudness.

Detection without repair ​

These run the analysis half of a repair processor and stop before it touches audio, so you can decide whether a repair is warranted — and show the user why — without rendering anything. Each returns a report only. All take the same options interface as the processor they measure. The mono ones accept a request object or a positional call (sampleRate required either way); the stereo one takes a request object only.

typescript
function masteringRepairDetectClicks(request: MasteringRepairDetectClicksRequest): ClickDetection
function masteringRepairDetectClipping(request: MasteringRepairDetectClippingRequest): ClipDetection
function masteringRepairDetectCrackle(request: MasteringRepairDetectCrackleRequest): CrackleDetection
function masteringRepairDetectHum(request: MasteringRepairDetectHumRequest): HumDetection
function masteringRepairDetectNoiseFloor(request: MasteringRepairDetectNoiseFloorRequest): NoiseDetection
function masteringRepairDetectReverb(request: MasteringRepairDetectReverbRequest): ReverbDetection
function masteringRepairDetectTrimRange(request: MasteringRepairDetectTrimRangeRequest): TrimRange
function masteringRepairDetectTrimRangeStereo(request: MasteringRepairDetectTrimRangeStereoRequest): TrimRange

interface TrimRange {
  first: number;          // half-open, in INPUT-buffer coordinates
  lastExclusive: number;
}
FunctionWhat it measuresWatch for
masteringRepairDetectClicksThe same LPC analysis the repair runs, with runs counted only where they stand above the local transient level, so a drum hit is not a clickRepair options shape the count; the repair itself still acts inside transients, so the samples it replaces can exceed the detected count. A large rejected means maxClickSamples or neighborRatio is too tight, not that the material is clean
masteringRepairDetectClippingReads only clipThresholdDb; lpcOrder and iterations are validated and then unread, and sampleRate is validated but never readCompare longestRunSamples against the 512-sample cap to identify runs too long for LPC reconstruction. The four flat-top fields look for three or more bit-identical samples within 1 dB of peak, which catches material that was clipped and then attenuated
masteringRepairDetectCrackleAlways the median criterion, whatever mode says, because wavelet shrinkage never decides that a sample is crackle; samples are counted only where they stand above the local transient level, so percussion reads as cleanThe counts do not describe what a wavelet-mode repair removes, but they give the same answer before you have chosen a mode
masteringRepairDetectHumAlways the estimation path regardless of adaptive, since the fixed path never looks for hum; a candidate has to be a stationary line through most of each analysis frame, so a repeating kick does not qualifyfundamentalProminence is a linear ratio, the winner's projected energy over the median candidate, so 1.0 means no peak was found at all (a repeating kick reads exactly 1.0); it is not a lock flag. harmonicDbfs covers every k*f0 the sample rate carries, not only the notched ones, and a harmonic at or past Nyquist reads the dB floor
masteringRepairDetectNoiseFloorStops before the gain mask, so there is no attenuation figurefloorDbfs is absolute: compare it only against a figure taken over the same channel count
masteringRepairDetectReverbWhat the dereverb itself measures while deciding how much to subtract; not an ISO 3382 RT60 (use estimateRoom(...) for that)lateDecayRatioDb runs counter-intuitively: less negative means more reverberant. latePredictability is exactly 0 under the default config, because the WPE stage runs only with wpeEnabled
masteringRepairDetectTrimRangeThe range the repair would cut to, with paddingSamples already inside it, not the detected extent of the signalNothing above threshold yields (length, length)
masteringRepairDetectTrimRangeStereoThe union of the per-channel rangesA channel with nothing above threshold contributes no edge at all rather than an edge at the buffer end, so a silent channel united with an active one is exactly the active channel's range

Flat-top detection has two failure modes. A genuinely flat-topped waveform is a false positive, and any per-sample perturbation (a downmix, a resample, lossy coding) erases a true flat top. Detect each channel separately, before any downmix, never on the mixed-down result.

masteringRepairDereverbConfigForRoom(...) ​

Turn a room measurement into a dereverb config.

typescript
function masteringRepairDereverbConfigForRoom(
  request: MasteringRepairDereverbConfigForRoomRequest,   // { estimate, ...DereverbClassicalOptions }
): DereverbClassicalConfig

It reads only volume and rt60Bands from the estimate (an estimateRoom(...) result) and returns a complete config — every field present, nothing optional — so you can show the user what will run before running it. Exactly two fields come back changed: t60Sec (the mid-frequency reverberation time, the mean of the 500 Hz and 1 kHz octaves) and lateDelayMs (the Polack mixing time, sqrt(volume) ms).

attenuation, threshold, overSubtraction and spectralFloor are never written: how much reverb to remove is taste, not measurement, and the function declines to guess. A band that did not converge leaves its own field alone, and a low-confidence estimate is still applied — filter the estimate yourself if you do not want that. Config fields you omit resolve to the library default rather than to zero. One edge to watch: if neither mid band converged, t60Sec falls back to the mean of whatever bands did, at which point it stops being a mid-frequency figure.

masteringRepairNoiseBandBins(...) ​

typescript
function masteringRepairNoiseBandBins(request: MasteringRepairNoiseBandBinsRequest): Int32Array

interface MasteringRepairNoiseBandBinsRequest {
  nFft?: number;        // default 1024; must be a power of two (RangeError otherwise)
  sampleRate: number;   // required
}

Returns the 33 edges of the 32-band analysis grid. Band k covers the one-sided bins [bins[k], bins[k + 1]), and bin b sits at b * sampleRate / nFft Hz. The grid depends on the analysis geometry.

An empty band (bins[k] === bins[k + 1]) has no entry in the detection result. Use bandFloorBand[i] to locate each reported bandFloorDbfs[i] on the grid. A measured band with zero power reads -Infinity.