Skip to content

JavaScript/TypeScript Worklet エンジン API ​

SonareEngine は RealtimeEngine を AudioWorklet 上で動かすためのファサードです。メソッド名、リクエスト型、単位は RealtimeEngine と同じで、すべての編集を worklet 内のライブエンジンへ転送します。@libraz/libsonare/worklet エントリで提供されます。ブリッジの設定、トランスポートモード、ファサードの一覧は リアルタイムとストリーミング にあります。

ライフサイクル ​

作成 ​

await SonareEngine.create(context, options) は worklet ノードを作り、プロセッサの準備完了を待ってエンジンを返します。コンストラクタは非公開です。options にはオフラインミラー用の offlineEngine、offlineBlockSize、offlineNumChannels を追加でき、ミラーのブロックサイズの既定は maxBlockSize、なければ 128 フレームです。engine.node をオーディオグラフに接続してください。

使用 ​

編集はすべて呼び出し側スレッドのオフラインミラーエンジンに適用され、worklet へ転送されます。そのため拒否された編集はどちらにも反映されません。セッターは void を返し、読み取りはミラーから同期的に答えます。オーディオスレッドの答えが必要な transportState、captureStatus、capturedAudio、resetCapture、pollInsertGainReduction は Promise を返します。suspend() と resume() はオーディオコンテキストを操作します。

解放 ​

destroy() は冪等で、[Symbol.dispose]() により using が使えます(ネイティブハンドルの解放)。suspend() と resume() は破棄済みのエンジンでは即座に解決します。

エラー ​

引数の拒否は RealtimeEngine と同じく TypeError と RangeError です。コマンドリングが満杯でコマンドを積めないセッターは OutOfMemory の SonareError を投げます。create は、エンジン ABI が一致しなければ AbiMismatch、SharedArrayBuffer と Atomics がないのに mode: 'sab' を求めれば NotSupported を投げます。表全体は エラー規約 にあります。

SonareEngine ​

