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

# Piano audio engine

The piano sampler (user taps, the chart's rhythm lane, melody auto-play) runs on one engine behind
the `PianoSamplerLike` surface: [`NativePianoSampler`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/engine/native/native-piano-sampler.ts)
over the local Nitro module [`modules/piano-audio-engine`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/piano-audio-engine/README.md)
(AVAudioEngine + a TinySoundFont `AVAudioSourceNode`).

| Platform | Piano                                                                                  |
| -------- | -------------------------------------------------------------------------------------- |
| iOS      | native engine                                                                          |
| Android  | **no piano sound yet** — the module is Apple-only; an Android native engine is planned |

`react-native-audio-api` (RNA) is no longer part of the app: the RNA piano sampler, its reverb /
limiter worklets and the engine switch are gone, and so is everything that played through RNA —
the free-play metronome and the recorded song-preview clips. Song previews now synthesise the
song's chart through the piano sampler. A recorded (mp3 / m4a / …) backing track is back, played by
the native engine itself — see [Audio files and the song backing](#audio-files-and-the-song-backing) — and the chart's MIDI rhythm
track remains the fallback for a song that has no recording or whose recording will not open.

UI sound effects (countdown, score tick, result stingers, hearts, tutorial) and the app-open chime
play through the native module's own **SFX engine** (`loadSfx` / `playSfx`: `SfxEngine.swift`, a second
`AVAudioEngine` with an `AVAudioPlayerNode` pool per sound → mixer → its own limiter, independent of the piano
engine so it works before `initialize`; a mono sound is duplicated to both channels so it keeps `AVAudioPlayer`'s
level): [`sfx.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/sfx.ts) loads the
`assets/sfx` set once the splash intro has played (the splash waits for the batch), except the
`ftue_*` sounds of the FTUE song pickers, which stay out of that batch and load as the tutorial opens
(`warmFtueSfx`, from `TutorialEntryScreen`): a sound not loaded by its cue is skipped, and the choose
screen is the first to play them. The countdown (Game Mode, the
tutorial song, Learn's pre-roll and count-in) plays DEV's prototype's own sounds (26/11/2026):
`countdown_tick` on 3 · 2 · 1 (4 voices) and `countdown_go` on GO! (`countdownSfx(go)`; DEV's own file
since 02/12/2026, its leading silence trimmed so it lands with the glyph), at their
mix (0.6 / 1.1 over the +6 dB the old `count_down_321` beep they replace needed); and
[`open-app-sound.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/open-app-sound.ts) decodes the chime at boot and plays it on
the splash intro's first frame. The splash never waits for it to finish (the chime runs \~2.5 s, the
intro 1.65 s): when the splash goes, whatever is left of it fades out under the next screen over
the time it has left (`fadeOutSfx`: the SFX engine ramps the sound's players to silence, then
stops them). The piano engine and the SFX batch start under the chime's tail, so nothing may
reconfigure the shared audio session by then: the first `loadSfx` (the chime's) already sets the piano's
10 ms IO buffer (`PlaybackSession.prepare`), later loads only reclaim a switched session, and
a development build silences Pulsar (which deactivates the session) before the chime loads
(`silencePulsarSound`). On a first launch the onboarding film waits for the chime's end too
(`useOpenAppSoundDone`): `expo-video` switches the session to `.moviePlayback` as its player is set up.
Both honour
`useSfxStore.muted`, and are silent where the module is not linked (Android).

Contracts and shared pure helpers live in [`@piano/audio-engine`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/audio-engine/README.md)
(no React Native imports).

## Layers

```text
@piano/audio-engine          contracts (PianoAudioEngine, TrackInstrument, AudioClock, AudioEffects,
                             AudioMixer, AudioSettings, AudioDiagnostics, PianoAudioPreset) + helpers
                             (velocity curves, createPianoInstrument, createAudioMixer,
                             resolveGroupMix, room presets, …)
src/core/audio/engine/
  native/                    NativePianoSampler, NativeClockPump, nativeSamplerFactory,
                             native-mixer-sink.ts (shared mixer → module setters)
  capabilities.ts            NATIVE_ENGINE_CAPABILITIES
src/core/audio/mixer/        persisted mixer config (useAudioMixerStore) + installAudioMixerSync
src/core/audio/pianoSamplerService.ts   the process-wide sampler: ensurePianoSampler / getPianoSampler
modules/piano-audio-engine   Swift: graph, MIDI scheduler, voice tracker, clock, diagnostics
```

`PianoSamplerLike` exposes:

- `backend`, `capabilities`, `engine` (the `PianoAudioEngine` facets).
- `outputState` (`running` / `suspended` / `closed`) and `resume()` — interruptions and
  app-state resume (`resume()` always reaches native, which revives whatever is dead).
- `createClockPump()` — the gameplay song clock (`NativeClockPump` forwarding the module's \~30 ms
  clock pulse, by polling the shared-memory clock mailbox each frame (or from the `onClockPulse` callback); worklets read the same mailbox with `readClockTick`).
- `applySynthConfig()` / `reloadSoundFont()` — the sampler settings and SoundFont swaps.

## Boot and failure

[`entrySetup.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/bootstrap/entrySetup.ts) registers `nativeSamplerFactory` with the sampler
service and installs the mixer sync. `ensurePianoSampler()` builds the engine once; concurrent
callers share one in-flight load.

If the factory throws (module not linked: Android, Expo Go; `initialize` or the SoundFont load
failing), `usePianoSamplerStore` goes to `status: "error"` with the message and the screens carry on
without sound. `useSoundFontSampler` retries a failed build once per mount, not in a loop.

### Background and interruptions

The app has no background audio mode, so iOS deactivates the audio session whenever it suspends
the app. The native engine (`PianoAudioEngineCore`) brings the output back on its own, for every
screen at once. Every lifecycle event runs on one serial queue, in the order it arrived:

- **Foreground** (`UIApplication.didBecomeActive`): `revive` re-asserts the session (`.playback`,
  then active), restarts a suspended or silently stopped engine, and probes a "running" one. The
  probe checks that the sampler node's render clock (`lastRenderTime.sampleTime`) moves within
  150 ms; when it doesn't, the engine is restarted. The clock re-bases, so JS time stays continuous.
- **Interruption `.began`** suspends the engine. One that never gets an `.ended` (or one iOS reports
  late, after the foreground revive) is undone by the next foreground return or key press.
- **`.ended`**: the engine revives whenever the app is in front, with or without `.shouldResume`.
  A piano only plays what the user presses.
- **Key press**: `noteOn` runs a health check, throttled to once every 500 ms (one host-time read on
  the hot path). Off the JS thread, it revives an output that is flagged, suspended, stopped, or
  whose session category is no longer `.playback`, and probes the render clock otherwise. The
  pressed note is already queued (frame `-1`) and sounds as soon as the engine renders.
- **Configuration change / media-services reset**: the session is re-activated before the
  restart. A start that fails leaves `needsRevive` set for the next foreground or key press.
- **Google Mobile Ads**: the module sets `audioVideoManager.audioSessionIsApplicationManaged` on
  create (through a runtime lookup, with no link dependency). Otherwise the SDK switches the shared
  session to `.ambient` around muted video ads, which the silent switch silences. With the flag set,
  ad audio plays under the app's `.playback` category.
- **SFX**: `SfxEngine` activates the session before restarting. After a media-services reset the
  module rebuilds it and replays every `loadSfx` and the last `setSfxLimiter`. It plays nothing and
  starts nothing while the app is in the background (`didEnterBackground` → `willEnterForeground` /
  `didBecomeActive`): a suspended app has no session, and a sound then is late anyway. `.inactive`
  (ad close, system alert, shade) still plays, so a 3-2-1 tick is not dropped there. Foregrounding
  and the end of an audio interruption restart the engine at once.
  - **Every start of a stopped engine re-arms its players** (`rearmPlayers`: each player stopped,
    every voice idle). This covers the next play, a configuration change, and an interruption that
    ended. After a stop, an `AVAudioPlayerNode` keeps reporting `isPlaying` and renders nothing, and
    a play only calls `play()` on a player that is not playing. So without the re-arm, every sound
    after an ad network's session switch was silent until relaunch: the 3-2-1 and the score
    count-up (PO 01/12).
  - **A fullscreen ad close revives it**: `ensurePlaybackSession` → `SfxEngine.revive()`. A stopped
    engine starts. A "running" one whose render clock (the SFX mixer's `lastRenderTime`) has not
    moved over 150 ms is restarted, the same check `probeRender` makes for the piano.
  - Checked offline by `modules/piano-audio-engine/tools/sfx-harness/run.sh`, which
    `sfx-engine.golden.test.ts` runs on macOS.

### Threading

`AVAudioEngine` is not thread-safe, and the AVFoundation NSExceptions it raises on misuse are
crashes, not throws: Swift traps an Objective-C exception crossing a Swift frame, so Nitro's
`catch (...)` never sees it. 1.0.11 (77) shipped that crash in `SfxEngine.play`
(`-[AVAudioPlayerNode play]`: "required condition is false: \_engine != nil"): moving from the
Expo module to Nitro replaced Expo's serial `AsyncFunction` queue with `Promise.parallel`'s
concurrent global queue, so a `loadSfx` could detach a player between a JS-thread play's pick and
its `play()`.

- **`SfxEngine`** touches its graph and players only on its own serial queue
  (`piano-audio-engine.sfx`): `load` decodes on the caller's thread, then wires the players there;
  `play` is fire-and-forget onto it; `fadeOut` steps there; configuration-change restarts hop
  there. A play also skips a detached player or a stopped engine instead of calling `play()`.
- **`HybridPianoAudioEngine`** runs `initialize`, `loadSoundFont`, `suspend`, `resume` and
  `loadAudioFile` on one serial queue (`piano-audio-engine.calls`), in call order, as Expo did.
  Only `loadSfx` stays on `Promise.parallel`'s global queue.
- A new `Promise.parallel` in a module with shared native state must name a serial queue.
  `modules/piano-audio-engine/__tests__/engine-threading.contract.test.ts` pins these rules, and
  `modules/piano-audio-engine/tools/sfx-harness/run-race.sh` hammers loads, reloads and fades
  against a play loop (it crashes the 1.0.11 `SfxEngine` within seconds).

JS is the backstop. `NativePianoSampler.resume()` always forwards to native (unless it is closed),
because an engine can report `running` while rendering nothing. Screens with no pause flow of their
own (Keyboard, Learn, tutorial practice) pass `useSoundFontSampler({ resumeOnForeground: true })`.
On the return to `active`, the hook resumes the engine and retries a refused resume after 300 ms and
then 1 s (`createForegroundResumeRetry`). It also rebuilds a sampler whose build failed while the app
was away. Gameplay's pause-panel Resume resumes the sampler before the controller. When the store
drops its sampler (disposed under memory pressure), the hook clears `samplerRef` so presses never
play into a dead engine.

### Memory pressure

`releaseMemoryPressure` clears the image cache, then — unless gameplay, a fullscreen ad or a
screen holding the live audio surface (`holdLiveAudioSurface`: Learn, the tutorial, Keyboard) is active —
disposes the sampler. The next screen that needs one builds it afresh.

## Native engine

Graph, the TinySoundFont sampler, scheduling rules and the offline verification harnesses are in the
[module README](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/piano-audio-engine/README.md). The points that matter to JS:

- Notes are timestamped on the engine clock (`getCurrentTime()` seconds on the render
  timeline). The JS lookahead sequencer hands native exact start / release times and native lands
  them on the exact sample.
- All three roles (user, melody, rhythm) share one sampler. Per-role gain is applied natively
  (`setRoleGain`; the rhythm role is also scaled by the music volume) and reaches notes that
  are already sounding.
- A note-off names the exact voice, and the pitch stays held while another holder owns it
  (per-pitch refcount). Polyphony is enforced natively (oldest voice stolen first; voices a held sustain pedal keeps sounding after their key-up still count, so a pedal held through a whole song cannot exhaust the sampler's pool).
- Envelope (ADSR), per-voice tone (filter, filter envelope, vibrato, spread, tune, drift) and
  the velocity curve are applied by the sampler core
  ([`native-sound-mapping.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/engine/native/native-sound-mapping.ts)). Each
  envelope stage is overridden on its own (`null` keeps the SoundFont's value); `release` is the real
  time a voice takes to fall 96 dB, as in the prototype.
- **Level per SoundFont.** Like the instrument-sampler prototype, each font has its own trim
  (`SOUND_FONT_GAIN_DB` in [`sound-font-gain.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/sound-font-gain.ts): Steinway −1 dB;
  a DevTool file −6.3). It is pushed with `setSoundFontGain` before the font loads and kept across
  reloads. Fonts are mastered at different levels, so each bundled font gets its own trim (one phrase ≈
  −22.7 dBFS, measured with `tools/render-ab`). Re-measure after adding or changing a bundled SF2.
- **The Sound is the prototype's model** (`DEFAULT_SOUND` in `@piano/network/devtool-protocol`): the SoundFont's
  own envelope and the sound approved in the DevTool — a \~2 kHz low-pass (key tracking 0.5), hard velocity curve
  (1…80), compressor + insert EQ on the piano group, a custom reverb (send 0.18, decay 5 s, size 1, damping 0.7,
  300 Hz – 7 kHz return, −5 dB), a ping-pong 1/8. echo (send 0.3, 4 kHz high cut) and the limiter on. Values are
  rounded to two decimals. [`audio-sound.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/devtool-sync/audio-sound.ts) converts it to `SampleSynthEngineConfig` + the mixer
  (`DEFAULT_SAMPLE_SYNTH_ENGINE_CONFIG` and `DEFAULT_MIXER_CONFIG` are kept equal to it by a test). The reverb bus
  goes through Reverb2 exactly as the prototype's graph does: tail `decay / 1.4`, damping `(1 − damping) / 0.9`,
  room size straight through (max reflection delay `12 ms + 110 ms · size`) and first-reflection time
  `preDelay + 1 ms + 19 ms · size`. The bus _return_ level and manual-mode _dry_ level are part of the mixer
  contract (`ReverbConfig.returnDb`, `MixerSends.dry`).
- **No master saturation, headroom, soft-clip, brightness cutoff or ducking knobs.** The prototype has none of
  them: the master is a fader, a 3-band EQ and a limiter. `mixer.master.saturation` stays at `off`; the brightness
  filter is the per-voice tone; the shared voice cap is a fixed default.
- SoundFont: the bundled `.sf2flac` (FLAC-packed samples, decoded on load — see the
  [module README](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/piano-audio-engine/README.md)) is resolved to a `file://` path and
  loaded as the piano preset (`NATIVE_SOUNDFONT_PIANO_PRESET`).
- The audio session (`playback`) is configured by the module itself on `initialize`; interruptions,
  route changes and media-services resets are handled natively.
- **Output route.** `getOutputRoute()` / `onRouteChange` report the `AVAudioSession` output port
  types, independent of `initialize`. [`audio-output.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/audio-output.ts) turns them
  into `speaker` vs `headphones` (`audioOutputKindOf`); the Learn challenge's headphone hit window and
  the [speaker output profile](#speaker-output-profile) follow it.

### Capabilities

`sampler.capabilities` drives which DevTool controls are enabled:

| Capability                                                         | Native | UI effect                                                                                                                                                                                                |
| ------------------------------------------------------------------ | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `customEnvelope`                                                   | yes    | ADSR; the release is converted (see the [module README](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/piano-audio-engine/README.md#envelope-release)) |
| `softClipShaper`                                                   | yes    | engine API only (the Sound tab does not expose it)                                                                                                                                                       |
| `releaseFade`                                                      | no     | `fadeSeconds` ignored natively                                                                                                                                                                           |
| `reverbRoomSize`, `reverbDamping`, `reverbFilters`, `delayFilters` | yes    | reverb / echo shape                                                                                                                                                                                      |
| `voiceTone`, `velocityCurveGamma`                                  | yes    | per-voice filter / vibrato / spread / tune / drift and the velocity curve                                                                                                                                |
| `insertEq`, `ampModels`                                            | yes    | channel EQ and amp models in the insert strip                                                                                                                                                            |
| `eq`, `filterModes`, `latencyMode`                                 | yes    | engine API only                                                                                                                                                                                          |
| `sampleAccurateScheduling`                                         | yes    | —                                                                                                                                                                                                        |
| `groupMixer`, `masterEq`, `limiterParams`, `saturation`            | yes    | shared mixer (below)                                                                                                                                                                                     |
| `groupInserts`                                                     | yes    | compressor / amp / chorus-tremolo inserts                                                                                                                                                                |
| `pingPongDelay`, `reverbRoomTypes`                                 | yes    | ping-pong echo and room presets                                                                                                                                                                          |

## Shared mixer

One mixer config drives the engine. The contract is `AudioMixer` in
[`@piano/audio-engine`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/audio-engine/src/contracts/mixer.ts), exposed as
`sampler.engine.mixer`:

- **Group `"piano"`** (every SoundFont voice): volume `0–2`, pan, mute, solo, sends
  `{ mode, reverb, delay, dry }`, inserts `{ compressor, amp, eq, modulation }`.
- **Master:** volume `0–4` (+12 dB), 3-band EQ (120 Hz low shelf, 1 kHz peak Q 0.7, 8 kHz high shelf),
  limiter `{ enabled, ceilingDb −3, lookaheadMs 5, releaseMs 1000 }` (shipped: volume +12 dB into it), saturation
  `off | warm | soft-clip` (engine API; stays `off`).

**Send law.** `resolveGroupMix` turns a group into dry / reverb / delay gains once, in JS. A send
amount is bus mix (`effects.reverb.mix`, `0` while that effect is off) × the group send. In `auto`
mode each send is `wet = sin(a·π/2)` and dry gets the remaining power, `dry = √(1 − Σwet²)` (wets
are scaled down together if they would exceed 1), so raising reverb never makes the piano louder.
`manual` keeps dry at unity and the sends additive.

**Native mapping** ([`native-mixer-sink.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/engine/native/native-mixer-sink.ts)):

| Section           | Native                                                                                                                                                                                                                                                    |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Group dry / sends | real dry bus + send mixers: `setMixerGroup(dry, reverb, delay, pan)`                                                                                                                                                                                      |
| Pan               | sampler node group pan                                                                                                                                                                                                                                    |
| Inserts           | `FxStrip` (`setInserts`, sent only when changed)                                                                                                                                                                                                          |
| Master volume     | cut (\< 1): `mixBus.outputVolume`; boost (> 1, up to ×4): the limiter's input gain (`AVAudioMixerNode` volume stops at unity), so a boost is caught by the limiter                                                                                        |
| Master EQ         | `AVAudioUnitEQ` (3 bands)                                                                                                                                                                                                                                 |
| Limiter           | `FxLimiter` (`setLimiter`) — always on by default; golden-tested against the TS reference [`limiter-kernel.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/output-limiter/limiter-kernel.ts) |
| Saturation        | `FxLimiter` shaper (`setSaturation`)                                                                                                                                                                                                                      |

**Ownership and persistence.** [`useAudioMixerStore`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/mixer/store.ts) persists the
config in MMKV (`audio-mixer-config`, valibot-validated on load; a bad field falls back to its
default and everything is clamped by the shared ranges).
[`installAudioMixerSync`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/mixer/mixer-sync.ts) (called from `entrySetup.ts`)
configures the sampler when it finishes building and re-applies it on any store change. The DevTool
writes the store from the Sound it edits (`devtool-audio.ts`), so a mixer left in MMKV by an earlier
session is overwritten when the DevTool flag is on.

**Room presets and tempo-synced delay.** `effects.reverb.setRoomType(studio | room | chamber |
hall | cathedral | plate)` loads decay / size / damping / pre-delay from `REVERB_ROOM_PRESETS`;
`effects.delay.setSync({ bpm, division })` and `setPingPong` drive the echo, with
`resolveDelayTimeSec` turning a division into seconds. Native maps the pre-delay onto Reverb2's
first-reflection time.

## Tuning the sound

There is **no in-app Sound settings screen**. Sound is tuned from the desktop DevTool's **Sound
tab** on a connected phone while it plays — protocol (`audio_*` messages, protocol v6), relay and
preset storage are in [devtool.md](/docs/devtool.md#sound-tab-realtime-audio-tuning).

- App side: [`createAudioControlPort`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/devtool-sync/audio-control-port.ts) edits a
  [`SoundState`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/devtool-sync/audio-sound-state.ts) (the prototype-model Sound, clamped by
  `mergeSound`); [`src/bootstrap/devtool-audio.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/bootstrap/devtool-audio.ts) applies every change through
  `soundToEngineConfig` / `soundToPianoGroup` / `soundToMasterPatch` into `useSamplerSettingsStore.setEngineConfig`
  and `useAudioMixerStore`, so every edit follows the normal `applySynthConfig` / mixer-sync path.
  `soundToBusLevels` feeds `@core/audio/bus-levels`: the SFX level scales every `playSfx`, the preview level scales
  each `ChartPreviewPlayer` note's velocity, the music level becomes the sampler's `musicVolume` (`bus-levels-sync.ts`).
- **A limiter per app source.** The sampler renders each role onto its own bus (`sc_render_buses`: user + melody =
  piano, rhythm = backing, preview = a fourth role); the backing and preview buses each go through an `FxLimiter`
  inside the render (`sc_render_limited`), then sum into the piano chain, so they keep its reverb / inserts. SFX
  has its limiter in `SfxEngine`. `soundToBusLimiters` → `@core/audio/bus-limiters` → `bus-limiters-sync.ts`
  (`setSfxLimiter` at boot and on change, `setBusLimiter` once a sampler is ready and on change). Each limiter has
  on / input (drive) / ceiling / look-ahead (= attack) / release, stereo-linked; while on it adds its look-ahead as
  latency (defaults: look-ahead 5 ms and release 1 s on all three; ceiling SFX −9 dB, backing −6 dB, preview −9 dB; levels SFX −18 dB, preview −15 dB, music 0 dB). Not implemented: true-peak /
  oversampling.
- Persistence: the Sound is **session-only** (a launch starts from `DEFAULT_SOUND`; **Reset to app defaults**
  returns to it). Approved sounds are saved as presets on the Mac and baked into the defaults by a developer
  (**Copy as TS defaults**).
- Meters (peak / RMS / CPU / voices / clipping) come from `sampler.engine.diagnostics` and are
  streamed at 100 ms only while a Sound tab is subscribed; native metering is switched off again
  when the last tab disconnects or the socket drops.
- The test phrase is a looping 6.5 s phrase scheduled sample-accurately through the sampler
  ([`audio-test-phrase.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/devtool-sync/audio-test-phrase.ts)).

## Diagnostics and dev tools

Component Labs → **Piano audio** → **Audio backend**
([`AudioBackendPanel`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/labs/components/AudioBackendPanel.tsx)):

- Status line: the live engine.
- Supported capabilities.
- **Mixer** ([`MixerLabSection`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/labs/components/MixerLabSection.tsx)): writes the shared
  store, so the engine follows and the change persists. **Bypass (A/B)** plays the neutral default
  mixer without losing the stored one (session-only). Rows: send mode, mute, group volume and pan,
  master EQ presets, limiter ceiling, inserts, room presets and ping-pong. **Reset** restores the
  defaults.
- Diagnostics polled every 500 ms: CPU %, xruns, output latency, sample rate, buffer frames,
  voices, peak / RMS, clipping. Native metering is switched on only while the panel is mounted
  (`setDiagnosticsMetering`). Metrics the engine cannot measure read `—`.

## Build

The module autolinks on `expo prebuild`. After pulling it: `bunx expo prebuild --platform ios`,
then `pod install`. The pod needs iOS 16.4.

The scheduler, clock and voice tracker also have a macOS offline harness (see the
[module README](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/piano-audio-engine/README.md#run-the-harness)). The C Fx kernels
are compiled and golden-tested against the TS limiter in `bun run test` (`test:app:config`
shard), and have their own graph harness ([module README](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/piano-audio-engine/README.md#fx-kernels)).

## Speaker output profile

On iOS the app adapts the mix to the phone loudspeaker (the worst case: the calibrated mix runs
near full scale and the speaker has its own protection DSP). The profile follows
[`output-profile-state.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/output-profile-state.ts), written only by
[`startOutputProfile`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/output-profile.ts) (boot) from the output route:

- **Speaker route** (`Speaker` / `Receiver`): trim, thinner reverb and halved echo — see
  `SPEAKER_OUTPUT_PROFILE` in [`output-profile.pure.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/output-profile.pure.ts).
- **Anything else, or an unknown route** (Android, a failed read): neutral.
- The trim is `FxLimiter`'s input gain (`setOutputTrim`, pushed by
  `NativePianoSampler.pushOutputTrim`), in front of the shaper and limiter. Reverb and echo wet are
  scaled in the config the sampler settings store pushes to the sampler (`applyOutputProfile`); the
  stored values are untouched.
- There is no longer an A/B switch for the profile.

## Audio files and the song backing

**The engine** plays notes and plays audio files, and knows nothing about what either is for. Its audio-file
side is a small fixed pool of players (`AUDIO_FILE_PLAYER_COUNT`, 3) in
[`AudioFilePlayer.swift`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/piano-audio-engine/ios/AudioFilePlayer.swift): `AVAudioPlayerNode` (streams the file
with `scheduleSegment`, never decoded whole) → fade gate → gain → `FxLimiter` → `mixBus`. A player joins after the piano
chain, so a file skips the piano's inserts / reverb / delay and shares the master EQ, limiter and volume. Every call
names a player index: `loadAudioFile` / `playAudioFile` / `pauseAudioFile` / `resumeAudioFile` / `seekAudioFile` /
`stopAudioFile` / `setAudioFileGain` / `setAudioFileLimiter`. Times are engine seconds, like `noteOn`'s: a future start is
handed to the player as a host time derived from the sampler node's last render
(`EngineClock.audioTime(atEngineSeconds:)`), so a file begins on the render quantum a note scheduled for that moment does;
a start already in the past skips that much of the file. The position is derived from the engine clock, not read back from
the node, so a pause lands on the moment the sequencer's transport froze on, and a pause before the start keeps the wait
that was left. A route change that stops the engine remembers the position and picks the music up when the engine is back;
a media-services reset reloads the file and leaves it stopped. Formats: whatever `AVAudioFile` reads — mp3, m4a, wav, aac,
caf. **ogg is not readable on iOS**; it would need a decoder in the module.

JS side, `NativePianoSampler.openAudioFile(path, { startSec, endSec })` → `NativeAudioFileTrack`
([`native-audio-file-track.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/engine/native/native-audio-file-track.ts)): takes a free player (rejects
when every one is busy), is an `IBackingTrackAdapter` for the sequencer, and applies **no fader and no limiter of its own**.
Dispose it to give the player back.

**The app** decides what a file is for. [`withAudioFileMix`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/audio-file-mix.ts) seats a track on the
DevTool's music or preview fader and backing or preview limiter, and keeps it there while the track lives.

**The catalog** answers "what plays under this song": `CatalogFacade.getBacking(song, purpose, options)` →
`{ kind: "audio", uri }` (the recording as a file on disk: bundled → disk cache → download, one download per file) or, when
there is none, `{ kind: "rhythm", midi }` (the song's MIDI — the Learn Mode MIDI for `"learn"` — whose rhythm track plays as
notes), or `{ kind: "none" }`. `purpose` picks the recording (`"gameplay"`: `SongAsset.audioAssetModule` / catalog `bgmUrl`;
`"learn"`: `learnmode/audio/<key>.mp3` / catalog `Learn Mode Audio`). `download: "background"` answers at once and fetches for
next time. Game Mode and Learn Mode ask this one thing
([`song-backing.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/infra/container/song-backing.ts)), then hand the file to the engine. A song preview never
does: it plays the song's MIDI only (copyright), see [features/catalog.md](/docs/features/catalog.md#runtime-bundled-default-providers-override).

**The sequencer** is the engine's `RhythmSequencer`: one track, the recording (`BackingScheduleTrack`) or the rhythm notes
(`NoteScheduleTrack`).

| Consumer   | Asks                              | Plays through                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| ---------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Game Mode  | `"gameplay"`, background download | `PlayController` — the recording replaces its rhythm lane; none → the chart's rhythm lane                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| Learn Mode | `"learn"`                         | its own `RhythmSequencer` ([`createBackingSequencer`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/backing-sequencer.ts)), started at the cue; the file may play one run ending (3.5 s) past the cue's end ([`learnRecordingEndSec`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/learn/audio/run-ending.ts)) so a last note at the cue's edge still gets its tail and fade; window end, fades and the run ending are the screen's |

Verify the file player offline (macOS, manual rendering; the test file is a ramp, so a rendered sample names the file frame it
came from):

```bash
modules/piano-audio-engine/tools/audio-file-harness/run.sh
# add a real compressed file:
AUDIO_FILE=src/assets/learnmode/audio/furelise.mp3 modules/piano-audio-engine/tools/audio-file-harness/run.sh
```

Not verified on a device: the host-time start path (offline rendering starts by sample time), a route change / interruption
under a playing file, and the audible level against the piano. A mono file is centre-panned by the mixer (−3 dB).

## Device QA checklist

iPhone, release-like build.

1. **Boot:** free-play keys sound on the first tap after launch.
2. **Latency:** tap rapid repeated notes and chords; compare the output latency and xrun readouts in
   the Piano audio lab.
3. **Play song:** the rhythm lane and melody auto-play stay in time with the tiles for the whole
   song. Check a long hold and pedal spans. Pause / resume re-schedules cleanly, with no stuck notes
   after pause.
4. **Learn:** the stage-7 backing (the song's recorded render, else the chart's rhythm track) starts on
   the cue, the run's music plays on and fades out after its tail — also on a song whose last note sits at the
   cue's end (Canon in D) — and the result comes in after the fixed ending beat.
5. **Recorded backing (gameplay):** on a song with a bundled or cached recording, the music stays in time with
   the tiles for the whole song; pause / resume and an auto-pause land back on the same bar; a song whose file
   is missing plays on its rhythm track.
6. **Interruptions:**
   - A phone call or Siri mid-song; background and foreground the app.
   - Free mode and Learn: leave the app in the background for 3+ minutes (or play audio in another
     app), then come back. The first key press sounds.
   - Free mode with the silent switch on while the banner refreshes: keys still sound.
   - Siri or an alarm over free mode, dismissed without leaving the app: keys sound.
   - Pause a song, background for minutes, come back, tap Resume: music and clock continue.
   - Plug and unplug headphones; connect and disconnect Bluetooth.
   - In each case sound returns (UI SFX too), and gameplay's app-state pause and resume still work.
7. **Route:** plug and unplug headphones mid-song; the level changes smoothly (no click). On
   headphones the Learn challenge uses the wider hit window.
8. **Ads:** a fullscreen interstitial or rewarded ad mid-flow. Audio resumes after it; the
   memory-pressure warning around ads does not leave a dead sampler.
9. **Song-list previews:** a cover tap plays \~15 s of the song's chart; only one preview sounds at a
   time and none under a popup.
10. **Polyphony:** a glissando plus sustain pedal. No dropouts, and steals are inaudible.
11. **Failure:** force a failure, e.g. by loading a missing SoundFont in a dev build. The error lands in
    `usePianoSamplerStore` and the app stays usable without sound.
12. **Diagnostics:** CPU % and xruns stay low through a dense song. Clipping stays at 0 at default
    volume.
13. **Shared mixer** (lab → Audio backend → Mixer): toggle **Bypass (A/B)**, EQ Warm / Bright, ceiling
    −6 dB, mute and pan L / R; the change is heard at once and survives a relaunch. Compressor / amp /
    chorus / tremolo, room presets and ping-pong are heard, and an interruption or media-services
    reset keeps them.
14. **Android:** the app boots and every screen works with no piano sound (no crash, no retry loop).

***

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