Files
sizzletracker-android/docs/DEVELOPER_HANDOVER.md
T
ReactorcoremeltdownandClaude Opus 5 dd04a61e22 0.41.1 (77): cleanup and optimisation round (Android and iOS)
Nothing user-visible changes, except that the Android app is half the size and
both are lighter on the battery.

R8 is on for release builds (21.5 MB -> 10.1 MB); only the two JNI classes are
pinned by name, since the app reflects over nothing of its own, and `make dist`
keeps the mapping beside the APK. The Kotlin DSP that core/ replaced in 0.37.0
was still compiled into every APK with nothing calling it — it moves to the test
source set, where it belongs as the reference the C++ is checked against — and
the golden tests' TestVoice wrappers leave core/src for core/tests/voices, so
neither app compiles them either.

Speed: channel gain, mute/solo and the FX chain are read once per audio block
instead of once per frame in Engine::fillBlock (both platforms, bit-identical —
all 61 reference scenarios still match); the transport pollers idle at 100 ms
(Android) and 10 Hz (iOS) instead of polling flat out while a song is stopped,
woken by any transport call; ProjectIo.save builds into one pre-sized buffer and
a burst of edits is coalesced into one engine sync; the Kotlin grain sources and
factory wavetables are built when their editor opens rather than at launch, where
they duplicated ~6 MB the engine already renders in core/; and Xcode builds the
DSP core at -O2, the level the golden tests measure, not -Os.

Fix: `make lint` failed on a manifest asking for ACCESS_FINE_LOCATION without
ACCESS_COARSE_LOCATION (the BLE MIDI scan on Android 8-11), so `make check`
passes again.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-11-18 10:21:09 +01:00

59 KiB
Raw Blame History

Sizzletracker (Android) — Developer Handover

This document is written for a developer who is new to Android and needs to understand, build, and extend this codebase. Read it top to bottom once; after that it works as a reference.


1. What this app is

A retro, grid-based music tracker for Android. The visual language is a monospace font + pixel blocks laid out on a strict grid (demoscene tracker style). It is playable with four equally-capable input methods: touchscreen, physical keyboard, gamepad, and MIDI (USB or Bluetooth).

The UI has four tabs:

Tab Package What it does
Tracker ui/tracker Pattern grid (4 tracks) + arrangement piano-roll (8 lanes)
Mix ui/mixer 4-channel mixer: instrument + 4 FX, MIDI ch, volume, mute/solo
Toolbox ui/toolbox 16 slots of instruments/effects with a generated parameter editor
Setup ui/settings Project save/load, themes, gamepad & MIDI bindings

2. How to build, version & publish

2.1 The Makefile is the entrypoint

make — not ./gradlew, not the Android Studio Run button — is how this project is built and shipped. Every target is atomic and declares its own dependencies, so any one of them can be invoked on a clean tree and will pull in exactly what it needs and nothing else:

Target What it does
make help lists every target and prints the current version
make deps fails loudly if the JDK or the Android SDK is missing
make check unit tests + lint — the gate before a commit
make staging non-debuggable build, release-like performance, debug key
make install adb install -r of the staging APK (keeps projects/presets)
make release unsigned release APK, named for F-Droid
make dist stages the release APK + its R8 mapping + F-Droid metadata under dist/
make publish uploads dist/ to the private F-Droid repo — manual only
make bump-minor feature bump: x.(y+1).0, versionCode +1

Android Studio still works for day-to-day editing and debugging; it is just not the source of truth for what a build is.

make deps exports ANDROID_HOME from the default macOS SDK location when the environment does not already set it, because Gradle only consults ANDROID_HOME / ANDROID_SDK_ROOT / local.properties and a fresh checkout usually has none of them.