typescript
class SonareEngine {
  readonly node: AudioWorkletNode;  // The underlying AudioWorkletNode; connect it into the audio graph.
  readonly capabilities: SonareRealtimeEngineNodeCapabilities;  // Transport mode and feature support detected when the engine was created.
  readonly transport: SonareEngineTransportFacade;  // Transport control: play, stop, seek and loop, mirrored on the offline engine.
  static create(context: BaseAudioContext, options: SonareEngineOptions): Promise<SonareEngine>;  // Creates the worklet node, waits for the processor to be ready and returns the engine.
  suspend(): Promise<void>;  // Suspends the audio context; resolves immediately when the engine is destroyed.
  resume(): Promise<void>;  // Resumes the audio context; resolves immediately when the engine is destroyed.
  setTempo(bpm: number): void;  // Sets one constant tempo, `bpm` in beats per minute (finite, in [1e-6, 100000]), on both engines.
  setTempoSegments(segments: readonly EngineTempoSegment[]): void;  // Replaces the tempo map with segments keyed by `startPpq` (quarter notes), on both engines.
  setTimeSignature(numerator: number, denominator: number): void;  // Sets one constant time signature, on both engines.
  setTimeSignatureSegments(segments: readonly EngineTimeSignatureSegment[]): void;  // Replaces the time-signature map with segments keyed by position, on both engines.
  setLoop(loop: EngineLoop): void;  // Sets the loop region. A loop wrap, seek or stop sends note-offs plus CC64=0, CC121, CC123 and a centred pitch bend on every channel played since the last reset. When playback next rolls, the controller, program, channel pressure and pitch bend values the clips set before the new position are sent again, so each loop pass and each seek starts from the state continuous playback reaches.
  countInEndSample(startSample: number, bars: number): number;  // Sample at which a count-in of `bars` bars from `startSample` ends. Counting starts at the beginning of the bar containing `startSample` (a mid-bar start gets a short first bar), and every counted bar has the length of the time signature in effect at `startSample`. Returns `startSample` when `bars <= 0`.
  transportState(): Promise<EngineTransportState>;  // Reads the transport from the worklet's live engine; the answer arrives asynchronously.
  cachedTransportState(): EngineTransportState | undefined;  // The latest transportState answer, or `undefined` before the first one.
  setParam(
    nodeId: string,
    param: string | number,
    value: number,
    options?: SonareEngineSetParamOptions,
  ): void;  // Sets one registered parameter by id or name, at the next block head unless `renderFrame` names the frame. `{ smoothed: true }` ramps to the value through the engine smoother, as RealtimeEngine.setParameter does; the refusals are that method's.
  setParamSmoothingMs(smoothingMs: number): void;  // Sets the ramp time (ms) of the engine-level smoother in the worklet; the domain, default and refusals are RealtimeEngine.setParamSmoothingMs's.
  scheduleParam(nodeId: string, param: string | number, point: EngineAutomationPoint): void;  // Adds one breakpoint to the automation lane of a registered parameter.
  addAutomationPoint(laneId: string | number, point: EngineAutomationPoint): void;  // Adds one breakpoint to an automation lane, addressed by lane id.
  setAutomationLane(paramId: number, points: ReadonlyArray<EngineAutomationPoint>): void;  // Replaces the automation lane for `paramId` with the given breakpoints. An empty array clears the lane; the points are defensively copied and sorted by ppq before mirroring to the offline and live worklet engines.
  // Returns the automation target id for a strip's fader, pan or width.
  //
  // The id addresses the engine's reserved mixer namespace, so it can be fed straight to setAutomationLane to automate a fader or pan without registering a parameter.
  resolveStripAutomationId(target: string | number, kind: 'faderDb' | 'pan' | 'width'): number;
  resolveBusAutomationId(busId: number, paramName: 'faderDb'): number;  // Returns the automation target id for a bus fader. The id names the bus, so it keeps driving that bus across bus reorders and the removal of other buses, and applies nothing once the bus is removed.
  // Resolves a strip insert parameter (JSON-key name) to the reserved insert-automation id fed straight to setAutomationLane. Declares a track's mixer lane first (like resolveStripAutomationId). The offline engine and the worklet's engine receive the same mixer configuration in the same order, so they number insert ids identically and an id resolved here drives the worklet.
  //
  // Track, bus and master insert ids share one lifetime rule: an id names its strip by identity and the kind of processor in its slot (for `effects.gsEfx`, its EFX type too), so it survives lane and bus reorders and the removal of other strips, and stays valid until its track or bus is removed or its slot comes to hold another kind of processor. After that it applies nothing, its queued edits are dropped, and it is never reissued; resolve again for the new processor. A change that would take the engine past its 8192 insert-id entries is refused.
  resolveStripInsertAutomationId(
    target: string | number,
    insertIndex: number,
    paramName: string,
  ): number;
  resolveBusInsertAutomationId(busId: number, insertIndex: number, paramName: string): number;  // Resolves a bus-strip insert parameter to its reserved insert-automation id. Declares the mixer bus first so the offline engine resolves the same bus selector.
  resolveInstrumentAutomationId(destinationId: number, paramName: string): number;  // Resolves a hosted instrument's continuous parameter to its reserved instrument-automation id, so an instrument parameter follows a breakpoint lane at audio-block precision like a strip insert. Bind the instrument (`setSynthInstrument`) before resolving.
  get automationLaneCount(): number;  // The number of automation lanes installed on the engine, including lanes whose breakpoint list is currently empty.
  parameters(): EngineParameterInfo[];  // The registered parameters, read from the offline mirror.
  addParameter(info: EngineParameterInfo): void;  // Registers a custom parameter on the offline mirror and worklet engine.
  clearParameters(): void;  // Clears custom parameters on both engines; automation lanes stay in place.
  setTrackSoloMute(target: string | number, state: TrackSoloMuteState): void;  // Queues a track's solo/mute state. An armed PFL/AFL cue (setTrackMonitorMode) stays off the program output here, which the facade renders with the cue kept separate; offline renders, bounces and freezes never include it.
  setTrackMonitorMode(
    target: string | number,
    mode: EngineTrackMonitorMode,
    renderFrame?: number,
  ): void;  // Queues a per-track PFL/AFL monitor tap mode change; `mode` is a string and an ordinal is a `TypeError`. The facade renders with the cue kept separate from the program output; offline renders, bounces and freezes never include it.
  setStripFaderDb(target: string | number, faderDb: number): void;  // Queues a strip fader change in dB, smoothed on the audio thread.
  setStripPan(target: string | number, pan: number): void;  // Queues a strip pan change, smoothed on the audio thread.
  resetMasterLoudnessMeter(renderFrame?: number): void;  // Resets the master's integrated loudness accumulator in both engine mirrors.
  resetProcessorState(renderFrame?: number): void;  // Queues a reset of every mixer and effect processor to its prepared state, applied to the offline mirror immediately and to the live engine at `renderFrame` (omitted: the next block head). The same command that follows it on the queue, such as `play()`, starts from the state an offline render starts from. Instruments are not reset. During playback it cuts running insert tails and delay lines mid-sound, like a seek.
  // Declares the mixer track lanes in an explicit order.
  //
  // Lane indices are append-only: the list must start with the already-declared track ids in their current order and may only append new ones after them; a reorder or removal throws. (The raw `RealtimeEngine.setTrackLanes` does accept both.) Existing queued and published track automation follows the track id, and so do track insert automation ids (see resolveStripInsertAutomationId). Entries carrying `sends` replace that track's send list; entries without `sends` leave existing sends untouched. At most `MAX_TRACK_LANES` (32) lanes are accepted.
  setTrackLanes(lanes: readonly EngineTrackLane[]): void;
  setTrackOutputBus(target: string | number, busId: number | null): void;  // Routes a track lane's post-fader output into a declared bus instead of the master mix (group/folder routing); `null` restores the master mix and `0` is a `RangeError`.
  setStripSidechain(
    target: string | number,
    insertIndex: number,
    source: SidechainSource | null,
  ): void;  // Keys one insert of a strip from another source (ducking/sidechainRouter inserts); `null` removes the binding. A track strip accepts only a `'track'` source, the master strip a track or a bus; a source `id` of `0` is a `RangeError`. Throws, leaving the existing bindings unchanged, for a lane keying itself or a binding that would close a cycle over the lane bindings; a refused binding is never recorded, so it is not replayed on resync.
  setTrackSends(target: string | number, sends: EngineTrackSend[]): void;  // Replaces the sends of one track or the master strip, on both engines; an empty array clears them.
  setTrackBuses(buses: EngineBus[]): void;  // Replaces the bus list, on both engines. Each bus names its output bus, channel layout and sends.
  setBusSidechain(busId: number, insertIndex: number, source: SidechainSource | null): void;  // Keys one insert of a bus strip from a track lane or another bus (ducking/sidechainRouter inserts); `null` removes the binding.
  canSetStripSidechain(
    target: string | number,
    insertIndex: number,
    source: SidechainSource,
  ): SidechainCheck;  // Reports whether setStripSidechain would accept the binding, without changing anything. Answers from the offline mirror, which holds the same configuration as the live engine, and never declares a missing lane or bus.
  canSetBusSidechain(busId: number, insertIndex: number, source: SidechainSource): SidechainCheck;  // Reports whether setBusSidechain would accept the binding, without changing anything.
  get tailSamples(): number;  // Longest audible tail in samples (an upper bound; `2147483647` is unbounded), answered from the offline mirror. The bound is conservative before the first note and narrows once a patch has sounded.
  get graphLatencySamples(): number;  // Processing latency in samples (fractional), answered from the offline mirror.
  setBusGainDb(busId: number, gainDb: number): void;  // Queues a bus fader change in dB, smoothed on the audio thread.
  setStrip(target: string | number, settings: MixSceneStripInput): void;  // Replaces a strip (a track's, or the master) with `settings`, the object a scene holds at `strips[i]`. A track is declared first when it has no lane yet.
  setBusStrip(busId: number, settings: MixSceneBusInput): void;  // Replaces a bus strip with `settings`, the object a scene holds at `buses[i]`.
  setStripEqBand(target: string | number, bandIndex: number, band: EqBandInput): void;  // Sets one EQ band of a strip (a track's, or the master).
  setBusEqBand(busId: number, bandIndex: number, band: EqBandInput): void;  // Sets one EQ band of a bus strip.
  setStripInsertBypassed(
    target: string | number,
    insertIndex: number,
    state: InsertBypassState,
  ): void;  // Bypasses or re-enables one insert of a strip. Bypassing keeps the insert's internal state (reverb tail, compressor envelope) unless `resetOnBypass` (default `false`) is set; re-posting the scene, the only alternative, rebuilds the chain and loses it.
  setBusInsertBypassed(busId: number, insertIndex: number, state: InsertBypassState): void;  // Bus counterpart of setStripInsertBypassed.
  setStripInsertParam(target: string | number, insertIndex: number, param: InsertParamValue): void;  // Sets one insert parameter of a strip by its JSON-key name.
  setBusInsertParam(busId: number, insertIndex: number, param: InsertParamValue): void;  // Bus counterpart of setStripInsertParam.
  setStripPanLaw(target: string | number, panLaw: PanLaw): void;  // Sets a track strip's pan law; `'master'` is a `RangeError`.
  setStripPanMode(target: string | number, panMode: PanMode): void;  // Sets a track strip's pan mode; `'master'` is a `RangeError`.
  setStripDualPan(target: string | number, leftPan: number, rightPan: number): void;  // Sets a track strip's dual-pan positions; `'master'` is a `RangeError`.
  setStripSurroundPan(target: string | number, pan: SurroundPan): void;  // Sets a track strip's surround placement (glitch-free, 5 ms placement glide). Takes effect on a destination wider than stereo, so set `numChannels` to the layout's plane count. Omitted fields default to a centered point source. `'master'` is a `RangeError`.
  setStripChannelDelaySamples(target: string | number, delaySamples: number): void;  // Sets a track strip's channel delay in samples; `'master'` is a `RangeError`.
  setBusPan(busId: number, pan: number): void;  // Bus counterpart of setStripPan's scene form; refused on a surround bus.
  setBusPanLaw(busId: number, panLaw: PanLaw): void;  // Sets a bus strip's pan law on both engines; an ordinal is a `TypeError`, an unknown bus a `RangeError`.
  setBusPanMode(busId: number, panMode: PanMode): void;  // Sets a bus strip's pan mode on both engines; an ordinal is a `TypeError`, an unknown bus a `RangeError`.
  setBusDualPan(busId: number, leftPan: number, rightPan: number): void;  // Sets a bus strip's dual-pan left and right positions (each -1 to 1, left to right) on both engines; an unknown bus is a `RangeError`.
  attachOpfsClipStream(
    options: OpfsClipStreamOptions,
  ): Promise<{ binding: OpfsClipPageProviderBinding; provider: ClipPageProvider; }>;  // Creates and primes an OPFS-backed page provider for this live worklet engine. Pass the returned `provider` to addClip in place of a `Float32Array[]`; the `clipId` in `options` must equal that clip's explicit `opts.id`. Subsequent cache misses are fetched on the main thread and supplied back to the worklet through its bounded pull protocol.
  // Sets the clip-page look-ahead window in timeline frames on both the worklet engine and this thread's offline engine.
  //
  // The audio thread reports the pages it is *about to* read that are not resident yet, so the sliding-window streamer can service them before the playhead reaches them. Without look-ahead a page miss is only reported after the read already produced silence, which costs one block of silence at every page boundary that was not primed.
  //
  // Defaults to half a second at the engine's sample rate. `0` disables it. Safe to call during playback.
  setClipPagePrefetchFrames(frames: number): void;
  setWarpVoiceCapacity(voices: number): void;  // Sets the number of concurrent time-stretch voices on both this thread's offline engine and the live worklet engine. `voices` must be an integer in `[0, 64]`; a non-integer, negative, or larger value throws and leaves the capacity unchanged on both engines. Default is 8. Capacity 0 disables time-stretch, so every warped clip plays resampled instead. A change applied while the engine is running restarts the splice state of any clip stretching through a voice at that moment.
  get warpVoiceCapacity(): number;  // The current time-stretch voice capacity (default 8).
  addClip(trackId: string | number, clip: Omit<EngineClip, 'trackId'>): number;  // Adds a clip to a track and returns its id (`clip.id`, or a fresh one). Give exactly one of `clip.channels` and `clip.pageProvider`; a page provider must come from attachOpfsClipStream, with `clip.id` equal to the stream's `clipId`.
  removeClip(clipId: number): void;  // Removes the clip carrying `clipId`, on both engines.
  setMidiClips(schedules: readonly EngineMidiClipSchedule[]): void;  // Replaces the scheduled MIDI clips, on both engines.
  setBuiltinInstrument(
    trackId: string | number,
    config?: Omit<BuiltinSynthConfig, 'destinationId'>,
  ): void;  // Binds an instrument to a track's MIDI destination on both engines. A change made while the transport is rolling reaches the worklet at once and takes effect at its next render block; the outgoing instrument's sounding notes fade out over 10 ms. The incoming instrument starts from its default channel state (program, bank, controllers), so a host that needs the current position's state resends it with pushMidiUmp afterwards. A binding is applied at a block boundary; for a frame-exact switch, bind both instruments ahead of time and switch with timed MIDI, or use a timed program change.
  setSynthInstrument(trackId: string | number, patch?: SynthPatch): void;  // Binds a NativeSynth patch; see setBuiltinInstrument for swap timing.
  setArticulation(trackId: string | number, channel: number, articulation: Articulation): void;  // Sets how one MIDI channel (0–15) of the instrument bound to a track's MIDI destination treats a note-on while another note on that channel is held, on both engines; see `RealtimeEngine.setArticulation` for the three modes and the refusals, which are the same here. The setting belongs to the bound instrument: binding another one (for example with setSynthInstrument) replaces it with that instrument's own, `'poly'` for a new one.
  articulation(trackId: string | number, channel: number): Promise<Articulation>;  // Reads one channel's articulation from the worklet's live engine — what the bound instrument holds, which an instrument bound after setArticulation has replaced.
  legatoFallbackCount(trackId: string | number): Promise<number>;  // Reads from the worklet's live engine how many legato continuations the bound instrument refused, so each note started a voice of its own; see `RealtimeEngine.legatoFallbackCount`. The count belongs to the instrument, so binding another one starts it from zero.
  loadSoundFont(data: Uint8Array): void;  // Loads SoundFont 2 bytes into the offline mirror and the worklet so SF2 instruments can be bound with setSf2Instrument. The bytes are copied for the call; a previously loaded SoundFont is replaced.
  setSf2Instrument(
    trackId: string | number,
    config?: Omit<Sf2InstrumentConfig, 'destinationId'>,
  ): void;  // Binds a SoundFont player; see setBuiltinInstrument for swap timing.
  setMidiDestinationExternal(trackId: string | number, midiDestinationExternal: boolean): void;  // Route a track's MIDI to the external output (drained via onMidiOut) instead of an internal instrument, so the track plays an external device. Pass `false` to restore internal-synth playback. The change takes effect at the next processed block; switching a destination's route first releases its notes and resets its controllers through the old route, and drops its pending MIDI-FX events.
  setExternalMidiClockEnabled(externalMidiClockEnabled: boolean): void;  // Enable/disable forwarding MIDI clock + transport (start/continue/stop) to the external output so external gear tracks the transport tempo. The bytes arrive through onMidiOut tagged with the transport destination.
  setMidiFx(trackId: string | number, config: MidiFxConfig): void;  // Install or replace a live, non-destructive MIDI-FX insert for one destination. The insert transforms the destination's MIDI before synthesis (transpose, quantize, velocity shaping, humanize, harmonize, arpeggiate) without rewriting any stored notes, so it can be bypassed by clearMidiFx. `config` is a MidiFxConfig, the same object the offline `Project.bakeMidiFx` takes.
  clearMidiFx(trackId: string | number): void;  // Remove the live MIDI-FX insert from one destination (a no-op when none).
  pushMidiNoteOn(
    trackId: string | number,
    group: number,
    channel: number,
    note: number,
    velocity: number,
    renderFrame?: number,
    options?: SonareEngineMidiTimingOptions,
  ): void;  // Queues a live MIDI note-on to the track's MIDI destination. `renderFrame` is the absolute render frame to fire at, or `options.contextTimeSec` the AudioContext time (not both); omitted: immediate. `group` and `channel` are 0 to 15; `note` and `velocity` are 0 to 127.
  pushMidiNoteOff(
    trackId: string | number,
    group: number,
    channel: number,
    note: number,
    velocity?: number,
    renderFrame?: number,
    options?: SonareEngineMidiTimingOptions,
  ): void;  // Queues a live MIDI note-off to the track's MIDI destination. `renderFrame` is the absolute render frame to fire at, or `options.contextTimeSec` the AudioContext time (not both); omitted: immediate. `group` and `channel` are 0 to 15; `note` is 0 to 127; `velocity` is 0 to 127 (omitted: 0).
  pushMidiCc(
    trackId: string | number,
    group: number,
    channel: number,
    controller: number,
    value: number,
    renderFrame?: number,
    options?: SonareEngineMidiTimingOptions,
  ): void;  // Queues a live MIDI control change to the track's MIDI destination. `renderFrame` is the absolute render frame to fire at, or `options.contextTimeSec` the AudioContext time (not both); omitted: immediate. `group` and `channel` are 0 to 15; `controller` and `value` are 0 to 127.
  pushMidiPitchBend(
    trackId: string | number,
    group: number,
    channel: number,
    bend14: number,
    renderFrame?: number,
    options?: SonareEngineMidiTimingOptions,
  ): void;  // Queues a live MIDI pitch bend to the track's MIDI destination. `renderFrame` is the absolute render frame to fire at, or `options.contextTimeSec` the AudioContext time (not both); omitted: immediate. `bend14` is unsigned 14-bit with centre 8192 (0 to 16383).
  pushMidiChannelPressure(
    trackId: string | number,
    group: number,
    channel: number,
    pressure: number,
    renderFrame?: number,
    options?: SonareEngineMidiTimingOptions,
  ): void;  // Queues a live MIDI channel pressure to the track's MIDI destination. `renderFrame` is the absolute render frame to fire at, or `options.contextTimeSec` the AudioContext time (not both); omitted: immediate. `pressure` is 0 to 127.
  pushMidiPolyPressure(
    trackId: string | number,
    group: number,
    channel: number,
    note: number,
    pressure: number,
    renderFrame?: number,
    options?: SonareEngineMidiTimingOptions,
  ): void;  // Queues a live MIDI polyphonic key pressure to the track's MIDI destination. `renderFrame` is the absolute render frame to fire at, or `options.contextTimeSec` the AudioContext time (not both); omitted: immediate. `note` and `pressure` are 0 to 127.
  pushMidiUmp(
    trackId: string | number,
    words: UmpWords,
    renderFrame?: number,
    options?: SonareEngineMidiTimingOptions,
  ): void;  // Queues a live raw UMP message to the track's MIDI destination. `words` is 1 to 4 words, most significant first, with a length matching the message type of `words[0]`. SysEx7 and data messages (MT 0x3 / 0x5) are refused; use pushMidiSysex. `renderFrame` is the absolute render frame to fire at, or `options.contextTimeSec` the AudioContext time (not both); omitted: immediate.
  pushMidiProgram(
    trackId: string | number,
    group: number,
    channel: number,
    program: number,
    bank?: MidiBank,
    renderFrame?: number,
    options?: SonareEngineMidiTimingOptions,
  ): void;  // Queues a live MIDI 2.0 Program Change, with an optional bank, to a track's MIDI destination; arguments follow RealtimeEngine.pushMidiProgram, and `options.contextTimeSec` places it on the AudioContext clock instead of `renderFrame`. Which receivers select programs: the SoundFont player (`setSf2Instrument`) selects bank and program under its own RX PROGRAM CHANGE / RX BANK SELECT gates; a NativeSynth bound with `useGmPrograms: true` (`setSynthInstrument`) resolves each channel's voice from the bank and program; a NativeSynth whose patch plays the GM kit (the `drumKit` preset, or a percussion patch with `gmKit` on) takes the program as the GS drum-set select on every channel. Every other receiver accepts the message and ignores it: the built-in synth, any other NativeSynth patch, a part with RX PROGRAM CHANGE off, and an MPE member channel.
  pushMidiSysex(
    trackId: string | number,
    data: Uint8Array,
    renderFrame?: number,
    options?: SonareEngineMidiTimingOptions,
  ): void;  // Queues a live MIDI SysEx frame to the track's MIDI destination. `data` is the full message including the leading 0xF0 and trailing 0xF7 (1 to 512 bytes). `renderFrame` is the absolute render frame to fire at, or `options.contextTimeSec` the AudioContext time (not both); omitted: immediate.
  bindMidiCc(binding: ProjectMidiCcBinding): void;  // Maps a MIDI controller to an engine parameter, on both engines.
  setMidiInputSource(destinationId?: number): void;  // Enables the engine-owned live MIDI input source for a destination on both engines; `destinationId` is the MIDI destination (omitted: 0).
  clearMidiInputSource(): void;  // Disables the engine-owned live MIDI input source on both engines.
  pushMidiInputNoteOn(
    group: number,
    channel: number,
    note: number,
    velocity: number,
    offsetInBlockSamples?: number,
    options?: SonareEngineMidiTimingOptions,
  ): void;  // Push a live MIDI note-on to the engine-owned MIDI input source.
  pushMidiInputNoteOff(
    group: number,
    channel: number,
    note: number,
    velocity?: number,
    offsetInBlockSamples?: number,
    options?: SonareEngineMidiTimingOptions,
  ): void;  // Push a live MIDI note-off to the engine-owned MIDI input source.
  pushMidiInputCc(
    group: number,
    channel: number,
    controller: number,
    value: number,
    offsetInBlockSamples?: number,
    options?: SonareEngineMidiTimingOptions,
  ): void;  // Push a live MIDI control change to the engine-owned MIDI input source.
  pushMidiInputPitchBend(
    group: number,
    channel: number,
    bend14: number,
    offsetInBlockSamples?: number,
    options?: SonareEngineMidiTimingOptions,
  ): void;  // Push a live MIDI pitch bend to the engine-owned MIDI input source.
  pushMidiInputChannelPressure(
    group: number,
    channel: number,
    pressure: number,
    offsetInBlockSamples?: number,
    options?: SonareEngineMidiTimingOptions,
  ): void;  // Push a live MIDI channel pressure to the engine-owned MIDI input source.
  pushMidiInputPolyPressure(
    group: number,
    channel: number,
    note: number,
    pressure: number,
    offsetInBlockSamples?: number,
    options?: SonareEngineMidiTimingOptions,
  ): void;  // Push a live MIDI polyphonic key pressure to the engine-owned MIDI input source.
  pushMidiInputProgram(
    group: number,
    channel: number,
    program: number,
    bank?: MidiBank,
    offsetInBlockSamples?: number,
    options?: SonareEngineMidiTimingOptions,
  ): void;  // Push a live MIDI 2.0 Program Change, with an optional bank, to the engine-owned MIDI input source. The arguments and refusals match pushMidiProgram; which receivers select programs is described there.
  pushMidiInputUmp(
    words: UmpWords,
    offsetInBlockSamples?: number,
    options?: SonareEngineMidiTimingOptions,
  ): void;  // Push a live MIDI raw UMP message to the engine-owned MIDI input source.
  lateMidiEventCount(): Promise<number>;  // Reads from the worklet's live engine how many timed MIDI events, live input and track-addressed alike, arrived after the render frame their `contextTimeSec` named had been rendered, so they played at the start of the next block instead. Cumulative since the engine was created.
  pushMidiPanic(renderFrame?: number): void;  // Queues a MIDI panic (all-notes-off) releasing every sounding note on both engines. `renderFrame` is the absolute render frame to fire at; omitted: immediate.
  configureCapture(options: CaptureOptions): void;  // Sets up capture in one call: buffer, source, record offset and punch window, on both engines. It leaves the input monitor (setInputMonitor) alone. The call states the whole setup, so an omitted field returns to its default and an omitted `punch` clears the punch window. `numChannels` defaults to the offline plane count.
  armCapture(state: CaptureArmState): void;  // Arms or disarms the engine-global capture path; per-track capture is not implemented.
  captureStatus(): Promise<EngineCaptureStatus>;  // Reads the capture state from the worklet; the answer arrives asynchronously.
  capturedAudio(): Promise<Float32Array[]>;  // Reads the audio captured so far from the worklet, one `Float32Array` per channel; the answer arrives asynchronously.
  resetCapture(): Promise<void>;  // Discards the captured audio on both engines; resolves once the worklet has done so.
  setMetronome(opts: EngineMetronomeConfig): void;  // Configures the metronome on both engines; if the command ring is full neither changes.
  setInputMonitor(monitor: EngineInputMonitorInput): void;  // Sets the dry input monitor on both engines: the live input passed straight to the output ahead of the master. Independent of the input track; a non-finite `gain` is a `RangeError` and changes neither engine.
  inputMonitor(): EngineInputMonitor;  // The dry input monitor, read from the offline mirror.
  setInputTrack(trackId: number): void;  // Routes the live input into the lane of `trackId` on both engines, ramping over 5 ms. An id no lane carries is a `RangeError` and changes neither engine; the dry monitor is not touched.
  clearInputTrack(): void;  // Stops routing the live input into a lane on both engines.
  get inputTrack(): number | undefined;  // The track the live input is routed into, or `undefined`, read from the offline mirror.
  addMarker(ppq: number, name?: string): number;  // Adds a marker at `ppq` (quarter notes, in [0, 1e12]) and returns its id.
  setMarkers(entries: ReadonlyArray<EngineMarkerInput>): EngineMarker[];  // Replaces the whole marker set in one call. Entries without an `id` are assigned fresh ids; entries carrying an `id` keep it. Returns the stored markers in the order given.
  markers(): EngineMarker[];  // The stored markers in timeline order, read from the offline mirror.
  marker(markerId: number): EngineMarker;  // One stored marker by id; an unknown id is a `RangeError`.
  seekMarker(markerId: number): void;  // Seeks to a marker; an unknown id is a `RangeError`.
  setLoopFromMarkers(startMarkerId: number, endMarkerId: number): void;  // Loops between two markers.
  // Renders the timeline offline through this thread's mirror engine, from the current transport position, and returns one planar buffer per offline channel. Primes the mirror first, so the result equals a bounce of the same span. Runs synchronously on the calling thread: the thread is blocked for the whole render.
  //
  // The request takes `totalFrames`, `blockSize` (default and ceiling: the offline block size; a larger value throws `RangeError`), `finalize` and With `finalize: false` a chunk leaves held notes and delay tails running into the next call, which does not prime again; end the series with finishOfflineRender. The mirror's transport position is restored when the timeline ends.
  renderOffline(request: SonareEngineRenderOfflineRequest): Promise<Float32Array[]>;
  finishOfflineRender(): void;  // Ends a chunked renderOffline series: releases every held note, flushes the delay lines and restores the mirror's transport position.
  bounceOffline(options: EngineBounceOptions): Promise<EngineBounceResult>;  // Bounces the timeline to planar channels with the options, defaults and result of RealtimeEngine.bounceOffline; `blockSize` defaults to the offline block size and must not exceed it (`RangeError`). Runs synchronously on the calling thread. The mirror's transport position is restored afterwards. OPFS-streamed clips are paged in for the span first.
  freezeOffline(options: EngineFreezeOptions): Promise<EngineFreezeResult>;  // Freezes the source layer with the options, defaults and result of RealtimeEngine.freezeOffline: master, monitor, graph, capture and metronome stay live. As there, the frozen clip replaces the clip set and the MIDI clips are withdrawn: the facade, the mirror and the worklet all end up holding only that clip. `blockSize` defaults to the offline block size and must not exceed it (`RangeError`). Runs synchronously on the calling thread.
  onMidiOut(callback: (events: ExternalMidiEvent[]) => void): () => void;  // Subscribe to batches of external-MIDI events (already lowered to MIDI 1.0 bytes) for delivery to Web MIDI output ports. Each event carries its absolute `renderFrame`; a batch is not a render block. With postMessage transport a batch holds one block's events; with the SAB ring it holds what accumulated since the previous poll, which may span many blocks. Returns an unsubscribe function.
  onMeter(callback: (meter: WorkletMeterSnapshot) => void): () => void;  // Subscribes to meter snapshots from the worklet. Returns a function that removes the subscription.
  onScope(callback: (scope: WorkletScopeSnapshot) => void): () => void;  // Subscribes to scope snapshots (spectrum and goniometer); produced only when `scopeIntervalFrames` is above 0 in SAB mode. Returns a function that removes the subscription.
  onTelemetry(callback: (telemetry: EngineTelemetry) => void): () => void;  // Subscribes to engine telemetry records from the worklet. Returns a function that removes the subscription.
  onSyncError(callback: (message: EngineSyncErrorMessage) => void): () => void;  // Subscribes to syncs the worklet refused after the offline mirror accepted them. Returns a function that removes the subscription.
  pollTelemetry(): EngineTelemetry[];  // Drains telemetry published since the last poll (SAB mode); empty otherwise. See SonareRealtimeEngineNode.pollTelemetry.
  pollMeters(): WorkletMeterSnapshot[];  // Drains meter snapshots published since the last poll (SAB mode); empty otherwise. See SonareRealtimeEngineNode.pollMeters.
  pollScope(): WorkletScopeSnapshot[];  // Drains scope snapshots published since the last poll (SAB mode with `scopeIntervalFrames` above 0); empty otherwise.
  pollInsertGainReduction(targetId: number): Promise<number[]>;  // Per-insert gain reduction for a meter target; see SonareRealtimeEngineNode.pollInsertGainReduction.
  destroy(): void;  // Stops the engine and releases the worklet node and the offline mirror. Safe to call more than once.
  [Symbol.dispose](): void;  // Same as destroy, for `using`.
}

