Skip to content

Python Engine Types ​

The records behind RealtimeEngine (transport, clips, MIDI schedules, capture, the processing graph, offline renders and telemetry), the meter records mix_stereo returns, and the structure and melody records analyze_sections, detect_boundaries and analyze_melody return. The methods that take or return them are on Python Realtime Engine API and Python Engine Mixing API; the analysis functions are on Python Analysis API and mix_stereo is on Python Mixer API. Build and catalog records are on Python Capabilities Types API.

The engine data records are frozen dataclasses; LiveSession is a managed connection that owns a device session.

Live devices and sessions ​

LiveSession.audio_devices() and LiveSession.midi_sources() return snapshots of the available devices and sources. A session strongly holds its RealtimeEngine; use close() or a context manager to stop it. Audio selections accept a LiveAudioDevice, "default" or None; MIDI input accepts a LiveMidiDevice or None. Positive sample_rate and block_size values and a uint32 destination_id are optional. Wrong object types raise TypeError, out-of-range scalar options raise SonareValueError, and device negotiation failures are SonareError values with a coded device reason.

python
# One available audio device, selected by its stable ``uid``.
@dataclass(frozen=True, slots=True)
class LiveAudioDevice:
    uid: str
    name: str
    input_channels: int
    output_channels: int
    is_default_input: bool
    is_default_output: bool
    nominal_sample_rate: float

# One available MIDI source, selected by its stable ``uid``.
@dataclass(frozen=True, slots=True)
class LiveMidiDevice:
    uid: str
    name: str

# A running device connection that drives a :class:`RealtimeEngine`.
class LiveSession:
    def __init__(
        self,
        engine: RealtimeEngine,
        *,
        audio_output: LiveAudioDevice | Literal['default'] | None = None,
        audio_input: LiveAudioDevice | Literal['default'] | None = None,
        midi_input: LiveMidiDevice | None = None,
        sample_rate: int | None = None,
        block_size: int | None = None,
        destination_id: int | None = None,
    ) -> None: ...
    # Return a copied snapshot of the available audio devices.
    @staticmethod
    def audio_devices() -> list[LiveAudioDevice]: ...
    # Return a copied snapshot of the available MIDI sources.
    @staticmethod
    def midi_sources() -> list[LiveMidiDevice]: ...
    # Stop the session on the control thread and release its handle.
    def close(self) -> None: ...
    # Return this session for use in a context manager.
    def __enter__(self) -> LiveSession: ...
    # Close the session when the context ends.
    def __exit__(self, *_exc: object) -> None: ...
    # Return the current connection state and counters.
    def status(self) -> LiveSessionStatus: ...
    # Drain the captured channel-voice MIDI events in arrival order.
    def captured_midi(self) -> list[ProjectMidiEvent]: ...

# Current connection state and counters for a live session.
@dataclass(frozen=True, slots=True)
class LiveSessionStatus:
    running: bool
    device_lost: bool
    rate_changed: bool
    sample_rate: int
    output_block_size: int
    input_block_size: int
    output_latency_ms: float
    input_latency_ms: float
    xrun_count: int
    input_overrun_frames: int
    input_underrun_frames: int
    dropped_midi_events: int

Transport, markers and automation ​

RealtimeEngine.transport_state() returns a TransportState snapshot. bar_index is zero-based and beat is one-based; beat_fraction is the position inside the current beat in [0, 1). Positions named *_ppq are in quarter notes.

EngineMarker takes ppq positionally; every other field is keyword-only. A None id asks set_markers to allocate one, and a marker read back always carries its id. name is at most 63 UTF-8 bytes. key_fifths (-7 to 7, sharps positive) and key_minor apply only to the "keySignature" kind.

EngineMetronomeConfig sets the click length with either click_samples (1 to 384000) or click_sec (up to 1); with both None the engine default of 2 ms applies. beat_gain and accent_gain are linear.

ParameterInfo registers an automatable parameter (RealtimeEngine.add_parameter), and AutomationPoint is one breakpoint of a lane (set_automation_lane): ppq is in quarter notes, value is in the parameter's own unit, and curve_to_next shapes the segment up to the next point.

