Python Types
Result and option types of the libsonare Python package; the functions that return them are on the Python API index and its sibling pages.
Types
Most result objects are frozen dataclasses with attribute access; mapping types are identified as TypedDict. The generated blocks list every field with its type and default; the records of each family are on their own pages: Python Analysis Types for key, chord, tempo, feature, pitch, loudness and metering results, Python Streaming Types for StreamAnalyzer records, Python Effects Types for separation, trim, note-editing and voice changer records, and Python Audio API for Audio and DecodedChannels.
Matrix layout
Matrix fields are 2-D NumPy arrays shaped (rows, n_frames): (n_bins, n_frames) for a spectrogram, (n_mels, n_frames) for Mel power, (n_chroma, n_frames) for a chromagram. Functions that take a spectrogram as a flat sequence (decompose, nn_filter) read it row-major; reshape a flat array by its row count to recover the 2-D form:
import numpy as np
mat = np.asarray(flat).reshape(rows, n) # e.g. reshape(12, n_frames) for a 12-pitch-class chromagramInteger sample alias
IntSamples is the integer-array input used by analyzer functions that take sample indices or flags. It accepts a sequence of Python integers or an integer NumPy array.
IntSamples: TypeAlias = Sequence[int] | list[int] | np.ndarray[Any, Any]Pitch classes
PitchClass is the pitch class used by Key.root, Chord.root and Chord.bass: C is 0 and B is 11, with sharps spelled CS, DS, FS, GS and AS.
# Musical pitch class (chromatic scale).
class PitchClass(IntEnum):
C = 0
CS = 1
D = 2
DS = 3
E = 4
F = 5
FS = 6
G = 7
GS = 8
A = 9
AS = 10
B = 11Other result classes
Additional Python result classes used by focused APIs:
| Area | Classes |
|---|---|
| Mastering | MasteringResult, MasteringStereoResult, MasteringChainResult, MasteringChainStereoResult, LoudnessMatchResult, LoudnessMatchStereoResult, StreamingLoudnessGain (from streaming_loudness_gain*) |
| Mastering reports | Frozen dataclasses the assistant, profile and analysis helpers return directly: MasteringAudioProfile (MasteringAudioProfileLoudness, MasteringAudioProfileSpectral, MasteringAudioProfileDynamics, AudioDefects), MasteringAssistantProfile, MasteringAssistantResult (chain_config is a flat MasteringChainConfig mapping), MasteringStreamingPreviewResult, MasteringStreamingPreviewPlatform, MasteringRepairAnalysis, MatchReferenceLoudnessResult, MatchTonalBalanceResult, MatchTonalBalanceBand, MatchEqCurveResult, MatchEstimateReferenceDelaySamplesResult, StereoMonoCompatCheckResult, StereoMonoCompatBand, StereoMonoCompatCheckLogBandsResult |
| Repair | RepairApplyResult, RepairStageReports (from mastering_repair_apply) |
| Acoustics | RoomEstimate (volume, length_m, width_m, height_m, drr_db, confidence, band_absorption, rt60_bands), RoomMorphResult (audio, sample_rate, diagnostics), RoomMorphStereoResult (left, right, sample_rate, diagnostics; from room_morph_stereo), RoomGeometry (a TypedDict, from room_geometry_from_estimate), MaterialPresetName, AcousticModeName |
| Analysis literals | ChordFunctionName |
| Mixing | MixAssistantTrack (id, channels, name, sample_rate; a track at another rate is resampled onto the call's rate), MixResult, MixerStereoResult, SidechainCheck (ok plus the first refusal reason; from the engine's can_set_*_sidechain) |
| Projects | AssistSidecar (element type of project.assist_sidecars(); see Project Editing), NotePairValidation, ProjectAutoTempoResult |
| Realtime engine jobs/telemetry | EngineBounceOptions, EngineBounceResult, EngineFreezeOptions, EngineFreezeResult, EngineCaptureStatus, EngineTelemetry, EngineTelemetryType, EngineTelemetryError, MeterTelemetryRecord, ScopeTelemetryRecord |
| Build introspection | Capabilities, CapabilityCatalog, CapabilityCatalogPresets, CapabilityCatalogChain, CapabilityCatalogChainStage, CapabilityCatalogChainList, SynthParamInfo, SynthParamCondition, MasteringPresetCatalogEntry, MasteringInsertParamInfo, MasteringInsertParamUnit, MasteringInsertParamScale, MasteringInsertParamRelation, MasteringInsertParamDependency, MasteringInsertSlot, MasteringInsertTiming, MasteringProcessorCatalogEntry (frozen dataclasses over the documents described on Capability Catalog) |
catalog.chain (CapabilityCatalogChain) describes every flat mastering chain key: the stages, the indexed lists with their item counts, and params, the keys no processor describes; catalog.presets.playback_room is always present. SynthParamInfo (from synth_engine_param_info and synth_patch_param_info) has name, type ("number" or "boolean"), default (float | bool; a bool for a switch), unit and integer, min, max and active_when, the last three None when they do not apply. active_when is a tuple of alternatives, each a tuple of SynthParamCondition records (key, scope "engine" or "patch", relation one of "eq", "ne", "gt", "ge", "lt", "le", and value): the field reaches the voice when every condition of at least one alternative holds; it is None for an unconditional field. catalog.mastering_presets contains MasteringPresetCatalogEntry values with name, kind, target_lufs, true_peak_ceiling_dbtp, and max_limiter_gain_reduction_db; restoration entries use None for the three numeric fields. MasteringProcessorCatalogEntry includes slots for conditional key groups and causal (false for repair.declick, repair.declip and repair.trimSilence). MasteringInsertParamInfo descriptors include id, rt_safe, type, min, max, default, unit (from the closed MasteringInsertParamUnit set), scale (linear or log), ui_min / ui_max (an optional display range inside [min, max]), depends_on (sibling keys whose live value bounds this one, each as key, relation and factor, read as this <relation> factor * sibling), coupled_with (a tuple of the other sibling keys that move the accepted range; min / max are measured with them at their defaults), choices, and slot, while MasteringInsertTiming contains latency_samples and tail_samples for the requested insert configuration.
Exceptions
Two classes cover failures reported through libsonare's Python exception hierarchy, and the second derives from the first, so they form one hierarchy rather than two. Ordinary Python call-shape and type errors are TypeError. ErrorCode is the IntEnum of the codes the libsonare exceptions carry, and the failure-cause table says which cause raises which class, code and CLI exit:
SonareError.reason is ErrorReason | None; ErrorReason lists the known non-null machine-readable causes.
ErrorReason = Literal['malformedJson', 'unsupportedSchemaVersion', 'notCompiledIn', 'notPersistable', 'unresolvedSource', 'unresolvedSoundFont', 'deviceUnavailable', 'deviceFormatRefused', 'engineDeviceDriven', 'releasedHandle']# Exception raised for non-OK Sonare C API return codes.
class SonareError(RuntimeError):
code: ErrorCode
entry: str | None
reason: ErrorReason | None
def __init__(self, code: int, message: str) -> None: ...
# The name of :attr:`code` shared by every binding, such as ``"InvalidParameter"``.
@property
def code_name(self) -> ErrorCodeName: ...
# Public C-ABI error codes carried by :class:`SonareError`.
class ErrorCode(IntEnum):
OK = 0
FILE_NOT_FOUND = 1
INVALID_FORMAT = 2
DECODE_FAILED = 3
INVALID_PARAMETER = 4
OUT_OF_MEMORY = 5
NOT_SUPPORTED = 6
INVALID_STATE = 7
CANCELLED = 8
ENCODE_FAILED = 9
ABI_MISMATCH = 10
STALE_RESULT = 11
UNKNOWN = 99
# Exception for an out-of-domain value or an unknown name.
class SonareValueError(SonareError, ValueError):
def __init__(self, message: str, code: int = ErrorCode.INVALID_PARAMETER) -> None: ...
code: ErrorCode
entry: str | None
reason: ErrorReason | None
# The name of :attr:`code` shared by every binding, such as ``"InvalidParameter"``.
@property
def code_name(self) -> ErrorCodeName: ...SonareError.code is the C-ABI error code, an ErrorCode value, and code_name is the name every binding shares, such as "InvalidState" or "FileNotFound". str(e) prefixes the code to the message: [7] Invalid state. ErrorCode.ABI_MISMATCH is binding-only: the loaded library does not match the binding. Argument refusals with INVALID_PARAMETER are SonareValueError instead; its str(e) carries no prefix, for example spectral_centroid: samples contains a non-finite sample at index 0.
A failure that comes from the library or from an object's state is always a SonareError with the matching code — NOT_SUPPORTED for a compiled-out feature or unsupported request, INVALID_STATE for a closed object, INVALID_FORMAT for an invalid native result — so except RuntimeError keeps catching it and .code tells the cases apart. ABI_MISMATCH is raised on first library use when the loaded library's ABI version differs from the binding's. The error contract lines these codes up with the other bindings and the CLI exit codes.
SonareValueError represents an argument refusal reported as INVALID_PARAMETER, whichever layer refused it: the binding before the call crosses into native code, or the core (an unknown or out-of-range id or value on Project, RealtimeEngine and transcribe, for example). A wrong Python type, missing required function argument or unexpected function keyword is a regular TypeError; a non-number handed to a numeric argument is one example. Because SonareValueError subclasses both SonareError and ValueError, except ValueError, except SonareError, except RuntimeError and except SonareValueError all catch it, and .code == ErrorCode.INVALID_PARAMETER matches it.
An instance is message-only. There is no attribute naming the offending parameter and none carrying the accepted range: .code is the only structured field, and for a SonareValueError it reads INVALID_PARAMETER; a document that fails to load is not a SonareValueError at all but a plain SonareError with INVALID_FORMAT. The parameter name and, where one applies, the range are in the text — a buffer refusal names the entry point and the argument (master_audio_stereo: right must not be empty), a scalar refusal names the field and the interval the C type can hold (sample_rate must be an integer within [-2147483648, 2147483647]). Code that needs the name has to read it from str(e); Python API covers the wording and why matching on it is fragile.
Where the validation layer stops
The binding validates in two layers, and the shape of each says what a SonareValueError at the call site rules out.
Sample buffers are preflighted on every public entry point whose leading parameter is a sample buffer, through the shared preflight guard or the same check written into the body. Each preflighted buffer is coerced to a contiguous one-dimensional float32 array, refused when empty, and scanned for NaN and Inf. An F0 track handed to the note functions is checked for shape only, because pYIN spells an unvoiced frame as nan. The set is derived rather than maintained: a test in the binding discovers every public callable whose leading parameter is annotated as a buffer and fails when one ships without the guard. A None element in a sample list is named (samples[7] is None, not a number) rather than reported as a NaN sample.
Scalars are narrowed at the conversion, not per function. Every integer or float that passes through the binding's ctypes readers or a config-struct field is refused when the C type would silently change it: an integer that would wrap (2**32 + 8000 handed to a c_int sample rate), a fractional value for an integer field, a double that would saturate a c_float, or a NaN or infinity. These are SonareValueError. A value that is not a number at all, such as a string or a bool, is a plain TypeError instead, so except ValueError does not catch it. The message names the field and the interval. Because the check sits at the conversion, it covers every entry point that hands the value on, and there is no per-function count to keep.
Five entry points refuse rather than answer. Refusing is a different contract from checking and continuing, and these are the ones whose input is refused outright instead of producing a defined empty result: trim_silence, split_silence and fix_frames raise on an empty buffer; tempogram_ratio raises on an empty matrix and on a factors entry that is not finite and positive; mix_stereo raises on a scene whose strips are all empty or carry a non-finite sample. Input some entry points refuse gives the reason for each.
What the layer does not do:
- Judge a value's meaning beyond the declared keys and bounds. Narrowing checks that a number is representable. A parameter mapping is also checked against the processor's declared keys and bounds before the call, so
ratio=0.5ondynamics.compressor(mastering_apply_processor: params.ratio must be finite and at least 1),dryWet=5oneffects.modulation.chorus, and a key the processor does not read, such asgainDbonutility.gain, are each aSonareValueErrornaming the key; an unknown key also lists the accepted ones. A handful of entry points do check a domain rule Python-side — the power-of-twon_fftof the classical repair functions, the odd kernel ofhpss, the FFT geometry oftime_stretchandpitch_shift— and their messages read the same way; everything else about a value's meaning is the core's to judge. - Go beyond the declared bounds. The parameter mappings handed to
mastering_apply_processor, the chain and the inserts are checked against the keys and bounds the capability catalog declares; a rule it does not declare is the core's to judge. - Preflight the exemptions. The entry points for which an empty buffer is a defined result — the element-wise conversions, the padding helpers, the tempogram family — accept one and return one; they are listed under What is not checked.
- Cover the CLI's own arguments. A command-line usage error is a plain
ValueError, since it reports a mistake in the command rather than an API argument.
Project types
The records Project takes and returns, and the string tokens its arguments accept. Python Projects API lists the Project members that use them.
Project records
ProjectAutomationLane is the stored lane read-back: typed targets have no target_param_id, and insert-specific fields are None for other target kinds. ProjectKeySegment, ProjectChordSymbol and ProjectSection are the mappings accepted by and returned from project annotation methods; unknown pitch classes are None, and an absent chord Roman numeral is omitted. ProjectPosition and ProjectTimeSignatureSegment describe the effective bar, beat and meter at a PPQ coordinate.
# One automation lane returned by :meth:`Project.automation_lanes`.
@dataclass(frozen=True, slots=True)
class ProjectAutomationLane:
track_id: int
lane_id: int
target_param_id: int | None
target_kind: ProjectAutomationTargetKind
points: tuple[AutomationPoint, ...]
send_id: str | None
insert_index: int | None
processor: str | None
param_name: str | None
# Chord annotation mapping returned by :meth:`Project.chord_annotations`.
class ProjectChordSymbol(TypedDict):
start_ppq: float
end_ppq: float
root_pc: int | None
quality: ProjectChordQuality
extensions: list[int]
slash_bass_pc: int | None
modulation_boundary: bool
roman_numeral: NotRequired[str]
# Key annotation mapping returned by :meth:`Project.key_annotations`.
class ProjectKeySegment(TypedDict):
start_ppq: float
end_ppq: float
tonic_pc: int | None
mode: ProjectKeyMode
# Effective tempo, time signature, bar, and beat at one PPQ position.
@dataclass(frozen=True, slots=True)
class ProjectPosition:
bpm: float
time_signature: ProjectTimeSignatureSegment
bar_start_ppq: float
bar_index: int
beat: int
beat_fraction: float
# Labeled PPQ interval mapping used by :meth:`Project.annotate_sections`.
class ProjectSection(TypedDict):
start_ppq: float
end_ppq: float
label: str
# The normalized time-signature segment active at a project position.
@dataclass(frozen=True, slots=True)
class ProjectTimeSignatureSegment:
start_ppq: float
numerator: int
denominator: int# Read-only, stored-order project track descriptor.
@dataclass(frozen=True, slots=True)
class ProjectTrack:
id: int
kind: ProjectTrackKind
midi_destination_id: int
gain: float
pan: float
mute: bool
solo: bool
name: str | None
channel_strip_ref: str | None = None
output_target: str | None = None
# Read-only, stored-order project clip descriptor.
@dataclass(frozen=True, slots=True)
class ProjectClip:
id: int
track_id: int
source_id: int
source_kind: ProjectSourceKind
start_ppq: float
length_ppq: float
source_offset_ppq: float
gain: float
loop_mode: ProjectLoopMode
loop_length_ppq: float | None
fade_in_ppq: float
fade_in_curve: ProjectFadeCurve
fade_out_ppq: float
fade_out_curve: ProjectFadeCurve
loop_crossfade_ppq: float
# Timeline marker stored on a headless :class:`~libsonare._project.Project`.
@dataclass(frozen=True, slots=True)
class ProjectMarker:
ppq: float
id: int
name: str | None = None
kind: MarkerKind = 'marker'
key_fifths: int = 0
key_minor: bool = False
# Read-only, stored-order project source descriptor.
@dataclass(frozen=True, slots=True)
class ProjectSource:
id: int
kind: ProjectSourceKind
num_channels: int
storage_handle_id: int
sample_rate_hint: float
name_or_uri: str
content_hash: str | None = None
external_stem_role: str | None = None
# One opaque assist sidecar stored on a :class:`Project`.
@dataclass(frozen=True)
class AssistSidecar:
module_id: str
schema_version: int
target_track_id: int
region_start_ppq: float
region_end_ppq: float
payload: bytes
# One compile diagnostic surfaced by :meth:`Project.compile`.
@dataclass(frozen=True)
class ProjectDiagnostic:
code: ProjectDiagnosticCode
severity: ProjectDiagnosticSeverity
target_id: int | None
message: str = ''
# Result of :meth:`Project.validate_midi_notes`.
@dataclass(frozen=True)
class NotePairValidation:
ok: bool
unmatched_note_ons: int
unmatched_note_offs: int
# A MIDI CC <-> automation-parameter binding (see :func:`midi_cc_learn`).
@dataclass(frozen=True, kw_only=True)
class MidiCcBinding:
cc_number: int
channel: int | None = None
kind: ProjectMidiCcBindingKind = 'controlChange7'
cc_lsb_number: int = 0
selector_msb: int = 0
selector_lsb: int = 0
consume: bool = False
param_id: int
min_value: float = 0.0
max_value: float = 1.0
# One project MIDI event: a PPQ position and a UMP message.
@dataclass(frozen=True, slots=True)
class ProjectMidiEvent:
ppq: float
word0: int
word1: int = 0
sysex: bytes | None = None
# Result of :func:`midi_route_events`.
@dataclass(frozen=True)
class MidiRouteResult:
events: list[ProjectMidiEvent]
overflowed: bool
overflow_count: int
# Result of :meth:`Project.compile` and :meth:`Project.last_bounce_compile_result`.
@dataclass(frozen=True)
class ProjectCompileResult:
diagnostics: tuple[ProjectDiagnostic, ...]
timeline: ProjectTimeline | None = None
# Project plus warning diagnostics emitted by a successful JSON load.
@dataclass(frozen=True)
class ProjectDeserializeResult:
project: Project
diagnostics: str
# Result of :meth:`Project.add_loop_recording_takes`.
@dataclass(frozen=True, slots=True)
class ProjectLoopRecordingResult:
clip_id: int
take_count: int
# Result of :meth:`Project.add_midi_clip`.
@dataclass(frozen=True, slots=True)
class ProjectMidiClipResult:
track_id: int
clip_id: int
# Result of :meth:`Project.import_external_stems`; entry ``i`` of each array is stem ``i``.
@dataclass(frozen=True, slots=True, eq=False)
class ExternalSeparatedStemImportResult:
track_ids: np.ndarray
clip_ids: np.ndarray
# A part-rig entry read back by :meth:`Project.part_rig`.
@dataclass(frozen=True, slots=True)
class PartRigEntry:
mode: PartRigMode
inserts: tuple[dict[str, object], ...] | None
# How well an :func:`align_take_to_reference` alignment was conditioned.
@dataclass(frozen=True)
class TakeAlignment:
mean_residual_frames: float
reference_frames: int
take_frames: int
# Result of :func:`align_take_to_reference`.
@dataclass(frozen=True, slots=True)
class AlignTakeToReferenceResult:
anchors: tuple[tuple[float, float], ...]
alignment: TakeAlignment
# The selected tempo and detected meter from :meth:`Project.auto_tempo`.
@dataclass(frozen=True, slots=True)
class ProjectAutoTempoResult:
bpm: float
bpm_confidence: float
time_signature: TimeSignatureProject tokens
ProjectInstrumentKind is the persisted instrument backend token: synth, builtin or sf2.
ProjectInstrumentKind: TypeAlias = Literal['synth', 'builtin', 'sf2']ProjectWarpMode = Literal['off', 'repitch', 'tempoSync', 'timeStretch']
ProjectTrackKind: TypeAlias = Literal['audio', 'midi', 'aux']
ProjectSourceKind: TypeAlias = Literal['audio', 'midi']
ProjectStemLayout: TypeAlias = Literal['mono', 'stereo']
ProjectFadeCurve: TypeAlias = Literal['linear', 'equalPower', 'exponential', 'logarithmic']
ProjectLoopMode: TypeAlias = Literal['off', 'loop']
ProjectOverlapPolicy: TypeAlias = Literal['disallow', 'allow']
ProjectAutomationTargetKind: TypeAlias = Literal['opaque', 'trackFaderDb', 'trackPan', 'trackSendDb', 'trackWidth', 'trackInsertParam']
ProjectMidiCcBindingKind: TypeAlias = Literal['controlChange7', 'controlChange14', 'rpn', 'nrpn']
ProjectKeyMode: TypeAlias = Literal['unknown', 'major', 'minor', 'dorian', 'phrygian', 'lydian', 'mixolydian', 'locrian']
ProjectChordQuality: TypeAlias = Literal['unknown', 'major', 'minor', 'diminished', 'augmented', 'dominant', 'halfDiminished', 'suspended']
ProjectDiagnosticSeverity: TypeAlias = Literal['error', 'warning']
ProjectDiagnosticCode: TypeAlias = Literal['ok', 'danglingSourceRef', 'clipOverlap', 'invalidTempo', 'invalidPpq', 'unsupportedGraph', 'unsupportedMixing', 'emptyAudioSource', 'invalidSampleRate', 'sourceKindMismatch', 'midiClipNoInstrument', 'raggedAudioSource', 'loopCrossfadeUnavailable', 'sharedChannelStrip', 'automationLaneConflict', 'invalidAutomationTargetKind', 'automationLaneCapacity', 'reservedAutomationRouteConflict', 'automationTargetUnrouted']Functions that build these types
align_take_to_reference(reference, take, sample_rate, *, take_sample_rate=None, ...) aligns a take to a reference timeline and returns an AlignTakeToReferenceResult. Its anchors are oriented for the take's own clip: the first element of each pair is a position on the reference timeline and the second the matching position in the take, so they go straight to Project.set_warp_map.
# Align a take to a reference timeline and return anchors placing it under it.
def align_take_to_reference(
reference: Sequence[float] | list[float] | np.ndarray,
take: Sequence[float] | list[float] | np.ndarray,
sample_rate: int,
*,
take_sample_rate: int | None = None,
hop_length: int | None = None,
bins_per_octave: int | None = None,
) -> AlignTakeToReferenceResult: ...mastering_repair_apply(channels, sample_rate, *, stages, ...) applies repair stages to every channel in the chain's fixed order (declip, declick, decrackle, dehum, denoise, dereverb) whatever order stages gives, and returns a RepairApplyResult.
# Apply repair stages to every channel in the chain's fixed order.
def mastering_repair_apply(
channels: Sequence[Sequence[float] | np.ndarray] | np.ndarray,
sample_rate: int,
*,
stages: Sequence[RepairStage],
on_progress: Callable[[float, str], None] | None = None,
cancel: Callable[[], bool] | None = None,
) -> RepairApplyResult: ...room_geometry_from_estimate(estimate, *, source=None, listener=None) turns a RoomEstimate into the geometry synthesize_rir takes, merging in a placement (source and listener positions in metres) and leaving out absorption bands that did not converge. It raises SonareValueError when the estimate has no measurable dimensions.
# Turn a room estimate into the geometry :func:`synthesize_rir` takes.
def room_geometry_from_estimate(
estimate: RoomEstimate,
*,
source: Sequence[float] | None = None,
listener: Sequence[float] | None = None,
) -> RoomGeometry: ...