interface SonareEngineOptions extends SonareRealtimeEngineNodeOptions {
  offlineEngine?: RealtimeEngine;  // Offline mirror to use instead of one created at the context rate.
  offlineBlockSize?: number;  // Offline render block size in frames. Default: `maxBlockSize`, else `128`.
  offlineNumChannels?: number;  // Planes the offline mirror renders and captures. Default: `numChannels`.
}

worklet エンジンファサード ​

@libraz/libsonare/worklet は、worklet エンジンファサードの SonareEngine と、それが包むノードの SonareRealtimeEngineNode を公開します。ここでは、ファサードのメソッドを用途別に、worklet から読み出す呼び出しとあわせて載せます。ノードの作り方と最初の例はリアルタイムとストリーミングにあります。

用途別のファサードメソッド ​

やりたいことworklet API
トラックルーティング、フェーダー、パン、ソロ/ミュートsetTrackLanes、setStripFaderDb、setStripPan、setStripPanLaw、setStripPanMode、setStripDualPan、setStripChannelDelaySamples、setTrackSoloMute
トラック/マスターのインサートと EQsetStrip、setStripEqBand、setStripInsertParam、setStripInsertBypassed、setStripSidechain
センドとバスsetTrackSends、setTrackOutputBus、setBusGainDb、setBusStrip、setBusEqBand、setBusInsertParam、setBusInsertBypassed、setBusSidechain
MIDI クリップとライブ MIDIsetMidiClips、pushMidiNoteOn、pushMidiNoteOff、pushMidiCc、pushMidiProgram、pushMidiPanic
パラメータオートメーションsetAutomationLane、addAutomationPoint、resolveStripAutomationId(target, kind)、resolveBusAutomationId(busId, 'faderDb')、parameters、automationLaneCount
楽器setBuiltinInstrument、setSynthInstrument、loadSoundFont、setSf2Instrument
録音とモニタリングconfigureCapture(punch を含む)、setInputMonitor、armCapture、capturedAudio、captureStatus
トランスポート、テンポ、マーカーtransportState、cachedTransportState、setTempoSegments、setTimeSignatureSegments、マーカー系メソッド(全置換の setMarkers を含む。解決後のマーカー一覧(各エントリがエンジン id を持つ)を返す)、setLoopFromMarkers
クリップ更新addClip、removeClip(差分のクリップデルタを worklet へ送る)
メーターとテレメトリonMeter / onTelemetry / onScope、pollMeters / pollTelemetry / pollScope。メーターレコードはマスター・レーン・バス・入力のターゲット id を持つ。オフライン/メインスレッド側エンジンは、全プレーンを持つメーターレコードとスコープスナップショットを読み出せる
オフライン書き出しメインスレッド側ミラーの renderOffline、finishOfflineRender、bounceOffline、freezeOffline(オフライン書き出しの API を参照)
プロセッサ状態とタイミングresetProcessorState(renderFrame?)、tailSamples、graphLatencySamples

