v1.0.11 · Release snapshot

Documentation comes from this release commit, without inheriting newer content. Commit: cc3dd17e61.

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 over the local Nitro module modules/piano-audio-engine (AVAudioEngine + a TinySoundFont AVAudioSourceNode).

PlatformPiano
iOSnative engine
Androidno 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 — 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 loads the assets/sfx set once the splash intro has played (the splash waits for the batch) and 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). Both honour useSfxStore.muted, and are silent where the module is not linked (Android).

Contracts and shared pure helpers live in @piano/audio-engine (no React Native imports).

Layers

@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 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.

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. 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). 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: 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 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 .sf2 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 turns them into speaker vs headphones (audioOutputKindOf); the Learn challenge's headphone hit window and the speaker output profile follow it.

Capabilities

sampler.capabilities drives which DevTool controls are enabled:

CapabilityNativeUI effect
customEnvelopeyesADSR; the release is converted (see the module README)
softClipShaperyesengine API only (the Sound tab does not expose it)
releaseFadenofadeSeconds ignored natively
reverbRoomSize, reverbDamping, reverbFilters, delayFiltersyesreverb / echo shape
voiceTone, velocityCurveGammayesper-voice filter / vibrato / spread / tune / drift and the velocity curve
insertEq, ampModelsyeschannel EQ and amp models in the insert strip
eq, filterModes, latencyModeyesengine API only
sampleAccurateSchedulingyes—
groupMixer, masterEq, limiterParams, saturationyesshared mixer (below)
groupInsertsyescompressor / amp / chorus-tremolo inserts
pingPongDelay, reverbRoomTypesyesping-pong echo and room presets

Shared mixer

One mixer config drives the engine. The contract is AudioMixer in @piano/audio-engine, 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):

SectionNative
Group dry / sendsreal dry bus + send mixers: setMixerGroup(dry, reverb, delay, pan)
Pansampler node group pan
InsertsFxStrip (setInserts, sent only when changed)
Master volumecut (< 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 EQAVAudioUnitEQ (3 bands)
LimiterFxLimiter (setLimiter) — always on by default; golden-tested against the TS reference limiter-kernel.ts
SaturationFxLimiter shaper (setSaturation)

Ownership and persistence. useAudioMixerStore 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 (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.

  • App side: createAudioControlPort edits a SoundState (the prototype-model Sound, clamped by mergeSound); 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).

Diagnostics and dev tools

Component Labs → Piano audio → Audio backend (AudioBackendPanel):

  • Status line: the live engine.
  • Supported capabilities.
  • Mixer (MixerLabSection): 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). 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).

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, written only by startOutputProfile (boot) from the output route:

  • Speaker route (Speaker / Receiver): trim, thinner reverb and halved echo — see SPEAKER_OUTPUT_PROFILE in 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: 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): 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 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), then hand the file to the engine. A song preview never does: it plays the song's MIDI only (copyright), see features/catalog.md.

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

ConsumerAsksPlays through
Game Mode"gameplay", background downloadPlayController — the recording replaces its rhythm lane; none → the chart's rhythm lane
Learn Mode"learn"its own RhythmSequencer (createBackingSequencer), started at the cue; the file may play one run ending (3.5 s) past the cue's end (learnRecordingEndSec) 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):

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).