From df64af8c9ba09a0ff2cf8b184a198a443b9b21f6 Mon Sep 17 00:00:00 2001 From: Reactorcoremeltdown Date: Thu, 12 Nov 2026 22:32:04 +0100 Subject: [PATCH] MIDI inputs list with per-source switches; reconnect dead virtual sources (v0.29.0) - Setup -> MIDI Sync lists every MIDI source that can send to Sizzle with a switch and its state (Listening / Not connected / Off) plus Reconnect. Off-choices persist by a stable MidiSourceKey (Android ids change). - When the app behind a virtual source dies/restarts, Android keeps the device and our connection, drops the service binding and sends no callback, so Sizzle went deaf to e.g. a restarted Mikro Seq. A worker thread now probes open virtual sources every 3 s (openOutputPort is null from a dead server) and reopens dead ones; resume re-scans; zero-open port status is also treated as dead. - Verified on an Android 15 emulator: force-stop + restart Mikro Seq -> reconnected within ~3 s, notes flowing with both apps in background. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 + .../android/sizzle/MainActivity.kt | 2 + .../tiredsysadmin/android/sizzle/SizzleApp.kt | 6 + .../android/sizzle/input/MidiInput.kt | 258 ++++++++++++++++-- .../android/sizzle/input/MidiSourceKey.kt | 29 ++ .../android/sizzle/io/SettingsStore.kt | 10 + .../android/sizzle/ui/AppViewModel.kt | 9 + .../sizzle/ui/settings/SettingsScreen.kt | 46 +++- .../android/sizzle/input/MidiSourceKeyTest.kt | 49 ++++ docs/DEVELOPER_HANDOVER.md | 23 +- docs/USER_GUIDE.md | 6 + versions.properties | 4 +- 12 files changed, 424 insertions(+), 29 deletions(-) create mode 100644 app/src/main/java/cc/tiredsysadmin/android/sizzle/input/MidiSourceKey.kt create mode 100644 app/src/test/java/cc/tiredsysadmin/android/sizzle/input/MidiSourceKeyTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 02a6404..e15fcc0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,17 @@ 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.29.0 (versionCode 58) + +- **MIDI inputs list** (Setup → MIDI Sync): every MIDI source Sizzle can hear + (controllers, other apps' virtual ports such as Mikro Seq), each with a switch + and its state (Listening / Not connected / Off), plus a **Reconnect** button. + The choice is saved; new sources are on by default. +- **Automatic reconnect** when the app behind a virtual source restarts (crash, + update, force stop). Android gives no signal for that and left Sizzle holding a + dead connection, so Mikro Seq could play into nothing. Sizzle now checks open + virtual sources every 3 s and reopens a dead one, and re-scans on every resume. + ## 0.28.0 (versionCode 57) - **Background MIDI sound module.** New setting "Keep running as MIDI sound diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/MainActivity.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/MainActivity.kt index c39e75e..29ae648 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/MainActivity.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/MainActivity.kt @@ -129,6 +129,8 @@ class MainActivity : ComponentActivity() { // 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) + // Pick up MIDI sources that appeared or whose app restarted while we were away. + app.refreshMidi() } override fun onStop() { diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/SizzleApp.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/SizzleApp.kt index 045b2a3..3de54f7 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/SizzleApp.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/SizzleApp.kt @@ -130,6 +130,10 @@ class SizzleApp : Application() { if (midiOwners.add(owner) && midiOwners.size == 1) { midiInput.start(); midiClock.start() } } + /** Re-scan MIDI sources (MainActivity.onResume): opens anything enabled that + * isn't open, e.g. after a source's app was reinstalled. */ + fun refreshMidi() { if (midiOwners.isNotEmpty()) midiInput.refresh() } + fun releaseMidi(owner: String) { if (midiOwners.remove(owner) && midiOwners.isEmpty()) { midiInput.stop(); midiClock.stop() } } @@ -162,6 +166,8 @@ class SizzleApp : Application() { audioEngine.midiOutEnabled = s.sendMidiClock midiClock.receiveEnabled = s.receiveMidiClock _soundModuleEnabled.value = s.soundModule + midiInput.restoreDisabled(s.midiSourcesOff) + midiInput.onDisabledChanged = { keys -> appScope.launch { settingsStore.saveMidiSourcesOff(keys) } } } private val appScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/input/MidiInput.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/input/MidiInput.kt index 7cc94da..b9bc13a 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/input/MidiInput.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/input/MidiInput.kt @@ -4,31 +4,59 @@ package cc.tiredsysadmin.android.sizzle.input import android.content.Context +import android.content.pm.ServiceInfo import android.media.midi.MidiDevice import android.media.midi.MidiDeviceInfo +import android.media.midi.MidiDeviceStatus import android.media.midi.MidiManager import android.media.midi.MidiOutputPort import android.media.midi.MidiReceiver +import android.os.Build import android.os.Handler import android.os.Looper +import android.os.SystemClock +import android.util.Log import cc.tiredsysadmin.android.sizzle.playback.MidiSoundModule +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +/** One MIDI source as the Setup screen lists it. [key] is stable across restarts + * (unlike Android's device id), so the on/off choice can be saved. */ +data class MidiSource(val key: String, val name: String, val enabled: Boolean, val connected: Boolean) /** * 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. * - * Every source gets its own [MidiByteParser] (running status is per stream). + * Every source that can send to us is listed in [sources]. Each is listened to + * unless the user switched it off in Setup ([setEnabled]; the off-keys are + * persisted by the caller via [onDisabledChanged]), so a new controller or app + * works with no setup. + * + * Every open 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. * - * A source that goes away (unplugged, or removed by the system) is closed and its - * held notes are released through [MidiSoundModule.sourceDisconnected]. + * Reconnecting: a virtual source's app can die and restart (crash, update, force + * stop, the system reclaiming it) without Android removing its device or telling + * its clients anything: our MidiDevice keeps pointing at the dead process and no + * callback fires (verified on Android 15). So every [PROBE_MS] a worker thread asks + * each open virtual source for an output port: a live one answers (the probe port + * is closed at once), a dead one fails, and that source is closed (releasing its + * held notes) and opened again, which makes Android rebind the app's MIDI service. + * A port-status report of "nobody has the output open" while we think we do is + * treated the same way. [refresh] (every Activity resume) probes at once and opens + * anything enabled that isn't open; [reconnect] (the Setup button) closes and + * reopens everything as a last resort. A source that goes away is + * closed and its held notes are released through [MidiSoundModule.sourceDisconnected]. * * Note: this handles MIDI *input*. Sending MIDI out lives in [MidiClock]. + * Main thread for everything except the parsers (each port's own thread). */ class MidiInput( context: Context, @@ -40,44 +68,173 @@ class MidiInput( private val midiManager = context.getSystemService(Context.MIDI_SERVICE) as? MidiManager private val handler = Handler(Looper.getMainLooper()) - /** Open sources by [MidiDeviceInfo.getId]. Touched only on the main thread. */ + /** Every device that can send to us, by [MidiDeviceInfo.getId]. */ + private val known = LinkedHashMap() + /** Open sources by device id. */ private val open = HashMap>() + /** Device ids with an [MidiManager.openDevice] in flight. */ + private val opening = HashSet() private var callback: MidiManager.DeviceCallback? = null + /** When we last opened or closed each device id, to ignore the port-status + * echoes of our own actions (see [onStatus]). */ + private val lastChange = HashMap() - /** 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. */ + /** Keys of the sources the user switched off. Set before [start]. */ + var disabledKeys: Set = emptySet() + private set + + /** Called with the new off-set when the user changes it, to persist it. */ + var onDisabledChanged: ((Set) -> Unit)? = null + + private val _sources = MutableStateFlow>(emptyList()) + /** All sources that can send to us, for the Setup screen. */ + val sources: StateFlow> = _sources.asStateFlow() + + fun restoreDisabled(keys: Set) { disabledKeys = keys; publish() } + + /** Start listening: open every enabled device that can send to us and watch for + * hot-plug and status events. Idempotent; safe if the device has no MIDI. */ fun start() { val mm = midiManager ?: return if (callback != null) return val cb = object : MidiManager.DeviceCallback() { - override fun onDeviceAdded(device: MidiDeviceInfo) = openDevice(device) - override fun onDeviceRemoved(device: MidiDeviceInfo) = closeDevice(device.id) + override fun onDeviceAdded(device: MidiDeviceInfo) = add(device) + override fun onDeviceRemoved(device: MidiDeviceInfo) { + known.remove(device.id) + closeDevice(device.id) + publish() + } + override fun onDeviceStatusChanged(status: MidiDeviceStatus) = onStatus(status) } callback = cb - mm.devices.forEach(::openDevice) - mm.registerDeviceCallback(cb, handler) + allDevices(mm).forEach(::add) + registerCallback(mm, cb) + handler.postDelayed(probeTick, PROBE_MS) } - /** Close every source (releasing their held notes). Main thread. */ + /** Close every source (releasing their held notes). */ fun stop() { callback?.let { cb -> runCatching { midiManager?.unregisterDeviceCallback(cb) } } callback = null + handler.removeCallbacks(probeTick) open.keys.toList().forEach(::closeDevice) + opening.clear() + known.clear() + publish() + } + + /** Pick up anything missed: new devices, and enabled ones that aren't open. */ + fun refresh() { + val mm = midiManager ?: return + if (callback == null) return + allDevices(mm).forEach(::add) + probe() + } + + /** Close and reopen every enabled source (Setup's Reconnect button). */ + fun reconnect() { + if (callback == null) return + open.keys.toList().forEach(::closeDevice) + known.clear() + refresh() + publish() + } + + /** Listen to the source with [key], or stop listening to it. */ + fun setEnabled(key: String, enabled: Boolean) { + disabledKeys = if (enabled) disabledKeys - key else disabledKeys + key + onDisabledChanged?.invoke(disabledKeys) + for ((id, info) in known) { + if (keyOf(info) != key) continue + if (enabled) openDevice(info) else closeDevice(id) + } + publish() + } + + private fun add(info: MidiDeviceInfo) { + // We want devices that can SEND to us (they expose output ports). + if (info.outputPortCount == 0) return + known[info.id] = info + if (keyOf(info) !in disabledKeys) openDevice(info) + publish() + } + + /** Port status from Android. If nobody holds the output open while we believe we + * do, the app behind it restarted and our connection is dead: reopen it. */ + private fun onStatus(status: MidiDeviceStatus) { + val info = status.deviceInfo + val id = info.id + if (id !in open || info.outputPortCount == 0) return + val sinceOwnChange = SystemClock.uptimeMillis() - (lastChange[id] ?: 0L) + if (sinceOwnChange < STATUS_SETTLE_MS) return + if (status.getOutputPortOpenCount(0) == 0) { + Log.i(TAG, "${nameOf(info)}: connection lost, reopening") + closeDevice(id) + openDevice(info) + publish() + } + } + + private val probeTick = object : Runnable { + override fun run() { + if (callback == null) return + probe() + handler.postDelayed(this, PROBE_MS) + } + } + + /** Off-main-thread liveness check of every open virtual source (see the class + * doc). A hung source app can't stall the UI this way. */ + private fun probe() { + val targets = open.entries + .filter { (_, dp) -> dp.first.info.type == MidiDeviceInfo.TYPE_VIRTUAL } + .map { (id, dp) -> id to dp.first } + if (targets.isEmpty() || probing) return + probing = true + probeExecutor.execute { + val dead = targets.filter { (_, device) -> + val port = runCatching { device.openOutputPort(0) }.getOrNull() + port?.let { runCatching { it.close() } } + port == null + } + handler.post { + probing = false + for ((id, device) in dead) { + // Still the same connection? (It may have been closed or replaced meanwhile.) + if (open[id]?.first !== device) continue + val info = device.info + Log.i(TAG, "${nameOf(info)}: connection lost, reopening") + closeDevice(id) + openDevice(info) + } + if (dead.isNotEmpty()) publish() + } + } + } + + private var probing = false + private val probeExecutor = java.util.concurrent.Executors.newSingleThreadExecutor { r -> + Thread(r, "sizzle-midi-probe").apply { isDaemon = true } } private fun openDevice(info: MidiDeviceInfo) { - // We want devices that can SEND to us (they expose output ports). - if (info.outputPortCount == 0 || info.id in open) return - midiManager?.openDevice(info, { device -> - 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 id = info.id + if (id in open || id in opening) return + val mm = midiManager ?: return + opening += id + mm.openDevice(info, { device -> + opening -= id + device ?: run { Log.w(TAG, "${nameOf(info)}: could not open"); publish(); return@openDevice } + // stop() ran, the device was opened twice, or the user switched it off + // while this was pending. + if (callback == null || id in open || keyOf(info) in disabledKeys) { + runCatching { device.close() }; return@openDevice + } + val port = device.openOutputPort(0) + ?: run { runCatching { device.close() }; publish(); return@openDevice } val parser = MidiByteParser( onChannel = { status, d1, d2 -> - val consumed = module.onChannelMessage(source, status, d1, d2) + val consumed = module.onChannelMessage(id, status, d1, d2) if (!consumed && (status and 0xF0) == 0xB0) handleCc(d1, d2) }, onRealtime = module::onRealtime, @@ -86,18 +243,63 @@ class MidiInput( override fun onSend(data: ByteArray, offset: Int, count: Int, timestamp: Long) = parser.feed(data, offset, count) }) - open[source] = device to port - module.sourceConnected(source) + open[id] = device to port + lastChange[id] = SystemClock.uptimeMillis() + module.sourceConnected(id) + Log.i(TAG, "${nameOf(info)}: listening") + publish() }, handler) } private fun closeDevice(id: Int) { val (device, port) = open.remove(id) ?: return + lastChange[id] = SystemClock.uptimeMillis() runCatching { port.close() } runCatching { device.close() } module.sourceDisconnected(id) } + private fun publish() { + _sources.value = known.values + .map { MidiSource(keyOf(it), nameOf(it), keyOf(it) !in disabledKeys, it.id in open) } + .distinctBy { it.key } + } + + @Suppress("DEPRECATION") // getDevices / the Handler overload: still the only way below API 33 + private fun allDevices(mm: MidiManager): List = mm.devices.toList() + + @Suppress("DEPRECATION") + private fun registerCallback(mm: MidiManager, cb: MidiManager.DeviceCallback) = + mm.registerDeviceCallback(cb, handler) + + private fun keyOf(info: MidiDeviceInfo): String { + val p = info.properties + @Suppress("DEPRECATION") + val service = if (Build.VERSION.SDK_INT >= 33) { + p.getParcelable(PROPERTY_SERVICE_INFO, ServiceInfo::class.java) + } else { + p.getParcelable(PROPERTY_SERVICE_INFO) + } + @Suppress("DEPRECATION") + val bluetooth = p.getParcelable(MidiDeviceInfo.PROPERTY_BLUETOOTH_DEVICE) + return MidiSourceKey.of( + type = info.type, + manufacturer = p.getString(MidiDeviceInfo.PROPERTY_MANUFACTURER), + product = p.getString(MidiDeviceInfo.PROPERTY_PRODUCT), + name = p.getString(MidiDeviceInfo.PROPERTY_NAME), + service = service?.let { "${it.packageName}/${it.name}" }, + bluetooth = bluetooth?.toString(), + ) + } + + private fun nameOf(info: MidiDeviceInfo): String = info.properties.let { p -> + MidiSourceKey.displayName( + p.getString(MidiDeviceInfo.PROPERTY_MANUFACTURER), + p.getString(MidiDeviceInfo.PROPERTY_PRODUCT), + p.getString(MidiDeviceInfo.PROPERTY_NAME), + ) + } + private fun handleCc(cc: Int, value: Int) { val actionId = ccBindings[cc] if (actionId == null) { @@ -133,4 +335,14 @@ class MidiInput( } action?.let(router::dispatch) } + + private companion object { + const val TAG = "SizzleMidi" + /** MidiDeviceInfo.PROPERTY_SERVICE_INFO: set on virtual devices, but @hide in the SDK. */ + const val PROPERTY_SERVICE_INFO = "service_info" + /** How often open virtual sources are checked for a dead app behind them. */ + const val PROBE_MS = 3000L + /** Port-status events this soon after our own open/close are its echo. */ + const val STATUS_SETTLE_MS = 1000L + } } diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/input/MidiSourceKey.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/input/MidiSourceKey.kt new file mode 100644 index 0000000..5d4f6ce --- /dev/null +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/input/MidiSourceKey.kt @@ -0,0 +1,29 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +package cc.tiredsysadmin.android.sizzle.input + +/** + * Stable identity and display name for a MIDI source. Android's device id changes + * on every reconnect and reboot, so the user's on/off choice is keyed on what the + * device says about itself instead: its type, maker/product/name, the service + * that publishes it (virtual devices from other apps) or its Bluetooth address. + * Pure Kotlin, unit-tested. + */ +object MidiSourceKey { + + fun of( + type: Int, + manufacturer: String?, + product: String?, + name: String?, + service: String?, + bluetooth: String?, + ): String = listOf(type.toString(), manufacturer, product, name, service, bluetooth) + .joinToString("|") { it.orEmpty().replace("|", "/") } + + /** What the device calls itself: its name, else its product ("Mikro Seq"), + * else its maker. */ + fun displayName(manufacturer: String?, product: String?, name: String?): String = + listOf(name, product, manufacturer).firstOrNull { !it.isNullOrBlank() } ?: "MIDI device" +} diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/SettingsStore.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/SettingsStore.kt index 4e0dd58..df6ef31 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/SettingsStore.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/SettingsStore.kt @@ -10,6 +10,7 @@ import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey +import androidx.datastore.preferences.core.stringSetPreferencesKey import androidx.datastore.preferences.preferencesDataStore import kotlinx.coroutines.flow.first @@ -36,6 +37,8 @@ data class AppSettings( /** 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, + /** MIDI sources the user switched off in Setup ([cc.tiredsysadmin.android.sizzle.input.MidiSourceKey]). */ + val midiSourcesOff: Set = emptySet(), ) /** @@ -61,6 +64,7 @@ class SettingsStore(private val context: Context) { sendMidiClock = prefs[MIDI_CLOCK_SEND] ?: false, receiveMidiClock = prefs[MIDI_CLOCK_RECV] ?: false, soundModule = prefs[SOUND_MODULE] ?: false, + midiSourcesOff = prefs[MIDI_SOURCES_OFF] ?: emptySet(), ) } @@ -105,6 +109,11 @@ class SettingsStore(private val context: Context) { context.settingsDataStore.edit { prefs -> prefs[SOUND_MODULE] = enabled } } + /** Persist the MIDI sources switched off in Setup. */ + suspend fun saveMidiSourcesOff(keys: Set) { + context.settingsDataStore.edit { prefs -> prefs[MIDI_SOURCES_OFF] = keys } + } + private companion object { val PALETTE = stringPreferencesKey("palette") val RECORD_DIR = stringPreferencesKey("recordDirUri") @@ -115,5 +124,6 @@ class SettingsStore(private val context: Context) { val MIDI_CLOCK_SEND = booleanPreferencesKey("midiClockSend") val MIDI_CLOCK_RECV = booleanPreferencesKey("midiClockRecv") val SOUND_MODULE = booleanPreferencesKey("soundModule") + val MIDI_SOURCES_OFF = stringSetPreferencesKey("midiSourcesOff") } } diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt index 57d1439..26ea56d 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt @@ -148,6 +148,15 @@ class AppViewModel( fun updateSoundModuleMode(enabled: Boolean) = sizzleApp.setSoundModuleEnabled(enabled) + /** Every MIDI source that can send to Sizzle, with whether it is listened to. */ + val midiInputSources: StateFlow> + get() = midiInput.sources + + fun setMidiSourceEnabled(key: String, enabled: Boolean) = midiInput.setEnabled(key, enabled) + + /** Close and reopen every MIDI source (e.g. after the sending app restarted). */ + fun reconnectMidi() = midiInput.reconnect() + // ----- 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. */ diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/settings/SettingsScreen.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/settings/SettingsScreen.kt index 006a3e4..1ff2d56 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/settings/SettingsScreen.kt @@ -523,14 +523,54 @@ private fun MidiSyncCard(vm: AppViewModel) { ) { 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.", + "use it as its synth), with a notification while on.", module, ) { vm.updateSoundModuleMode(it) } + HorizontalDivider() + MidiInputsList(vm) + } +} + +/** The MIDI sources Sizzle can listen to (controllers, other apps' virtual ports), + * each with a switch, plus Reconnect for a source whose app restarted. */ +@Composable +private fun MidiInputsList(vm: AppViewModel) { + val sources by vm.midiInputSources.collectAsState() + Row( + Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text("MIDI inputs", style = MaterialTheme.typography.bodyMedium) + Text( + "Sources Sizzle listens to. Each mixer track plays the notes on its MIDI channel.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + OutlinedButton(onClick = { vm.reconnectMidi() }) { Text("Reconnect") } + } + if (sources.isEmpty()) { + Text( + "No MIDI sources found.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + for (src in sources) { + ToggleRow( + src.name, + when { + !src.enabled -> "Off" + src.connected -> "Listening" + else -> "Not connected (tap Reconnect)" + }, + src.enabled, + ) { vm.setMidiSourceEnabled(src.key, it) } } } diff --git a/app/src/test/java/cc/tiredsysadmin/android/sizzle/input/MidiSourceKeyTest.kt b/app/src/test/java/cc/tiredsysadmin/android/sizzle/input/MidiSourceKeyTest.kt new file mode 100644 index 0000000..72de5d4 --- /dev/null +++ b/app/src/test/java/cc/tiredsysadmin/android/sizzle/input/MidiSourceKeyTest.kt @@ -0,0 +1,49 @@ +// 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.Assert.assertNotEquals +import org.junit.Test + +class MidiSourceKeyTest { + + private val mikroSeq = MidiSourceKey.of( + 2, "tiredsysadmin", "Mikro Seq", null, + "cc.tiredsysadmin.android.mikroseq/cc.tiredsysadmin.android.mikroseq.SeqMidiService", null, + ) + + @Test fun sameDeviceSameKeyRegardlessOfAndroidId() { + val again = MidiSourceKey.of( + 2, "tiredsysadmin", "Mikro Seq", null, + "cc.tiredsysadmin.android.mikroseq/cc.tiredsysadmin.android.mikroseq.SeqMidiService", null, + ) + assertEquals(mikroSeq, again) + } + + @Test fun differentDevicesDiffer() { + val usb = MidiSourceKey.of(1, "Android", "USB Peripheral Port", "Android USB Peripheral Port", null, null) + val sunvox = MidiSourceKey.of(2, "NightRadio", "SunVox", null, "nightradio.sunvox/x.MidiService", null) + assertNotEquals(mikroSeq, usb) + assertNotEquals(mikroSeq, sunvox) + val bt1 = MidiSourceKey.of(3, null, null, "WIDI", null, "AA:BB") + val bt2 = MidiSourceKey.of(3, null, null, "WIDI", null, "AA:CC") + assertNotEquals(bt1, bt2) + } + + @Test fun separatorInsideAFieldCannotForgeAnotherKey() { + assertNotEquals( + MidiSourceKey.of(1, "a|b", null, null, null, null), + MidiSourceKey.of(1, "a", "b", null, null, null), + ) + } + + @Test fun displayNamePrefersNameThenProductThenMaker() { + assertEquals("Android USB Peripheral Port", + MidiSourceKey.displayName("Android", "USB Peripheral Port", "Android USB Peripheral Port")) + assertEquals("Mikro Seq", MidiSourceKey.displayName("tiredsysadmin", "Mikro Seq", null)) + assertEquals("tiredsysadmin", MidiSourceKey.displayName("tiredsysadmin", " ", "")) + assertEquals("MIDI device", MidiSourceKey.displayName(null, null, null)) + } +} diff --git a/docs/DEVELOPER_HANDOVER.md b/docs/DEVELOPER_HANDOVER.md index e777ad9..ee6e1d9 100644 --- a/docs/DEVELOPER_HANDOVER.md +++ b/docs/DEVELOPER_HANDOVER.md @@ -206,7 +206,8 @@ cc.tiredsysadmin.android.sizzle │ ├── GamepadInput.kt KeyEvent/MotionEvent -> InputAction (rebindable) │ ├── 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 +│ ├── MidiSourceKey.kt Stable key + display name for a MIDI source (persisted on/off choice) +│ └── MidiInput.kt Lists/opens MIDI sources (USB, BLE, other apps' virtual ports), reconnects dead ones -> MidiSoundModule / CC bindings │ ├── audio/ The real-time sound engine (own thread) │ ├── Transport.kt TransportState snapshot published to the UI @@ -347,6 +348,26 @@ foreground on pause, and its notification manager re-derives that state from `InputRouter` as `NoteOn(…, sounded = true)`, which the ViewModel records but does not play again. With no UI collecting, the router drops them. +**Which sources, and staying connected (0.29.0).** `MidiInput` keeps every +device that can send to us in `sources` (a `StateFlow>` the +Setup screen lists with a switch each). Sources are listened to unless switched +off; the off-set is persisted as `MidiSourceKey`s (type + maker/product/name + +publishing service or Bluetooth address), because Android's device id changes on +every reconnect. The trap this solves: when the app behind a *virtual* source +dies and restarts (crash, update, force stop), Android keeps the device, keeps +our connection record, drops its service binding, and tells clients nothing: +no `onDeviceRemoved`, no `onDeviceStatusChanged` (checked on Android 15: +`dumpsys midi` shows `Status: null … mServiceConnection: null`). Our +`MidiOutputPort` just goes silent. So a worker thread probes each open virtual +source every 3 s with `MidiDevice.openOutputPort(0)` (null from a dead server; +a live one's probe port is closed at once) and reopens dead ones through +`MidiManager.openDevice`, which makes Android rebind the app's MIDI service. +`refresh()` runs on every Activity resume and the Setup "Reconnect" button closes +and reopens everything. A status report of zero open output ports while we hold +one is treated as dead too (events within 1 s of our own open/close are ignored). +USB and Bluetooth sources are not probed: Android reports their removal. +`MidiInput` logs connects/reconnects under the `SizzleMidi` tag. + **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 diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md index e2ea7ad..8943103 100644 --- a/docs/USER_GUIDE.md +++ b/docs/USER_GUIDE.md @@ -303,6 +303,12 @@ you delete stay deleted. 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. +- **MIDI Sync → MIDI inputs** — every MIDI source Sizzle can hear (controllers, + and other apps such as Mikro Seq), each with a switch. New sources are on. If a + source shows "Not connected", or an app you play from stopped being heard, tap + **Reconnect** (Sizzle also reconnects by itself within a few seconds when the + sending app restarts). Remember to give each mixer track a MIDI channel and an + instrument, or incoming notes have nowhere to sound. - **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. diff --git a/versions.properties b/versions.properties index f4a8466..75d65e7 100644 --- a/versions.properties +++ b/versions.properties @@ -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.28.0 -android.versionCode = 57 +android.versionName = 0.29.0 +android.versionCode = 58 # 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