pushMidiProgram が届くのは、プログラムを選択するレシーバーです。SoundFont プレーヤー、useGmPrograms を指定したシンセ、drumKit(GM キット)のシンセがそれに当たり、drumKit ではプログラムが GS のドラムセットを選びます。組み込みシンセとそれ以外のシンセパッチは、メッセージを受け取っても無視します。

configureCapture ではバッファ、ソース、録音オフセット、パンチ範囲を設定します。ドライ入力モニターは setInputMonitor({ enabled, gain? }) で別に設定します。captureStatus() の応答には、バッファ満杯で破棄したフレーム数を示す droppedFrames が必須です。

worklet API では、ストリップを指定するメソッドはトラック id または名前(target: string | number)を受け取り、setTrackSoloMute(target, { solo, mute }) はトラックを id または名前で受け取ります。setStripEqBand は EqBandInput オブジェクトを直接受け取ります。

resolveStripAutomationId(target, 'faderDb' | 'pan' | 'width') と resolveBusAutomationId(busId, 'faderDb') は予約済みエンジンパラメータ id を返すので、addParameter でカスタムパラメータを登録しなくても、それらをそのまま setAutomationLane(paramId, points) に渡してトラック/マスターのフェーダーやパン、マスターのステレオ幅(トラックには幅がありません)、あるいはバスのフェーダー(そのフェーダーゲイン dB に解決されます)を自動化できます。target/busId は初回利用時にミキサーのレーン/バスを宣言します。トラックやバスの id はリスト内の位置ではなく、その対象自体を指します。id は計算せず、必ずこれらのメソッドで取得してください。メインスレッド側ミラーと worklet 側エンジンは同じ番号を割り当てます。

