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
@@ -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() {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<Int, MidiDeviceInfo>()
|
||||
/** Open sources by device id. */
|
||||
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
|
||||
/** 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
|
||||
* 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<String> = emptySet()
|
||||
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() {
|
||||
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<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) {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.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<String> = 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<String>) {
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<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) -----
|
||||
/** Waiting for the user to confirm replacing the current song, or to read why
|
||||
* it can't be opened. */
|
||||
|
||||
@@ -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) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user