Skip to content

Python エンジンの型 ​

RealtimeEngine の背後にあるレコード(トランスポート、クリップ、MIDI スケジュール、キャプチャ、処理グラフ、オフラインレンダー、テレメトリ)と、mix_stereo が返すメーターのレコード、analyze_sections・detect_boundaries・analyze_melody が返す構造とメロディのレコードをまとめています。これらを受け取る・返すメソッドは Python リアルタイムエンジン API と Python エンジンミキシング API に、解析関数は Python 解析 API に、mix_stereo は Python Mixer クラス API にあります。ビルド情報とカタログのレコードは Python 機能情報の型 API です。

エンジンのデータレコードは frozen dataclass です。LiveSession はデバイスセッションを所有する管理対象の接続です。

ライブデバイスとセッション ​

LiveSession.audio_devices() と LiveSession.midi_sources() は、利用可能なデバイスとソースのスナップショットを返します。セッションは RealtimeEngine を強参照します。停止には close() またはコンテキストマネージャーを使います。オーディオ選択には LiveAudioDevice、"default"、None を指定できます。MIDI 入力には LiveMidiDevice または None を指定します。sample_rate と block_size は正の値を任意で指定します。オブジェクト型が違うと TypeError、スカラー値が範囲外だと SonareValueError、デバイスのネゴシエーション失敗はデバイス原因コード付きの SonareError になります。

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

トランスポート、マーカー、オートメーション ​

RealtimeEngine.transport_state() は TransportState のスナップショットを返します。bar_index は 0 始まり、beat は 1 始まりで、beat_fraction は現在の拍の中での位置([0, 1))です。*_ppq の位置は四分音符単位です。

EngineMarker は ppq だけが位置引数で、ほかのフィールドはキーワード専用です。id が None なら set_markers が採番し、エンジンから読み戻したマーカーには必ず id が付きます。name は UTF-8 で最大 63 バイトです。key_fifths(-7 から 7、シャープが正)と key_minor は "keySignature" の種別でのみ使われます。

EngineMetronomeConfig のクリック長は click_samples(1 から 384000)か click_sec(最大 1)のどちらかで指定します。両方が None ならエンジンの既定値 2 ms です。beat_gain と accent_gain はリニアゲインです。

ParameterInfo はオートメーション可能なパラメータを登録するときの記述(RealtimeEngine.add_parameter)、AutomationPoint はレーンの 1 ブレークポイント(set_automation_lane)です。ppq は四分音符単位、value はそのパラメータ自身の単位、curve_to_next は次の点までの区間の形を決めます。

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 は RealtimeEngine.set_markers に渡す入力形式です。ppq は必須で、id、name、kind、調のフィールドには宣言済みの既定値があります。id を省略するとエンジンが割り当てます。調号の fifths は [-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

クリップと MIDI スケジュール ​

EngineClip は set_clips / upsert_clip に渡すオーディオクリップです。channels(メモリ上のプレーナーデータ)か page_provider(必要に応じてページを供給。このとき channels は None)のどちらかを指定します。length_samples が None ならソースの終わりまで再生し、clip_offset_samples はソース内の再生開始位置、warp_anchors は (source, target) の組です。プロバイダーを使う場合、エンジンは ClipPageRequest(pop_clip_page_request())でページを要求します。sample は要求ページの先頭フレームで、クリップソース内の位置です。

EngineMidiClipSchedule は set_midi_clips に渡すコンパイル済み MIDI クリップで、events は絶対レンダーフレームを持ちます。destination_id が None なら track_id にフォールバックし、length_samples が None なら終端なし、loop_length_samples は loop が設定されているときだけ読まれます。

EngineMidiEvent は UMP メッセージを word0 から word3 に持ち、有効なワード数が word_count です。エンジンはグループを word0(ビット 24 から 27)から読みます。group も [0, 15] の範囲である必要がありますが、word0 と食い違う値は無視されます。sysex_handle はイベントが参照する SysEx ペイロードのハンドルで、0 は参照なしです。

ExternalMidiEvent は逆方向で、drain_external_midi() が取り出す MIDI 1.0 の 1 メッセージ(1 から 3 バイト)です。destination_id が None のものは、すべての外部ポートに向けたクロックまたはトランスポートのバイトで、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

キャプチャ ​

RealtimeEngine.configure_capture はパンチ範囲を CapturePunch で受け取ります。入力モニターは set_input_monitor で設定します。capture_status() は EngineCaptureStatus を返します。

CapturePunch は半開区間 [start, end) です。各端は *_ppq、*_sample、*_sec のいずれか 1 つを指定します。秒は最も近いサンプルに丸められます。負の値は拒否されます。入力モニターの gain はリニアゲインです。ステータスの source は "output" か "input" です。dropped_frames は最後のリセット以降にバッファ満杯で破棄したフレーム数です。

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

グラフとサイドチェイン ​

RealtimeEngine.set_graph は EngineGraphSpec を設置します。ノード id はグラフ内で一意で、EngineGraphConnection のポートは 0 始まりです。ノードの num_ports が None なら仕様の num_channels を使い、gain_db は "gain" ノード種別で適用されます。parameter_bindings はオートメーションのパラメータ id をノードのプロセッサに結び付けます。

SidechainSource は kind("track" か "bus")と id でキー入力の供給元を指定します。set_strip_sidechain と set_bus_sidechain が受け取り、ソースの代わりに None を渡すと結び付けを外します。can_set_*_sidechain は何も変更せずに SidechainCheck を返し、reason は最初の拒否理由で、ok のときは None です。

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

オフラインレンダー ​

bounce_offline は EngineBounceOptions を受け取って EngineBounceResult を、freeze_offline は EngineFreezeOptions を受け取って EngineFreezeResult を返します。どちらのオプションも num_channels が必須です。block_size を省略するとエンジンが準備した最大値を上限とする既定のオフラインブロックになり、明示的な 0 は拒否されます。source_sample_rate を指定する場合は準備済みのレートと一致している必要があり、target_sample_rate が None ならリサンプルしません。どちらも明示的な 0 は拒否されます。target_lufs と dither_seed が None のときはライブラリの値(-14 LUFS と組み込みのシード)で、指定した値はそのまま読まれるため、0 は 0 LUFS またはシード 0 です。dither_bits は [2, 32] の範囲です。

EngineBounceResult.interleaved はチャンネルインターリーブで、frames はフレーム数です。process(..., with_monitor=True) は EngineProcessWithMonitorResult を返し、プログラムのプレーンが output、モニターバスのプレーンが 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], ...]