ファサードの setTrackLanes は追加専用です。既存のトラック id をすべて同じ順序で残し、その後ろに新しい id を追加してください。既存レーンの並べ替えや削除は拒否されます。生の RealtimeEngine ではレーンリストを置き換えて並べ替えられます。その場合も予約済みオートメーション id は同じトラックを指し続け、そのトラックがない間は何も適用しません。

worklet 側でスコープスナップショットを流す場合は、SonareRealtimeEngineNode.create(...) に scopeIntervalFrames、scopeBands、必要に応じて scopeSharedBuffer / scopeRingCapacity を渡します。scopeIntervalFrames は [0, 2147483647] の整数で、0 なら取得を無効にします。外部スコープリングには 1〜64 バンドを指定します。SAB のスコープ共有リングはレンダーコールバック内で確保を行わず、pollScope() で読み出します。onScope() は同じ WorkletScopeSnapshot 形式を受け取ります。SAB が使えない場合や mode: 'postMessage' を指定した場合、プロセッサは bands と points を転送する Float32Array バッファとして各スナップショットに含めて送ります。この場合も onScope() は同じ形式で受け取りますが、共有リングがないため pollScope() は空配列を返します。postMessage 経路では転送前にスナップショットごとの配列を作ります。独自ブリッジでスペクトラムとベクトルスコープのスナップショットを共有リングに流したい場合は、低レベルの createScopeRingBuffer(...) と readScopeRingBuffer(...) を使えます。

