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
+27
View File
@@ -0,0 +1,27 @@
# Changelog
Sizzletracker for Android (`cc.tiredsysadmin.android.sizzle`). One entry per
version in `versions.properties`; versions before 0.28.0 are described in the git
log (one commit per version).
## 0.28.0 (versionCode 57)
- **Background MIDI sound module.** New setting "Keep running as MIDI sound
module" (Setup → MIDI Sync). While on, a foreground service with a notification
(open-source count, Stop) keeps Sizzle from being frozen in the background, so
another app such as Mikro Seq can play Sizzle's mixer over MIDI with Sizzle's
transport stopped and its screen gone.
- MIDI notes are now played by a sound-module layer that lives with the engine,
not the UI. The UI still shows them and punch-in still records them.
- Notes held by a MIDI source are released when it disconnects; All Notes Off
(CC 123) and All Sound Off (CC 120) release a channel.
- MIDI input understands running status and messages split across packets.
- MIDI clock follow (Start/Stop/tempo) works without the UI.
- **Open `.sng` from other apps**: "Open with" / "Share to" Sizzletracker for
`.sng` files (`application/octet-stream`, `text/plain`,
`application/x-sizzle-song`, or the `.sng` extension). Sizzle asks before it
replaces the current song's patterns and arrangement.
- `.sng` import follows the desktop reader: block names with spaces, `#`
comments, `loop`, `group`/`scale`/`root` lines, track slots by number with
fallback, on-roll blocks kept first when a file has more than 8, block length
capped. Mikro Seq exports in 4/4 and 3/4 import correctly.
+56
View File
@@ -50,6 +50,53 @@
<meta-data
android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="@xml/usb_device_filter" />
<!-- Open a .sng song handed over by another app (Mikro Seq's "Open in
Sizzle", a file manager, the share sheet). Senders rarely have a
type for .sng, so the generic types are accepted too; the content
is sniffed (io/SongIntents.kt) and the user confirms before the
current song is replaced. -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="content" />
<data android:scheme="file" />
<data android:mimeType="application/x-sizzle-song" />
<data android:mimeType="application/octet-stream" />
<data android:mimeType="text/plain" />
</intent-filter>
<!-- …any type, by the .sng extension (pathPattern needs a host; the
repeats cope with dots earlier in the path, which a single
non-greedy ".*" pattern would not match). -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="content" />
<data android:scheme="file" />
<data android:host="*" />
<data android:mimeType="*/*" />
<data android:pathPattern=".*\\.sng" />
<data android:pathPattern=".*\\..*\\.sng" />
<data android:pathPattern=".*\\..*\\..*\\.sng" />
</intent-filter>
<!-- …and the same by extension when the sender gave no type at all. -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="content" />
<data android:scheme="file" />
<data android:host="*" />
<data android:pathPattern=".*\\.sng" />
<data android:pathPattern=".*\\..*\\.sng" />
<data android:pathPattern=".*\\..*\\..*\\.sng" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/x-sizzle-song" />
<data android:mimeType="application/octet-stream" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
<!-- Exposes saved preset files (and zip bundles) as content:// URIs so they
@@ -84,5 +131,14 @@
</intent-filter>
</service>
<!-- Background MIDI sound module: a foreground service held while the
"Keep running as MIDI sound module" setting is on, so the cached-app
freezer never suspends Sizzle while another app plays it over MIDI.
mediaPlayback because that is what it does: it renders audio. -->
<service
android:name=".playback.SoundModuleService"
android:exported="false"
android:foregroundServiceType="mediaPlayback" />
</application>
</manifest>
@@ -5,6 +5,7 @@ package cc.tiredsysadmin.android.sizzle
import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
@@ -15,14 +16,19 @@ import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewmodel.initializer
import androidx.annotation.OptIn
import androidx.lifecycle.viewmodel.viewModelFactory
import androidx.media3.common.util.UnstableApi
import cc.tiredsysadmin.android.sizzle.input.GamepadInput
import cc.tiredsysadmin.android.sizzle.input.KeyboardInput
import cc.tiredsysadmin.android.sizzle.input.MidiInput
import cc.tiredsysadmin.android.sizzle.io.SongIntents
import cc.tiredsysadmin.android.sizzle.playback.PlaybackService
import cc.tiredsysadmin.android.sizzle.playback.SoundModuleService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import cc.tiredsysadmin.android.sizzle.ui.AppViewModel
import cc.tiredsysadmin.android.sizzle.ui.SizzleApp as SizzleAppUi
import cc.tiredsysadmin.android.sizzle.ui.theme.SizzleTheme
@@ -32,7 +38,8 @@ import cc.tiredsysadmin.android.sizzle.ui.theme.SizzleTheme
* 1. build the [AppViewModel] wired to the app-wide singletons,
* 2. host the Compose UI, themed by the ViewModel's current palette,
* 3. forward hardware key / motion events into the keyboard & gamepad handlers,
* 4. start MIDI listening and the background playback service.
* 4. hold the MIDI ports and start the background services,
* 5. hand `.sng` files opened from other apps to the ViewModel.
*
* All four input methods converge on the same InputRouter -> ViewModel path, so
* there is no per-input special-casing beyond the translation done here.
@@ -44,7 +51,6 @@ class MainActivity : ComponentActivity() {
// Handlers are app-wide singletons (shared with the Settings rebind UI).
private val keyboard: KeyboardInput get() = app.keyboardInput
private val gamepad: GamepadInput get() = app.gamepadInput
private val midi: MidiInput get() = app.midiInput
private val viewModel: AppViewModel by lazy {
ViewModelProvider(
@@ -79,14 +85,36 @@ class MainActivity : ComponentActivity() {
}
}
// Start MIDI listening (USB + BLE) and the MIDI clock here — bound to the
// Activity's WHOLE lifetime (onCreate..onDestroy), not onStart/onStop — so a
// connected controller keeps driving the app while the screen is off. The
// audio engine already runs a continuous output stream via the started
// PlaybackService, which keeps the process alive to receive those events in
// the background; closing the ports on onStop was the only reason input died.
midi.start()
app.midiClock.start()
// Hold the MIDI ports (USB, Bluetooth, other apps' virtual devices) for the
// Activity's WHOLE lifetime (onCreate..onDestroy), not onStart/onStop, so a
// controller keeps driving the app with the screen off. The PlaybackService
// and the SoundModuleService hold their own references, so MIDI outlives
// the Activity while either runs; the notes themselves are played by
// SizzleApp.soundModule, not by this Activity or its ViewModel.
app.acquireMidi(MIDI_OWNER)
handleOpenIntent(intent)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handleOpenIntent(intent)
}
/**
* A `.sng` handed over by another app (Mikro Seq's "Open in Sizzle", a file
* manager, the share sheet): read it off the main thread, then let the UI ask
* before it replaces the current song. See [SongIntents] for what is accepted.
*/
private fun handleOpenIntent(intent: Intent?) {
intent ?: return
if (intent.action != Intent.ACTION_VIEW && intent.action != Intent.ACTION_SEND) return
// Consume it, so a configuration change or a re-delivered intent can't
// offer the same import twice.
setIntent(Intent(this, MainActivity::class.java))
lifecycleScope.launch {
val song = withContext(Dispatchers.IO) { SongIntents.read(this@MainActivity, intent) }
viewModel.offerIncomingSong(song)
}
}
// media3's MediaSessionService surface is still marked unstable; we pin the
@@ -98,6 +126,9 @@ class MainActivity : ComponentActivity() {
// foreground — a plain startService() from a not-yet-foreground state
// throws BackgroundServiceStartNotAllowedException on Android 12+.
runCatching { PlaybackService.start(this) }
// Sound-module mode: (re)start its foreground service while we are allowed
// to — a start from the background would be refused.
if (app.soundModuleEnabled.value) SoundModuleService.start(this)
}
override fun onStop() {
@@ -112,8 +143,9 @@ class MainActivity : ComponentActivity() {
override fun onDestroy() {
// Release MIDI only when the Activity is actually torn down (task removed or
// finishing), not merely backgrounded / screen-off.
midi.stop()
app.midiClock.stop()
// The PlaybackService / SoundModuleService keep their own references, so
// MIDI stays open while either runs.
app.releaseMidi(MIDI_OWNER)
super.onDestroy()
}
@@ -166,4 +198,8 @@ class MainActivity : ComponentActivity() {
}
if (needed.isNotEmpty()) requestPermissions.launch(needed.toTypedArray())
}
private companion object {
const val MIDI_OWNER = "activity"
}
}
@@ -4,11 +4,14 @@
package cc.tiredsysadmin.android.sizzle
import android.app.Application
import android.os.Handler
import android.os.Looper
import cc.tiredsysadmin.android.sizzle.audio.AudioEngine
import cc.tiredsysadmin.android.sizzle.input.BindingStore
import cc.tiredsysadmin.android.sizzle.input.GamepadInput
import cc.tiredsysadmin.android.sizzle.input.InputRouter
import cc.tiredsysadmin.android.sizzle.input.KeyboardInput
import cc.tiredsysadmin.android.sizzle.input.InputAction
import cc.tiredsysadmin.android.sizzle.input.MidiInput
import cc.tiredsysadmin.android.sizzle.io.PresetLibrary
import cc.tiredsysadmin.android.sizzle.io.ProjectStore
@@ -16,7 +19,16 @@ import cc.tiredsysadmin.android.sizzle.io.SettingsStore
import cc.tiredsysadmin.android.sizzle.io.SongLibrary
import cc.tiredsysadmin.android.sizzle.io.ThemeLibrary
import cc.tiredsysadmin.android.sizzle.model.Project
import cc.tiredsysadmin.android.sizzle.playback.MidiSoundModule
import java.io.File
import cc.tiredsysadmin.android.sizzle.playback.SoundModuleService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
/**
@@ -35,7 +47,7 @@ class SizzleApp : Application() {
/** Neutral input bus shared by touch / keyboard / gamepad / MIDI. */
val inputRouter: InputRouter by lazy { InputRouter() }
/** The real-time sound engine (started/stopped by the PlaybackService). */
/** The real-time sound engine (started/released through [acquireEngine]). */
val audioEngine: AudioEngine by lazy { AudioEngine() }
// Input source handlers are singletons so their (re)bindable maps are shared
@@ -43,7 +55,17 @@ class SizzleApp : Application() {
// screen (which edits their bindings via MIDI-learn / gamepad rebind).
val keyboardInput: KeyboardInput by lazy { KeyboardInput(inputRouter) }
val gamepadInput: GamepadInput by lazy { GamepadInput(inputRouter) }
val midiInput: MidiInput by lazy { MidiInput(this, inputRouter) }
val midiInput: MidiInput by lazy { MidiInput(this, inputRouter, soundModule) }
/** Headless MIDI → engine routing (see [MidiSoundModule]). Lives here, with the
* engine, so it keeps playing incoming notes with no Activity or ViewModel. */
val soundModule: MidiSoundModule by lazy {
MidiSoundModule(object : MidiSoundModule.NoteSink {
override fun busNoteOn(channel: Int, note: Int, velocity: Int) =
audioEngine.busNoteOn(channel, note, velocity)
override fun busNoteOff(channel: Int, note: Int) = audioEngine.busNoteOff(channel, note)
})
}
/** MIDI clock sync (send/receive) over USB + Bluetooth MIDI. */
val midiClock: cc.tiredsysadmin.android.sizzle.input.MidiClock by lazy {
@@ -85,11 +107,80 @@ class SizzleApp : Application() {
// single small read; blocking briefly at cold start keeps the input maps
// authoritative from the first keypress rather than racing an async load.
runBlocking { bindingStore.loadInto(keyboardInput, gamepadInput, midiInput) }
// Feed incoming MIDI real-time (clock / start / stop) to the clock sync module.
midiInput.onRealtime = midiClock::handleRealtime
wireMidi()
installCrashAutosave()
}
// ------------------------------------------------ shared engine / MIDI lifetime
// The Activity, the media PlaybackService and the SoundModuleService can each
// outlive the others, so the engine and the MIDI ports are reference-counted by
// owner name: started by the first owner, released by the last. Main thread.
private val engineOwners = HashSet<String>()
private val midiOwners = HashSet<String>()
fun acquireEngine(owner: String) {
if (engineOwners.add(owner) && engineOwners.size == 1) audioEngine.start()
}
fun releaseEngine(owner: String) {
if (engineOwners.remove(owner) && engineOwners.isEmpty()) audioEngine.release()
}
fun acquireMidi(owner: String) {
if (midiOwners.add(owner) && midiOwners.size == 1) { midiInput.start(); midiClock.start() }
}
fun releaseMidi(owner: String) {
if (midiOwners.remove(owner) && midiOwners.isEmpty()) { midiInput.stop(); midiClock.stop() }
}
/**
* MIDI plumbing that must work with no UI: real-time bytes to the clock
* follower, the follower driving the transport/tempo, the clock sender reading
* the transport, and each note the sound module plays mirrored onto the input
* bus so a visible UI can show it / punch it in (marked `sounded`, so the UI
* does not play it a second time). The clock toggles are restored here for the
* same reason; the ViewModel restores them again when it exists.
*/
private fun wireMidi() {
val main = Handler(Looper.getMainLooper())
soundModule.realtime = midiClock::handleRealtime
soundModule.noteListener = { on, channel, note, velocity ->
inputRouter.dispatch(
if (on) InputAction.NoteOn(note, velocity, channel, sounded = true)
else InputAction.NoteOff(note, channel, sounded = true),
)
}
midiClock.playingProvider = { audioEngine.transport.value.isPlaying }
midiClock.bpmProvider = { project.tempoBpm }
midiClock.noteSource = { audioEngine.pollMidiOut() } // forward sequenced notes out
midiClock.onReceiveStart = { main.post { if (!audioEngine.transport.value.isPlaying) audioEngine.play() } }
midiClock.onReceiveStop = { main.post { audioEngine.pause() } }
midiClock.onReceiveTempo = { bpm -> main.post { project.tempoBpm = bpm.coerceIn(20f, 300f) } }
val s = runBlocking { settingsStore.load() }
midiClock.sendEnabled = s.sendMidiClock
audioEngine.midiOutEnabled = s.sendMidiClock
midiClock.receiveEnabled = s.receiveMidiClock
_soundModuleEnabled.value = s.soundModule
}
private val appScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val _soundModuleEnabled = MutableStateFlow(false)
/** "Keep running as MIDI sound module" (Settings). Held here, not in the
* ViewModel, because the notification's Stop action turns it off with no UI. */
val soundModuleEnabled: StateFlow<Boolean> = _soundModuleEnabled.asStateFlow()
/** Turn sound-module mode on or off: persist it and start / stop
* [SoundModuleService]. Turning it on must happen while the app is in the
* foreground (Android refuses a foreground-service start from the background);
* [MainActivity] retries on every resume, so a refused start heals itself. */
fun setSoundModuleEnabled(enabled: Boolean) {
_soundModuleEnabled.value = enabled
appScope.launch { settingsStore.saveSoundModule(enabled) }
if (enabled) SoundModuleService.start(this) else SoundModuleService.stop(this)
}
/** Flush an autosave of the current project on any uncaught exception, then let
* the default handler crash/report as usual — so state survives a crash. */
private fun installCrashAutosave() {
@@ -37,8 +37,10 @@ sealed interface InputAction {
// routed to the mixer track(s) listening on it; it is -1 when the source has no
// channel of its own (physical / on-screen keyboard), which falls back to the
// on-screen keyboard's channel.
data class NoteOn(val pitch: Int, val velocity: Int, val channel: Int = -1) : InputAction
data class NoteOff(val pitch: Int, val channel: Int = -1) : InputAction
// [sounded] is true when the note was already played by the headless sound
// module (MIDI input): the UI only shows it / punches it in, never plays it again.
data class NoteOn(val pitch: Int, val velocity: Int, val channel: Int = -1, val sounded: Boolean = false) : InputAction
data class NoteOff(val pitch: Int, val channel: Int = -1, val sounded: Boolean = false) : InputAction
// ----- Transport -----
data object PlayPause : InputAction
@@ -0,0 +1,59 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.input
/**
* Turns a raw MIDI byte stream into whole messages. Pure Kotlin (no Android types)
* so it is unit-tested directly.
*
* One parser per source: it keeps running status (a channel message may omit its
* status byte when it repeats the previous one, which USB and serial gear do) and
* a message split across two `onSend` packets, and both are per-stream state.
* System Real-Time bytes (0xF8..0xFF) may sit anywhere, even inside another
* message, and go straight to [onRealtime]. SysEx (0xF0..0xF7) is skipped.
*
* Not thread-safe; Android delivers one port's packets on one thread.
*/
class MidiByteParser(
/** A complete channel message: status (0x80..0xEF) and its data bytes (0 when absent). */
private val onChannel: (status: Int, d1: Int, d2: Int) -> Unit,
/** A System Real-Time byte: clock 0xF8, Start 0xFA, Continue 0xFB, Stop 0xFC, … */
private val onRealtime: (status: Int) -> Unit,
) {
private var running = 0 // running status, 0 = none
private var need = 0 // data bytes the current message needs
private var got = 0
private var d1 = 0
private var inSysex = false
fun feed(data: ByteArray, offset: Int, count: Int) {
val end = (offset + count).coerceAtMost(data.size)
for (i in offset.coerceAtLeast(0) until end) byte(data[i].toInt() and 0xFF)
}
private fun byte(b: Int) {
when {
b >= 0xF8 -> onRealtime(b) // never disturbs running status
b == 0xF0 -> { inSysex = true; running = 0 }
b == 0xF7 -> inSysex = false
b >= 0xF1 -> { // system common: cancels running status; its data is ignored
inSysex = false; running = 0; need = 0
}
b >= 0x80 -> {
inSysex = false
running = b; got = 0
need = if ((b and 0xF0) == 0xC0 || (b and 0xF0) == 0xD0) 1 else 2
}
inSysex || running == 0 -> {} // stray data byte
else -> {
if (got == 0) d1 = b
got++
if (got >= need) {
onChannel(running, d1, if (need == 2) b else 0)
got = 0 // running status: the next data byte starts a new message
}
}
}
}
}
@@ -10,6 +10,10 @@ import android.media.midi.MidiManager
import android.os.Handler
import android.os.Looper
import java.util.concurrent.CopyOnWriteArrayList
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import java.util.concurrent.locks.LockSupport
/**
@@ -34,30 +38,43 @@ class MidiClock(context: Context) {
@Volatile var sendEnabled = false
@Volatile var receiveEnabled = false
/** Live transport state for the send thread, supplied by the ViewModel. */
/** Live transport state for the send thread, wired up by [cc.tiredsysadmin.android.sizzle.SizzleApp]. */
var playingProvider: () -> Boolean = { false }
var bpmProvider: () -> Float = { 120f }
/** Source of queued outgoing note messages (packed (status<<16)|(d1<<8)|d2), or -1
* when empty — drained by the send thread while [sendEnabled]. Set by the ViewModel
* when empty — drained by the send thread while [sendEnabled]. Set by SizzleApp
* to the audio engine's queue, so Sizzle's sequenced notes reach external gear. */
var noteSource: (() -> Int)? = null
/** Receive callbacks (invoked on the MIDI handler thread; the ViewModel hops to
* the main thread as needed). */
/** Receive callbacks (invoked on the MIDI port's thread; SizzleApp hops to the
* main thread). */
var onReceiveStart: (() -> Unit)? = null
var onReceiveStop: (() -> Unit)? = null
var onReceiveTempo: ((Float) -> Unit)? = null
private val _followedTempo = MutableSharedFlow<Float>(
extraBufferCapacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
/** Each tempo taken from an external clock, after [onReceiveTempo] applied it, so
* the UI can redraw. Nothing is buffered for a UI that isn't collecting. */
val followedTempo: SharedFlow<Float> = _followedTempo.asSharedFlow()
private var thread: Thread? = null
@Volatile private var running = false
private var callback: MidiManager.DeviceCallback? = null
/** Open every writable device and start the send thread. Idempotent. Main thread. */
fun start() {
val mm = midiManager ?: return
mm.devices.forEach(::openDevice)
mm.registerDeviceCallback(object : MidiManager.DeviceCallback() {
if (running) return
val cb = object : MidiManager.DeviceCallback() {
override fun onDeviceAdded(device: MidiDeviceInfo) = openDevice(device)
}, handler)
}
callback = cb
mm.devices.forEach(::openDevice)
mm.registerDeviceCallback(cb, handler)
running = true
thread = Thread({ sendLoop() }, "sizzle-midi-clock").apply {
priority = Thread.MAX_PRIORITY; isDaemon = true; start()
@@ -65,6 +82,8 @@ class MidiClock(context: Context) {
}
fun stop() {
callback?.let { cb -> runCatching { midiManager?.unregisterDeviceCallback(cb) } }
callback = null
running = false
thread?.join(200); thread = null
outPorts.forEach { runCatching { it.close() } }
@@ -152,7 +171,10 @@ class MidiClock(context: Context) {
if (++pulseCount >= 24) {
val avgNs = pulseAccum / pulseCount
val bpm = (60_000_000_000.0 / (avgNs * 24.0)).toFloat()
if (bpm.isFinite() && bpm in 20f..300f) onReceiveTempo?.invoke(bpm)
if (bpm.isFinite() && bpm in 20f..300f) {
onReceiveTempo?.invoke(bpm)
_followedTempo.tryEmit(bpm)
}
pulseAccum = 0.0; pulseCount = 0
}
}
@@ -4,100 +4,98 @@
package cc.tiredsysadmin.android.sizzle.input
import android.content.Context
import android.media.midi.MidiDevice
import android.media.midi.MidiDeviceInfo
import android.media.midi.MidiManager
import android.media.midi.MidiOutputPort
import android.media.midi.MidiReceiver
import android.os.Handler
import android.os.Looper
import cc.tiredsysadmin.android.sizzle.playback.MidiSoundModule
/**
* Bridges hardware MIDI (USB *and* Bluetooth — Android surfaces both through the
* same [MidiManager]) into the app's [InputAction] stream.
* Bridges hardware and virtual MIDI sources (USB, Bluetooth, and other apps'
* virtual devices such as Mikro Seq; Android lists all of them through the same
* [MidiManager]) into the app.
*
* MIDI note-on/off become live notes; MIDI Control Change (CC) messages are
* matched against [ccBindings] so any knob/pad can drive navigation or transport.
* Unmatched CCs are forwarded as [InputAction.RawControl] so the Settings screen
* can "learn" them.
* Every source gets its own [MidiByteParser] (running status is per stream).
* Notes, all-notes-off and real-time bytes go to the [module], the headless sound
* module that plays them on the engine whether or not the UI exists. Control
* Change (CC) messages the module does not consume are matched against
* [ccBindings] so any knob/pad can drive navigation or transport; unmatched CCs
* are forwarded as [InputAction.RawControl] so the Settings screen can "learn" them.
*
* Note: this handles MIDI *input*. Sending MIDI out lives in the audio/midi
* output module; both share the same [MidiManager].
* A source that goes away (unplugged, or removed by the system) is closed and its
* held notes are released through [MidiSoundModule.sourceDisconnected].
*
* Note: this handles MIDI *input*. Sending MIDI out lives in [MidiClock].
*/
class MidiInput(
context: Context,
private val router: InputRouter,
private val module: MidiSoundModule,
/** CC number -> action id, editable from Settings (MIDI bindings section). */
var ccBindings: MutableMap<Int, String> = mutableMapOf(),
) {
/** Sink for MIDI System Real-Time status bytes (0xF8..0xFF), notably clock (0xF8)
* and Start/Continue/Stop (0xFA/0xFB/0xFC) — wired to [MidiClock] for clock sync. */
var onRealtime: ((Int) -> Unit)? = null
private val midiManager = context.getSystemService(Context.MIDI_SERVICE) as? MidiManager
private val handler = Handler(Looper.getMainLooper())
private val openPorts = mutableListOf<MidiOutputPort>()
/** Start listening. Opens every currently-attached input-capable device and
* watches for hot-plug events. Safe to call if the device has no MIDI. */
/** Open sources by [MidiDeviceInfo.getId]. Touched only on the main thread. */
private val open = HashMap<Int, Pair<MidiDevice, MidiOutputPort>>()
private var callback: MidiManager.DeviceCallback? = null
/** Start listening. Opens every currently-attached device that can send to us
* and watches for hot-plug events. Idempotent; safe if the device has no MIDI.
* Main thread. */
fun start() {
val mm = midiManager ?: return
mm.devices.forEach(::openDevice)
mm.registerDeviceCallback(object : MidiManager.DeviceCallback() {
if (callback != null) return
val cb = object : MidiManager.DeviceCallback() {
override fun onDeviceAdded(device: MidiDeviceInfo) = openDevice(device)
}, handler)
override fun onDeviceRemoved(device: MidiDeviceInfo) = closeDevice(device.id)
}
callback = cb
mm.devices.forEach(::openDevice)
mm.registerDeviceCallback(cb, handler)
}
/** Close every source (releasing their held notes). Main thread. */
fun stop() {
openPorts.forEach { runCatching { it.close() } }
openPorts.clear()
callback?.let { cb -> runCatching { midiManager?.unregisterDeviceCallback(cb) } }
callback = null
open.keys.toList().forEach(::closeDevice)
}
private fun openDevice(info: MidiDeviceInfo) {
// We want devices that can SEND to us (they expose output ports).
if (info.outputPortCount == 0) return
if (info.outputPortCount == 0 || info.id in open) return
midiManager?.openDevice(info, { device ->
val port = device?.openOutputPort(0) ?: return@openDevice
port.connect(parser)
openPorts += port
device ?: return@openDevice
// stop() ran (or the same device was opened twice) while this was pending.
if (callback == null || info.id in open) { runCatching { device.close() }; return@openDevice }
val port = device.openOutputPort(0) ?: run { runCatching { device.close() }; return@openDevice }
val source = info.id
val parser = MidiByteParser(
onChannel = { status, d1, d2 ->
val consumed = module.onChannelMessage(source, status, d1, d2)
if (!consumed && (status and 0xF0) == 0xB0) handleCc(d1, d2)
},
onRealtime = module::onRealtime,
)
port.connect(object : MidiReceiver() {
override fun onSend(data: ByteArray, offset: Int, count: Int, timestamp: Long) =
parser.feed(data, offset, count)
})
open[source] = device to port
module.sourceConnected(source)
}, handler)
}
/** Parses the raw MIDI byte stream. MIDI status bytes have the high bit set;
* the low nibble is the channel, the high nibble the message type. */
private val parser = object : MidiReceiver() {
override fun onSend(data: ByteArray, offset: Int, count: Int, timestamp: Long) {
var i = offset
val end = offset + count
while (i < end) {
val status = data[i].toInt() and 0xFF
if (status < 0x80) { i++; continue } // skip stray data bytes
// System Real-Time (0xF8..0xFF) are single-byte and may be interleaved
// anywhere; forward them (clock / start / stop) and move on one byte.
if (status >= 0xF8) { onRealtime?.invoke(status); i++; continue }
val type = status and 0xF0
// Low nibble is the MIDI channel (0..15); expose it 1-based (1..16) so
// it matches the mixer channels' `midiChannel` for routing.
val channel = (status and 0x0F) + 1
when (type) {
0x90 -> { // Note On
val note = data.getOrZero(i + 1)
val vel = data.getOrZero(i + 2)
if (vel > 0) router.dispatch(InputAction.NoteOn(note, vel, channel))
else router.dispatch(InputAction.NoteOff(note, channel)) // vel 0 == note off
i += 3
}
0x80 -> { // Note Off
router.dispatch(InputAction.NoteOff(data.getOrZero(i + 1), channel)); i += 3
}
0xB0 -> { // Control Change
val cc = data.getOrZero(i + 1)
val value = data.getOrZero(i + 2)
handleCc(cc, value); i += 3
}
0xC0, 0xD0 -> i += 2 // program change / channel pressure: 1 data byte
else -> i += 3
}
}
}
private fun closeDevice(id: Int) {
val (device, port) = open.remove(id) ?: return
runCatching { port.close() }
runCatching { device.close() }
module.sourceDisconnected(id)
}
private fun handleCc(cc: Int, value: Int) {
@@ -135,7 +133,4 @@ class MidiInput(
}
action?.let(router::dispatch)
}
private fun ByteArray.getOrZero(index: Int): Int =
if (index < size) this[index].toInt() and 0xFF else 0
}
@@ -33,6 +33,9 @@ data class AppSettings(
val sendMidiClock: Boolean = false,
/** Follow an external MIDI clock's tempo + start/stop. */
val receiveMidiClock: Boolean = false,
/** Keep a foreground service up so incoming MIDI plays with the app in the
* background ("Keep running as MIDI sound module"). */
val soundModule: Boolean = false,
)
/**
@@ -57,6 +60,7 @@ class SettingsStore(private val context: Context) {
vuMeters = prefs[VU_METERS] ?: true,
sendMidiClock = prefs[MIDI_CLOCK_SEND] ?: false,
receiveMidiClock = prefs[MIDI_CLOCK_RECV] ?: false,
soundModule = prefs[SOUND_MODULE] ?: false,
)
}
@@ -96,6 +100,11 @@ class SettingsStore(private val context: Context) {
}
}
/** Persist the "Keep running as MIDI sound module" toggle. */
suspend fun saveSoundModule(enabled: Boolean) {
context.settingsDataStore.edit { prefs -> prefs[SOUND_MODULE] = enabled }
}
private companion object {
val PALETTE = stringPreferencesKey("palette")
val RECORD_DIR = stringPreferencesKey("recordDirUri")
@@ -105,5 +114,6 @@ class SettingsStore(private val context: Context) {
val VU_METERS = booleanPreferencesKey("vuMeters")
val MIDI_CLOCK_SEND = booleanPreferencesKey("midiClockSend")
val MIDI_CLOCK_RECV = booleanPreferencesKey("midiClockRecv")
val SOUND_MODULE = booleanPreferencesKey("soundModule")
}
}
@@ -92,36 +92,72 @@ object SngFormat {
}
// -------------------------------------------------------------------- read
/** Parse `.sng` [text] into the existing [project] (resetting its content). */
/** Cheap content sniff: does [text] look like a `.sng` at all? Used before
* anything is replaced, since `text/plain` intents can carry any text. */
fun looksLikeSng(text: String): Boolean =
Regex("(?m)^\\s*(version|bpm|sig|block)\\b").containsMatchIn(text)
/** Longest block accepted, matching the desktop tracker's bound (the file is
* untrusted; an absurd length would allocate millions of cells). */
const val MAX_BLOCK_LENGTH = 1024
/**
* Parse `.sng` [text] into the existing [project] (resetting its content).
*
* Follows the desktop reader: `block <name...> <length> <numTracks>` (the name
* may contain spaces, the two trailing integers are read from the right),
* `track <name> <channel 0..15>`, step lines `tick note vel chan`, and `#`
* comments. `group`, `scale`, `root`, `kind` and `intro` are accepted and
* ignored (this app has no block groups, and scales are per song here);
* `loop` turns the arrangement loop on.
*
* This app has [Arrangement.LANE_COUNT] blocks of [Pattern.TRACK_COUNT]
* tracks. A track keeps its `Tn` slot when free, otherwise takes the next free
* one; tracks past the fourth are dropped. With more blocks than lanes, blocks
* that are on the roll win over ones that are not (Mikro Seq writes muted
* tracks into such off-roll blocks).
*/
fun importInto(project: Project, text: String): Project {
// Clear blocks and arrangement (keep the 8 lane-blocks, wipe their cells).
project.patterns.forEach { p -> for (t in 0 until Pattern.TRACK_COUNT) p.tracks[t].forEach { it.clear() } }
for (lane in project.arrangement.slots.indices) project.arrangement.slots[lane].fill(Arrangement.EMPTY)
project.arrangement.laneMuted.fill(false)
var blockIndex = 0
val lines = text.lineSequence().map { it.trim() }
.filter { it.isNotEmpty() && !it.startsWith("#") }
.map { it.split(Regex("\\s+")) }
.toList()
val keep = blocksToKeep(lines, project.patterns.size)
var blockOrdinal = -1 // index of the block in the file
var nextPattern = 0 // next free pattern (lane) to fill
var current: Pattern? = null
var track = 0
var track = -1
var trackChannel = 1
val usedTracks = BooleanArray(Pattern.TRACK_COUNT)
var maxRoll = 0
text.lineSequence().map { it.trim() }.filter { it.isNotEmpty() }.forEach { line ->
val tok = line.split(Regex("\\s+"))
for (tok in lines) {
when (tok[0]) {
"version" -> {}
"bpm" -> project.tempoBpm = tok.getOrNull(1)?.toFloatOrNull() ?: 120f
"version", "group", "scale", "root", "kind", "intro" -> {}
"bpm" -> tok.getOrNull(1)?.toFloatOrNull()?.takeIf { it.isFinite() }
?.let { project.tempoBpm = it.coerceIn(20f, 300f) }
"sig" -> project.timeSignature = when (tok.getOrNull(1)?.toIntOrNull()) {
3 -> TimeSignature.THREE_FOUR
5 -> TimeSignature.FIVE_FOUR
else -> TimeSignature.FOUR_FOUR
}
"loop" -> if (tok.size >= 3) project.arrangement.loopEnabled = true
"block" -> {
current = project.patterns.getOrNull(blockIndex)?.also { blk ->
tok.getOrNull(1)?.let { blk.name = it }
tok.getOrNull(2)?.toIntOrNull()?.let { blk.resize(it) }
blockOrdinal++
current = if (blockOrdinal in keep) project.patterns.getOrNull(nextPattern++) else null
current?.let { blk ->
val (name, length) = blockHeader(tok)
blk.name = name
length?.let { blk.resize(it.coerceIn(1, MAX_BLOCK_LENGTH)) }
}
blockIndex++
track = 0; trackChannel = 1
track = -1; trackChannel = 1
usedTracks.fill(false)
}
"roll" -> current?.let { blk ->
val roll = tok.getOrNull(1) ?: ""
@@ -134,11 +170,14 @@ object SngFormat {
maxRoll = maxOf(maxRoll, roll.length)
}
"track" -> {
track = tok.getOrNull(1)?.filter { it.isDigit() }?.toIntOrNull()?.minus(1)?.coerceIn(0, Pattern.TRACK_COUNT - 1) ?: 0
val wanted = tok.getOrNull(1)?.filter { it.isDigit() }?.toIntOrNull()?.minus(1)
track = if (wanted != null && wanted in 0 until Pattern.TRACK_COUNT && !usedTracks[wanted]) wanted
else usedTracks.indexOfFirst { !it }
if (track >= 0) usedTracks[track] = true
trackChannel = tok.getOrNull(2)?.toIntOrNull()?.plus(1)?.coerceIn(1, 16) ?: 1
}
"endblock" -> current = null
else -> applyStep(project, current, track, trackChannel, tok)
"endblock" -> { current = null; track = -1 }
else -> if (track >= 0) applyStep(project, current, track, trackChannel, tok)
}
}
// Grow the canvas (in bars) if the imported roll is longer than the default.
@@ -152,6 +191,33 @@ object SngFormat {
return project
}
/** `block <name...> <length> [<numTracks>]` -> (name, length). Two trailing
* integers are length and track count (desktop and Mikro Seq; this app's own
* exports write beats-per-bar there, equally ignored); one is the length. */
private fun blockHeader(tok: List<String>): Pair<String, Int?> {
val rest = tok.drop(1)
val trailing = rest.takeLastWhile { it.toIntOrNull() != null }.size.coerceAtMost(2)
val length = when (trailing) {
2 -> rest[rest.size - 2].toIntOrNull()
1 -> rest.last().toIntOrNull()
else -> null
}
val name = rest.dropLast(trailing).joinToString(" ").ifEmpty { rest.firstOrNull() ?: "PTN" }
return name to length
}
/** Which block ordinals get one of the [slots] patterns: all of them when they
* fit, otherwise on-roll blocks first, then the rest, in file order. */
private fun blocksToKeep(lines: List<List<String>>, slots: Int): Set<Int> {
val onRoll = ArrayList<Boolean>()
for (tok in lines) when (tok[0]) {
"block" -> onRoll += false
"roll" -> if (onRoll.isNotEmpty() && '#' in (tok.getOrNull(1) ?: "")) onRoll[onRoll.size - 1] = true
}
val order = onRoll.indices.filter { onRoll[it] } + onRoll.indices.filter { !onRoll[it] }
return order.take(slots).toSet()
}
private fun applyStep(project: Project, block: Pattern?, track: Int, trackChannel: Int, tok: List<String>) {
val blk = block ?: return
val tick = tok.getOrNull(0)?.toIntOrNull() ?: return
@@ -0,0 +1,93 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.io
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.OpenableColumns
import java.io.InputStream
/** A song handed over by another app: its display [name] and [text], or an [error]
* to show instead. */
data class IncomingSong(val name: String, val text: String?, val error: String? = null)
/**
* Reads a `.sng` that another app opened in Sizzle (Mikro Seq's "Open in Sizzle",
* a file manager, the share sheet). The manifest accepts:
*
* - `ACTION_VIEW` of a `content:` / `file:` URI typed `application/octet-stream`,
* `text/plain` or `application/x-sizzle-song`, or of any type whose path ends
* in `.sng`;
* - `ACTION_SEND` of those types, with the file in `EXTRA_STREAM` (or the clip
* data), or for `text/plain` the song text itself in `EXTRA_TEXT`.
*
* Because `text/plain` and `application/octet-stream` match far more than songs,
* nothing here trusts the type: [SngFormat.looksLikeSng] checks the content before
* the UI offers to import it. Size is capped, the file is untrusted input.
*/
object SongIntents {
/** Larger than any real song (Mikro Seq's biggest export is a few tens of KB). */
const val MAX_BYTES = 4 * 1024 * 1024
fun read(context: Context, intent: Intent): IncomingSong {
val uri: Uri? = when (intent.action) {
Intent.ACTION_VIEW -> intent.data
Intent.ACTION_SEND -> streamExtra(intent) ?: intent.clipData?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.uri
else -> null
}
if (uri == null) {
val text = intent.getStringExtra(Intent.EXTRA_TEXT)
return when {
text == null -> IncomingSong("shared song", null, "Nothing to open: the other app sent no file.")
!SngFormat.looksLikeSng(text) -> IncomingSong("shared text", null, NOT_A_SONG)
else -> IncomingSong(intent.getStringExtra(Intent.EXTRA_SUBJECT) ?: "shared song", text)
}
}
val name = displayName(context, uri)
val bytes = runCatching {
context.contentResolver.openInputStream(uri)?.use(::readCapped)
}.getOrElse { e ->
return IncomingSong(name, null, "Couldn't read $name: ${e.message ?: e.javaClass.simpleName}")
} ?: return IncomingSong(name, null, "Couldn't read $name.")
val text = String(bytes, Charsets.UTF_8)
if (!SngFormat.looksLikeSng(text)) return IncomingSong(name, null, NOT_A_SONG)
return IncomingSong(name, text)
}
private const val NOT_A_SONG = "This doesn't look like a Sizzle .sng song, so nothing was imported."
@Suppress("DEPRECATION")
private fun streamExtra(intent: Intent): Uri? =
if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java)
else intent.getParcelableExtra(Intent.EXTRA_STREAM) as? Uri
private fun displayName(context: Context, uri: Uri): String {
val fromProvider = runCatching {
context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
}.getOrNull()
return (fromProvider ?: uri.lastPathSegment ?: "song").substringAfterLast('/')
}
private fun readCapped(input: InputStream): ByteArray {
val bytes = input.readNBytesCompat(MAX_BYTES + 1)
require(bytes.size <= MAX_BYTES) { "file is larger than ${MAX_BYTES / 1024 / 1024} MB" }
return bytes
}
// InputStream.readNBytes is API 33+; minSdk is 26.
private fun InputStream.readNBytesCompat(limit: Int): ByteArray {
val out = java.io.ByteArrayOutputStream()
val buf = ByteArray(16 * 1024)
while (out.size() < limit) {
val n = read(buf, 0, minOf(buf.size, limit - out.size()))
if (n < 0) break
out.write(buf, 0, n)
}
return out.toByteArray()
}
}
@@ -0,0 +1,134 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.playback
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
/**
* The headless multitimbral sound module: incoming MIDI → audio engine, with no UI
* in the path. It lives in [cc.tiredsysadmin.android.sizzle.SizzleApp] next to the
* engine, so it keeps working while the Activity and its ViewModel are gone and the
* [SoundModuleService] holds the process in the foreground.
*
* - Note On / Off on channel N play / release every mixer track listening on N
* ([NoteSink.busNoteOn] / [NoteSink.busNoteOff]).
* - All Notes Off (CC 123) and All Sound Off (CC 120) release what is held on
* that channel. Mikro Seq sends CC 123 on stop.
* - Real-time bytes (clock, Start, Stop) go to [realtime]; the app points it at
* the MIDI clock follower, which acts on them only while "Receive MIDI clock"
* is on.
* - Notes are tracked per source, so a source that disconnects mid-note
* ([sourceDisconnected]) has its held notes released instead of droning.
*
* The UI only observes: [noteListener] mirrors each note so the ViewModel can show
* held keys and punch notes into the grid, without sounding them again.
*
* Pure Kotlin, unit-tested. Thread-safe: each MIDI port delivers on its own
* thread, so every entry point takes one lock (uncontended in practice).
*/
class MidiSoundModule(private val sink: NoteSink) {
/** Where notes are played. [cc.tiredsysadmin.android.sizzle.audio.AudioEngine]
* in the app; a recorder in tests. */
interface NoteSink {
fun busNoteOn(channel: Int, note: Int, velocity: Int)
fun busNoteOff(channel: Int, note: Int)
}
/** Mirror of every note the module played or released (channel 1..16). */
@Volatile var noteListener: ((on: Boolean, channel: Int, note: Int, velocity: Int) -> Unit)? = null
/** MIDI System Real-Time bytes (0xF8..0xFF). */
@Volatile var realtime: ((Int) -> Unit)? = null
private val lock = Any()
/** source id -> held keys, key = (channel-1) * 128 + note. */
private val held = HashMap<Int, MutableSet<Int>>()
private val _sources = MutableStateFlow(0)
/** How many MIDI sources are open right now (shown in the notification). */
val sources: StateFlow<Int> = _sources.asStateFlow()
fun sourceConnected(source: Int) = synchronized(lock) {
held.getOrPut(source) { HashSet() }
_sources.value = held.size
}
/** [source] went away (unplugged, its app died, or we closed it): release its notes. */
fun sourceDisconnected(source: Int) = synchronized(lock) {
held.remove(source)?.let(::releaseKeys)
_sources.value = held.size
}
/**
* One channel message from [source]. Returns true when the module consumed it
* (notes and the all-notes-off controls); other messages (CC bindings, program
* change, …) are left to the caller.
*/
fun onChannelMessage(source: Int, status: Int, d1: Int, d2: Int): Boolean {
val channel = (status and 0x0F) + 1
val note = d1 and 0x7F
return when (status and 0xF0) {
0x90 -> { if (d2 > 0) noteOn(source, channel, note, d2) else noteOff(source, channel, note); true }
0x80 -> { noteOff(source, channel, note); true }
0xB0 -> if (d1 == CC_ALL_NOTES_OFF || d1 == CC_ALL_SOUND_OFF) { channelOff(channel); true } else false
else -> false
}
}
fun onRealtime(status: Int) { realtime?.invoke(status) }
/** Release everything any source holds (panic, shutdown). */
fun releaseAll() = synchronized(lock) { held.values.forEach { releaseKeys(it); it.clear() } }
/** Held (channel, note) pairs per source, for tests and diagnostics. */
fun heldNotes(source: Int): Set<Pair<Int, Int>> = synchronized(lock) {
held[source].orEmpty().map { it / 128 + 1 to it % 128 }.toSet()
}
private fun noteOn(source: Int, channel: Int, note: Int, velocity: Int) = synchronized(lock) {
held.getOrPut(source) { HashSet() }.add(key(channel, note))
if (held.size != _sources.value) _sources.value = held.size
sink.busNoteOn(channel, note, velocity)
noteListener?.invoke(true, channel, note, velocity)
}
// Every Note Off reaches the engine, even for a note we don't think is held:
// a stuck voice is worse than a redundant release.
private fun noteOff(source: Int, channel: Int, note: Int) = synchronized(lock) {
held[source]?.remove(key(channel, note))
sink.busNoteOff(channel, note)
noteListener?.invoke(false, channel, note, 0)
}
/** CC 123 / 120 on [channel]: a receiver releases the channel's notes whoever
* sent them, so this clears that channel across all sources. */
private fun channelOff(channel: Int) = synchronized(lock) {
for (keys in held.values) {
val it = keys.iterator()
while (it.hasNext()) {
val k = it.next()
if (k / 128 + 1 == channel) { release(k); it.remove() }
}
}
}
private fun releaseKeys(keys: Set<Int>) = keys.forEach(::release)
private fun release(k: Int) {
val channel = k / 128 + 1
val note = k % 128
sink.busNoteOff(channel, note)
noteListener?.invoke(false, channel, note, 0)
}
private fun key(channel: Int, note: Int) = (channel - 1) * 128 + note
private companion object {
const val CC_ALL_SOUND_OFF = 120
const val CC_ALL_NOTES_OFF = 123
}
}
@@ -25,13 +25,16 @@ import kotlinx.coroutines.launch
@UnstableApi
class PlaybackService : MediaSessionService() {
private val engine get() = (application as SizzleApp).audioEngine
private val app get() = application as SizzleApp
private val engine get() = app.audioEngine
private var session: MediaSession? = null
private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
override fun onCreate() {
super.onCreate()
engine.start()
// Shared with the Activity and the SoundModuleService (reference-counted).
app.acquireEngine(OWNER)
app.acquireMidi(OWNER)
val player = EnginePlayer(engine)
session = MediaSession.Builder(this, player).build()
// Keep the session's reported state in sync with the engine (the on-screen
@@ -45,11 +48,14 @@ class PlaybackService : MediaSessionService() {
scope.cancel()
session?.run { player.release(); release() }
session = null
engine.release()
app.releaseMidi(OWNER)
app.releaseEngine(OWNER)
super.onDestroy()
}
companion object {
private const val OWNER = "playback"
/** Start the service from a foreground context (safe: plain startService,
* MediaSessionService promotes itself to foreground when playback begins). */
fun start(context: Context) {
@@ -0,0 +1,145 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.playback
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.app.ServiceCompat
import androidx.core.content.ContextCompat
import cc.tiredsysadmin.android.sizzle.MainActivity
import cc.tiredsysadmin.android.sizzle.R
import cc.tiredsysadmin.android.sizzle.SizzleApp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
/**
* Keeps Sizzle alive as a background MIDI sound module, like an iOS Inter-App
* Audio instrument: while it runs, another app (Mikro Seq, a DAW, a controller)
* can play Sizzle's mixer from the background even with Sizzle's own transport
* stopped.
*
* Why it exists: on Android 14+ the cached-app freezer suspends a backgrounded
* process within seconds unless it has a foreground service. The media
* [PlaybackService] is only in the foreground while the transport plays (media3
* drops foreground on pause), so on its own Sizzle stops answering MIDI as soon
* as it leaves the screen. This plain foreground service of type
* `mediaPlayback` (Sizzle does play audio) holds the process up instead.
*
* Trigger: the "Keep running as MIDI sound module" setting, not "a MIDI source is
* connected". Android lists every installed app's virtual MIDI device at all
* times, so "connected" would be true almost always; and a source plugged in
* while Sizzle is already in the background could not start a foreground service
* anyway (Android 12+ forbids that, and MIDI is not an exemption). So the user
* opts in, the service starts while Sizzle is on screen, and the notification
* shows how many sources are open and offers Stop.
*
* It owns a reference to the engine and the MIDI ports (see
* [SizzleApp.acquireEngine] / [SizzleApp.acquireMidi]), so they stay open after
* the Activity is destroyed. Routing itself is [MidiSoundModule].
*/
class SoundModuleService : Service() {
private val app get() = application as SizzleApp
private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
override fun onCreate() {
super.onCreate()
createChannel()
ServiceCompat.startForeground(
this, NOTIFICATION_ID, buildNotification(app.soundModule.sources.value),
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK else 0,
)
app.acquireEngine(OWNER)
app.acquireMidi(OWNER)
scope.launch {
app.soundModule.sources.collect { n ->
getSystemService(NotificationManager::class.java)
?.notify(NOTIFICATION_ID, buildNotification(n))
}
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == ACTION_STOP) app.setSoundModuleEnabled(false) // persists, stops us
// Not sticky: a restart after the system killed us would come from the
// background, where a foreground start is refused. The next time the user
// opens Sizzle, MainActivity starts the service again.
return START_NOT_STICKY
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onDestroy() {
scope.cancel()
app.releaseMidi(OWNER) // closes the ports when no one else holds them
app.soundModule.releaseAll()
app.releaseEngine(OWNER)
super.onDestroy()
}
private fun createChannel() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val channel = NotificationChannel(CHANNEL_ID, "MIDI sound module", NotificationManager.IMPORTANCE_LOW)
.apply { description = "Shown while Sizzle keeps running to play incoming MIDI" }
getSystemService(NotificationManager::class.java)?.createNotificationChannel(channel)
}
private fun buildNotification(sources: Int): Notification {
val open = PendingIntent.getActivity(
this, 0, Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
val stop = PendingIntent.getService(
this, 1, Intent(this, SoundModuleService::class.java).setAction(ACTION_STOP),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
val text = when (sources) {
0 -> "Waiting for a MIDI source"
1 -> "Playing MIDI from 1 source"
else -> "Playing MIDI from $sources sources"
}
return NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_sound_module)
.setContentTitle("Sizzle MIDI sound module")
.setContentText(text)
.setContentIntent(open)
.addAction(0, "Stop", stop)
.setOngoing(true)
.setOnlyAlertOnce(true)
.setSilent(true)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)
.build()
}
companion object {
private const val OWNER = "sound-module"
private const val CHANNEL_ID = "sound_module"
private const val NOTIFICATION_ID = 0x51221E
private const val ACTION_STOP = "cc.tiredsysadmin.android.sizzle.action.STOP_SOUND_MODULE"
/** Start (or keep) the service. Only succeeds from the foreground. */
fun start(context: Context) {
runCatching {
ContextCompat.startForegroundService(context, Intent(context, SoundModuleService::class.java))
}
}
fun stop(context: Context) {
context.stopService(Intent(context, SoundModuleService::class.java))
}
}
}
@@ -82,6 +82,32 @@ fun SizzleApp(vm: AppViewModel) {
confirmButton = { TextButton(onClick = { vm.dismissNativeAudioError() }) { Text("OK") } },
)
}
// A .sng opened from another app (Mikro Seq's "Open in Sizzle", a file manager,
// the share sheet): ask before it replaces the current song, or say why not.
vm.incomingSong?.let { song ->
if (song.text == null) {
AlertDialog(
onDismissRequest = { vm.dismissIncomingSong() },
title = { Text("Open song") },
text = { Text(song.error ?: "Couldn't open ${song.name}.") },
confirmButton = { TextButton(onClick = { vm.dismissIncomingSong() }) { Text("OK") } },
)
} else {
AlertDialog(
onDismissRequest = { vm.dismissIncomingSong() },
title = { Text("Open ${song.name}?") },
text = {
Text(
"This replaces the patterns and arrangement of the current song " +
"(mixer and instruments stay). Save it first if you want to keep it.",
)
},
confirmButton = { TextButton(onClick = { vm.acceptIncomingSong() }) { Text("Replace") } },
dismissButton = { TextButton(onClick = { vm.dismissIncomingSong() }) { Text("Cancel") } },
)
}
}
}
/** The active tab's screen. */
@@ -136,6 +136,48 @@ class AppViewModel(
persistMidiClock(); touched()
}
// ----- MIDI sound module (Settings) -----
private val sizzleApp get() = appContext as cc.tiredsysadmin.android.sizzle.SizzleApp
/** "Keep running as MIDI sound module": owned by SizzleApp because the
* notification's Stop action changes it with no UI around. */
val soundModuleMode: StateFlow<Boolean> get() = sizzleApp.soundModuleEnabled
/** MIDI sources currently open (USB, Bluetooth, other apps' virtual ports). */
val midiSources: StateFlow<Int> get() = sizzleApp.soundModule.sources
fun updateSoundModuleMode(enabled: Boolean) = sizzleApp.setSoundModuleEnabled(enabled)
// ----- A song opened from another app (VIEW / SEND intent) -----
/** Waiting for the user to confirm replacing the current song, or to read why
* it can't be opened. */
var incomingSong by mutableStateOf<cc.tiredsysadmin.android.sizzle.io.IncomingSong?>(null); private set
fun offerIncomingSong(song: cc.tiredsysadmin.android.sizzle.io.IncomingSong) { incomingSong = song }
fun dismissIncomingSong() { incomingSong = null }
/** Replace the current song with the offered one. Stops playback first so the
* audio thread isn't reading the model while it is rewritten. Returns false
* (leaving the song as it was parsed so far) if the import fails. */
fun acceptIncomingSong(): Boolean {
val song = incomingSong ?: return false
val text = song.text ?: return false.also { incomingSong = null }
incomingSong = null
engine.stop()
val ok = importSng(text)
if (ok) {
project.name = song.name.substringBeforeLast(".sng").ifBlank { "untitled" }
clearArrangementSelection()
selectTab(TAB_TRACKER)
} else {
incomingSong = cc.tiredsysadmin.android.sizzle.io.IncomingSong(
"song", null, "Couldn't import this file. It doesn't look like a valid .sng song.",
)
}
return ok
}
private fun persistMidiClock() {
viewModelScope.launch { settingsStore.saveMidiClock(sendMidiClock, receiveMidiClock) }
}
@@ -547,10 +589,14 @@ class AppViewModel(
InputAction.NoteOffCell -> noteOffFocused()
is InputAction.NoteOn -> {
markNoteOn(action.pitch)
// MIDI notes route to the mixer track(s) listening on their channel;
// a channel-less source (physical keyboard) plays the default synth.
if (action.channel >= 1) engine.busNoteOn(action.channel, action.pitch, action.velocity)
else engine.liveNoteOn(action.pitch, action.velocity)
// MIDI notes were already played by the headless sound module
// (SizzleApp.soundModule) on the mixer track(s) listening on their
// channel; here they are only shown and punched in. A channel-less
// source (physical keyboard) plays the default synth.
if (!action.sounded) {
if (action.channel >= 1) engine.busNoteOn(action.channel, action.pitch, action.velocity)
else engine.liveNoteOn(action.pitch, action.velocity)
}
// On the Tracker tab with punch-in armed, also enter the note into the
// grid — recording its own velocity/channel so it plays back correctly.
if (selectedTab == TAB_TRACKER && punchInMode) {
@@ -560,8 +606,10 @@ class AppViewModel(
}
is InputAction.NoteOff -> {
markNoteOff(action.pitch)
if (action.channel >= 1) engine.busNoteOff(action.channel, action.pitch)
else engine.liveNoteOff(action.pitch)
if (!action.sounded) {
if (action.channel >= 1) engine.busNoteOff(action.channel, action.pitch)
else engine.liveNoteOff(action.pitch)
}
}
InputAction.PlayPause -> playPause()
InputAction.Stop -> stop()
@@ -973,20 +1021,10 @@ class AppViewModel(
kbdOctave = s.kbdOctave.coerceIn(0, 8)
vuMeters = s.vuMeters
// MIDI clock sync: feed the send thread live transport, follow an external
// clock into the transport/tempo, and restore the persisted toggles.
midiClock.playingProvider = { engine.transport.value.isPlaying }
midiClock.bpmProvider = { project.tempoBpm }
midiClock.noteSource = { engine.pollMidiOut() } // forward sequenced notes out
midiClock.onReceiveStart = {
viewModelScope.launch(Dispatchers.Main) { if (!engine.transport.value.isPlaying) engine.play() }
}
midiClock.onReceiveStop = {
viewModelScope.launch(Dispatchers.Main) { engine.pause() }
}
midiClock.onReceiveTempo = { bpm ->
viewModelScope.launch(Dispatchers.Main) { setTempo(bpm) }
}
// MIDI clock sync: the transport/tempo follow and the send thread's
// providers are wired in SizzleApp (they must work with no UI); here we
// restore the persisted toggles and redraw when a followed tempo lands.
viewModelScope.launch { midiClock.followedTempo.collect { setTempo(it) } }
sendMidiClock = s.sendMidiClock
midiClock.sendEnabled = s.sendMidiClock; engine.midiOutEnabled = s.sendMidiClock
receiveMidiClock = s.receiveMidiClock; midiClock.receiveEnabled = s.receiveMidiClock
@@ -1070,8 +1108,7 @@ class AppViewModel(
* look like a `.sng` (so the caller can surface a popup) rather than silently
* wiping the song with garbage. */
fun importSng(text: String): Boolean {
val looksLikeSng = Regex("(?m)^\\s*(version|bpm|sig|block)\\b").containsMatchIn(text)
if (!looksLikeSng) return false
if (!cc.tiredsysadmin.android.sizzle.io.SngFormat.looksLikeSng(text)) return false
runCatching {
cc.tiredsysadmin.android.sizzle.io.SngFormat.importInto(project, text)
}.getOrElse { return false }
@@ -52,6 +52,7 @@ import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@@ -503,7 +504,7 @@ private fun openUrl(context: Context, url: String) {
}
/** MIDI clock sync over USB + Bluetooth: drive external gear, or follow an external
* clock. Both off by default. */
* clock. Both off by default. Also the background sound-module switch. */
@Composable
private fun MidiSyncCard(vm: AppViewModel) {
@Suppress("UNUSED_VARIABLE") val rev = vm.revision
@@ -520,6 +521,16 @@ private fun MidiSyncCard(vm: AppViewModel) {
"Follow an external clock's tempo, and start/stop with it.",
vm.receiveMidiClock,
) { vm.updateReceiveMidiClock(it) }
HorizontalDivider()
val module by vm.soundModuleMode.collectAsState()
val sources by vm.midiSources.collectAsState()
ToggleRow(
"Keep running as MIDI sound module",
"Keep playing incoming MIDI with Sizzle in the background (another app can " +
"use it as its synth), with a notification while on. " +
"MIDI sources open now: $sources.",
module,
) { vm.updateSoundModuleMode(it) }
}
}
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Status-bar icon for the MIDI sound-module notification: a beamed pair of
eighth notes. Status-bar icons must be a single opaque colour on transparent. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M9,3v11.55A4,4 0,1 0,11 18V7h8v7.55A4,4 0,1 0,21 18V3H9z" />
</vector>
@@ -0,0 +1,58 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.input
import org.junit.Assert.assertEquals
import org.junit.Test
class MidiByteParserTest {
private val channel = mutableListOf<Triple<Int, Int, Int>>()
private val realtime = mutableListOf<Int>()
private val parser = MidiByteParser({ s, a, b -> channel += Triple(s, a, b) }, { realtime += it })
private fun feed(vararg b: Int) {
val bytes = ByteArray(b.size) { b[it].toByte() }
parser.feed(bytes, 0, bytes.size)
}
@Test fun oneMessagePerPacket() {
feed(0x99, 36, 100)
feed(0x89, 36, 0)
assertEquals(listOf(Triple(0x99, 36, 100), Triple(0x89, 36, 0)), channel)
}
@Test fun runningStatus() {
feed(0x90, 60, 100, 64, 90, 60, 0)
assertEquals(listOf(Triple(0x90, 60, 100), Triple(0x90, 64, 90), Triple(0x90, 60, 0)), channel)
}
@Test fun messageSplitAcrossPackets() {
feed(0x90, 60)
feed(100)
assertEquals(listOf(Triple(0x90, 60, 100)), channel)
}
@Test fun realtimeInsideAMessageDoesNotBreakIt() {
feed(0x90, 0xF8, 60, 0xFA, 100, 0xFC)
assertEquals(listOf(Triple(0x90, 60, 100)), channel)
assertEquals(listOf(0xF8, 0xFA, 0xFC), realtime)
}
@Test fun oneDataByteMessagesAndSysexSkipped() {
feed(0xC2, 5, 0xF0, 0x7E, 0x01, 0x02, 0xF7, 0xB0, 123, 0)
assertEquals(listOf(Triple(0xC2, 5, 0), Triple(0xB0, 123, 0)), channel)
}
@Test fun strayDataBytesWithoutStatusAreIgnored() {
feed(60, 100, 0x80, 60, 0)
assertEquals(listOf(Triple(0x80, 60, 0)), channel)
}
@Test fun offsetAndCountAreHonoured() {
val bytes = byteArrayOf(0x00, 0x90.toByte(), 60, 100, 0x7F)
parser.feed(bytes, 1, 3)
assertEquals(listOf(Triple(0x90, 60, 100)), channel)
}
}
@@ -0,0 +1,140 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.io
import cc.tiredsysadmin.android.sizzle.model.Arrangement
import cc.tiredsysadmin.android.sizzle.model.Cell
import cc.tiredsysadmin.android.sizzle.model.Pitch
import cc.tiredsysadmin.android.sizzle.model.Project
import cc.tiredsysadmin.android.sizzle.model.TimeSignature
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Files exported by Mikro Seq (internal/seq/sizzle.go, its sample pattern) in 4/4
* and 3/4: `#` comments, `loop`, `group`, `scale`/`root`, block names with spaces
* ("C1 muted"), blocks off the roll, `OFF` notes and channel-10 drums.
*/
class SngMikroSeqImportTest {
private fun load(name: String): String =
javaClass.getResource("/mikroseq/$name")!!.readText()
@Test
fun fourFour() {
val text = load("sig44.sng")
assertTrue(SngFormat.looksLikeSng(text))
val p = SngFormat.importInto(Project(), text)
assertEquals(97f, p.tempoBpm, 0.001f)
assertEquals(TimeSignature.FOUR_FOUR, p.timeSignature)
assertTrue(p.arrangement.loopEnabled)
assertEquals(listOf("C1", "C1 muted", "C2", "C6"), p.patterns.take(4).map { it.name })
assertEquals(listOf(16, 16, 48, 64), p.patterns.take(4).map { it.length })
// C1: drums on channel 10 (file channel 9), T1 and T3 keep their slots.
val c1 = p.patterns[0]
assertEquals(Pitch.parse("C-2"), c1.cell(0, 0).note)
assertEquals(10, c1.cell(0, 0).channel)
assertEquals(0x6E, c1.cell(0, 0).velocity)
assertEquals(Cell.OFF, c1.cell(0, 1).note)
assertEquals(Pitch.parse("F#2"), c1.cell(2, 2).note)
// C2: the tied bass on T4, channel 1, with OFF tokens.
val c2 = p.patterns[2]
assertEquals(Pitch.parse("B-1"), c2.cell(3, 0).note)
assertEquals(1, c2.cell(3, 0).channel)
assertEquals(Pitch.parse("C#2"), c2.cell(3, 6).note)
assertEquals(Cell.OFF, c2.cell(3, 9).note)
// C6: lead on channel 3.
assertEquals(3, p.patterns[3].cell(0, 0).channel)
// The roll: 96 beats for C1, C2, C6; the muted block is not on it.
for (lane in listOf(0, 2, 3)) {
assertEquals(lane, p.arrangement.patternAt(lane, 0))
assertEquals(lane, p.arrangement.patternAt(lane, 95))
assertEquals(Arrangement.EMPTY, p.arrangement.patternAt(lane, 96))
}
assertEquals(Arrangement.EMPTY, p.arrangement.patternAt(1, 0))
assertTrue(p.arrangement.lengthBars >= 24)
}
@Test
fun threeFour() {
val p = SngFormat.importInto(Project(), load("sig34.sng"))
assertEquals(TimeSignature.THREE_FOUR, p.timeSignature)
assertEquals(listOf("C1", "C1 muted", "C2", "C6"), p.patterns.take(4).map { it.name })
assertEquals(listOf(12, 12, 36, 48), p.patterns.take(4).map { it.length })
val c1 = p.patterns[0]
for (step in listOf(0, 3, 6, 9)) assertEquals(Pitch.parse("C-2"), c1.cell(0, step).note)
for (step in listOf(1, 4, 7, 10)) assertEquals(Cell.OFF, c1.cell(0, step).note)
assertEquals(Pitch.parse("D-2"), p.patterns[1].cell(1, 3).note) // muted T2
val c2 = p.patterns[2]
assertEquals(Pitch.parse("C#2"), c2.cell(3, 5).note)
assertEquals(Cell.OFF, c2.cell(3, 7).note)
assertEquals(Cell.OFF, c2.cell(3, 16).note)
assertEquals(2, p.arrangement.patternAt(2, 95))
assertEquals(Arrangement.EMPTY, p.arrangement.patternAt(2, 96))
assertTrue(p.arrangement.lengthBars >= 96 / 3)
}
@Test
fun moreBlocksThanLanesKeepsTheOnesOnTheRoll() {
// 8 canvases, each with a live block on the roll and a muted one off it:
// 16 blocks for 8 lanes.
val text = buildString {
appendLine("version 1\nbpm 120\nsig 4 4")
for (c in 1..8) {
appendLine("block C$c 16 1\nroll ####\ntrack T1 0\n0 C-4 64 ..\nendblock")
appendLine("block C$c muted 16 1\ntrack T2 0\n0 D-4 64 ..\nendblock")
}
}
val p = SngFormat.importInto(Project(), text)
assertEquals((1..8).map { "C$it" }, p.patterns.map { it.name })
for (lane in 0 until 8) assertEquals(lane, p.arrangement.patternAt(lane, 0))
}
@Test
fun trackNumbersBeyondFourTakeFreeSlotsAndExtraTracksAreDropped() {
val text = """
version 1
block A 16 6
track T1 0
0 C-4 .. ..
track T7 1
0 D-4 .. ..
track T2 2
0 E-4 .. ..
track T9 3
0 F-4 .. ..
track T12 4
0 G-4 .. ..
endblock
""".trimIndent()
val b = SngFormat.importInto(Project(), text).patterns[0]
assertEquals(Pitch.parse("C-4"), b.cell(0, 0).note)
assertEquals(Pitch.parse("D-4"), b.cell(1, 0).note) // T7 -> first free (2nd) slot
assertEquals(Pitch.parse("E-4"), b.cell(2, 0).note) // T2 taken -> next free
assertEquals(Pitch.parse("F-4"), b.cell(3, 0).note)
// T12 has no slot left: its G-4 is dropped rather than overwriting a track.
assertFalse((0 until 4).any { b.cell(it, 0).note == Pitch.parse("G-4") })
}
@Test
fun absurdBlockLengthIsBounded() {
val p = SngFormat.importInto(Project(), "version 1\nblock A 999999999 1\nendblock\n")
assertEquals(SngFormat.MAX_BLOCK_LENGTH, p.patterns[0].length)
}
@Test
fun plainTextIsNotASong() {
assertFalse(SngFormat.looksLikeSng("shopping list\nmilk\neggs"))
}
}
@@ -0,0 +1,93 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.playback
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class MidiSoundModuleTest {
/** Records engine calls as "on ch note vel" / "off ch note". */
private val engine = mutableListOf<String>()
private val module = MidiSoundModule(object : MidiSoundModule.NoteSink {
override fun busNoteOn(channel: Int, note: Int, velocity: Int) { engine += "on $channel $note $velocity" }
override fun busNoteOff(channel: Int, note: Int) { engine += "off $channel $note" }
})
@Test fun noteOnOffRouteToTheMixerChannel() {
assertTrue(module.onChannelMessage(1, 0x99, 36, 110)) // channel 10: drums
assertTrue(module.onChannelMessage(1, 0x89, 36, 0))
assertTrue(module.onChannelMessage(1, 0x92, 60, 90)) // channel 3
assertTrue(module.onChannelMessage(1, 0x92, 60, 0)) // velocity 0 == note off
assertEquals(listOf("on 10 36 110", "off 10 36", "on 3 60 90", "off 3 60"), engine)
assertTrue(module.heldNotes(1).isEmpty())
}
@Test fun otherMessagesAreLeftToTheCaller() {
assertFalse(module.onChannelMessage(1, 0xB0, 7, 100)) // CC 7: bindings / learn
assertFalse(module.onChannelMessage(1, 0xC0, 3, 0)) // program change
assertTrue(engine.isEmpty())
}
@Test fun disconnectReleasesOnlyThatSourcesHeldNotes() {
module.sourceConnected(1); module.sourceConnected(2)
assertEquals(2, module.sources.value)
module.onChannelMessage(1, 0x90, 60, 100)
module.onChannelMessage(1, 0x99, 38, 100)
module.onChannelMessage(2, 0x91, 64, 100)
engine.clear()
module.sourceDisconnected(1)
assertEquals(setOf("off 1 60", "off 10 38"), engine.toSet())
assertEquals(1, module.sources.value)
assertEquals(setOf(2 to 64), module.heldNotes(2))
}
@Test fun allNotesOffReleasesTheChannelAcrossSources() {
module.onChannelMessage(1, 0x90, 60, 100)
module.onChannelMessage(2, 0x90, 62, 100)
module.onChannelMessage(1, 0x93, 70, 100)
engine.clear()
assertTrue(module.onChannelMessage(1, 0xB0, 123, 0))
assertEquals(setOf("off 1 60", "off 1 62"), engine.toSet())
assertEquals(setOf(4 to 70), module.heldNotes(1))
assertTrue(module.heldNotes(2).isEmpty())
}
@Test fun allSoundOffAlsoReleases() {
module.onChannelMessage(1, 0x90, 60, 100)
engine.clear()
assertTrue(module.onChannelMessage(1, 0xB0, 120, 0))
assertEquals(listOf("off 1 60"), engine)
}
@Test fun listenerMirrorsNotesSoTheUiNeedNotSoundThem() {
val seen = mutableListOf<String>()
module.noteListener = { on, ch, note, vel -> seen += "${if (on) "on" else "off"} $ch $note $vel" }
module.onChannelMessage(1, 0x90, 60, 100)
module.sourceDisconnected(1)
assertEquals(listOf("on 1 60 100", "off 1 60 0"), seen)
}
@Test fun realtimeIsForwarded() {
val rt = mutableListOf<Int>()
module.realtime = { rt += it }
module.onRealtime(0xFA); module.onRealtime(0xF8); module.onRealtime(0xFC)
assertEquals(listOf(0xFA, 0xF8, 0xFC), rt)
}
@Test fun releaseAllEmptiesEverySource() {
module.onChannelMessage(1, 0x90, 60, 100)
module.onChannelMessage(2, 0x95, 61, 100)
engine.clear()
module.releaseAll()
assertEquals(setOf("off 1 60", "off 6 61"), engine.toSet())
assertTrue(module.heldNotes(1).isEmpty() && module.heldNotes(2).isEmpty())
}
}
+108
View File
@@ -0,0 +1,108 @@
# sizzletracker song
# exported from Mikro Seq: one block per canvas, all looping in parallel
version 1
bpm 97
sig 3 4
loop 0 23
group 0 Mikro Seq
block C1 12 2
scale Mel Minor
root D
roll ################################################################################################
track T1 9
0 C-2 6E ..
1 OFF .. ..
3 C-2 6E ..
4 OFF .. ..
6 C-2 6E ..
7 OFF .. ..
9 C-2 6E ..
10 OFF .. ..
track T3 9
2 F#2 46 ..
3 OFF .. ..
endblock
block C1 muted 12 1
scale Mel Minor
root D
track T2 9
3 D-2 64 ..
4 OFF .. ..
endblock
block C2 36 1
scale Mel Minor
root D
roll ################################################################################################
track T4 0
0 B-1 5A ..
5 C#2 5A ..
7 OFF .. ..
8 C#2 5A ..
9 D-2 5A ..
14 B-1 5A ..
16 OFF .. ..
17 B-1 5A ..
18 C#2 5A ..
23 D-2 5A ..
25 OFF .. ..
26 D-2 5A ..
27 B-1 5A ..
32 C#2 5A ..
34 OFF .. ..
35 C#2 5A ..
endblock
block C6 48 1
scale Mel Minor
root D
roll ################################################################################################
track T1 2
0 B-3 50 ..
1 D-4 40 ..
2 OFF .. ..
3 D-4 40 ..
4 OFF .. ..
5 F-4 50 ..
6 OFF .. ..
7 D-4 50 ..
8 D-4 40 ..
9 F-4 50 ..
10 D-4 40 ..
11 OFF .. ..
12 D-4 40 ..
13 OFF .. ..
14 E-4 50 ..
15 OFF .. ..
16 B-3 50 ..
17 D-4 40 ..
18 D-4 50 ..
19 D-4 40 ..
20 OFF .. ..
21 D-4 40 ..
22 OFF .. ..
23 D-4 50 ..
24 OFF .. ..
25 F-4 50 ..
26 D-4 40 ..
27 C#4 50 ..
28 D-4 40 ..
29 OFF .. ..
30 D-4 40 ..
31 OFF .. ..
32 B-3 50 ..
33 OFF .. ..
34 D-4 50 ..
35 D-4 40 ..
36 F-4 50 ..
37 D-4 40 ..
38 OFF .. ..
39 D-4 40 ..
40 OFF .. ..
41 F-4 50 ..
42 OFF .. ..
43 C#4 50 ..
44 D-4 40 ..
45 E-4 50 ..
46 D-4 40 ..
47 OFF .. ..
endblock
+123
View File
@@ -0,0 +1,123 @@
# sizzletracker song
# exported from Mikro Seq: one block per canvas, all looping in parallel
version 1
bpm 97
sig 4 4
loop 0 23
group 0 Mikro Seq
block C1 16 2
scale Mel Minor
root D
roll ################################################################################################
track T1 9
0 C-2 6E ..
1 OFF .. ..
4 C-2 6E ..
5 OFF .. ..
8 C-2 6E ..
9 OFF .. ..
12 C-2 6E ..
13 OFF .. ..
track T3 9
2 F#2 46 ..
3 OFF .. ..
endblock
block C1 muted 16 1
scale Mel Minor
root D
track T2 9
4 D-2 64 ..
5 OFF .. ..
endblock
block C2 48 1
scale Mel Minor
root D
roll ################################################################################################
track T4 0
0 B-1 5A ..
6 C#2 5A ..
9 OFF .. ..
10 C#2 5A ..
12 D-2 5A ..
18 B-1 5A ..
21 OFF .. ..
22 B-1 5A ..
24 C#2 5A ..
30 D-2 5A ..
33 OFF .. ..
34 D-2 5A ..
36 B-1 5A ..
42 C#2 5A ..
45 OFF .. ..
46 C#2 5A ..
endblock
block C6 64 1
scale Mel Minor
root D
roll ################################################################################################
track T1 2
0 B-3 50 ..
1 D-4 40 ..
2 OFF .. ..
3 D-4 50 ..
4 D-4 40 ..
5 OFF .. ..
6 F-4 50 ..
7 D-4 40 ..
8 OFF .. ..
9 D-4 50 ..
10 D-4 40 ..
11 OFF .. ..
12 F-4 50 ..
13 D-4 40 ..
14 OFF .. ..
15 C#4 50 ..
16 D-4 40 ..
17 OFF .. ..
18 E-4 50 ..
19 D-4 40 ..
20 OFF .. ..
21 B-3 50 ..
22 D-4 40 ..
23 OFF .. ..
24 D-4 50 ..
25 D-4 40 ..
26 OFF .. ..
27 F-4 50 ..
28 D-4 40 ..
29 OFF .. ..
30 D-4 50 ..
31 D-4 40 ..
32 OFF .. ..
33 F-4 50 ..
34 D-4 40 ..
35 OFF .. ..
36 C#4 50 ..
37 D-4 40 ..
38 OFF .. ..
39 E-4 50 ..
40 D-4 40 ..
41 OFF .. ..
42 B-3 50 ..
43 D-4 40 ..
44 OFF .. ..
45 D-4 50 ..
46 D-4 40 ..
47 OFF .. ..
48 F-4 50 ..
49 D-4 40 ..
50 OFF .. ..
51 D-4 50 ..
52 D-4 40 ..
53 OFF .. ..
54 F-4 50 ..
55 D-4 40 ..
56 OFF .. ..
57 C#4 50 ..
58 D-4 40 ..
59 OFF .. ..
60 E-4 50 ..
61 D-4 40 ..
62 OFF .. ..
endblock
+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.
---
+2 -2
View File
@@ -8,8 +8,8 @@
# or polish. android.versionCode is monotonic and bumps by 1 on every release,
# because F-Droid and the Android package manager order installs by it alone.
android.versionName = 0.27.0
android.versionCode = 56
android.versionName = 0.28.0
android.versionCode = 57
# No desktop builds exist yet. These lines are the agreed slots so a port starts
# with a version instead of inventing one; `-` means "not built on this