Library versions live in one file: gradle/libs.versions.toml (the "version catalog"). Change a number there and the whole project follows. The Gradle wrapper jar is committed (Gradle's recommended practice), so a fresh clone builds with no extra setup.

2.2 Identity and versioning

User-visible changes are listed in CHANGELOG.md (started at 0.28.0; earlier history is the git log, one commit per version).

The application id and namespace are cc.tiredsysadmin.android.sizzle — cc.tiredsysadmin.<operating_system>.<application>, so a future desktop port sits beside this one instead of colliding with it. The same string appears in the JNI symbol names in app/src/main/cpp/native_audio.cpp (Java_cc_tiredsysadmin_android_sizzle_audio_NativeAudioBridge_*); JNI resolves symbols by mangled package path, so renaming the package without renaming those two functions produces an UnsatisfiedLinkError at runtime, not a build error.

App versions live in versions.properties at the repo root, not in app/build.gradle.kts — Gradle reads them from there, and so does the Makefile when it names the published APK. One source means the artifact name and the manifest can never disagree.

versionName = 0.37.0
versionCode = 71

Since 0.37.0 the version is shared by Android and iOS (ios/Makefile reads the same two keys and make -C ios bump-minor bumps them through the root Makefile): both apps ship the same features, so every change bumps once, for both.

The file also carries macos / linux / bsd / windows slots, set to - until such a port exists, so a port starts from a tracked version instead of inventing one.

Semantic versioning, applied on every change: minor for a feature, patch for a fix or polish. versionCode always moves by exactly +1 — both F-Droid and the Android package manager order installs by that integer alone, and a skipped or reused code cannot be taken back once published. make bump-minor / bump-patch / bump-major does both halves correctly; editing the numbers by hand is how they drift apart.

2.3 Build types

Type Debuggable R8 Signing Use
debug yes no debug key breakpoints, instant-run edits
staging no no debug key anything on a real device
release no yes unsigned publishing only

staging exists because debug is misleading: a debuggable build makes ART run the app un-optimised and Compose several times slower, so UI "snappiness" measured on it means nothing. staging flips debuggability off — the single biggest performance lever — while reusing the debug signing key so it still installs without a release keystore. Use staging for every on-device test.

release is deliberately left unsigned. The signing key lives only inside the private F-Droid repo; fdroid publish signs what lands in the unsigned directory. No keystore should ever exist in this checkout.

release is also the only build R8 touches (shrink + optimise + obfuscate, plus unused-resource removal). The app reflects over nothing of its own — songs, presets, themes and bindings are all hand-written text parsers — so app/proguard-rules.pro keeps exactly one thing: native method names. JNI resolves Java_cc_tiredsysadmin_android_sizzle_audio_NativeEngine_* by name at runtime, so a renamed class or method is an UnsatisfiedLinkError on first play, not a build error. Everything else (Compose, media3, DataStore, coroutines) ships its own consumer rules inside its AAR.

A release stack trace is therefore obfuscated. make dist copies app/build/outputs/mapping/release/mapping.txt to dist/<application_id>_<versionCode>-mapping.txt; keep it for every published APK, because it is the only way to read a crash from that build. It is never uploaded. staging keeps R8 off on purpose: it exists to measure the UI, and a readable stack trace is worth more there than the last few hundred KB.

2.4 Publishing

Publishing is always a manual action, never automatic — it is not a side effect of a build, not wired into check or release, and never run unattended. make publish is the only thing that reaches the network, and the APK/metadata halves are separate targets so a metadata fix does not re-upload a 20 MB APK:

dist/<application_id>_<version_code>.apk  ->  rcmd@garage.rcmd.space:/var/lib/fdroid/unsigned
dist/<application_id>.yml                 ->  rcmd@garage.rcmd.space:/var/lib/fdroid/metadata

<application_id>_<version_code>.apk is the naming scheme the unsigned directory expects; app/build.gradle.kts stamps that same name onto the release output via the legacy variant API (the Kotlin-DSL android {} receiver does not expose output naming), deriving it from applicationId so the two cannot drift. The metadata YAML is regenerated from versions.properties on every make dist, so CurrentVersion can never lag the APK sitting next to it.

Run make dist first and look at what landed in dist/ before running make publish. Then sign the upload on the repo host.


3. The big picture (architecture)

            ┌──────────── Input sources ────────────┐
  Touch ───▶│ (Compose gestures, call ViewModel)     │
  Keyboard ─▶ KeyboardInput ─┐                        │
  Gamepad ──▶ GamepadInput ──┤─▶ InputRouter (flow) ──┼──▶ AppViewModel
  MIDI ─────▶ MidiInput ──┬──┘                        │        │
            └────────────│───────────────────────────┘        │ reads/writes
                         ▼ notes, all-notes-off, clock      (observes MIDI notes,
                    MidiSoundModule ──▶ AudioEngine.busNote*   punches them in)
                                                              ▼
                                                          Project  (the song)
                                                              ▲
                                     reads on audio thread    │
                                          AudioEngine ─────────┘  ──▶ Oboe / AudioTrack ──▶ speakers
                                          (own thread)

Three ideas hold it together:

  1. One neutral action type. Every non-touch device is translated into an InputAction (see input/InputAction.kt) and pushed through InputRouter. The ViewModel reacts to those actions in exactly one place (AppViewModel.onAction). Touch gestures call the same ViewModel methods directly. That is why all four inputs are equally capable — features are implemented once.

  2. One song object. model/Project.kt holds the entire song in memory. The UI edits it; the audio engine reads it; the file format serializes it.

  3. MIDI plays without the UI. MIDI notes do not go through the ViewModel: playback/MidiSoundModule (owned by SizzleApp, next to the engine) plays them on the mixer and mirrors them onto the router marked sounded, so the UI only shows / punches them in. With the "Keep running as MIDI sound module" setting on, SoundModuleService keeps the process in the foreground, so another app can play Sizzle from the background. See §5.5.

  4. Two threads. The UI runs on the main thread (Jetpack Compose). The sound runs on a dedicated high-priority thread inside AudioEngine. They share the Project object. Because the audio thread only ever reads simple Int/ Float fields, we accept the occasional benign race instead of locking (locks would risk audio glitches). See §7.


4. Package/file map

cc.tiredsysadmin.android.sizzle
├── SizzleApp.kt            Application = tiny DI container; ref-counted engine/MIDI owners; MIDI clock wiring
├── MainActivity.kt         Hosts Compose UI; forwards HW key/motion events; holds MIDI; starts services; .sng intents
│
├── model/                  Pure data, no Android imports (unit-test friendly)
│   ├── Music.kt            Pitch, TimeSignature, Scale (incl. scale-step logic)
│   ├── Pattern.kt          Cell, CellColumn, Pattern (4 tracks x N lines)
│   ├── Arrangement.kt      Arrangement (8 lanes; canvas denominated in bars, up to 256), LoopRegion A/B
│   ├── Mixer.kt            Mixer, MixerChannel (4 channels; volume/mute/solo/limiter)
│   ├── Toolbox.kt          ToolboxType (all instruments+effects), ParamSpec, ToolboxSlot, SamplerPads
│   ├── AmbiencePresets.kt  Factory reverb spaces seeded into the preset library
│   └── Project.kt          The whole song
│
├── input/                  The unified input layer
│   ├── InputAction.kt      The neutral action vocabulary
│   ├── InputActions.kt     Bindable-action catalogue (for the rebind/learn UI)
│   ├── InputRouter.kt      Flow-based message bus (+ learn mode)
│   ├── BindingStore.kt     Persists gamepad/MIDI bindings
│   ├── KeyboardInput.kt    KeyEvent  -> InputAction (+ a 2-octave typing piano)
│   ├── GamepadInput.kt     KeyEvent/MotionEvent -> InputAction (rebindable)
│   ├── MidiByteParser.kt   MIDI byte stream -> messages (running status, split packets, realtime, SysEx)
│   ├── MidiClock.kt        MIDI clock send / follow
│   ├── MidiSourceKey.kt    Stable key + display name for a MIDI source (persisted on/off choice)
│   ├── MidiTrace.kt        Optional receive/engine trace (setprop log.tag.SizzleMidiTrace VERBOSE)
│   └── MidiInput.kt        Lists/opens MIDI sources (USB, BLE, other apps' virtual ports), reconnects dead ones -> MidiSoundModule / CC bindings
│
├── audio/                  The engine's face (the DSP itself is core/, in C++)
│   ├── AudioEngine.kt      Drives core/ through NativeEngine: transport, sync, meters, recording
│   ├── NativeEngine.kt     JNI to core/src/host/EngineHost (src/main/cpp/jni_engine.cpp)
│   ├── NativeAudioBridge.kt  Starts/stops the Oboe stream (which renders in C++, no JVM call)
│   ├── Transport.kt        TransportState snapshot published to the UI
│   ├── SampleStore.kt      Process-wide decoded-PCM cache + WAV encode/decode (mirrored into core/)
│   ├── SampleRecorder.kt   Ad-hoc mic/USB capture into a sample
│   ├── SoundFontLoader.kt  Extract PCM from an .sf2 / .xi into the SampleStore
│   └── GrainSources.kt     The Grain Cloud's ten built-in sources (the UI draws their peaks)
│
├── frasil/                 MPL-2.0 (not GPL): the Morph Pad, ported from FRASIL (see §5.7)
│   └── FrasilDefs.kt       Its settings, engine-unit mapping, the 36 drone presets
│
├── wavetable/              The Wavetable synth (Sizzle's own, GPL; see §5.9)
│   ├── WaveTables.kt       Band-limited tables: FFT, one mip level per octave (the editor draws them)
│   └── WaveDefs.kt         Its settings, 12 factory presets
│
├── echofield/              MIT: the Grain Cloud, ported from ECHOFIELD (see §5.8)
│   └── EchofieldDefs.kt    Its settings, 14 factory presets, the source list
│
├── cpp/native_audio.cpp    Low-latency Oboe stream; its RT callback renders core/ directly
├── cpp/jni_engine.cpp      The JNI surface of core/src/host/EngineHost
│
├── io/                     Human-readable text persistence
│   ├── PresetIo.kt         Instrument/effect preset  <->  KEY=VALUE text
│   ├── PresetLibrary.kt    On-disk preset library (+ .zip sample bundles)
│   ├── ProjectIo.kt        Whole song  <->  internal .sng text (full fidelity)
│   ├── ProjectStore.kt     Autosave / load of the current project
│   ├── SongLibrary.kt      Named project save/load browser backing
│   ├── SngFormat.kt        Desktop-compatible .sng interchange read/write (also Mikro Seq exports)
│   ├── SongIntents.kt      Reads a .sng from a VIEW / SEND intent (size cap, content sniff)
│   ├── SettingsStore.kt    App settings (theme, recording dir, keyboard) via DataStore
│   ├── ThemeIo.kt          RetroPalette  <->  .szt text
│   └── ThemeLibrary.kt     On-disk theme library (import/export/delete)
│
├── playback/
│   ├── EnginePlayer.kt     SimpleBasePlayer wrapping the engine for MediaSession
│   ├── PlaybackService.kt  MediaSessionService: background playback + media notification
│   ├── MidiSoundModule.kt  Headless MIDI -> engine routing, held notes per source (pure Kotlin)
│   └── SoundModuleService.kt  Foreground service for background sound-module mode
│
└── ui/
    ├── AppViewModel.kt     Screen state + THE single InputAction handler
    ├── App.kt              Tab shell
    ├── Responsive.kt       Portrait/landscape layout helpers (nav rail, two-column)
    ├── StackedKeyboard.kt  On-screen audition / punch-in piano
    ├── theme/Theme.kt      RetroPalette + monospace typography + SizzleTheme
    ├── components/         Widgets (RetroButton/Dropdown…), GlyphCache, Piano
    ├── tracker/            TrackerScreen, PatternGrid, ArrangementRoll
    ├── mixer/MixerScreen.kt
    ├── toolbox/            ToolboxScreen, ParamControl, Sampler/SoundFont/Delay/Lfo editors
    └── settings/SettingsScreen.kt

5. Key concepts you must understand

5.1 Ticks, beats, bars

A tracker line (row) is one tick. The number of lines per beat is set by the time signature (model/Music.kt):

  • 3/4 → 3 lines per beat, lengths 12/24/48
  • 4/4 → 4 lines per beat, lengths 16/32/64
  • 5/4 → 5 lines per beat, lengths 20/40/80

PatternGrid tints every beat row and every bar row differently using line % linesPerBeat and line % linesPerBar.

5.2 The "revision" redraw trick (and the strong-skipping rule)

The model classes are plain (not Compose-observable) so the audio thread can read them cheaply. After any edit the ViewModel does revision++ (AppViewModel.touched(), exposed as bumpForToolbar() for direct model edits).

The rule that makes this actually work: the Compose compiler we use (2.0.20) has strong skipping enabled by default. It will skip a composable whose parameters are referentially unchanged — even "unstable" ones like vm — so a revision++ in a parent is NOT enough; a child that reads plain model data would be skipped and only refresh on a tab switch (which recreates the subtree).

So: every composable that reads plain, mutable model data must itself read vm.revision (e.g. val rev = vm.revision). Reading a snapshot state directly subscribes that composable's restart scope, so revision++ invalidates it regardless of skipping. Where a composable has no vm (e.g. SlotTile), pass rev = vm.revision as a parameter instead — a changed Int param defeats skipping too. Observable state (cursor position, transport, palette) already works without this because it is real Compose state.

If you edit the model and the screen doesn't update: (a) did you call a touched()/bumpForToolbar() path, and (b) does the leaf that renders that data read vm.revision? This was the cause of an early "UI only redraws on tab switch" bug.

5.3 The note-entry gesture

Tap a cell → cursor moves there (focusCell). Drag up/down → editFocused(dir):

  • On the NOTE column, Scale.step() moves to the next in-scale pitch.
  • On VELOCITY/CHANNEL it steps the number. Every step fires a haptic tick. The same editFocused runs from keyboard PageUp/ Down, gamepad right-stick, and MIDI CC — one implementation, four inputs.

5.4 Toolbox devices are data, not classes

Instead of a class per instrument/effect, every device is one ToolboxType enum entry that lists its ParamSpecs. A ToolboxSlot stores the chosen type + a name -> value string map. The parameter editor UI and the preset text format are both generated from that list. See §6 to add a new device.

5.4.0 The generic device editor: cards, tones, tabs (0.35.0)

Every device without a bespoke editor is drawn by DevicePanels (ui/toolbox/Panels.kt) from a layout in DeviceLayouts.pagesFor(type): a list of Pages (tabs, shown only when there are several), each a list of Panels (cards). A panel names its parameter keys, a Tone (SOURCE / FILTER / ENV / MOD / OUT, which picks the card and knob colour), an optional Viz (envelope, filter response or LFO wave, read live from the slot) and optional short-label overrides. Inside a card, choices come first (a segmented switch when the choices are short, else a dropdown), then knobs, up to six to a row. A panel with faders draws its keys as vertical bipolar faders instead (the graphic EQ).

Why: the old editor was two columns of horizontal sliders, hard to scan and easy to scroll past; grouping by function with a picture per group is how hardware synth pages read. Why tabs and not the old swipe pager: the pager had a fixed height, which clipped long sections, and swiping fought the knobs' vertical drags; tabs let each page take its natural height inside the editor's scroll.

Labels and values are derived, not written per device: shortLabel strips a section prefix and unit from ParamSpec.label ("Osc1 Level" → "Level", "LFO > Pitch" → "→ Pitch"), and formatParam picks the unit (time keys in ms / s, "(dB)" labels in dB, 0..1 as %, TimeDivision indices by name, plus a small key → unit table). DeviceLayoutsTest checks that every parameter of every laid-out device is on exactly one card and that knob labels stay short. A device missing from DeviceLayouts falls back to one card with all its parameters.

Fit above the keyboard (0.36.1). Instruments pin an audition keyboard, which leaves the editor about 460 dp on a 20:9 phone, of which the title, preset bar and tab strip take about 170. A page should therefore stay under ~290 dp (one card with a drawing, a choice row and a knob row is ~230; two such cards don't fit). That is why the Wavetable has one oscillator per tab and separate AMP and MOD tabs (with more than five tabs the labels drop to 10 sp, so they fit the narrower landscape column). Its table drawing is a Viz.Wavetable(osc) inside each oscillator card (WavetablePreview), and LOAD TABLE is a Panel.action in Oscillator 1's title (LoadTableAction, WavetableEditor.kt). Tabs share the strip's width (up to seven fit) instead of scrolling sideways.

Recomposition pitfall (fixed in 0.35.1). Slot params live in a plain map that Compose can't observe; edits bump vm.revision instead. Because the compiler's strong skipping compares vm/slot by identity, a child composable that receives only those is skipped on a revision bump and shows stale values, and a Canvas lambda that captures only them is memoized and never redraws. So every control in Panels.kt (SpecKnob, Segmented, FaderBank, VizCanvas) takes rev: Int, and VizCanvas reads rev inside its draw lambda. Do the same in any new control.

5.4.1 Opening a device's settings from another tab

The Toolbox owns its editor state (editing in ToolboxScreen). Other screens ask for an editor through AppViewModel.openSlotEditor(index, returnTab), which stores a slotEditorRequest and switches to the Toolbox; ToolboxScreen consumes the request in a LaunchedEffect, opens the editor, and on CLOSE / Back returns to returnTab. The mixer's INSTRUMENT and FX dropdowns use it on long-press (RetroDropdown's optional onLongClick, with a haptic tick; a tap still opens the menu).

5.4.2 Three source trees: shared engine, Android UI, iOS UI (0.37.0)

  • core/ — the C++ engine both apps play through: model and file formats, sequencer and mixer (engine/), every instrument and effect, the sample store, MIDI parsing, ZIP, and host/ (EngineHost: the song, the engine, live-note queues, the master recorder and custom wavetable builds behind one lock the audio thread only try-locks). Tests: make -C ios core-test (on the Mac).
  • app/ — the Android app: Compose UI, the Kotlin model (the UI's state), file I/O, input and playback services. audio/AudioEngine.kt is the engine's face: it drives core/ through NativeEngine (JNI, src/main/cpp/jni_engine.cpp), and native_audio.cpp renders from it inside the Oboe callback. CMake builds core/ into libsizzle_native.so as an object library (the device makers are weak placeholders in core/src/fx/Registry.cpp; a static library would link the placeholders).
  • ios/app/ — the iOS app: SwiftUI, the AUv3 plugins, and the Objective-C++ session around the same core.

How the Kotlin model reaches the engine: after every edit (AppViewModel.touched → AudioEngine.requestSync, coalesced to one per main-loop turn), before every transport or routing call, and every 500 ms as a safety net, AudioEngine sends ProjectIo.save(project) to EngineHost::syncProjectText. The host parses it off the lock, compares it with the last text it applied (song settings, each pattern, arrangement, mixer, each toolbox slot) and copies only what changed under the lock, so an edit holds the audio thread off for microseconds and playback continues. Samples go across as they enter SampleStore (put / remove mirror into the native store). Transport, meters, scope and finished recordings are polled from a 10 ms thread.

The Kotlin engine is now only a reference, and lives in the test source set: app/src/test/java/.../audio (ReferenceEngine, SynthVoice, SynthPatch, Effects, AmbienceReverb, SampleVoice, MasterRecorder), .../frasil (FrasilVoice, FrasilPatch), .../echofield (GrainCloud) and .../wavetable (WaveVoice). The IosGolden* unit tests render it so the C++ can be checked bit for bit (make -C ios golden core-test). It is not in src/main, because nothing in the app calls it any more — there it would only be dead code in every APK. What the UI genuinely still needs to draw did stay in src/main: wavetable/WaveTables (table frames), audio/GrainSources (source peaks), audio/SampleStore + SoundFontLoader (sample decoding), and the three *Defs files (parameter and preset data, shared with the editors).

Parity rule: every feature or fix lands in both apps in the same change, with one shared version bump. Engine and DSP work goes into core/ only.

5.4.3 Bluetooth LE MIDI controllers (0.38.0)

Android lists a BLE MIDI device to MIDI apps only after some app has connected it. input/BleMidi.kt scans for the BLE MIDI service (03B80E5A-EDE8-4B33-A751-6CE34EC4C700, 15 s, low-latency mode), connects the chosen device with MidiManager.openBluetoothDevice and holds that MidiDevice open while Sizzle's MIDI runs; the device then reaches MidiInput through the ordinary device callback, so it is listed and played like USB gear. Connected addresses are remembered (SettingsStore.bleMidiDevices) and reopened by address at start, without a scan. Permissions: BLUETOOTH_SCAN (neverForLocation) + BLUETOOTH_CONNECT on Android 12+, ACCESS_FINE_LOCATION with ACCESS_COARSE_LOCATION (the platform treats FINE as an upgrade of COARSE and refuses a FINE-only request; make lint enforces it) and the legacy BLUETOOTH / BLUETOOTH_ADMIN on 8-11, asked for when SCAN is first tapped. The emulator has no usable Bluetooth radio (its Bluetooth service crashes on a scan); test on a phone.

iOS (ios/app/Host/BluetoothMidi.swift): the system panel (CABTMIDICentralViewController) finds and connects; when it closes, the connected BLE MIDI peripherals are remembered and reconnected at launch through CoreBluetooth (best effort: iOS decides whether that brings the CoreMIDI source back without the panel).

5.5 Sizzle as a background MIDI sound module

Goal: another app (Mikro Seq, a DAW, a controller app) plays Sizzle's mixer over MIDI while Sizzle is in the background, like an iOS Inter-App Audio instrument.

The problem. Android 14+ freezes a cached (backgrounded, no foreground service) process within seconds; a frozen process receives no MIDI. The media PlaybackService is foreground only while the transport plays (media3 drops foreground on pause, and its notification manager re-derives that state from playWhenReady asynchronously, so overriding onUpdateNotification cannot pin it).

The fix.

  • SoundModuleService: a plain foreground service (type mediaPlayback; it does render audio) with its own low-importance notification showing the number of open MIDI sources and a Stop action. Started by SizzleApp.setSoundModuleEnabled and on every MainActivity.onResume while the setting is on (a foreground start from the background is refused, so the next resume heals a refused or killed service). START_NOT_STICKY for the same reason.
  • Trigger = a setting, not "a source is connected". MidiManager lists every installed app's virtual MIDI device permanently (Mikro Seq's "Mikro Seq" port is there whether or not it runs), so "connected" is nearly always true; and a source appearing while Sizzle is already in the background could not start a foreground service anyway (Android 12+ background-start ban; MIDI is not an exemption).
  • MidiSoundModule (pure Kotlin, unit-tested) is the routing: Note On/Off on channel N → AudioEngine.busNoteOn/Off (every mixer track on N); CC 123 / 120 release the channel; real-time bytes → MidiClock.handleRealtime. It tracks held notes per source and releases them when MidiInput sees the source go away (onDeviceRemoved) or MIDI is closed. Each MIDI port delivers on its own thread, so the module serialises entry with one lock; engine calls happen on that thread (as touch auditions do from the main thread; see §7).
  • Ownership. The engine and the MIDI ports are reference-counted in SizzleApp (acquireEngine/acquireMidi by owner name): the Activity, the PlaybackService and the SoundModuleService each hold a reference, so destroying the Activity no longer closes MIDI while a service runs.
  • The MIDI clock follow (Start/Stop/tempo) and the clock sender's providers are wired in SizzleApp.wireMidi, not the ViewModel, and the clock toggles are restored there; the ViewModel only redraws on MidiClock.followedTempo. While sound-module mode is on, clock Start/Stop are ignored (0.29.2): the sender's notes already play, and starting Sizzle's own song too doubled them (e.g. a song just imported from Mikro Seq) out of reach of the sender's mutes. Tempo is still followed.
  • Punch-in recording stays UI-driven: the module mirrors notes onto InputRouter as NoteOn(…, sounded = true), which the ViewModel records but does not play again. With no UI collecting, the router drops them.

Which sources, and staying connected (0.29.0). MidiInput keeps every device that can send to us in sources (a StateFlow<List<MidiSource>> the Setup screen lists with a switch each). Sources are listened to unless switched off; the off-set is persisted as MidiSourceKeys (type + maker/product/name + publishing service or Bluetooth address), because Android's device id changes on every reconnect. The trap this solves: when the app behind a virtual source dies and restarts (crash, update, force stop), Android keeps the device, keeps our connection record, drops its service binding, and tells clients nothing: no onDeviceRemoved, no onDeviceStatusChanged (checked on Android 15: dumpsys midi shows Status: null … mServiceConnection: null). Our MidiOutputPort just goes silent. So a worker thread probes each open virtual source every 3 s with MidiDevice.openOutputPort(0) (null from a dead server; a live one's probe port is closed at once) and reopens dead ones through MidiManager.openDevice, which makes Android rebind the app's MIDI service. refresh() runs on every Activity resume and the Setup "Reconnect" button closes and reopens everything. A status report of zero open output ports while we hold one is treated as dead too (events within 1 s of our own open/close are ignored). USB and Bluetooth sources are not probed: Android reports their removal. MidiInput logs connects/reconnects under the SizzleMidi tag.

Recording on the clock (0.34.0). MidiClock.onTransport reports every Start/Continue/Stop byte, before the receiveEnabled gate, and SizzleApp forwards it to AudioEngine.externalClockStart/Stop. The master recorder's state machine treats "the sequencer plays OR an external clock runs" as running: Start begins an armed take (maybeStartRecording), and the TAIL countdown starts on the edge where both have stopped. pause() / stop() clear the external flag, so Sizzle's own Stop ends a clock-started take. ClockRecordingTest covers start, tail and stop.

Tracing (0.29.1). input/MidiTrace logs, when switched on with adb shell setprop log.tag.SizzleMidiTrace VERBOSE (re-read every 500 ms, free when off), every received packet (recv <source> [bytes] <decoded> late=…ms), each note handed to the engine with the strips it reaches (AudioEngine.describeBusTargets: "strip1 SAMPLER pad3", "no strip on channel 10", "pad empty (silent)") and a [Sizzle transport PLAYING] flag, and clock Start/Stop acting on the transport. Mikro Seq's debug builds log what they send under MidiOut, so adb logcat -s MidiOut SizzleMidiTrace lines the two up. Checked this way on the Android 15 emulator (Mikro Seq 0.13.0): 666 note messages, sent = received byte for byte and in order, median 0.6 ms late; 243 notes over 20 s all balanced; muting a Mikro Seq track stops its notes at the sender. The trap found: with "Receive MIDI clock" on, Mikro Seq's Start also starts Sizzle's own sequencer, so a song imported from Mikro Seq plays along with the live notes, and Mikro Seq's mutes can't reach it.

Verifying. With the setting on and the app backgrounded, adb shell dumpsys activity processes must not show isFrozen=true for the Sizzle process, and another app's notes must keep sounding. Opening a virtual port binds the other app's MidiDeviceService, which keeps that app alive, not Sizzle — hence the service here.

5.6 Opening .sng files from other apps

MainActivity accepts ACTION_VIEW (content:/file:; types application/x-sizzle-song, application/octet-stream, text/plain; or any type whose path ends in .sng, and no type with that path) and ACTION_SEND (same three types; EXTRA_STREAM / clip data, or the song itself in EXTRA_TEXT). io/SongIntents reads at most 4 MB off the main thread and sniffs the content (SngFormat.looksLikeSng), because text/plain and octet-stream match far more than songs. The ViewModel then holds an incomingSong, and App.kt asks before SngFormat.importInto replaces the patterns and arrangement (mixer and instruments stay); the intent is consumed so a rotation can't offer it twice. Mikro Seq's "Open in Sizzle" sends its exported .sng this way with a FileProvider URI.

One-tap transfer from Mikro Seq (0.36.0). Mikro Seq's "Current to Sizzle" button sends the same ACTION_VIEW plus the boolean extra cc.tiredsysadmin.android.sizzle.extra.REPLACE. SongIntents.isTrustedReplace skips the dialog only when the action is ACTION_VIEW, the extra is true, the URI is content:, and PackageManager.resolveContentProvider(authority) belongs to cc.tiredsysadmin.android.mikroseq. Mikro Seq's provider isn't exported, so only Mikro Seq can grant us such a URI; any other sender, extra or not, gets the dialog. The lookup needs Mikro Seq in the manifest's <queries> (package visibility, Android 11+). Because nothing asks first, replaceFromMikroSeq saves the current song in full to the library as "Before Mikro Seq import" (one rolling backup, overwritten on every transfer), then imports and shows a toast. Checked on the emulator: the Mikro Seq button replaces without a dialog; the same intent from Sizzle's own FileProvider still asks.

5.7 The Morph Pad (FRASIL port, MPL-2.0)

The Morph Pad instrument (ToolboxType.MORPH_PAD) is the drone voice of FRASIL 3.3 (commit e7a8fb2), a custom firmware for the M-VAVE FM-1 by Styves Goupil, translated from C to Kotlin. It was chosen from the FM-1 firmware hub (thefirmwarehub.com) because it was the cleanest evolving-pad engine there and its licence fits.

Licence boundary. FRASIL is MPL-2.0, which is file-level copyleft. The three files in frasil/ are derived from FRASIL's files, so they stay MPL-2.0: they keep FRASIL's copyright line and the MPL header, and their source must stay published. MPL-2.0 §3.3 lets them live in a GPL program (none of FRASIL's files is marked "Incompatible With Secondary Licenses"); the rest of Sizzle stays GPL-3.0-or-later. The text is in LICENSES/MPL-2.0.txt. Keep FRASIL-derived code in that package. Glue code that only uses it (SynthVoice, AudioEngine, the editor) is Sizzle's own and stays GPL. Most other firmwares on the hub are GPL-3.0-only; porting from those would make the whole app GPL-3.0-only, so that was avoided.

What was ported (engine/dsp/frasil.c, engine/params.c): the voice's three layers (CHOIR: three PolyBLEP saws with SHAPE/SOFT and a one-pole or TPT SVF filter; PARTIALS: eight magic-circle partials with tilt, odd, stretch, formant, EVOLVE and BEAT; BREATH: noise or grains through three resonators), MOTION (an Ornstein-Uhlenbeck walk per drifting value, a step per 256-frame block), TIDE, the mix's DC blocker, warmth and the BODY high-pass, and the 36 drone presets. Left out: GLINT, BASS, LEAD, the NUAGE reverb (use an Ambience insert), the master effects, stereo SPREAD, pressure and FRASIL's load shedding.

Where it plugs in. A Morph Pad note is played by a SynthVoice whose SynthPatch.pad is set: the voice then forwards everything to its embedded FrasilVoice. That way every existing synth pool (sequencer, mix-bus/MIDI sound-module, editor audition) plays pads with no change to allocation, stealing or note-off. AudioEngine.patchForSlot/refreshSynthPatches build the patch (FrasilPatch.from(slot)) only when the slot version changes, so knob turns and MIDI-LFO moves reach held notes; FrasilVoice glides every value to the new patch over ~25 ms (FRASIL glides its parameters the same way).

Rendering. FrasilVoice.render() is per sample, as Sizzle's voices are, but internally FRASIL's structure is kept: a 256-frame block recomputes frequencies, filter coefficients and drift; 64-frame chunks are computed at once and handed out a sample at a time. FRASIL's 44.1 kHz per-step constants are rescaled with its own br_k rule (1 - (1 - k)^(44100/fs)). The mono mix is centre + sides at -3 dB. TIDE is one shared sine in FRASIL; here FrasilClock (advanced once per fillBlock) is the shared time, so the voices of a chord swell together.

Morph is Sizzle's addition. FRASIL morphs whole scenes over 1–120 s. Here a pad names one factory sound as MORPH TO; MORPH sets where a note starts between the slot's own sound and that one (an LFO can move it), and MORPH TIME (seconds) carries each held note the rest of the way on a smoothstep. Float values are interpolated; the choir filter TYPE switches at the halfway point.

Cost. On a desktop JVM, 32 voices of the heaviest setting run at about 7 % of real time (FrasilVoiceTest.cpuBudgetForFullPolyphony). The level of a held pad is matched to a synth note (aHeldPadIsAboutAsLoudAsASynthNote).

5.8 The Grain Cloud (ECHOFIELD port, MIT)

The Grain Cloud instrument (ToolboxType.GRAIN_CLOUD) is the granular engine of ECHOFIELD FM-1 (commit 4734e97) by Philip Bos, translated from C to Kotlin. It was picked as the granular drone machine from the FM-1 firmware hub because it is a real sample-to-cloud instrument with note pitch, float maths, and the MIT licence: the two ported files keep the MIT notice and Philip Bos's copyright (LICENSES/MIT.txt); nothing else is affected.

Ported (app/dsp/engine.c, app/params.c, app/presets.c): the six modes (CLOUD, DUST, TAPE, BLOOM, PULSE, DRIFT) and their control laws (compute_ctl), the asynchronous scheduler and PULSE's euclidean 16 steps, grain spawning (size, pitch, harmony intervals, reverse, scatter, the colour filter, overlap-normalised level), the five windows, the gate (ATTACK/RELEASE), the source swap fade, the random walks and LFOs, FREEZE, and the auto-level that keeps the cloud near one loudness. Left out: ECHOFIELD's effects (filter, drive, echo, reverb with shimmer, tape), WIDTH/pan (Sizzle's channels are mono), the DRIFT ORACLE, LATCH and the performance effects. Put Ambience / Tape Delay / Tape Engine on the channel.

One cloud per mixer channel, not a voice per note. ECHOFIELD has a single cloud whose grains take their pitch from the held notes in turn (round robin, up to 8); eight independent clouds would cost eight times as much and break the overlap normalisation. So AudioEngine owns clouds[4] (one per channel) plus an auditionCloud for the editor keyboard, outside the voice pools: playNote, busNoteOn/Off, releaseBus, releaseTrackVoices, allSeqVoicesOff and panic route notes to the cloud. Notes carry an owner (a tracker track, OWNER_SEQ for an arpeggio's, OWNER_LIVE for keys/MIDI), so a track's next note and the transport stop release only the sequencer's notes and never a note held on a MIDI keyboard. A cloud renders while its channel's instrument is a Grain Cloud (cloudOn), every sample into channelSum like a voice; its patch (GrainPatch.from) is rebuilt only when the slot's version or the tempo changes.

Sources. ECHOFIELD's own factory sounds come from a generator outside its public repository, and its published copies are 16–22 kHz ADPCM, so Sizzle makes ten sources of its own (audio/GrainSources.kt, GPL): felt piano, bowed glass, music box, warm pad, strings, low drone, rain field, kalimba, breath choir, glass tines — six seconds each at 24 kHz, pitched material on C (note C4 plays a source at its own pitch), rendered on a background thread at startup (prewarm). GrainSources.get never blocks; the cloud asks every control block, so a source that is still rendering simply starts when ready. SOURCE "Custom" plays the slot's own sample, loaded (WAV, or an SF2/XI's sample) or recorded in the editor. It is kept under the SF2/XI loader's keys (sfSample / sfFile), so preset saving, project bundles and startup rehydration handle it with the same code, and AppViewModel.setGrainSample writes the WAV into the preset folder at once, so a custom source survives a restart without saving a preset.

Level and cost. The auto-level holds a sounding cloud near RMS 0.126, which is about a synth note's level (GrainCloudTest.aCloudIsAboutAsLoudAsASynthNote). Four dense clouds (32 grains each) took about 1.3 % of real time on a desktop JVM.

5.9 The Wavetable synth (Sizzle's own)

The Wavetable instrument (ToolboxType.WAVETABLE) was the third pick from the FM-1 firmware hub, but the candidates there (Clipper's WAVE engine, TastyWaves) are GPL-3.0-only: copying them would have made the whole app GPL-3.0-only. So it was written from scratch with the standard techniques they also use; no code was taken.

Tables (WaveTables). A table is up to 256 single-cycle frames (16 in the factory set). Each frame is kept as a spectrum (cosine/sine of harmonics 1..512) and rendered by an inverse FFT into one mip level per octave: level k holds 512 >> k harmonics in max(64, 4·harmonics) samples, the top quarter of its harmonics faded with a raised cosine so switching levels is inaudible. The voice picks, every 16 samples, the level whose top harmonic (times BEND's steepening) stays under 0.45·fs — WavetableTest.aHighSawDoesNotAlias measures the off-harmonic energy of a C7 saw at about 3e-5. Reads are linear inside a cycle (four samples per top harmonic make that clean) and linear between neighbouring frames.

Factory tables are formulas (no audio ships): Classic (sine → tri → saw → square → pulse), PWM, Vowels (moving formants), Harmonic Sweep, Sync, FM, Organ (drawbar registrations), Fold, Digital (bit reduction), Glass (sparse harmonics), Odd Even, Comb (moving notches). They are built on a background thread at startup (prewarm); a table not ready yet is silent rather than blocking.

Import. LOAD TABLE takes a WAV: Serum's clm chunk gives the frame length; otherwise 16384 samples is read as WaveEdit (64 × 256), then 2048-, 256-, 1024- or 512-sample frames by divisibility (Frame Size overrides it). The table is built on the UI thread at import; the WAV is kept like the Grain Cloud's custom source (sfSample/sfFile, a copy in the preset folder), so after a restart only the WAV comes back and WaveTables.forSample rebuilds the table once on its worker.

Voice (WaveVoice, played inside SynthVoice like the Morph Pad): two oscillators (table, POSITION, octave/semi/fine, level, BEND), up to 4 unison copies spread ±30 cents, a sub sine, noise, tanh drive, a TPT state-variable filter (low/band/high), a linear amp envelope, a mod envelope (to position and cutoff) and a tempo-synced LFO (to position, pitch, cutoff). BEND is a two-segment phase warp, as in phase-distortion synthesis. 32 voices with 2 oscillators × 4 unison took about 6 % of real time on a desktop JVM.


6. How to extend

Add a new instrument or effect

  1. Add an entry to ToolboxType (model/Toolbox.kt) with its ParamSpec list.
  2. Teach the engine how to sound it: It all happens in core/ (C++), which is what both apps play — never in the Kotlin reference, which only follows so the golden comparison still holds:
    • Instrument: handle its type where the engine picks a voice per channel (see how NES_SYNTH, SAMPLER and SOUNDFONT are dispatched in core/src/engine/Engine.cpp).
    • Signal effect: add a processor under core/src/fx/ implementing sizzle::Effect (core/include/sizzle/Effect.hpp) and register its maker in core/src/fx/Registry.cpp; the per-channel insert chain picks it up automatically, and so does the AUv3 wrapper once it is in ios/app/components.txt.
    • MIDI effect (arp/transpose/LFO-style): hook into the sequencer instead of the signal path (see advanceArps / applyLfos in Engine.cpp).
    • Keep the reference in step: mirror the change in the Kotlin file under app/src/test/.../audio (or frasil / echofield / wavetable), then make -C ios golden core-test to check the two sample for sample. The Toolbox picker, parameter editor, and preset save/load all work automatically from the ParamSpec list (the editor then shows one card with every parameter).
  3. Group its controls: add a case to DeviceLayouts.pagesFor (cards, tones, drawings; see §5.4.0) and add the type to nothing else — DeviceLayoutsTest fails if a parameter is missing or listed twice. A device that needs a custom gesture can ship a bespoke editor instead (see ui/toolbox/DelayEditor.kt, SamplerEditor.kt) and join the test's bespoke set.

Add a new input gesture/control

  1. Add a case to InputAction.
  2. Emit it from each source (KeyboardInput, GamepadInput, MidiInput) and/or a Compose gesture.
  3. Handle it once in AppViewModel.onAction.

Add a new color theme

Add a RetroPalette to RetroPalette.ALL in ui/theme/Theme.kt. It appears in the Settings theme picker immediately.


7. Threading & performance notes

  • The audio render loop is Engine::fillBlock in core/src/engine/Engine.cpp, called from the Oboe real-time callback (src/main/cpp/native_audio.cpp) — all C++, with no JVM call on the audio thread, so no GC pause can glitch it. It must never allocate, lock or block. Keep it that way: the active-voice index lists are rebuilt once per block, per-channel mixer gains and FX-chain pointers are hoisted out of the per-sample loop, and EngineHost only ever try-locks. (AudioEngine.startAudioTrack keeps a Kotlin MAX_PRIORITY loop as the fallback when Oboe cannot start; it calls the same nativeRender.)
  • Timing is derived from counting audio samples (samplesPerLine), not from timers, so playback never drifts.
  • UI ⇄ audio sharing crosses through text: ProjectIo.save plus EngineHost::syncProjectText, which diffs and copies only what changed (§5.4.2). save is therefore a hot path, not just the file writer — it builds into one pre-sized buffer, and AudioEngine.requestSync coalesces a burst of edits (a drag fires one per pointer event) into one sync per SYNC_COALESCE_MS.
  • The transport poller (AudioEngine.start) runs at 100 Hz only while the song plays or a take is armed; stopped and idle it waits 100 ms a turn, and any transport call wakes it through a semaphore so the playhead is never late. AppModel.pollTransport does the same on iOS (30 Hz playing, 10 Hz idle).
  • Block size is BLOCK_FRAMES = 192 (~4 ms @ 48 kHz). Lower = tighter latency, higher = safer against underruns.
  • UI rendering: the pattern grid (PatternGrid) and arrangement roll (ArrangementRoll) are each drawn as ONE Canvas with a cached rememberTextMeasurer, not a tree of per-cell composables. This is what keeps the grid smooth while the playhead moves — a single draw pass instead of recomposing hundreds of Text nodes each frame. If you add grid features, draw them in the Canvas rather than adding child composables.
  • Arrangement model: each of the 8 lanes is tied to its own block (lane i ⟷ block i; Project.patterns holds 8 blocks). Toggling a beat cell on lane i enables block i at that beat; the sequencer plays it when the playhead crosses. Tap a lane number (left column) to edit that block in the tracker above.

8. File formats

Preset (PresetIo)

SIZZLE-PRESET 1
TYPE=NES_SYNTH
NAME=Lead
wave=Pulse25
attack=0.01
...

Copy/paste from the Toolbox parameter editor uses this exact text.

Preset bundle (.zip)

What SHARE sends for a Sampler, SF2/XI, Grain Cloud or Wavetable preset: a ZIP holding <name>.szp and the WAVs it names. In a song, pads name sample ids (padN, sfSample); in a bundle they name files (padNFile=<name>_padN.wav, sfFile=<name>_sf.wav). Android: PresetLibrary.bundleForShare / importZip. iOS: core/src/io/PresetBundle. The two are checked against each other. IosGoldenPresetBundle (part of make -C ios golden) writes a bundle with Android's code for core/tests/bundle_test.cpp to import. bundle_test also writes app/src/test/resources/presetbundle/ios_sampler.zip (checked byte for byte), which PresetBundleInteropTest imports with Android's code.

MIDI mapping (MidiMapIo, .szm, 0.39.0)

One device's parameter → MIDI CC mapping, exported and imported from the ⇄ MIDI panel. Written and read by io/MidiMapIo.kt (Android) and core/src/io/MidiMapIo (iOS); both tests read the same fixture, app/src/test/resources/midimap/filter.szm.

SIZZLE-MIDIMAP 1
# comments start with '#'
TYPE=FILTER
NAME=Sweep
cutoff=74
resonance=71

The header and TYPE (a ToolboxType name) are required; NAME is the slot's name, for information. Then one parameter=CC line per mapping (CC 0..127), in the device's parameter order. Reading skips anything else, and a repeated parameter or CC keeps its first line. Importing needs the same TYPE and replaces the slot's mappings. Parameters the device doesn't have are skipped, and a CC that another parameter (in any slot) used moves to the imported one, because one control drives one parameter. In the song, a mapping is the slot value midicc@<parameter>.

Interchange .sng (SngFormat)

The desktop sizzletracker format, read the way the desktop reader does it: block <name...> <length> <numTracks> (names may contain spaces; the trailing integers are read from the right), track <name> <channel 0..15>, step lines tick note vel chan (OFF / === = note off, .. = default), roll (# plays, x = off marker, an extension), # comments. group, scale, root, kind and intro are ignored; loop turns the arrangement loop on. Mapping limits: 8 blocks (on-roll blocks win when a file has more, e.g. Mikro Seq's "Cn muted" blocks), 4 tracks per block (a Tn keeps its slot when free, else takes the next free one, extras are dropped), block length capped at 1024 lines like the desktop reader. Fixtures from Mikro Seq (4/4 and 3/4) live in app/src/test/resources/mikroseq/.

Project .sng (ProjectIo)

Line-oriented, sectioned ([PATTERN ...], [ARRANGEMENT ...], [MIXER], [TOOLBOX]). Only non-empty cells are written. It is fully round-trip safe.


9. Current status — implemented vs. TODO

This is an honest map so you know where the edges are. The architecture and all four tabs are in place and interactive, and the feature set below is implemented and working; the short "Remaining / optional" list at the end is polish and interchange niceties, not functional gaps.

Implemented and working

  • Full 4-tab UI, retro monospace theme (+ theme switching), tab navigation.
  • Tracker pattern grid: beat/bar coloring, cursor, tap-to-focus, drag-to-edit with haptics, scale-aware note entry, transport toolbar, length/scale/root.
  • Arrangement roll: 8 lanes, place/clear blocks, playhead follow, loop toolbar with A/B enable + repeat counts.
  • Mixer: 4 strips, instrument/FX routing to toolbox, MIDI ch, volume, mute/solo.
  • Background MIDI sound module (§5.5) and opening .sng from other apps (§5.6), for Mikro Seq's "Open in Sizzle" (0.28.0).
  • Toolbox: 16 slots, device picker, auto-generated parameter editor, preset copy/paste (text).
  • Audio engine: dedicated thread, sample-accurate sequencer, NES-style synth (pulse/tri/noise + ADSR), per-track mute/solo/volume, live note audition.
  • Arrangement-driven playback (milestone 1 ✓): the sequencer walks a pre-expanded beat playlist (with A/B loop repeats) across all 8 lanes; each lane keeps its own within-pattern cursor so multi-beat blocks advance through the pattern. Falls back to looping the active pattern when the arrangement is empty. Voices are a lane×track matrix so lanes layer polyphonically.
  • Per-channel effect DSP (milestone 3 ✓): each mixer channel runs an insert chain built from its FX slots — Tape Delay, Digital Reverb, Filter (LP/HP/BP), Bitcrusher, and 10-band EQ are real processors in core/src/fx/. Effect parameters update live per audio block; add/remove rebuilds the chain.
  • Sampler instrument ✓: WAV import (SAF file picker) + ad-hoc mic/USB recorder (audio/SampleRecorder.kt), decoded to a mono cache (audio/SampleStore.kt), played pitched + sliced by core/src/sampler/SampleVoice.cpp. Its editor (ui/toolbox/SamplerEditor.kt) shows a waveform with two draggable slice markers, start-octave + volume, and a two-octave audition keyboard. Each (lane, track) has both a synth and a sample voice; the channel instrument type selects which one a note triggers.
  • Input: keyboard (nav + typing-piano + transport), gamepad (buttons + sticks + hat), MIDI in (note + CC, USB & BT), all via the unified router.
  • MIDI-learn & gamepad rebind ✓: the Settings tab lists every bindable action with its current binding and a Learn button; arming it sets the router's learnMode, and the next unbound CC / gamepad button is written into MidiInput.ccBindings / GamepadInput.bindings (the handlers are now app singletons shared with Settings). Bindings are clearable per action.
  • MIDI effects (Transposer / Arpeggiator / LFO) ✓: Transposer shifts notes by its semitone amount; the Arpeggiator octave-cycles a captured note (Up/Down/UpDown/Random, 1–4 octaves) at a tempo-synced division (AudioEngine.advanceArps); the LFO (applyLfos) modulates a chosen target parameter of another device around a captured centre (Sine/Tri/Saw/Square/S&H), with a target picker in its editor (ui/toolbox/LfoEditor.kt).
  • USB / audio device selection ✓: Settings → Audio Devices lists the system's output and input devices; choosing one routes the engine's AudioTrack and the recorder's AudioRecord via setPreferredDevice (API 28+), so a USB DAC / USB audio interface can be used for playback and recording.
  • Full MediaSession ✓: playback/PlaybackService is now a media3 MediaSessionService hosting a session that wraps the engine via EnginePlayer (SimpleBasePlayer). This gives lock-screen controls, Bluetooth/headset media buttons, and the media notification for free, mirroring the on-screen transport.
  • Persistence: preset text I/O, a full-fidelity internal project text format (ProjectIo, keeps mixer/FX/instruments), AND desktop-compatible .sng read/write (io/SngFormat.kt) matching the reference sizzletracker line format (version/bpm/sig, block…endblock with roll/track/steps) — covered by passing JVM unit tests in app/src/test.
  • Background playback foreground service with Play/Pause/Stop notification.
  • Full C++ audio port ✓ (0.37.0): the whole DSP — sequencer, mixer, every instrument and effect, the master recorder — is core/, shared with the iOS app and driven over JNI. The Kotlin DSP it replaced lives on in the test source set (app/src/test/.../audio, frasil, echofield, wavetable) as the reference the C++ is checked against, so none of it ships in the APK.
  • Oboe / AAudio native output ✓ (default): src/main/cpp/native_audio.cpp opens a low-latency Oboe stream whose real-time callback pulls audio via JNI (audio/NativeAudioBridge.kt) from the SAME Engine::fillBlock the AudioTrack fallback loop reaches through nativeRender — so both backends produce identical sound, only the delivery path differs. Oboe is the default engine; it falls back to the AudioTrack loop only if it fails to initialise (or the native lib is absent), surfacing a popup with the reason (there is no user toggle). Built via NDK r27 (ndkVersion in app/build.gradle.kts) + CMake + the com.google.oboe:oboe:1.10.0 prefab AAR. All packaged .so files are 16 KB page-aligned (Android 15 / Google Play requirement): NDK r27 aligns ELF load segments to 16 KB and ships a 16 KB-aligned libc++_shared.so, Oboe 1.10.0's lib is aligned, our CMakeLists.txt also passes -Wl,-z,max-page-size=16384, and AGP stores each .so at a 16 KB-aligned offset in the APK. (Verify with llvm-readelf -l <lib>.so → LOAD Align 0x4000.)
  • SF2 / XI loader instrument ✓: audio/SoundFontLoader.kt extracts PCM from an .sf2 / .xi into the SampleStore, played back through the same SampleVoice path in core/ as the Sampler; edited via ui/toolbox/SoundFontEditor.kt (root note, volume, ADSR).
  • Master recording ✓: core/src/host/MasterRecorder.cpp renders the stereo master bus (plus a configurable FX tail) to a WAV in a user-chosen folder (SAF).
  • Stereo output & recording ✓: fillBlock renders interleaved stereo and the recorder captures two channels (voices/inserts are mono, so both channels carry the same sum).
  • Responsive landscape layout ✓ (ui/Responsive.kt): nav rail, side-by-side screens, two-column mixer/editors, wider on-screen keyboards for tablets/handhelds. Instrument editors (ParamEditor in ToolboxScreen.kt) pin their audition keyboard, or the Sampler's pads, on the right in landscape at the Toolbox tab's 1 : 1.3 split, and below the controls in portrait (1.7 : 1) (0.36.2).
  • Arrangement niceties ✓: 256-bar canvas with viewport-culled drawing, per-lane mutes, and centre-follow scrolling.
  • Per-bus soft-clip limiter ✓, sampler QoL (fire-on-tap, clear, normalize), theme import/export, and preset .zip bundle import/export.
  • Sample-pack builder ✓: tools/samplepack-builder.html, a standalone offline page that assembles importable Sampler .zip bundles.

Remaining / optional

  • Byte-exact desktop .sng compatibility. io/SngFormat.kt reads/writes the reference line format and round-trips musically; a field-for-field byte match with the CLI project layout is the remaining interchange nicety.
  • Route the Oboe backend through the chosen output device (Oboe setDeviceId), matching the AudioTrack path's device selection.
  • Block-rate FX processing. Insert effects are process(float) per sample, so a four-effect chain on four channels is 16 virtual calls per frame. Giving Effect a block entry point (defaulting to a loop over process) would let the heavier ports vectorise. Sample-for-sample identical if done carefully, but it touches every effect and the golden comparison, so it is its own change.

10. Testing suggestions

  • Pure model/ classes (Scale.step, TimeSignature, Pattern.resize, ProjectIo round-trip, PresetIo round-trip) are plain Kotlin — cover them with JVM unit tests first; they need no device.
  • For the engine, render a few blocks with a known pattern and assert the voice triggers on the expected sample offsets.