メータースナップショットは、どちらの経路でも同じ形で onMeter に届きます。ステレオより多いチャンネルを持つターゲット(5.1 や 7.1 のバス)では、numChannels と、チャンネルごとの peakDb、rmsDb、truePeakDbtp、inputPeakDb 配列(標準の WAVE チャンネル順)が加わります。ステレオ用フィールドは常にプレーン 0 と 1 を保持します。SAB のメーターリングの 1 レコードは SONARE_METER_RING_RECORD_FLOATS(49)個の float で、ヘッダーのスロット 3 にはプロトコルバージョン SONARE_METER_RING_PROTOCOL_VERSION(現在は 3)が入ります。スペクトラム、スコープ、テレメトリの各リングは、それぞれ SONARE_SPECTRUM_RING_PROTOCOL_VERSION、SONARE_SCOPE_RING_PROTOCOL_VERSION、SONARE_ENGINE_TELEMETRY_RING_PROTOCOL_VERSION(現在はいずれも 1)を持ちます。これらのリングはスロットごとに状態ワードを持つので、読み出し側が 2 回の書き込みが混ざったレコードを受け取ることはなく、書き込み中のレコードは次の呼び出しで読まれます。テレメトリリングのヘッダーは、読み出し側がスロットを保持していたために捨てられたレコードを lost ワードで数えます。各リングは対応する create*RingBuffer ヘルパー(createMeterRingBuffer、createSpectrumRingBuffer、createScopeRingBuffer、createEngineTelemetryRingBuffer など)で作成してください。手でサイズを決めたバッファは、プロセッサの構築時に拒否されます。不正なリング寸法や 64 を超える scopeBands も同様です。独自の読み出し側は export されている定数でサイズを決め、worklet とメインスレッドのコードは同じパッケージバージョンから読み込んでください。リングはバージョンをまたいで共有できません。

