Skip to content

JavaScript/TypeScript SonareEngine API ​

SonareEngine is the AudioWorklet-backed facade of the RealtimeEngine: it shares its method names, request types and units, and forwards every edit to the live engine in the worklet. It ships in the @libraz/libsonare/worklet entry. Realtime and Streaming covers the bridge setup, the transport modes and the facade table.

Lifecycle ​

Create ​

await SonareEngine.create(context, options) creates the worklet node, waits for the processor to be ready and resolves with the engine; the constructor is private. options adds offlineEngine, offlineBlockSize and offlineNumChannels for the offline mirror, whose block size defaults to maxBlockSize, then 128 frames. Connect engine.node into the audio graph.

Use ​

Every edit applies to an offline mirror engine on the calling thread and is forwarded to the worklet, so a refused edit changes neither. Setters return void; reads are answered synchronously from the mirror. The calls that need the audio thread's answer return a Promise: transportState, captureStatus, capturedAudio, resetCapture and pollInsertGainReduction. suspend() and resume() drive the audio context.

Release ​

destroy() is idempotent and [Symbol.dispose]() makes using work (Releasing Native Handles); suspend() and resume() resolve immediately on a destroyed engine.

Errors ​

Argument refusals are TypeError and RangeError, as on RealtimeEngine. A setter that cannot queue its command because the command ring is full throws SonareError with OutOfMemory. create throws AbiMismatch on an engine ABI mismatch and NotSupported when mode: 'sab' is requested without SharedArrayBuffer and Atomics. Error Contract has the full table.

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 engine facade ​

@libraz/libsonare/worklet exports SonareEngine, the worklet engine facade, and SonareRealtimeEngineNode, the node it wraps. This section lists the facade methods by need and the calls that drain the worklet; creating the node and a first example are on Realtime and Streaming.

Facade methods by need ​

NeedFacade API
Track routing, fader, pan, solo/mutesetTrackLanes, setStripFaderDb, setStripPan, setStripPanLaw, setStripPanMode, setStripDualPan, setStripChannelDelaySamples, setTrackSoloMute
Track and master inserts and EQsetStrip, setStripEqBand, setStripInsertParam, setStripInsertBypassed, setStripSidechain
Sends and busessetTrackSends, setTrackOutputBus, setBusGainDb, setBusStrip, setBusEqBand, setBusInsertParam, setBusInsertBypassed, setBusSidechain
MIDI clips and live MIDIsetMidiClips, pushMidiNoteOn, pushMidiNoteOff, pushMidiCc, pushMidiProgram, pushMidiPanic
Parameter automationsetAutomationLane, addAutomationPoint, resolveStripAutomationId(target, kind), resolveBusAutomationId(busId, 'faderDb'), parameters, automationLaneCount
InstrumentssetBuiltinInstrument, setSynthInstrument, loadSoundFont, setSf2Instrument
Recording and monitoringconfigureCapture (incl. punch), setInputMonitor, armCapture, capturedAudio, captureStatus
Transport, tempo, markerstransportState, cachedTransportState, setTempoSegments, setTimeSignatureSegments, marker methods (incl. the replace-all setMarkers, which returns the resolved marker list — each entry carries its engine id), setLoopFromMarkers
Clip updatesaddClip, removeClip — sends incremental clip deltas to the worklet
Meters and telemetryonMeter / onTelemetry / onScope, pollMeters / pollTelemetry / pollScope; meter records carry master, lane, bus, and input target ids. Offline/main-thread engines drain meter records that carry every plane, and scope snapshots
Offline exportrenderOffline, finishOfflineRender, bounceOffline, freezeOffline on the main-thread mirror (see Offline render, bounce, and freeze)
Processor state and timingresetProcessorState(renderFrame?), tailSamples, graphLatencySamples

pushMidiProgram reaches the receivers that select programs: the SoundFont player, a synth bound with useGmPrograms, and a drumKit (GM-kit) synth, where the program selects the GS drum set. The built-in synth and other synth patches accept the message and ignore it.

configureCapture sets the buffer, source, record offset and punch window. Configure the dry input monitor separately with setInputMonitor({ enabled, gain? }). A captureStatus() response requires droppedFrames, the number of frames discarded because the buffer was full.

On the worklet API, strip-addressing methods take a track id or name (target: string | number), and setTrackSoloMute(target, { solo, mute }) takes the track by id or name. setStripEqBand accepts an EqBandInput object directly.

resolveStripAutomationId(target, 'faderDb' | 'pan' | 'width') and resolveBusAutomationId(busId, 'faderDb') return reserved engine parameter ids, so you can pass them straight to setAutomationLane(paramId, points) to automate a track or master fader or pan, the master's stereo width (a track has none), or a bus fader (which resolves to its fader gain in dB), without first registering a custom parameter via addParameter. The target/busId declares the mixer lane/bus on first use. A track or bus id names that target rather than its list position. Resolve ids through these methods rather than computing them; the main-thread mirror and the worklet engine number them identically.

The facade's setTrackLanes is append-only: preserve all existing track ids in their current order, and append new ids. Reordering or removing an existing lane is refused. The raw RealtimeEngine can replace and reorder its lane list; its reserved automation ids continue to address the same track, and apply nothing while that track is absent.

