Python Mastering API
The mastering family of the libsonare Python package: chains, processors, presets, reference-track processing and the assistant that profiles a source and suggests a chain. The Python API index lists the other families. Mixing is on Python Mixer API, standalone dynamics and repair on Python Dynamics and Repair API, and streaming and block-by-block processors on Python Streaming API.
Mastering API
Python exposes the same named mastering processors as the browser demo. Use the name-list helpers to inspect the active build, then call mono, stereo, pair, or analysis APIs with explicit parameters. To bring one file to a loudness target and nothing more, Normalize Audio to -14 LUFS in Python is the whole script. A full chain runs its stages in a fixed order:
Pick an entry point by purpose:
| Purpose | Function |
|---|---|
| Apply simple loudness mastering | mastering() |
| List built-in mastering presets | mastering_preset_names() |
| Get a built-in preset's flat chain parameters | mastering_preset_params() |
| Validate a chain configuration JSON document and get its parameters | mastering_chain_config_from_json() |
Apply a preset, or an explicit chain config through overrides, to mono audio | master_audio() |
Apply a preset, or an explicit chain config through overrides, to stereo audio | master_audio_stereo() |
| Run a streaming chain (block-by-block) | StreamingMasteringChain |
| Generate an audio profile for mastering decisions | mastering_audio_profile() |
| Generate an audio profile from both stereo channels | mastering_audio_profile_stereo() |
Generate assistant suggestions (the chain parameters are .chain_config) from source analysis | mastering_assistant_suggest() |
| Generate assistant suggestions from both stereo channels | mastering_assistant_suggest_stereo() |
| Preview delivery loudness by platform | mastering_streaming_preview() |
| Preview delivery loudness from both stereo channels | mastering_streaming_preview_stereo() |
| List the built-in delivery platforms | mastering_platform_names() |
| List mono/stereo processors | mastering_processor_names() |
| Get machine-readable processor classifications | mastering_processor_catalog() |
| List the guitar-amp presets with their parameters | mastering_amp_preset_catalog() |
| List chain insert processors | mastering_insert_names() |
| List the parameter keys an insert accepts | mastering_insert_param_names() |
| Describe insert construction keys and automation targets | mastering_insert_param_info() |
| Get configured insert latency and tail | mastering_insert_timing() |
| Process mono audio | mastering_apply_processor() |
| Process stereo audio | mastering_apply_processor_stereo() |
| List pair processors | mastering_pair_processor_names() |
| Process source/reference pair | mastering_apply_pair_processor() |
| Process stereo source/reference pair | mastering_apply_pair_processor_stereo() |
| List pair analyses | mastering_pair_analysis_names() |
| Analyze source/reference pair | mastering_analyze_pair() |
| Match source loudness to a reference | mastering_ab_match_loudness() |
| Match stereo source loudness to a stereo reference | mastering_ab_match_loudness_stereo() |
| List stereo analyses | mastering_stereo_analysis_names() |
| Analyze stereo channels | mastering_analyze_stereo() |
Related mastering guides: Preset selection, Delivery targets, Meter reading, Quality checklist.
Run one processor
import libsonare as sonare
print(sonare.mastering_processor_names())
# e.g. ['dynamics.brickwallLimiter', 'dynamics.compressor', 'dynamics.deesser', 'dynamics.expander', ...]
result = sonare.mastering_apply_processor(
"spectral.airBand",
samples,
sample_rate,
params={
"amount": 0.4,
"shelfFrequencyHz": 14000,
},
)
report = sonare.mastering_analyze_stereo(
"stereo.monoCompatCheck",
left,
right,
sample_rate,
)
print(report.correlation, report.likely_mono_compatible)
catalog = sonare.mastering_processor_catalog()
insert_params = sonare.mastering_insert_param_info("eq.parametric")# Return supported mastering processor names shared by CLI/Node/WASM/Python.
def mastering_processor_names() -> list[str]: ...
# Return the full catalog of mastering processors.
def mastering_processor_catalog() -> list[MasteringProcessorCatalogEntry]: ...
# Return the built-in amp-sim rig catalog.
def mastering_amp_preset_catalog() -> list[MasteringAmpPresetCatalogEntry]: ...
# Return the mastering insert (FX) names shared by CLI/Node/WASM/Python.
def mastering_insert_names() -> list[str]: ...
# Return the camelCase parameter names a given insert/FX processor reads.
def mastering_insert_param_names(insert: str) -> list[str]: ...
# Return parameter metadata for a given insert/FX processor.
def mastering_insert_param_info(
insert: str,
sample_rate: int | None = None,
) -> list[MasteringInsertParamInfo]: ...
# Return the latency and tail of one insert built from ``params`` at ``sample_rate``.
def mastering_insert_timing(
insert: str,
params: Mapping[str, float | bool | str | Sequence[float]] | None = None,
sample_rate: int | None = None,
) -> MasteringInsertTiming: ...
# Apply a named mastering processor using the shared cross-language API.
def mastering_apply_processor(
processor: str,
samples: Sequence[float] | list[float],
sample_rate: int,
params: dict[str, float | int | bool | str] | None = None,
) -> MasteringResult: ...
# Apply a named stereo mastering processor using the shared cross-language API.
def mastering_apply_processor_stereo(
processor: str,
left: Sequence[float] | list[float],
right: Sequence[float] | list[float],
sample_rate: int,
params: dict[str, float | int | bool | str] | None = None,
) -> MasteringStereoResult: ...
# Return supported stereo mastering analysis names.
def mastering_stereo_analysis_names() -> list[str]: ...
# Run a named stereo mastering analysis and return its record.
def mastering_analyze_stereo(
analysis: str,
left: Sequence[float] | list[float],
right: Sequence[float] | list[float],
sample_rate: int,
params: dict[str, float | int | bool] | None = None,
) -> StereoMonoCompatCheckResult | StereoMonoCompatCheckLogBandsResult: ...Presets and full chains
# Preset-driven chain (one-shot)
sonare.mastering_preset_names()
# -> ['pop', 'edm', 'acoustic', 'hipHop', 'aiMusic', 'speech', 'streaming', 'youtube', 'broadcast', 'podcast', 'audiobook', 'cinema', 'jpop', 'ambient', 'lofi', 'classical', 'drumAndBass', 'techno', 'metal', 'trap', 'rnb', 'jazz', 'kpop', 'trance', 'gameOst', 'vinyl', 'tapeHiss', 'fieldRecording', 'voiceMemo', 'shellac78']
preset_params = sonare.mastering_preset_params("aiMusic")
chain_result = sonare.master_audio(
samples,
sample_rate,
preset="aiMusic",
overrides={
"loudness.targetLufs": -13,
"maximizer.truePeakLimiter.releaseMs": 50,
"maximizer.truePeakLimiter.applyGainAtInputRate": False,
},
)
print(chain_result.output_lufs, chain_result.output_true_peak_dbtp, chain_result.output_loudness_range_lu)
print(chain_result.stage_gain_reductions)
if chain_result.report is not None:
print(chain_result.report.before, chain_result.report.after)
print(chain_result.report.band_energy_delta_db)mastering_chain_config_from_json() validates a chain configuration JSON document, read the way the native CLI's --chain-config reads it (version 2, version may be left out), and returns every chain parameter at its document value or its default, in the shape mastering_preset_params() returns and ready to pass to master_audio() as overrides.
# Apply mastering loudness normalization with a true-peak ceiling.
def mastering(
samples: Sequence[float] | list[float],
sample_rate: int,
target_lufs: float = -14.0,
ceiling_dbtp: float = -1.0,
true_peak_oversample: int | None = None,
release_ms: float | None = None,
apply_gain_at_input_rate: bool = False,
) -> MasteringResult: ...
# Return built-in mastering preset identifiers (e.g.
def mastering_preset_names() -> list[str]: ...
# Return a built-in preset's chain configuration document's params.
def mastering_preset_params(preset: str) -> MasteringChainConfig: ...
# Validate a chain configuration document and return its params.
def mastering_chain_config_from_json(document: str) -> MasteringChainConfig: ...
# Master mono audio with a named preset, a chain of overrides, or both.
def master_audio(
samples: Sequence[float] | list[float],
sample_rate: int,
*,
preset: str | None = None,
overrides: MasteringChainConfigInput | None = None,
on_progress: Callable[[float, str], None] | None = None,
cancel: Callable[[], bool] | None = None,
) -> MasteringChainResult: ...
# Master stereo audio with a named preset, a chain of overrides, or both.
def master_audio_stereo(
left: Sequence[float] | list[float],
right: Sequence[float] | list[float],
sample_rate: int,
*,
preset: str | None = None,
overrides: MasteringChainConfigInput | None = None,
on_progress: Callable[[float, str], None] | None = None,
cancel: Callable[[], bool] | None = None,
) -> MasteringChainStereoResult: ...Streaming chain
# Block-by-block streaming variant
with sonare.StreamingMasteringChain(
{
"eq.tilt.tiltDb": 0.5,
"dynamics.compressor.thresholdDb": -20.0,
},
sample_rate=48000,
num_channels=1,
max_block_size=512,
) as chain:
print(chain.stage_names(), chain.latency_samples) # latency_samples is a property
output = [chain.process_mono([0.0] * 512)]
tail = chain.flush_mono()
while tail.size:
output.append(tail)
tail = chain.flush_mono()chain.set_parameter(key, value) changes one streaming-safe parameter at a block boundary. The call is serialized with processing, flushing and resetting; unknown keys, structural keys, and keys for disabled stages are rejected before mutation, so a failed call leaves the chain and its audio history unchanged. Parameter changes take effect without automatic smoothing.
After the final streaming input block, call flush_mono() until it returns an empty array; for stereo, call flush_stereo() until both returned channels are empty.
# Block-by-block streaming variant of :func:`master_audio`.
class StreamingMasteringChain:
# Build and prepare a streaming mastering chain.
def __init__(
self,
config: MasteringChainConfigInput | None = None,
*,
sample_rate: int,
num_channels: int,
max_block_size: int | None = None,
loudness_static_gain_db: float | None = None,
loudness_static_gain_peak_dbtp: float | None = None,
) -> None: ...
# Process one mono block, returning the processed samples (length unchanged).
def process_mono(self, samples: Sequence[float] | np.ndarray) -> np.ndarray: ...
# Process one stereo block, returning the processed (left, right) channels.
def process_stereo(
self,
left: Sequence[float] | np.ndarray,
right: Sequence[float] | np.ndarray,
) -> StereoBlock: ...
# Emit delayed audio and finite processor tails after the final mono block.
def flush_mono(self) -> np.ndarray: ...
# Stereo counterpart of :meth:`flush_mono`.
def flush_stereo(self) -> StereoBlock: ...
# Reset all processor state without rebuilding.
def reset(self) -> None: ...
# Update one realtime-safe full-chain parameter between processing calls.
def set_parameter(self, key: str, value: float) -> None: ...
# The largest block :meth:`process_mono` / :meth:`process_stereo` accept.
@property
def max_block_size(self) -> int: ...
# Total reported latency in samples across all active processors.
@property
def latency_samples(self) -> int: ...
# Non-finite samples this chain's stages replaced.
@property
def non_finite_substitution_count(self) -> int: ...
# Process/flush calls in which a stage discarded its state.
@property
def non_finite_discard_count(self) -> int: ...
# Return the realized stage names in processing order.
def stage_names(self) -> list[str]: ...
# Release the underlying C handle.
def close(self) -> None: ...
# Return the object itself for ``with`` use.
def __enter__(self) -> StreamingMasteringChain: ...
# Close the object on leaving the ``with`` block; never suppresses exceptions.
def __exit__(self, exc_type: object, exc: object, tb: object) -> None: ...Reference-track processing
Reference-track workflows use mastering_pair_processor_names(), mastering_apply_pair_processor(), mastering_apply_pair_processor_stereo(), mastering_pair_analysis_names(), and mastering_analyze_pair(). The mono pair processor accepts mastering_apply_pair_processor() and returns a MasteringResult; source and reference lengths may differ. The stereo form accepts source_left, source_right, reference_left, and reference_right and returns a MasteringStereoResult with left, right, sample_rate, input_lufs, output_lufs, applied_gain_db, latency_samples, loudness_target_limited, and non_finite_substitution_count. Each source pair and each reference pair must have equal left/right lengths, but the source and reference pair lengths may differ; the stereo match.abCrossfade result uses the shorter pair length. Every pair processor, pair analysis and A/B match takes reference_sample_rate (default sample_rate): a reference at another rate is resampled onto the source's, and a delay estimate is reported in source-rate samples.
For loudness-matched A/B comparisons, mastering_ab_match_loudness() returns a LoudnessMatchResult (samples, sample_rate, reference_lufs, source_lufs, applied_gain_db, matched_true_peak_dbtp). mastering_ab_match_loudness_stereo() returns a LoudnessMatchStereoResult with left and right in place of samples. Each stereo source/reference pair must have equal channel lengths, while source and reference lengths may differ. The stereo helper applies one shared gain to both source channels and does not apply a ceiling.
# Return supported two-input mastering processor names.
def mastering_pair_processor_names() -> list[str]: ...
# Apply a named two-input mastering processor.
def mastering_apply_pair_processor(
processor: str,
source: Sequence[float] | list[float],
reference: Sequence[float] | list[float],
sample_rate: int,
params: dict[str, float | int | bool] | None = None,
*,
reference_sample_rate: int | None = None,
) -> MasteringResult: ...
# Apply the stereo ``match.abCrossfade`` pair processor.
def mastering_apply_pair_processor_stereo(
processor: str,
source_left: Sequence[float] | list[float],
source_right: Sequence[float] | list[float],
reference_left: Sequence[float] | list[float],
reference_right: Sequence[float] | list[float],
sample_rate: int,
params: dict[str, float | int | bool] | None = None,
*,
reference_sample_rate: int | None = None,
) -> MasteringStereoResult: ...
# Return supported two-input mastering analysis names.
def mastering_pair_analysis_names() -> list[str]: ...
# Run a named two-input mastering analysis and return its record.
def mastering_analyze_pair(
analysis: str,
source: Sequence[float] | PlanarChannels,
reference: Sequence[float] | PlanarChannels,
sample_rate: int,
params: dict[str, float | int | bool] | None = None,
*,
reference_sample_rate: int | None = None,
) -> MatchReferenceLoudnessResult | MatchTonalBalanceResult | MatchEqCurveResult | MatchEstimateReferenceDelaySamplesResult: ...
# Gain-match ``source`` to ``reference``'s integrated loudness.
def mastering_ab_match_loudness(
source: Sequence[float] | list[float] | np.ndarray,
reference: Sequence[float] | list[float] | np.ndarray,
sample_rate: int,
*,
reference_sample_rate: int | None = None,
) -> LoudnessMatchResult: ...
# Gain-match a stereo source to a stereo reference with one shared gain.
def mastering_ab_match_loudness_stereo(
source_left: Sequence[float] | list[float] | np.ndarray,
source_right: Sequence[float] | list[float] | np.ndarray,
reference_left: Sequence[float] | list[float] | np.ndarray,
reference_right: Sequence[float] | list[float] | np.ndarray,
sample_rate: int,
*,
reference_sample_rate: int | None = None,
) -> LoudnessMatchStereoResult: ...Progress callbacks
master_audio() and master_audio_stereo() accept an optional on_progress=callable keyword.
The callback receives (progress: float, stage: str) after each stage:
| Value | Meaning |
|---|---|
progress | Overall progress from 0.0 to 1.0. |
stage | The named processor that just completed, such as eq.tilt, dynamics.compressor, or loudness.optimize. |
Use it to drive UI progress bars or to log per-stage timing.
def on_step(progress: float, stage: str) -> None:
print(f"{progress:5.1%} {stage}")
result = sonare.master_audio(
samples,
sample_rate,
overrides={"loudness.targetLufs": -14, "loudness.ceilingDbtp": -1},
on_progress=on_step,
)Config keys and insert descriptors
A config dict reaches the arbitrary-band multiband compressor too: dynamics.multibandComp takes crossover (cutoffsHz, slope, mode, firKernelSize) and bands (one dict per band), or the flat keys dynamics.multibandComp.crossover.cutoffsHz.<i>, the scalar cutoff family dynamics.multibandComp.cutoff{i}Hz, and dynamics.multibandComp.bands.<i>.<field> in overrides. The band count is 2 to 64, and cutoffsHz replaces the cutoff list and sets the band count to its length plus one. An enum-valued key takes its choices name beside the number ("repair.denoise.noiseEstimator": "spp", dynamics.compressor.detector, the multiband slope, mode and detector keys); mastering_apply_processor, mastering_apply_processor_stereo and mastering_insert_timing params accept the same names. A streaming chain with repair.denoise.enabled defaults the estimator to spp and refuses quantile by name.
mastering_insert_param_names(insert) lists construction keys for IDs returned by mastering_insert_names(). mastering_insert_param_info(insert, sample_rate=...) returns descriptors for processor-catalog IDs, including offline repair stages, with their type, bounds, default, choices, conditional slot, and the depends_on / coupled_with siblings that move a bound. With a sample_rate, a Nyquist-bounded ceiling is resolved for that rate. Each function raises SonareValueError for an ID outside its accepted set. mastering_insert_timing() builds that configured insert and returns its latency_samples and tail_samples; keys the insert does not read are rejected. params takes every value type the descriptor declares (numbers, booleans, enum names, strings, number lists); a value of the wrong type is a TypeError and a non-finite number a SonareValueError. mastering_preset_params() returns the preset's flat override map, which can be passed to master_audio(..., overrides=...) unchanged.
Assistant, profile and preview
The analysis side of mastering: the audio profile, the assistant's chain suggestion and the streaming-platform preview, each with a stereo entry point. The chains these suggestions feed are described above, and the repair stages the assistant can recommend are on Python Dynamics and Repair API.
profile = sonare.mastering_audio_profile(samples, sample_rate, params={
"nFft": 2048,
"hopLength": 512,
"truePeakOversample": 4,
})
print(profile.loudness.integrated_lufs, profile.spectral.centroid_hz)
suggestion = sonare.mastering_assistant_suggest(samples, sample_rate, params={
"targetLufs": -14,
"ceilingDbtp": -1,
"preferStreamingSafe": True,
})
print(suggestion.explanation, suggestion.chain_config)
preview = sonare.mastering_streaming_preview(samples, sample_rate, platforms=[
{"name": "YouTube", "target_lufs": -14, "ceiling_dbtp": -1},
{"name": "Podcast", "target_lufs": -16, "ceiling_dbtp": -1},
])
for platform in preview.platforms:
print(platform.name, platform.normalization_gain_db, platform.ceiling_risk)
# Stereo entry points: same params, same records, measured from both channels.
stereo_profile = sonare.mastering_audio_profile_stereo(left, right, sample_rate, params={
"nFft": 2048,
"hopLength": 512,
"truePeakOversample": 4,
})
stereo_suggestion = sonare.mastering_assistant_suggest_stereo(left, right, sample_rate, params={
"targetLufs": -14,
"ceilingDbtp": -1,
"preferStreamingSafe": True,
})
# Omitting platforms uses the built-in Spotify / Apple Music / YouTube set.
stereo_preview = sonare.mastering_streaming_preview_stereo(left, right, sample_rate)# Analyze audio and return the mastering assistant profile.
def mastering_audio_profile(
samples: Sequence[float] | list[float],
sample_rate: int,
params: dict[str, float | int | bool] | None = None,
) -> MasteringAudioProfile: ...
# Return the mastering assistant profile of a stereo pair.
def mastering_audio_profile_stereo(
left: Sequence[float] | list[float],
right: Sequence[float] | list[float],
sample_rate: int,
params: dict[str, float | int | bool] | None = None,
) -> MasteringAudioProfile: ...
# Analyze audio and suggest a mastering chain with the reasoning behind it.
def mastering_assistant_suggest(
samples: Sequence[float] | list[float],
sample_rate: int,
params: dict[str, float | int | bool | str] | None = None,
) -> MasteringAssistantResult: ...
# Suggest a mastering chain for a stereo pair.
def mastering_assistant_suggest_stereo(
left: Sequence[float] | list[float],
right: Sequence[float] | list[float],
sample_rate: int,
params: dict[str, float | int | bool | str] | None = None,
) -> MasteringAssistantResult: ...
# Preview streaming-platform normalization and ceiling risk.
def mastering_streaming_preview(
samples: Sequence[float] | list[float],
sample_rate: int,
platforms: Sequence[StreamingPlatform] | None = None,
) -> MasteringStreamingPreviewResult: ...
# Preview streaming normalization for a stereo pair.
def mastering_streaming_preview_stereo(
left: Sequence[float] | list[float],
right: Sequence[float] | list[float],
sample_rate: int,
platforms: Sequence[StreamingPlatform] | None = None,
) -> MasteringStreamingPreviewResult: ...
# Return the delivery targets the mastering assistant accepts.
def mastering_platform_names() -> list[str]: ...Each of the three helpers has a _stereo sibling that takes left and right instead of one buffer, accepts the same params / platforms, and returns the same record type. Use it whenever you have two channels: the mono entry points measure a 0.5 * (left + right) downmix, which reads about 6 dB low on decorrelated material and pulls integrated loudness, the normalization gain derived from it, and the ceiling-risk judgment down by the same amount.
Why the stereo entry points matter
On a decorrelated pink-noise pair (48 kHz, 4 s) the downmix path reports -22.55 LUFS against -16.44 LUFS from the stereo path, a 6.11 dB gap that turns a Spotify normalizationGainDb of +2.44 into +8.55. A correlated pair differs by only 3.01 dB, the plain downmix 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 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 on the downmix and remain directly comparable with the mono call.
Options and result fields
| Entry point / result | Keys | Notes |
|---|---|---|
mastering_audio_profile(params=) | nFft, hopLength, truePeakOversample | All optional. |
mastering_assistant_suggest(params=) | targetLufs, ceilingDbtp, enableRepair, preferStreamingSafe, speechMonoAmount, preset, targetPlatform | All optional. Keys are camelCase; a snake_case spelling is refused by name. |
mastering(...) | release_ms, apply_gain_at_input_rate | Limiter release and static-gain staging; omit release_ms or pass None for the 50 ms library default; an explicit 0 or a negative value raises SonareValueError. Preset and chain overrides use the flat keys "maximizer.truePeakLimiter.releaseMs" and "maximizer.truePeakLimiter.applyGainAtInputRate", applied as given. |
| Offline chain or preset result | output_true_peak_dbtp, output_loudness_range_lu, stage_gain_reductions | True peak at the configured loudness oversample factor; output_loudness_range_lu is the EBU R128 loudness range in LU; each reduction names the dynamics or maximizer stage and its most recent gain reduction in dB (zero or negative). |
result.report | before, after, band_energy_delta_db | before and after each hold integrated_lufs, max_momentary_lufs, max_short_term_lufs, true_peak_dbtp and loudness_range_lu. band_energy_delta_db is the 32-band logarithmic spectral-energy change. The report also holds the applied gain, the maximum gain reduction, and whether peak headroom limited the loudness target. |