Background MIDI sound module and opening .sng from other apps (v0.28.0)

- "Keep running as MIDI sound module" setting: a mediaPlayback foreground
  service (SoundModuleService) keeps Sizzle from being frozen in the
  background, so another app (Mikro Seq) can play its mixer over MIDI with
  the transport stopped. Notification shows open sources and has Stop.
- MIDI notes are routed by MidiSoundModule, owned by SizzleApp next to the
  engine, not by the ViewModel; the UI only mirrors/punches them in. Held
  notes are released per source on disconnect and on CC 120/123. MIDI clock
  follow is wired in SizzleApp. Engine and MIDI ports are ref-counted
  between the Activity and both services.
- MidiByteParser: running status, split packets, realtime, SysEx.
- VIEW/SEND intent filters for .sng (application/x-sizzle-song,
  application/octet-stream, text/plain, .sng path); confirm before replacing.
- SngFormat reader follows the desktop reader: spaced block names, comments,
  loop/group/scale/root, track slot fallback, on-roll blocks first, length
  cap. Mikro Seq 4/4 and 3/4 exports as test fixtures.
- CHANGELOG.md started; handover §5.5/§5.6 and user guide updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Reactorcoremeltdown
2026-11-12 22:11:18 +01:00
co-authored by Claude Opus 5.5
parent bcec71597d
commit fb9a219e27
26 changed files with 1590 additions and 141 deletions
+99 -8
View File
@@ -60,6 +60,9 @@ 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
@@ -139,8 +142,10 @@ Run `make dist` first and look at what landed in `dist/` before running
Touch ───▶│ (Compose gestures, call ViewModel) │
Keyboard ─▶ KeyboardInput ─┐ │
Gamepad ──▶ GamepadInput ──┤─▶ InputRouter (flow) ──┼──▶ AppViewModel
MIDI ─────▶ MidiInput ─────┘ │ │
└───────────────────────────────────────┘ │ reads/writes
MIDI ─────▶ MidiInput ──┬──┘ │ │
└────────────│───────────────────────────┘ │ reads/writes
▼ notes, all-notes-off, clock (observes MIDI notes,
MidiSoundModule ──▶ AudioEngine.busNote* punches them in)
▼
Project (the song)
▲
@@ -161,7 +166,14 @@ Three ideas hold it together:
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. **Two threads.** The UI runs on the main thread (Jetpack Compose). The sound
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
@@ -173,8 +185,8 @@ Three ideas hold it together:
```
cc.tiredsysadmin.android.sizzle
├── SizzleApp.kt Application = tiny DI container (Project, InputRouter, AudioEngine)
├── MainActivity.kt Hosts Compose UI; forwards HW key/motion events; starts MIDI + service
├── 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)
@@ -192,7 +204,9 @@ cc.tiredsysadmin.android.sizzle
│ ├── BindingStore.kt Persists gamepad/MIDI bindings
│ ├── KeyboardInput.kt KeyEvent -> InputAction (+ a 2-octave typing piano)
│ ├── GamepadInput.kt KeyEvent/MotionEvent -> InputAction (rebindable)
│ └── MidiInput.kt MIDI bytes -> InputAction (USB & Bluetooth via MidiManager)
│ ├── MidiByteParser.kt MIDI byte stream -> messages (running status, split packets, realtime, SysEx)
│ ├── MidiClock.kt MIDI clock send / follow
│ └── MidiInput.kt Opens MIDI sources (USB, BLE, other apps' virtual ports) -> MidiSoundModule / CC bindings
│
├── audio/ The real-time sound engine (own thread)
│ ├── Transport.kt TransportState snapshot published to the UI
@@ -215,14 +229,17 @@ cc.tiredsysadmin.android.sizzle
│ ├── 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
│ ├── 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
│ ├── 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
@@ -289,6 +306,66 @@ 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`.
- 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.
**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
@@ -358,6 +435,18 @@ 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 <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.
@@ -378,6 +467,8 @@ polish and interchange niceties, not functional gaps.
- 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
+8
View File
@@ -298,6 +298,11 @@ you delete stay deleted.
note ever hangs.
- **Project** — save / new / delete full projects on the device, and **Export /
Import `.sng`** for desktop interchange. (See [Files](#files-projects--sharing).)
- **MIDI Sync → Keep running as MIDI sound module** — keeps Sizzle playing
incoming MIDI while it is in the background, so another app (Mikro Seq, a
DAW) can use it as its synth. A notification shows while it is on; its
**Stop** button turns it off. Each mixer track plays the notes on its MIDI
channel.
- **Audio Devices** — route **Output** and **Input** to USB or built‑in.
- **Color Theme** — pick a palette, or **Export / Import `.szt`** themes. Stock
themes can't be deleted; imported ones join the list.
@@ -344,6 +349,9 @@ One‑shot actions (play, stop, tab switch, note/clear) still fire once even if
| **`.szt`** | A colour palette | Sharing themes |
Projects auto‑save, so a crash or process death resumes where you left off.
Other apps can hand Sizzle a `.sng` directly (Mikro Seq's **Open in Sizzle**,
a file manager's **Open with**, the share sheet); Sizzle asks before it replaces
the current song's notes and arrangement.
Export a `.sng` before wiping data if you want a portable copy of the song.
---