SAB のコマンドレコードは SONARE_ENGINE_COMMAND_RECORD_BYTES(40)バイトで、直前に送られた sync のシーケンス番号を持ちます。プロセッサは、その sync が処理されるまでコマンドを保留します。必須のオペランドがないか型が違う場合、sendCommand はフィールド名を含む TypeError を送出します。canSendCommand はそのレコードに false を返します。値が範囲外かリングが満杯の場合、sendCommand は false を返します。

オフライン書き出しの API ​

renderOffline、bounceOffline、freezeOffline はファサードのメインスレッド側エンジンで動き、レンダーが終わるまで呼び出しスレッドをブロックします。長い処理はブロックしても問題ない場所で実行してください。OPFS ストリーミングのクリップは対象区間分を先に読み込みます。書き出されるのはプログラム出力だけで、PFL/AFL のキューが混ざることはありません。完了したレンダーはミラーのトランスポート位置を元に戻します。finalize: false の場合はチャンクごとに位置が進み、最後のチャンクまたは finishOfflineRender() で開始位置へ戻ります。bounceOffline と freezeOffline は素のエンジンの同名メソッドと同じオプションを受け取り、同じ結果を返します。詳しくはリアルタイムエンジンを参照してください。

呼び出し動作
renderOffline({ totalFrames, blockSize?, finalize? })現在位置からレンダーし、オフラインのチャンネルごとに 1 本のプレーナーバッファを返します(リクエストオブジェクトが必須で、フレーム数だけを渡すと TypeError です)。blockSize の既定値と上限はエンジンのオフラインブロックサイズで、超えると RangeError です。finalize: false は長いタイムラインの 1 チャンクをレンダーし、保持中のノートとディレイの残響を次の呼び出しへ持ち越します。
finishOfflineRender()チャンク分割レンダーを終えます。保持中のノートを解放し、ディレイラインを空にし、トランスポート位置を戻します。
bounceOffline(options)タイムラインをプレーナーな { channels, sampleRate, integratedLufs } へバウンスします。blockSize の上限は同じです。
freezeOffline(options)ソース層を 1 つのクリップにフリーズします。以後、ファサード、ミラー、worklet はそのクリップだけを保持します。
typescript
const total = 4 * 48000;
const chunkFrames = 48000;
const left: Float32Array[] = [];
for (let done = 0; done < total; done += chunkFrames) {
  const last = done + chunkFrames >= total;
  const chunk = await engine.renderOffline({
    totalFrames: Math.min(chunkFrames, total - done),
    finalize: last,
  });
  left.push(chunk[0]);
}

