> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Audio engine — full flow (Mermaid)

Diagrams of the iOS piano engine: the audio signal graph (sampler, per-voice filter, inserts, EQ + filter
band, sends, mixer, master EQ, limiter), the JS → native control path, and the note scheduling path.
Prose and rules: [audio-engine.md](/docs/audio-engine.md), [module README](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/piano-audio-engine/README.md).

Sources of truth: [`PianoAudioGraph.swift`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/piano-audio-engine/ios/PianoAudioGraph.swift),
[`FxUnits.swift`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/piano-audio-engine/ios/FxUnits.swift),
[`SamplerCore.h`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/piano-audio-engine/ios/dsp/SamplerCore.h),
[`native-piano-sampler.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/engine/native/native-piano-sampler.ts),
[`native-mixer-sink.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/engine/native/native-mixer-sink.ts).

## 1. Signal flow (AVAudioEngine graph)

Built once in `PianoAudioGraph`; setters only change parameters, nodes are never re-created or re-connected.

```mermaid
flowchart TB
  classDef src fill:#e8f0fe,stroke:#4a6fa5,color:#111
  classDef fx fill:#fff4e0,stroke:#c28a2c,color:#111
  classDef filt fill:#fde8f0,stroke:#b5476e,color:#111
  classDef bus fill:#e9f7ec,stroke:#3d8b54,color:#111
  classDef out fill:#eee,stroke:#555,color:#111

  subgraph SAMPLER["SamplerNode (AVAudioSourceNode) → SamplerCore.c + TinySoundFont"]
    direction TB
    EVQ["Event queue<br/>sample-accurate note on/off<br/>(frame on render clock, voice id)"]
    VOICE["Voices (max polyphony, oldest stolen first)<br/>SoundFont zones · velocity curve<br/>ADSR (per-stage override, release = time to -96 dB)"]
    VFILT["Per-voice FILTER (setTone)<br/>low-pass cutoff + resonance<br/>velocity→cutoff · key tracking · filter envelope"]
    VMOD["Vibrato · stereo spread · tune · drift"]
    ROLE["Role gains: user / melody / rhythm / preview<br/>× per-SoundFont trim (setSoundFontGain)<br/>buses: piano (user + melody) · backing (rhythm) · preview<br/>backing and preview each through their own FxLimiter, then summed"]
    PAN["Group pan (sampler node pan)"]
    EVQ --> VOICE --> VFILT --> VMOD --> ROLE --> PAN
  end

  PIANOBUS["pianoBus<br/>instrumentVolume × outputGain"]
  STRIP["FxStrip — group inserts (C kernel)<br/>1 compressor → 2 amp (drive/tone/cabinet)<br/>→ 3 insert EQ (low cut, 120 Hz shelf, peak, 6 kHz shelf)<br/>→ 4 chorus / tremolo / auto-pan"]
  EQ["AVAudioUnitEQ (4 bands)<br/>bands 0-2: user EQ (shelf / peak / pass)<br/>band 3: FILTER LP / HP / BP (resonant)"]

  DRY["dryBus<br/>group dry gain"]
  RSEND["reverbSend<br/>group send × bus mix"]
  DSEND["delaySend<br/>group send × bus mix"]

  REV["Reverb2 (Apple AU, 100% wet)<br/>decay = tail × 1.4 · damping · room size<br/>pre-delay · diffusion · +18 dB makeup"]
  RETEQ["reverbReturnEq<br/>band 0: low cut (HPF)<br/>band 1: high cut (LPF)"]
  DLY["FxDelay (C kernel, wet only)<br/>time · feedback ≤ 0.95 · ping-pong<br/>high cut / low cut · tape mod"]

  MIX["mixBus<br/>bus 0 dry · bus 1 reverb · bus 2 delay<br/>mixer master fader (outputVolume cut · boost via limiter input gain)"]
  MEQ["masterEq (3 bands)<br/>120 Hz low shelf · 1 kHz peak Q 0.7 · 8 kHz high shelf"]

  subgraph LIM["FxLimiter (C kernel)"]
    direction TB
    TRIM["Input gain = speaker output trim"] --> SAT["Saturation: off / warm / soft-clip"] --> LK["Look-ahead limiter<br/>ceiling · look-ahead 1-20 ms · release"]
  end

  MAIN["mainMixer<br/>app master volume 0-1"]
  OUT(["Hardware output<br/>AVAudioSession playback"])

  PAN --> PIANOBUS --> STRIP --> EQ
  EQ --> DRY
  EQ --> RSEND
  EQ --> DSEND
  DRY --> MIX
  RSEND --> REV --> RETEQ --> MIX
  DSEND --> DLY --> MIX
  MIX --> MEQ --> TRIM
  LK --> MAIN --> OUT

  class EVQ,VOICE,VFILT,VMOD,ROLE,PAN src
  class STRIP,DLY,TRIM,SAT,LK fx
  class EQ,RETEQ,MEQ,REV filt
  class PIANOBUS,DRY,RSEND,DSEND,MIX,MAIN bus
  class OUT out
```

Where the filters live (three different stages, do not confuse them):

| Filter                                                           | Where                                   | Scope                                    |
| ---------------------------------------------------------------- | --------------------------------------- | ---------------------------------------- |
| Voice low-pass (cutoff, resonance, filter envelope)              | `SamplerCore` (`setTone`)               | per voice, before any bus                |
| EQ bands 0-2 + FILTER band 3 (`setEqBand` / `setFilter`)         | `eq` `AVAudioUnitEQ`, after `FxStrip`   | whole piano group, in front of the sends |
| Reverb return low/high cut, delay high/low cut, master 3-band EQ | `reverbReturnEq`, `FxDelay`, `masterEq` | per bus / master                         |