python
# Read-only snapshot of the realtime engine transport state.
@dataclass(frozen=True, slots=True)
class TransportState:
    playing: bool
    looping: bool
    render_frame: int
    sample_position: int
    ppq_position: float
    bpm: float
    loop_start_ppq: float
    loop_end_ppq: float
    sample_rate: int
    bar_start_ppq: float
    bar_index: int
    time_signature: TimeSignature
    beat: int
    beat_fraction: float

# Timeline marker stored on the realtime engine transport, as read back.
@dataclass(frozen=True, slots=True)
class EngineMarker:
    ppq: float
    id: int
    name: str | None = None
    kind: MarkerKind = 'marker'
    key_fifths: int = 0
    key_minor: bool = False

# Realtime engine metronome click configuration.
@dataclass(frozen=True, slots=True)
class EngineMetronomeConfig:
    enabled: bool = False
    beat_gain: float = 0.35
    accent_gain: float = 0.7
    click_samples: int | None = None
    click_sec: float | None = None

# DAW parameter metadata for automation/introspection UIs.
@dataclass(frozen=True, slots=True)
class ParameterInfo:
    id: int
    name: str
    unit: str
    min_value: float
    max_value: float
    default_value: float
    rt_safe: bool
    default_curve: AutomationCurve

# PPQ automation breakpoint.
@dataclass(frozen=True, slots=True)
class AutomationPoint:
    ppq: float
    value: float
    curve_to_next: AutomationCurve = 'linear'

EngineMarkerInput is the input form for RealtimeEngine.set_markers: ppq is required, while id, name, kind and key fields have the declared defaults. An omitted id is allocated by the engine; key-signature fifths must be in [-7, 7].

python
# A marker handed to :meth:`~libsonare.RealtimeEngine.set_markers`.
@dataclass(frozen=True, slots=True)
class EngineMarkerInput:
    ppq: float
    id: int | None = None
    name: str | None = None
    kind: MarkerKind = 'marker'
    key_fifths: int = 0
    key_minor: bool = False

Clips and MIDI schedules ​

EngineClip is an audio clip for set_clips / upsert_clip. Give it either channels (in-memory planar data) or a page_provider (pages supplied on demand, channels is None). length_samples None plays to the end of the source; clip_offset_samples is where playback starts inside the source; warp_anchors are (source, target) pairs. When a provider is in use the engine asks for pages through ClipPageRequest (pop_clip_page_request()): sample is the first frame of the requested page in the clip source.

EngineMidiClipSchedule is a compiled MIDI clip for set_midi_clips; its events carry absolute render frames. destination_id None falls back to track_id; length_samples None is open-ended; loop_length_samples is read only when loop is set.

EngineMidiEvent holds a UMP message in word0 to word3 with word_count valid words. The engine reads the group from word0 (bits 24 to 27); group must still be in [0, 15], and a value that contradicts word0 is ignored. sysex_handle is the SysEx payload the event refers to, 0 for none.

ExternalMidiEvent is the other direction: one MIDI 1.0 byte message (1 to 3 bytes) drained by drain_external_midi(). destination_id is None for a clock or transport byte meant for every external port, and render_frame is the absolute device render frame.

python
# Owned audio clip schedule for realtime engine playback.
@dataclass(frozen=True, slots=True)
class EngineClip:
    id: int
    channels: PlanarChannels | None
    start_ppq: float
    track_id: int | None = None
    length_samples: int | None = None
    clip_offset_samples: int = 0
    loop: bool = False
    gain: float = 1.0
    fade_in_samples: int = 0
    fade_out_samples: int = 0
    warp_mode: ProjectWarpMode = 'off'
    warp_anchors: list[tuple[float, float]] | None = None
    page_provider: object | None = None

# Paged clip sample request drained from the realtime engine.
@dataclass(frozen=True, slots=True)
class ClipPageRequest:
    clip_id: int
    channel: int
    sample: int

# Compiled realtime MIDI clip schedule.
@dataclass(frozen=True, slots=True)
class EngineMidiClipSchedule:
    events: list[EngineMidiEvent]
    id: int | None = None
    track_id: int | None = None
    destination_id: int | None = None
    start_sample: int = 0
    start_ppq: float = 0.0
    length_samples: int | None = None
    loop: bool = False
    loop_length_samples: int | None = None
    gain: float = 1.0
    fade_in_samples: int = 0
    fade_out_samples: int = 0