オフラインレンダーは、新しいレンダーセッションの開始時にミラーのミキサーとエフェクトの各プロセッサを準備直後の状態へ戻します。継続するチャンクでは、前のチャンクのプロセッサ状態、保持中のノート、残響を引き継ぎます。この準備処理は楽器をリセットしないため、現在のボイスやコントローラーの状態は結果に影響する場合があります。resetProcessorState(renderFrame?) はプロセッサのリセットをライブエンジンに対して行います。シークと同様に、鳴っているインサートの残響とディレイラインを断ち切り、renderFrame で適用され(省略時は次のブロック先頭)、楽器には影響しません。tailSamples は最長の可聴テールをサンプル数の上限値で返し(2147483647 は無制限)、graphLatencySamples は処理レイテンシをサンプル単位で返します。どちらも読み取り専用プロパティで、ミラーから答えます。

ノード直接の制御とポーリング ​

ここで挙げるのは、SonareRealtimeEngineNode.create(...) が返すノードのメソッドです。サンプル精度のコマンドをキューに積み、worklet の出力キューを回収します。SonareEngine.node は connect() するための素の AudioWorkletNode です。ファサードはエンジンノードを非公開にしており、同等の機能は transport.*、resetProcessorState、resetMasterLoudnessMeter、transportState()、captureStatus() / capturedAudio() / resetCapture()、onMidiOut、pollInsertGainReduction で使えます。

メソッド用途
play、stop、seekSample(timelineSample, renderFrame?)、seekPpq(ppq, renderFrame?)、resetProcessorState、resetMasterLoudnessMeter絶対フレーム renderFrame でトランスポートやリセットのコマンドをキューに積みます。省略すると次のブロック先頭で適用され、負の値は RangeError です。いずれもキューに積めたかどうかを返し、コマンドのリングが満杯なら false です。
requestTransportState()worklet 側のトランスポート状態で解決します。
requestCaptureStatus()、requestCapturedAudio()、requestCaptureReset()worklet が持つキャプチャバッファを読み書きします。
pollMidiOut() / onMidiOut(cb)MIDI 1.0 バイトに変換済みの外部 MIDI イベントを回収し、Web MIDI の出力ポートへ渡します。onMidiOut を購読している間はリングがそちらに消費されるため、手動のポーリングには以降に届いた分しか見えません。
pollClipPageRequests() / onClipPageRequests(cb)独自のページング処理向けに、クリップページのミスをバッチで回収します。
onSyncError(cb)worklet が拒否したコントロールメッセージを受け取ります。購読解除関数を返します。