テレメトリとメーター ​

drain_telemetry() は EngineTelemetry のイベントを返します。type は EngineTelemetryType のトークンで、イベントがエラーを報告するときは error が設定されます。audible_timeline_sample は今聞こえている音のタイムライン位置、graph_latency_samples は小数です。

drain_meter_telemetry() はミックスターゲットごとの MeterTelemetryRecord を返します。peak_db、rms_db、true_peak_dbtp は num_channels 個の有効なプレーンを WAVE 標準の順で持ちます(5.1 は L R C LFE Ls Rs、7.1 はそれに Lss Rss を加えたもの)。ステレオターゲットの左右はプレーン 0 と 1 です。True Peakは BS.1770-4 の 4 倍ポリフェーズ再構成によるサンプル間ピークで、ストリーミングで測るためブロックより再構成フィルターの群遅延(数サンプル)だけ遅れ、ブロックサイズには依存しません。レベルは dBFS、True Peakは dBTP で、correlation は [-1, 1] です。

drain_scope_telemetry() は ScopeTelemetryRecord を返します。bands はスペクトラムの帯域レベル、points は (left, right) タプルのベクトルスコープ点です(Node と WASM は同じデータを {left, right} オブジェクトで返します)。dropped_records はテレメトリキューが満杯で失われたレコード数です。

MixMeterSnapshot は MixResult.meters(mix_stereo が返す)に入るストリップごとのメーターで、True Peak の測り方は同じです。mono_compat_peak と mono_compat_side_rms は、折り畳み 0.5 * (L + R) とサイド信号 0.5 * (L - R) のフルスケール基準のリニア振幅です。GoniometerPoint はベクトルスコープ表示用の左右 1 組のサンプルです。

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

構造とメロディの結果 ​

analyze_sections() は SectionAnalysis を返します。Section.energy_level は、そのセクションのフレーム RMS の中央値を最も大きいセクションの値で割ったもので、[0, 1] です。group が同じセクションは同じ素材の繰り返しで、最初に現れた順に 0、1、... と番号が付きます。種別が "unknown" のセクションはどのラベル付け規則にも当てはまらず、confidence は 0 です。SectionAnalysis.form はセクションごとに 1 文字(例 "AABA")で、セクションがなければ空です。

detect_boundaries() は BoundaryResult を返します。Boundary.time_sec が正式な出力で、frame は解析グリッド上の添字です。22.05 kHz を超える入力はリサンプルされ、長い入力は平均プーリングされるため、元の STFT グリッドとは一致しません(frame_stride は解析 1 フレームあたりの元フレーム数で、プーリングされなければ 1)。sample_rate は入力のレートではなく解析を行ったレートです。novelty_curve は自身の最大値で正規化されて [0, 1] に収まります。absolute_threshold と比較される元の応答値に戻すには novelty_peak を掛けます。数値の下限を超えるものがなければ novelty_peak は None です。

analyze_melody() は MelodyResult を返します。MelodyPoint は無声のとき frequency_hz が None で、mean_frequency_hz は有声の点の平均です。

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