# Absolute render-frame MIDI event for realtime engine MIDI clips.
@dataclass(frozen=True, slots=True)
class EngineMidiEvent:
    render_frame: int
    word0: int = 0
    word1: int = 0
    word2: int = 0
    word3: int = 0
    word_count: int = 0
    group: int = 0
    sysex_handle: int = 0

# One lowered MIDI 1.0 message drained from the external-MIDI output queue.
@dataclass(frozen=True, slots=True)
class ExternalMidiEvent:
    destination_id: int | None
    render_frame: int
    bytes: bytes

Capture ​

RealtimeEngine.configure_capture accepts a CapturePunch for the punch window. Configure the input monitor with set_input_monitor. capture_status() returns EngineCaptureStatus.

CapturePunch is a half-open window [start, end). Give each bound once, as *_ppq, *_sample or *_sec. Seconds are rounded to the nearest sample. Negative bounds are refused. Input monitor gain is linear. The status reports a source of "output" or "input" and the number of dropped_frames since the last reset.

python
# The realtime engine's dry input monitor, as read back by :meth:`~libsonare.RealtimeEngine.input_monitor`.
@dataclass(frozen=True, slots=True)
class EngineInputMonitor:
    enabled: bool
    gain: float

# A dry input monitor handed to :meth:`~libsonare.RealtimeEngine.set_input_monitor`.
@dataclass(frozen=True, slots=True)
class EngineInputMonitorInput:
    enabled: bool
    gain: float = 1.0

# A half-open punch-in window ``[start, end)`` for :meth:`RealtimeEngine.configure_capture`.
@dataclass(frozen=True, slots=True, kw_only=True)
class CapturePunch:
    start_ppq: float | None = None
    start_sample: int | None = None
    start_sec: float | None = None
    end_ppq: float | None = None
    end_sample: int | None = None
    end_sec: float | None = None

# Capture progress for the realtime engine recording sink.
@dataclass(frozen=True, slots=True)
class EngineCaptureStatus:
    captured_frames: int
    armed: bool
    punch_enabled: bool
    source: EngineCaptureSource
    record_offset_samples: int
    dropped_frames: int

Graph and sidechain ​

RealtimeEngine.set_graph installs an EngineGraphSpec. Node ids are unique within the graph; EngineGraphConnection ports are zero-based; a node's num_ports None uses the spec's num_channels; gain_db applies to the "gain" node type. parameter_bindings map an automation parameter id to the processor of a node.

SidechainSource names a key source by kind ("track" or "bus") and id; set_strip_sidechain and set_bus_sidechain take it, and passing None instead removes the binding. The can_set_*_sidechain queries return a SidechainCheck without changing anything: reason names the first refusal and is None when ok.

python
# Prepared realtime engine graph specification.
@dataclass(frozen=True, slots=True)
class EngineGraphSpec:
    nodes: list[EngineGraphNode]
    connections: list[EngineGraphConnection]
    input_node: str
    output_node: str
    num_channels: int = 2
    parameter_bindings: list[EngineGraphParameterBinding] | None = None

# Prepared realtime engine graph node.
@dataclass(frozen=True, slots=True)
class EngineGraphNode:
    id: str
    type: EngineGraphNodeType = 'passThrough'
    gain_db: float = 0.0
    num_ports: int | None = None

# Prepared realtime engine graph connection.
@dataclass(frozen=True, slots=True)
class EngineGraphConnection:
    source_node: str
    source_port: int
    dest_node: str
    dest_port: int
    mix: EngineGraphMix = 'add'

# Map an engine automation parameter id to a graph node processor.
@dataclass(frozen=True, slots=True)
class EngineGraphParameterBinding:
    param_id: int
    node_id: str

# A sidechain key source: a track lane or a bus, by id.
@dataclass(frozen=True, slots=True)
class SidechainSource:
    kind: SidechainSourceKind
    id: int

# Outcome of a ``can_set_*_sidechain`` query.
@dataclass(frozen=True, slots=True)
class SidechainCheck:
    ok: bool
    reason: SidechainRefusal | None = None

Offline renders ​