For Worklet-side scope snapshots, pass scopeIntervalFrames, scopeBands, and optionally scopeSharedBuffer / scopeRingCapacity to SonareRealtimeEngineNode.create(...). scopeIntervalFrames is an integer in [0, 2147483647], with 0 disabling capture. An external scope ring must declare 1–64 bands. The SAB scope ring keeps the render callback allocation-free; pollScope() drains it, and onScope() receives the same WorkletScopeSnapshot shape. When SAB is unavailable or mode: 'postMessage' is selected, the processor sends each snapshot with transferred Float32Array buffers for bands and points; onScope() receives the same shape, while pollScope() returns an empty array because there is no ring. The postMessage fallback materializes the bounded arrays for each snapshot before transfer. The lower-level createScopeRingBuffer(...) and readScopeRingBuffer(...) helpers are exported for custom shared-ring bridges.

Meter snapshots reach onMeter the same way on both transports. A target wider than stereo (a 5.1 or 7.1 bus) adds numChannels plus per-plane peakDb, rmsDb, truePeakDbtp, and inputPeakDb arrays in canonical WAVE channel order; the stereo fields always hold planes 0 and 1. The SAB meter ring record is SONARE_METER_RING_RECORD_FLOATS (49) floats, and header slot 3 carries the protocol version, SONARE_METER_RING_PROTOCOL_VERSION (currently 3). The spectrum, scope and telemetry rings carry their own SONARE_SPECTRUM_RING_PROTOCOL_VERSION, SONARE_SCOPE_RING_PROTOCOL_VERSION and SONARE_ENGINE_TELEMETRY_RING_PROTOCOL_VERSION (currently 1). Every slot of these rings has a state word, so a reader never returns a record that mixes two writes, and a record still being written is read on the next call. The telemetry ring header counts, in a lost word, the records dropped while a reader held their slot. Create each ring with its create*RingBuffer helper (createMeterRingBuffer, createSpectrumRingBuffer, createScopeRingBuffer, createEngineTelemetryRingBuffer, and so on); a hand-sized buffer is refused when the processor is constructed, as are bad ring dimensions and scopeBands above 64. Size a custom reader from the exported constants, and load worklet and main-thread code from the same package version, since rings are not shared across versions.

A SAB command record is SONARE_ENGINE_COMMAND_RECORD_BYTES (40) bytes and carries the sequence number of the last sync posted before it; the processor holds the command until that sync is processed. sendCommand raises TypeError naming a required operand that is missing or has the wrong type. canSendCommand returns false for that record. sendCommand returns false if a value is out of range or the ring is full.

Offline render, bounce, and freeze ​

renderOffline, bounceOffline, and freezeOffline run on the facade's main-thread engine and block the calling thread for the whole render, so run long jobs where blocking is acceptable. OPFS-streamed clips are paged in for the span first. The renders contain the program output only; an armed PFL/AFL cue is never mixed in. A completed render restores the mirror's transport position; with finalize: false, the position advances across chunks and is restored only by the final chunk or finishOfflineRender(). bounceOffline and freezeOffline take the options of the raw engine's methods of the same name and return its results; see Realtime Engine.

CallBehavior
renderOffline({ totalFrames, blockSize?, finalize? })Renders from the current position and returns one planar buffer per offline channel (the request object is required; a bare frame count is a TypeError). blockSize defaults to the engine's offline block size and must not exceed it (RangeError). finalize: false renders one chunk of a longer timeline, leaving held notes and delay tails running into the next call.
finishOfflineRender()Ends a chunked series: releases held notes, flushes the delay lines, and restores the transport position.
bounceOffline(options)Bounces the timeline to planar { channels, sampleRate, integratedLufs }. blockSize has the same ceiling.
freezeOffline(options)Freezes the source layer into one clip. The facade, the mirror, and the worklet then hold only that clip.
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]);
}

An offline render primes the mirror's mixer and effect processors to their prepared state at the start of a new render session. Continuing chunks preserve processor state, held notes, and tails from the previous chunk. Instruments are not reset by the prime, so their current voice and controller state can still affect the result. resetProcessorState(renderFrame?) exposes the processor reset for the live engine: it cuts running insert tails and delay lines like a seek, applies at renderFrame (omitted: the next block head), and leaves instruments alone. tailSamples is an upper bound on the longest audible tail in samples (2147483647 means unbounded), and graphLatencySamples is the processing latency in samples; both are read-only properties that answer from the mirror.

Node-level control and polling ​

These are the methods of the node that SonareRealtimeEngineNode.create(...) returns. They queue sample-accurate commands and drain the worklet's output queues. SonareEngine.node is a plain AudioWorkletNode for you to connect(); the facade keeps the engine node private and exposes the same capabilities through transport.*, resetProcessorState, resetMasterLoudnessMeter, transportState(), captureStatus() / capturedAudio() / resetCapture(), onMidiOut, and pollInsertGainReduction.

MethodUse
play, stop, seekSample(timelineSample, renderFrame?), seekPpq(ppq, renderFrame?), resetProcessorState, resetMasterLoudnessMeterQueue a transport or reset command at an absolute renderFrame. Omit it to apply at the next block head; a negative value throws RangeError. Each returns whether the command was queued: false when the command ring is full.
requestTransportState()Resolves with the worklet's own transport state.
requestCaptureStatus(), requestCapturedAudio(), requestCaptureReset()Read the capture buffer held in the worklet.
pollMidiOut() / onMidiOut(cb)Drain external-MIDI events already lowered to MIDI 1.0 bytes, for a Web MIDI output port. While onMidiOut is subscribed it consumes the ring, so a manual poll sees only what arrived since.
pollClipPageRequests() / onClipPageRequests(cb)Drain batches of clip-page misses for your own paging code.
onSyncError(cb)Receives control messages the worklet rejected; returns an unsubscribe function.