Documentation comes from this release commit, without inheriting newer content. Commit: 63ea8c2b3d.
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 Expo module modules/piano-audio-engine
(AVAudioEngine + a TinySoundFont AVAudioSourceNode).
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 waits for it via open-app-chime-gate). 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
PianoSamplerLike exposes:
backend,capabilities,engine(thePianoAudioEnginefacets).outputState(running/suspended/closed) andresume()— interruptions and app-state resume (resume()always reaches native, which revives whatever is dead).createClockPump()— the gameplay song clock (NativeClockPumpforwarding the module's 20 msonClockPulse).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):revivere-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
.begansuspends 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:
noteOnruns 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
needsReviveset for the next foreground or key press. - Google Mobile Ads: the module sets
audioVideoManager.audioSessionIsApplicationManagedon create (through a runtime lookup, with no link dependency). Otherwise the SDK switches the shared session to.ambientaround muted video ads, which the silent switch silences. With the flag set, ad audio plays under the app's.playbackcategory. - SFX:
SfxEngineactivates the session before restarting. After a media-services reset the module rebuilds it and replays everyloadSfxand the lastsetSfxLimiter.
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 (nullkeeps the SoundFont's value);releaseis 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_DBinsound-font-gain.ts: Steinway −1 dB; a DevTool file −6.3). It is pushed withsetSoundFontGainbefore 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 withtools/render-ab). Re-measure after adding or changing a bundled SF2. - The Sound is the prototype's model (
DEFAULT_SOUNDin@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.tsconverts it toSampleSynthEngineConfig+ the mixer (DEFAULT_SAMPLE_SYNTH_ENGINE_CONFIGandDEFAULT_MIXER_CONFIGare kept equal to it by a test). The reverb bus goes through Reverb2 exactly as the prototype's graph does: taildecay / 1.4, damping(1 − damping) / 0.9, room size straight through (max reflection delay12 ms + 110 ms · size) and first-reflection timepreDelay + 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.saturationstays atoff; the brightness filter is the per-voice tone; the shared voice cap is a fixed default. - SoundFont: the bundled
.sf2is resolved to afile://path and loaded as the piano preset (NATIVE_SOUNDFONT_PIANO_PRESET). - The audio session (
playback) is configured by the module itself oninitialize; interruptions, route changes and media-services resets are handled natively. - Output route.
getOutputRoute()/onRouteChangereport theAVAudioSessionoutput port types, independent ofinitialize.audio-output.tsturns them intospeakervsheadphones(audioOutputKindOf); the Learn challenge's headphone hit window and the speaker output profile follow it.
Capabilities
sampler.capabilities drives which DevTool controls are enabled:
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): volume0–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), saturationoff | warm | soft-clip(engine API; staysoff).
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):
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:
createAudioControlPortedits aSoundState(the prototype-model Sound, clamped bymergeSound);src/bootstrap/devtool-audio.tsapplies every change throughsoundToEngineConfig/soundToPianoGroup/soundToMasterPatchintouseSamplerSettingsStore.setEngineConfiganduseAudioMixerStore, so every edit follows the normalapplySynthConfig/ mixer-sync path.soundToBusLevelsfeeds@core/audio/bus-levels: the SFX level scales everyplaySfx, the preview level scales eachChartPreviewPlayernote's velocity, the music level becomes the sampler'smusicVolume(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 anFxLimiterinside the render (sc_render_limited), then sum into the piano chain, so they keep its reverb / inserts. SFX has its limiter inSfxEngine.soundToBusLimiters→@core/audio/bus-limiters→bus-limiters-sync.ts(setSfxLimiterat boot and on change,setBusLimiteronce 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.diagnosticsand 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 — seeSPEAKER_OUTPUT_PROFILEinoutput-profile.pure.ts. - Anything else, or an unknown route (Android, a failed read): neutral.
- The trim is
FxLimiter's input gain (setOutputTrim, pushed byNativePianoSampler.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).
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):
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.
- Boot: free-play keys sound on the first tap after launch.
- Latency: tap rapid repeated notes and chords; compare the output latency and xrun readouts in the Piano audio lab.
- 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.
- 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.
- 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.
- 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.
- Route: plug and unplug headphones mid-song; the level changes smoothly (no click). On headphones the Learn challenge uses the wider hit window.
- 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.
- 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.
- Polyphony: a glissando plus sustain pedal. No dropouts, and steals are inaudible.
- Failure: force a failure, e.g. by loading a missing SoundFont in a dev build. The error lands in
usePianoSamplerStoreand the app stays usable without sound. - Diagnostics: CPU % and xruns stay low through a dense song. Clipping stays at 0 at default volume.
- 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.
- Android: the app boots and every screen works with no piano sound (no crash, no retry loop).