bounce_offline takes an EngineBounceOptions and returns an EngineBounceResult; freeze_offline takes an EngineFreezeOptions and returns an EngineFreezeResult. num_channels is required in both options. An omitted block_size is the default offline block, capped at the engine's prepared maximum, and an explicit 0 is refused. source_sample_rate must equal the prepared rate when given, and target_sample_rate None means no resampling; an explicit 0 is refused for either. target_lufs and dither_seed None select the library values (-14 LUFS and the built-in seed); a given value is read literally, so 0 is 0 LUFS or seed 0. dither_bits is in [2, 32].

EngineBounceResult.interleaved is channel-interleaved; frames is the frame count. process(..., with_monitor=True) returns an EngineProcessWithMonitorResult with the program planes in output and the monitor-bus planes in monitor.

python
# Offline export options for the realtime engine.
@dataclass(frozen=True, slots=True)
class EngineBounceOptions:
    total_frames: int
    num_channels: int
    block_size: int | None = None
    target_sample_rate: int | None = None
    source_sample_rate: int | None = None
    normalize_lufs: bool = False
    target_lufs: float | None = None
    dither: EngineDither | None = None
    dither_bits: int = 16
    dither_seed: int | None = None

# Interleaved offline export result from the realtime engine.
@dataclass(frozen=True, slots=True)
class EngineBounceResult:
    interleaved: np.ndarray
    frames: int
    num_channels: int
    sample_rate: int
    integrated_lufs: float
    quantize_clipped_samples: int | None = None

# Offline freeze options for replacing current engine output with a clip.
@dataclass(frozen=True, slots=True)
class EngineFreezeOptions:
    total_frames: int
    num_channels: int
    block_size: int | None = None
    clip_id: int = 1
    start_ppq: float = 0.0
    gain: float = 1.0

# Result of freezing current engine output into a scheduled clip.
@dataclass(frozen=True, slots=True)
class EngineFreezeResult:
    clip_id: int
    frames: int
    num_channels: int

# Result of ``RealtimeEngine.process(..., with_monitor=True)``: program and monitor planes.
@dataclass(frozen=True, slots=True, eq=False)
class EngineProcessWithMonitorResult:
    output: tuple[npt.NDArray[np.float32], ...]
    monitor: tuple[npt.NDArray[np.float32], ...]

Telemetry and metering ​

drain_telemetry() returns EngineTelemetry events; type is an EngineTelemetryType token and error is set when the event reports an error. audible_timeline_sample is the position of the audio now audible, and graph_latency_samples is fractional.

drain_meter_telemetry() returns a MeterTelemetryRecord per plane set of a mix target. peak_db, rms_db and true_peak_dbtp hold num_channels valid planes in canonical WAVE order (5.1 is L R C LFE Ls Rs, 7.1 adds Lss Rss); a stereo target's left and right are planes 0 and 1. True peaks are inter-sample peaks from the BS.1770-4 4x polyphase reconstruction, measured while streaming, so they trail the block by one reconstruction-filter group delay (a few samples) and do not depend on the block size. Levels are in dBFS and true peaks in dBTP; correlation is in [-1, 1].

drain_scope_telemetry() returns ScopeTelemetryRecord snapshots: bands are the spectrum band levels and points are vectorscope points as (left, right) tuples (Node and WASM expose the same data as {left, right} objects). dropped_records counts records lost because the telemetry queue was full.

MixMeterSnapshot is the per-strip meter in MixResult.meters (from mix_stereo), with the same true-peak measurement. mono_compat_peak and mono_compat_side_rms are linear full-scale amplitudes of the fold-down 0.5 * (L + R) and the side signal 0.5 * (L - R). GoniometerPoint is one left/right sample pair for a vectorscope display.

python
# Realtime engine telemetry event.
@dataclass(frozen=True, slots=True)
class EngineTelemetry:
    type: EngineTelemetryType
    error: EngineTelemetryError
    render_frame: int
    timeline_sample: int
    audible_timeline_sample: int
    graph_latency_samples: float
    value: int