## 2. Control flow (JS → native)

```mermaid
flowchart TB
  classDef js fill:#e8f0fe,stroke:#4a6fa5,color:#111
  classDef pure fill:#f3e8fd,stroke:#7a4aa5,color:#111
  classDef nat fill:#fff4e0,stroke:#c28a2c,color:#111

  DEVTOOL["Desktop DevTool — Sound tab<br/>audio_* messages, protocol v6"]
  PORT["audio-control-port.ts → SoundState<br/>(mergeSound clamps)"]
  BOOT["bootstrap/devtool-audio.ts<br/>soundToEngineConfig · soundToPianoGroup · soundToMasterPatch"]
  SETSTORE["useSamplerSettingsStore.setEngineConfig<br/>(synth config: envelope, tone, velocity, effects)"]
  MIXSTORE["useAudioMixerStore<br/>MMKV audio-mixer-config, valibot, bypass A/B"]
  PROFILE["output-profile.ts<br/>speaker vs headphones route"]

  APPLY["NativePianoSampler.applySynthConfig"]
  FACETS["applySynthConfigToFacets → effects + settings facets"]
  VOICE["pushVoiceSound<br/>setEnvelope · setTone · setVelocityCurve<br/>(only when changed)"]
  EFFECTS["AudioEffects facet<br/>reverb · delay · eq · filter"]
  SETTINGS["AudioSettings facet<br/>master / instrument / music volume<br/>polyphony · latency mode"]

  SYNC["installAudioMixerSync → mixer-sync.ts<br/>engine.mixer.configure(effectiveMixerPreset)"]
  RESOLVE["resolveGroupMix (pure JS)<br/>fader · mute/solo · constant-power send law<br/>dry = √(1 − Σwet²) in auto mode"]
  SINK["native-mixer-sink.ts<br/>applyGroup · applyMaster"]
  TRIMPUSH["pushOutputTrim"]

  MOD["PianoAudioEngine Expo module (Swift)<br/>core.apply(key) { graph.set… }"]
  SAMPLER["SamplerNode / SamplerCore<br/>envelope · tone/filter · velocity curve · role gain"]
  GRAPH["PianoAudioGraph<br/>Reverb2 · EQ + filter · delay · mixer buses · master EQ"]
  FXU["FxAudioUnit kernels<br/>strip · delay · limiter"]

  DEVTOOL --> PORT --> BOOT
  BOOT --> SETSTORE
  BOOT --> MIXSTORE
  SETSTORE --> APPLY --> FACETS
  APPLY --> VOICE
  FACETS --> EFFECTS
  FACETS --> SETTINGS
  MIXSTORE --> SYNC --> RESOLVE --> SINK
  PROFILE --> TRIMPUSH

  VOICE -->|"setEnvelope / setTone / setVelocityCurve"| MOD
  EFFECTS -->|"setReverb · setReverbPredelay · setReverbShape<br/>setDelay · setEqBand · setEqEnabled · setFilter"| MOD
  SETTINGS -->|"setMasterVolume · setPianoGain<br/>setRoleGain (rhythm × musicVolume)"| MOD
  SINK -->|"setMixerGroup(dry, reverbSend, delaySend, pan)<br/>setInserts · setMixerMasterVolume<br/>setMasterEq · setLimiter · setSaturation"| MOD
  TRIMPUSH -->|"setOutputTrim"| MOD

  MOD --> SAMPLER
  MOD --> GRAPH
  GRAPH --> FXU

  EFFECTS -. "refreshGroups: send levels depend on bus mix" .-> RESOLVE

  class DEVTOOL,PORT,BOOT,SETSTORE,MIXSTORE,PROFILE,APPLY,FACETS,VOICE,EFFECTS,SETTINGS,SYNC,SINK,TRIMPUSH js
  class RESOLVE pure
  class MOD,SAMPLER,GRAPH,FXU nat
```

## 3. Note path (gameplay → sound)

```mermaid
sequenceDiagram
  autonumber
  participant G as Gameplay / lookahead sequencer (JS)
  participant S as NativePianoSampler (user / melody / rhythm track)
  participant M as Expo module (JSI sync call)
  participant SC as MidiScheduler + VoiceTracker
  participant CK as EngineClock
  participant CORE as SamplerCore (audio thread)
  participant GR as PianoAudioGraph
  participant HW as Output

  G->>S: playNote(note, velocity, when)
  S->>M: noteOn(note, velocity, atTime = getCurrentTime + when, role)
  M->>SC: noteOn(...)
  SC->>CK: renderFrame(at: time)
  alt starts within 20 ms
    SC->>CORE: sc_note_on_at(role, key, vel, frame, voiceId) — lock-free ring
  else later
    SC-->>SC: pending queue (4 ms timer, cancellable for free)
    SC->>CORE: sc_note_on_at(...) when due
  end
  SC-->>S: voiceId
  Note over CORE: next render block: apply queued commands,<br/>start the voice on its exact frame
  CORE->>CORE: velocity curve → ADSR → voice low-pass filter → vibrato / spread / tune → role gain
  CORE->>GR: stereo buffer via sampler node (pan)
  GR->>GR: pianoBus → FxStrip → EQ + filter → dry / reverb / delay buses → mixBus → masterEq → FxLimiter → mainMixer
  GR->>HW: output
  G->>S: releaseVoice(handle, when)
  S->>M: noteOff(voiceId, atTime)
  M->>SC: noteOff (10 ms lead, per-pitch refcount, CC64 sustain in core)
  SC->>CORE: sc_voice_off_at(voiceId, frame)
  CK-->>S: onClockPulse every ~30 ms (song clock)
```

***

<small>Source: [`docs/audio-engine-flow.md`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/docs/audio-engine-flow.md)</small>
