# 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 + 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..`, 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. ```properties android.versionName = 0.22.0 android.versionCode = 49 ``` 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. `android.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 | Signing | Use | |------|-----------|---------|-----| | `debug` | yes | debug key | breakpoints, instant-run edits | | `staging` | **no** | debug key | anything on a real device | | `release` | no | **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. ### 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/_.apk -> rcmd@garage.rcmd.space:/var/lib/fdroid/unsigned dist/.yml -> rcmd@garage.rcmd.space:/var/lib/fdroid/metadata ``` `_.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 real-time sound engine (own thread) │ ├── Transport.kt TransportState snapshot published to the UI │ ├── SynthVoice.kt One NES-style voice: pulse/triangle/noise + ADSR │ ├── SampleVoice.kt Pitched + sliced playback of a decoded sample │ ├── SampleStore.kt Process-wide decoded-PCM cache + WAV encode/decode │ ├── SampleRecorder.kt Ad-hoc mic/USB capture into a sample │ ├── SoundFontLoader.kt Extract PCM from an .sf2 / .xi into the SampleStore │ ├── Effects.kt Insert DSP: TapeDelay, Filter, Bitcrusher, GraphicEq (+ AudioEffect API) │ ├── AmbienceReverb.kt FDN reverb processor │ ├── MasterRecorder.kt Renders the master bus (with FX tail) to a WAV │ ├── NativeAudioBridge.kt JNI bridge to the Oboe callback (calls fillBlock) │ └── AudioEngine.kt Oboe/AudioTrack + sample-accurate sequencer + voice/FX mixing │ ├── cpp/native_audio.cpp Low-latency Oboe stream; RT callback pulls audio via JNI │ ├── 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 `ParamSpec`s. 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.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>` the Setup screen lists with a switch each). Sources are listened to unless switched off; the off-set is persisted as `MidiSourceKey`s (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. **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 [bytes] 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. --- ## 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: - **Instrument**: handle its type where the engine picks a voice per channel (see how `NES_SYNTH`, `SAMPLER`, and `SOUNDFONT` are dispatched in `AudioEngine`). - **Signal effect**: add a processor in `audio/Effects.kt` implementing `AudioEffect` and register it in `AudioEffect.create(...)`; the per-channel insert chain picks it up automatically. - **MIDI effect** (arp/transpose/LFO-style): hook into the sequencer instead of the signal path (see `advanceArps` / `applyLfos` in `AudioEngine`). The Toolbox picker, parameter editor, and preset save/load all work automatically from the `ParamSpec` list. A device with many parameters can ship a bespoke editor (see `ui/toolbox/DelayEditor.kt`, `SamplerEditor.kt`). ### 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 in `AudioEngine.renderLoop()` on a `MAX_PRIORITY` thread. It **must never allocate or block**. Keep it that way. - Timing is derived from *counting audio samples* (`samplesPerLine`), not from timers, so playback never drifts. - UI ⇄ audio sharing is lock-free by design (audio reads plain fields). This can produce a one-frame-stale read during a simultaneous edit — harmless for a tracker. If you ever add compound state that must be read atomically, publish it as an immutable snapshot (like `TransportState`) rather than adding locks. - 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. ### Interchange `.sng` (`SngFormat`) The desktop sizzletracker format, read the way the desktop reader does it: `block ` (names may contain spaces; the trailing integers are read from the right), `track `, 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 `audio/Effects.kt`. 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 `audio/SampleVoice.kt`. 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. - **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 `AudioEngine.fillBlock` the AudioTrack loop uses — 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 .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 as the Sampler; edited via `ui/toolbox/SoundFontEditor.kt` (root note, volume, ADSR). - **Master recording** ✓: `audio/MasterRecorder.kt` 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. - **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. - **Full C++ audio port.** The DSP currently runs in Kotlin behind the Oboe callback (via JNI). Porting the hot path to C++ would remove JVM/GC from the real-time thread — a performance hardening step, not a functional gap. - **Route the Oboe backend through the chosen output device** (Oboe `setDeviceId`), matching the AudioTrack path's device selection. --- ## 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.