# A per-plane meter snapshot for a mix target.
@dataclass(frozen=True, slots=True, eq=False)
class MeterTelemetryRecord:
    target_id: int
    render_frame: int
    seq: int
    num_channels: int
    peak_db: npt.NDArray[np.float32]
    rms_db: npt.NDArray[np.float32]
    true_peak_dbtp: npt.NDArray[np.float32]
    max_true_peak_dbtp: float | None
    correlation: float | None
    mono_compat_width: float | None
    momentary_lufs: float | None
    short_term_lufs: float | None
    integrated_lufs: float | None
    gain_reduction_db: float
    dropped_records: int
    input_peak_db: npt.NDArray[np.float32]

# A spectrum/vectorscope snapshot drained from the realtime engine.
@dataclass(frozen=True, slots=True, eq=False)
class ScopeTelemetryRecord:
    target_id: int
    render_frame: int
    seq: int
    dropped_records: int
    bands: npt.NDArray[np.float32]
    points: list[tuple[float, float]]

# Realtime mixer meter snapshot.
@dataclass(frozen=True, slots=True)
class MixMeterSnapshot:
    correlation: float | None
    mono_compat_width: float | None
    mono_compat_peak: float
    mono_compat_side_rms: float
    likely_mono_compatible: bool
    momentary_lufs: float | None
    short_term_lufs: float | None
    integrated_lufs: float | None
    gain_reduction_db: float
    max_true_peak_dbtp: float | None
    seq: int
    num_channels: int
    peak_db: tuple[float | None, ...]
    rms_db: tuple[float | None, ...]
    true_peak_dbtp: tuple[float | None, ...]

# Result of rendering a small stereo mixer scene.
@dataclass(frozen=True, slots=True, eq=False)
class MixResult:
    left: npt.NDArray[np.float32]
    right: npt.NDArray[np.float32]
    sample_rate: int
    meters: list[MixMeterSnapshot]

# A single left/right sample pair for goniometer (vectorscope) display.
@dataclass(frozen=True, slots=True)
class GoniometerPoint:
    left: float
    right: float

Structure and melody results ​

analyze_sections() returns a SectionAnalysis. Section.energy_level is the section's median frame RMS over the loudest section's, in [0, 1]. Sections sharing a group repeat the same material, numbered 0, 1, ... by first appearance. A section of type "unknown" matched no labeling rule and has confidence 0. SectionAnalysis.form has one letter per section (for example "AABA") and is empty when there are none.

detect_boundaries() returns a BoundaryResult. Boundary.time_sec is the authoritative output; frame indexes the analysis grid, not the source's STFT grid, because input above 22.05 kHz is resampled and a long input is mean-pooled (frame_stride raw frames per analysis frame, 1 unless pooled). sample_rate is the rate the analysis ran at, not the input's. novelty_curve is scaled by its own maximum, so it lies in [0, 1]; multiply by novelty_peak to recover the raw response that absolute_threshold is compared against. novelty_peak is None when nothing rose above the numerical floor.

analyze_melody() returns a MelodyResult. A MelodyPoint has frequency_hz None when it is unvoiced, and mean_frequency_hz is taken over voiced points.

python
# A detected song-structure section.
@dataclass(frozen=True, slots=True)
class Section:
    type: SectionType
    start_sec: float
    end_sec: float
    energy_level: float
    confidence: float
    group: int
    name: str

# What :func:`analyze_sections` returns: the sections and the form they spell.
@dataclass(frozen=True, slots=True)
class SectionAnalysis:
    sections: list[Section]
    form: str

# A detected structural transition.
@dataclass(frozen=True, slots=True)
class Boundary:
    time_sec: float
    frame: int
    strength: float

# Structural boundaries and the novelty curve (float32) they were picked from.
@dataclass(frozen=True, slots=True, eq=False)
class BoundaryResult:
    boundaries: list[Boundary]
    novelty_curve: npt.NDArray[np.float32]
    novelty_peak: float | None
    sample_rate: int
    hop_length: int
    frame_stride: int

# A single point on a melody contour; ``frequency_hz`` is ``None`` when unvoiced.
@dataclass(frozen=True, slots=True)
class MelodyPoint:
    time_sec: float
    frequency_hz: float | None
    confidence: float

# Melody contour analysis result.
@dataclass(frozen=True, slots=True)
class MelodyResult:
    points: list[MelodyPoint]
    pitch_range_octaves: float | None
    pitch_stability: float | None
    mean_frequency_hz: float | None
    vibrato_rate_hz: float | None