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 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
fb9a219e27
commit
df64af8c9b
@@ -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
|
version in `versions.properties`; versions before 0.28.0 are described in the git
|
||||||
log (one commit per version).
|
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)
|
## 0.28.0 (versionCode 57)
|
||||||
|
|
||||||
- **Background MIDI sound module.** New setting "Keep running as MIDI sound
|
- **Background MIDI sound module.** New setting "Keep running as MIDI sound
|
||||||
|
|||||||
@@ -129,6 +129,8 @@ class MainActivity : ComponentActivity() {
|
|||||||
// Sound-module mode: (re)start its foreground service while we are allowed
|
// Sound-module mode: (re)start its foreground service while we are allowed
|
||||||
// to — a start from the background would be refused.
|
// to — a start from the background would be refused.
|
||||||
if (app.soundModuleEnabled.value) SoundModuleService.start(this)
|
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() {
|
override fun onStop() {
|
||||||
|
|||||||
@@ -130,6 +130,10 @@ class SizzleApp : Application() {
|
|||||||
if (midiOwners.add(owner) && midiOwners.size == 1) { midiInput.start(); midiClock.start() }
|
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) {
|
fun releaseMidi(owner: String) {
|
||||||
if (midiOwners.remove(owner) && midiOwners.isEmpty()) { midiInput.stop(); midiClock.stop() }
|
if (midiOwners.remove(owner) && midiOwners.isEmpty()) { midiInput.stop(); midiClock.stop() }
|
||||||
}
|
}
|
||||||
@@ -162,6 +166,8 @@ class SizzleApp : Application() {
|
|||||||
audioEngine.midiOutEnabled = s.sendMidiClock
|
audioEngine.midiOutEnabled = s.sendMidiClock
|
||||||
midiClock.receiveEnabled = s.receiveMidiClock
|
midiClock.receiveEnabled = s.receiveMidiClock
|
||||||
_soundModuleEnabled.value = s.soundModule
|
_soundModuleEnabled.value = s.soundModule
|
||||||
|
midiInput.restoreDisabled(s.midiSourcesOff)
|
||||||
|
midiInput.onDisabledChanged = { keys -> appScope.launch { settingsStore.saveMidiSourcesOff(keys) } }
|
||||||
}
|
}
|
||||||
|
|
||||||
private val appScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
private val appScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||||
|
|||||||
@@ -4,31 +4,59 @@
|
|||||||
package cc.tiredsysadmin.android.sizzle.input
|
package cc.tiredsysadmin.android.sizzle.input
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.content.pm.ServiceInfo
|
||||||
import android.media.midi.MidiDevice
|
import android.media.midi.MidiDevice
|
||||||
import android.media.midi.MidiDeviceInfo
|
import android.media.midi.MidiDeviceInfo
|
||||||
|
import android.media.midi.MidiDeviceStatus
|
||||||
import android.media.midi.MidiManager
|
import android.media.midi.MidiManager
|
||||||
import android.media.midi.MidiOutputPort
|
import android.media.midi.MidiOutputPort
|
||||||
import android.media.midi.MidiReceiver
|
import android.media.midi.MidiReceiver
|
||||||
|
import android.os.Build
|
||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
|
import android.os.SystemClock
|
||||||
|
import android.util.Log
|
||||||
import cc.tiredsysadmin.android.sizzle.playback.MidiSoundModule
|
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'
|
* 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
|
* virtual devices such as Mikro Seq; Android lists all of them through the same
|
||||||
* [MidiManager]) into the app.
|
* [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
|
* 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
|
* 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
|
* Change (CC) messages the module does not consume are matched against
|
||||||
* [ccBindings] so any knob/pad can drive navigation or transport; unmatched CCs
|
* [ccBindings] so any knob/pad can drive navigation or transport; unmatched CCs
|
||||||
* are forwarded as [InputAction.RawControl] so the Settings screen can "learn" them.
|
* 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
|
* Reconnecting: a virtual source's app can die and restart (crash, update, force
|
||||||
* held notes are released through [MidiSoundModule.sourceDisconnected].
|
* 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].
|
* 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(
|
class MidiInput(
|
||||||
context: Context,
|
context: Context,
|
||||||
@@ -40,44 +68,173 @@ class MidiInput(
|
|||||||
private val midiManager = context.getSystemService(Context.MIDI_SERVICE) as? MidiManager
|
private val midiManager = context.getSystemService(Context.MIDI_SERVICE) as? MidiManager
|
||||||
private val handler = Handler(Looper.getMainLooper())
|
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<Int, MidiDeviceInfo>()
|
||||||
|
/** Open sources by device id. */
|
||||||
private val open = HashMap<Int, Pair<MidiDevice, MidiOutputPort>>()
|
private val open = HashMap<Int, Pair<MidiDevice, MidiOutputPort>>()
|
||||||
|
/** Device ids with an [MidiManager.openDevice] in flight. */
|
||||||
|
private val opening = HashSet<Int>()
|
||||||
private var callback: MidiManager.DeviceCallback? = null
|
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<Int, Long>()
|
||||||
|
|
||||||
/** Start listening. Opens every currently-attached device that can send to us
|
/** Keys of the sources the user switched off. Set before [start]. */
|
||||||
* and watches for hot-plug events. Idempotent; safe if the device has no MIDI.
|
var disabledKeys: Set<String> = emptySet()
|
||||||
* Main thread. */
|
private set
|
||||||
|
|
||||||
|
/** Called with the new off-set when the user changes it, to persist it. */
|
||||||
|
var onDisabledChanged: ((Set<String>) -> Unit)? = null
|
||||||
|
|
||||||
|
private val _sources = MutableStateFlow<List<MidiSource>>(emptyList())
|
||||||
|
/** All sources that can send to us, for the Setup screen. */
|
||||||
|
val sources: StateFlow<List<MidiSource>> = _sources.asStateFlow()
|
||||||
|
|
||||||
|
fun restoreDisabled(keys: Set<String>) { 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() {
|
fun start() {
|
||||||
val mm = midiManager ?: return
|
val mm = midiManager ?: return
|
||||||
if (callback != null) return
|
if (callback != null) return
|
||||||
val cb = object : MidiManager.DeviceCallback() {
|
val cb = object : MidiManager.DeviceCallback() {
|
||||||
override fun onDeviceAdded(device: MidiDeviceInfo) = openDevice(device)
|
override fun onDeviceAdded(device: MidiDeviceInfo) = add(device)
|
||||||
override fun onDeviceRemoved(device: MidiDeviceInfo) = closeDevice(device.id)
|
override fun onDeviceRemoved(device: MidiDeviceInfo) {
|
||||||
|
known.remove(device.id)
|
||||||
|
closeDevice(device.id)
|
||||||
|
publish()
|
||||||
|
}
|
||||||
|
override fun onDeviceStatusChanged(status: MidiDeviceStatus) = onStatus(status)
|
||||||
}
|
}
|
||||||
callback = cb
|
callback = cb
|
||||||
mm.devices.forEach(::openDevice)
|
allDevices(mm).forEach(::add)
|
||||||
mm.registerDeviceCallback(cb, handler)
|
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() {
|
fun stop() {
|
||||||
callback?.let { cb -> runCatching { midiManager?.unregisterDeviceCallback(cb) } }
|
callback?.let { cb -> runCatching { midiManager?.unregisterDeviceCallback(cb) } }
|
||||||
callback = null
|
callback = null
|
||||||
|
handler.removeCallbacks(probeTick)
|
||||||
open.keys.toList().forEach(::closeDevice)
|
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) {
|
private fun openDevice(info: MidiDeviceInfo) {
|
||||||
// We want devices that can SEND to us (they expose output ports).
|
val id = info.id
|
||||||
if (info.outputPortCount == 0 || info.id in open) return
|
if (id in open || id in opening) return
|
||||||
midiManager?.openDevice(info, { device ->
|
val mm = midiManager ?: return
|
||||||
device ?: return@openDevice
|
opening += id
|
||||||
// stop() ran (or the same device was opened twice) while this was pending.
|
mm.openDevice(info, { device ->
|
||||||
if (callback == null || info.id in open) { runCatching { device.close() }; return@openDevice }
|
opening -= id
|
||||||
val port = device.openOutputPort(0) ?: run { runCatching { device.close() }; return@openDevice }
|
device ?: run { Log.w(TAG, "${nameOf(info)}: could not open"); publish(); return@openDevice }
|
||||||
val source = info.id
|
// 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(
|
val parser = MidiByteParser(
|
||||||
onChannel = { status, d1, d2 ->
|
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)
|
if (!consumed && (status and 0xF0) == 0xB0) handleCc(d1, d2)
|
||||||
},
|
},
|
||||||
onRealtime = module::onRealtime,
|
onRealtime = module::onRealtime,
|
||||||
@@ -86,18 +243,63 @@ class MidiInput(
|
|||||||
override fun onSend(data: ByteArray, offset: Int, count: Int, timestamp: Long) =
|
override fun onSend(data: ByteArray, offset: Int, count: Int, timestamp: Long) =
|
||||||
parser.feed(data, offset, count)
|
parser.feed(data, offset, count)
|
||||||
})
|
})
|
||||||
open[source] = device to port
|
open[id] = device to port
|
||||||
module.sourceConnected(source)
|
lastChange[id] = SystemClock.uptimeMillis()
|
||||||
|
module.sourceConnected(id)
|
||||||
|
Log.i(TAG, "${nameOf(info)}: listening")
|
||||||
|
publish()
|
||||||
}, handler)
|
}, handler)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun closeDevice(id: Int) {
|
private fun closeDevice(id: Int) {
|
||||||
val (device, port) = open.remove(id) ?: return
|
val (device, port) = open.remove(id) ?: return
|
||||||
|
lastChange[id] = SystemClock.uptimeMillis()
|
||||||
runCatching { port.close() }
|
runCatching { port.close() }
|
||||||
runCatching { device.close() }
|
runCatching { device.close() }
|
||||||
module.sourceDisconnected(id)
|
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<MidiDeviceInfo> = 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<android.os.Parcelable>(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) {
|
private fun handleCc(cc: Int, value: Int) {
|
||||||
val actionId = ccBindings[cc]
|
val actionId = ccBindings[cc]
|
||||||
if (actionId == null) {
|
if (actionId == null) {
|
||||||
@@ -133,4 +335,14 @@ class MidiInput(
|
|||||||
}
|
}
|
||||||
action?.let(router::dispatch)
|
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
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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"
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ import androidx.datastore.preferences.core.booleanPreferencesKey
|
|||||||
import androidx.datastore.preferences.core.edit
|
import androidx.datastore.preferences.core.edit
|
||||||
import androidx.datastore.preferences.core.intPreferencesKey
|
import androidx.datastore.preferences.core.intPreferencesKey
|
||||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||||
|
import androidx.datastore.preferences.core.stringSetPreferencesKey
|
||||||
import androidx.datastore.preferences.preferencesDataStore
|
import androidx.datastore.preferences.preferencesDataStore
|
||||||
import kotlinx.coroutines.flow.first
|
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
|
/** Keep a foreground service up so incoming MIDI plays with the app in the
|
||||||
* background ("Keep running as MIDI sound module"). */
|
* background ("Keep running as MIDI sound module"). */
|
||||||
val soundModule: Boolean = false,
|
val soundModule: Boolean = false,
|
||||||
|
/** MIDI sources the user switched off in Setup ([cc.tiredsysadmin.android.sizzle.input.MidiSourceKey]). */
|
||||||
|
val midiSourcesOff: Set<String> = emptySet(),
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -61,6 +64,7 @@ class SettingsStore(private val context: Context) {
|
|||||||
sendMidiClock = prefs[MIDI_CLOCK_SEND] ?: false,
|
sendMidiClock = prefs[MIDI_CLOCK_SEND] ?: false,
|
||||||
receiveMidiClock = prefs[MIDI_CLOCK_RECV] ?: false,
|
receiveMidiClock = prefs[MIDI_CLOCK_RECV] ?: false,
|
||||||
soundModule = prefs[SOUND_MODULE] ?: 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 }
|
context.settingsDataStore.edit { prefs -> prefs[SOUND_MODULE] = enabled }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Persist the MIDI sources switched off in Setup. */
|
||||||
|
suspend fun saveMidiSourcesOff(keys: Set<String>) {
|
||||||
|
context.settingsDataStore.edit { prefs -> prefs[MIDI_SOURCES_OFF] = keys }
|
||||||
|
}
|
||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
val PALETTE = stringPreferencesKey("palette")
|
val PALETTE = stringPreferencesKey("palette")
|
||||||
val RECORD_DIR = stringPreferencesKey("recordDirUri")
|
val RECORD_DIR = stringPreferencesKey("recordDirUri")
|
||||||
@@ -115,5 +124,6 @@ class SettingsStore(private val context: Context) {
|
|||||||
val MIDI_CLOCK_SEND = booleanPreferencesKey("midiClockSend")
|
val MIDI_CLOCK_SEND = booleanPreferencesKey("midiClockSend")
|
||||||
val MIDI_CLOCK_RECV = booleanPreferencesKey("midiClockRecv")
|
val MIDI_CLOCK_RECV = booleanPreferencesKey("midiClockRecv")
|
||||||
val SOUND_MODULE = booleanPreferencesKey("soundModule")
|
val SOUND_MODULE = booleanPreferencesKey("soundModule")
|
||||||
|
val MIDI_SOURCES_OFF = stringSetPreferencesKey("midiSourcesOff")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -148,6 +148,15 @@ class AppViewModel(
|
|||||||
|
|
||||||
fun updateSoundModuleMode(enabled: Boolean) = sizzleApp.setSoundModuleEnabled(enabled)
|
fun updateSoundModuleMode(enabled: Boolean) = sizzleApp.setSoundModuleEnabled(enabled)
|
||||||
|
|
||||||
|
/** Every MIDI source that can send to Sizzle, with whether it is listened to. */
|
||||||
|
val midiInputSources: StateFlow<List<cc.tiredsysadmin.android.sizzle.input.MidiSource>>
|
||||||
|
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) -----
|
// ----- A song opened from another app (VIEW / SEND intent) -----
|
||||||
/** Waiting for the user to confirm replacing the current song, or to read why
|
/** Waiting for the user to confirm replacing the current song, or to read why
|
||||||
* it can't be opened. */
|
* it can't be opened. */
|
||||||
|
|||||||
@@ -523,14 +523,54 @@ private fun MidiSyncCard(vm: AppViewModel) {
|
|||||||
) { vm.updateReceiveMidiClock(it) }
|
) { vm.updateReceiveMidiClock(it) }
|
||||||
HorizontalDivider()
|
HorizontalDivider()
|
||||||
val module by vm.soundModuleMode.collectAsState()
|
val module by vm.soundModuleMode.collectAsState()
|
||||||
val sources by vm.midiSources.collectAsState()
|
|
||||||
ToggleRow(
|
ToggleRow(
|
||||||
"Keep running as MIDI sound module",
|
"Keep running as MIDI sound module",
|
||||||
"Keep playing incoming MIDI with Sizzle in the background (another app can " +
|
"Keep playing incoming MIDI with Sizzle in the background (another app can " +
|
||||||
"use it as its synth), with a notification while on. " +
|
"use it as its synth), with a notification while on.",
|
||||||
"MIDI sources open now: $sources.",
|
|
||||||
module,
|
module,
|
||||||
) { vm.updateSoundModuleMode(it) }
|
) { 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) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -206,7 +206,8 @@ cc.tiredsysadmin.android.sizzle
|
|||||||
│ ├── GamepadInput.kt KeyEvent/MotionEvent -> InputAction (rebindable)
|
│ ├── GamepadInput.kt KeyEvent/MotionEvent -> InputAction (rebindable)
|
||||||
│ ├── MidiByteParser.kt MIDI byte stream -> messages (running status, split packets, realtime, SysEx)
|
│ ├── MidiByteParser.kt MIDI byte stream -> messages (running status, split packets, realtime, SysEx)
|
||||||
│ ├── MidiClock.kt MIDI clock send / follow
|
│ ├── 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)
|
├── audio/ The real-time sound engine (own thread)
|
||||||
│ ├── Transport.kt TransportState snapshot published to the UI
|
│ ├── 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
|
`InputRouter` as `NoteOn(…, sounded = true)`, which the ViewModel records but
|
||||||
does not play again. With no UI collecting, the router drops them.
|
does not play again. With no UI collecting, the router drops them.
|
||||||
|
|
||||||
|
**Which sources, and staying connected (0.29.0).** `MidiInput` keeps every
|
||||||
|
device that can send to us in `sources` (a `StateFlow<List<MidiSource>>` the
|
||||||
|
Setup screen lists with a switch each). Sources are listened to unless switched
|
||||||
|
off; the off-set is persisted as `MidiSourceKey`s (type + maker/product/name +
|
||||||
|
publishing service or Bluetooth address), because Android's device id changes on
|
||||||
|
every reconnect. The trap this solves: when the app behind a *virtual* source
|
||||||
|
dies and restarts (crash, update, force stop), Android keeps the device, keeps
|
||||||
|
our connection record, drops its service binding, and tells clients nothing:
|
||||||
|
no `onDeviceRemoved`, no `onDeviceStatusChanged` (checked on Android 15:
|
||||||
|
`dumpsys midi` shows `Status: null … mServiceConnection: null`). Our
|
||||||
|
`MidiOutputPort` just goes silent. So a worker thread probes each open virtual
|
||||||
|
source every 3 s with `MidiDevice.openOutputPort(0)` (null from a dead server;
|
||||||
|
a live one's probe port is closed at once) and reopens dead ones through
|
||||||
|
`MidiManager.openDevice`, which makes Android rebind the app's MIDI service.
|
||||||
|
`refresh()` runs on every Activity resume and the Setup "Reconnect" button closes
|
||||||
|
and reopens everything. A status report of zero open output ports while we hold
|
||||||
|
one is treated as dead too (events within 1 s of our own open/close are ignored).
|
||||||
|
USB and Bluetooth sources are not probed: Android reports their removal.
|
||||||
|
`MidiInput` logs connects/reconnects under the `SizzleMidi` tag.
|
||||||
|
|
||||||
**Verifying.** With the setting on and the app backgrounded, `adb shell dumpsys
|
**Verifying.** With the setting on and the app backgrounded, `adb shell dumpsys
|
||||||
activity processes` must not show `isFrozen=true` for the Sizzle process, and
|
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
|
another app's notes must keep sounding. Opening a virtual port binds the other
|
||||||
|
|||||||
@@ -303,6 +303,12 @@ you delete stay deleted.
|
|||||||
DAW) can use it as its synth. A notification shows while it is on; its
|
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
|
**Stop** button turns it off. Each mixer track plays the notes on its MIDI
|
||||||
channel.
|
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.
|
- **Audio Devices** — route **Output** and **Input** to USB or built‑in.
|
||||||
- **Color Theme** — pick a palette, or **Export / Import `.szt`** themes. Stock
|
- **Color Theme** — pick a palette, or **Export / Import `.szt`** themes. Stock
|
||||||
themes can't be deleted; imported ones join the list.
|
themes can't be deleted; imported ones join the list.
|
||||||
|
|||||||
+2
-2
@@ -8,8 +8,8 @@
|
|||||||
# or polish. android.versionCode is monotonic and bumps by 1 on every release,
|
# 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.
|
# because F-Droid and the Android package manager order installs by it alone.
|
||||||
|
|
||||||
android.versionName = 0.28.0
|
android.versionName = 0.29.0
|
||||||
android.versionCode = 57
|
android.versionCode = 58
|
||||||
|
|
||||||
# No desktop builds exist yet. These lines are the agreed slots so a port starts
|
# 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
|
# with a version instead of inventing one; `-` means "not built on this
|
||||||
|
|||||||
Reference in New Issue
Block a user