iOS couldn't import Android's Sampler preset bundle (a ZIP with the .szp and its WAVs) and shared sample presets as bare text naming iOS sample ids. - core/src/io/PresetBundle: import/export in Android's bundle layout (padNFile / sfFile), used by iOS IMPORT and SHARE - bundle_test imports a bundle written by Android's PresetLibrary (IosGoldenPresetBundle); PresetBundleInteropTest imports the iOS-written fixture with Android's importZip Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
950 lines
56 KiB
Markdown
950 lines
56 KiB
Markdown
# 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.<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.
|
||
|
||
```properties
|
||
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 | 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/<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 real-time sound engine (own thread)
|
||
│ ├── Transport.kt TransportState snapshot published to the UI
|
||
│ ├── SynthVoice.kt One synth note (3-osc subtractive), or a Morph Pad / Wavetable note (FrasilVoice / WaveVoice)
|
||
│ ├── GrainSources.kt The Grain Cloud's ten built-in sources, synthesised in the background
|
||
│ ├── 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
|
||
│
|
||
├── 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
|
||
│ ├── FrasilPatch.kt Parsed slot snapshot (+ morph target); FrasilClock (the shared TIDE time)
|
||
│ └── FrasilVoice.kt One pad note: choir + partials + breath, drift, tide, warmth
|
||
│
|
||
├── wavetable/ The Wavetable synth (Sizzle's own, GPL; see §5.9)
|
||
│ ├── WaveTables.kt Band-limited tables: FFT, one mip level per octave, 12 generated tables, WAV import
|
||
│ ├── WaveDefs.kt Its settings, 12 factory presets
|
||
│ └── WaveVoice.kt WavePatch + one note: 2 table oscillators, bend, unison, sub, SVF, 2 envelopes, LFO
|
||
│
|
||
├── echofield/ MIT: the Grain Cloud, ported from ECHOFIELD (see §5.8)
|
||
│ ├── EchofieldDefs.kt Its settings, 14 factory presets, the source list
|
||
│ └── GrainCloud.kt GrainPatch + one channel's cloud: modes, scheduler, grains, gate, auto-level
|
||
│
|
||
├── 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.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
|
||
`Page`s (tabs, shown only when there are several), each a list of `Panel`s (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 (`ReferenceEngine` and the voices and effects under `audio/`,
|
||
`frasil/`, `echofield/`, `wavetable/`) is now only a reference: the
|
||
`IosGolden*` unit tests render it so the C++ can be checked bit for bit
|
||
(`make -C ios golden core-test`). The UI still uses a few of those Kotlin classes
|
||
to draw (wavetable frames, Grain Cloud source peaks, sample decoding).
|
||
|
||
**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`
|
||
(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 `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.
|
||
|
||
**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](https://github.com/styvesgoupil/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](https://github.com/Philip-Bos/echofield-fm1) (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:
|
||
- **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 (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 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.
|
||
|
||
### 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 `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 <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 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.
|
||
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.
|
||
- **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.
|