0.38.0 (72): Bluetooth LE MIDI controllers in Settings (Android and iOS)
- Android: BleMidi scans for the BLE MIDI service, connects through MidiManager.openBluetoothDevice, remembers and reconnects controllers; Settings › MIDI inputs › Bluetooth MIDI (Scan / Connect / Disconnect / Forget) - iOS: the system Bluetooth MIDI panel from Setup › MIDI Sync, connected controllers remembered and reconnected at launch via CoreBluetooth Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
2bc5cb1cbb
commit
4d9e2328cb
@@ -5,6 +5,15 @@ version in `versions.properties`; versions before 0.28.0 are described in the gi
|
||||
log (one commit per version). Since 0.37.0 Android and iOS share one version and
|
||||
one feature set; the iOS side of each version is in `ios/CHANGELOG.md`.
|
||||
|
||||
## 0.38.0 (versionCode 72)
|
||||
|
||||
- **Bluetooth LE MIDI controllers:** Settings › MIDI Sync › MIDI inputs has a
|
||||
Bluetooth MIDI section. SCAN looks for BLE MIDI controllers for 15 s (asking for
|
||||
the Bluetooth permission the first time), CONNECT opens one, and from then on it
|
||||
is one of the MIDI inputs: listed, switchable and played on the mixer tracks of
|
||||
its channel. Connected controllers are remembered and connected again at every
|
||||
start until FORGET. (iOS has the same in 0.38.0.)
|
||||
|
||||
## 0.37.0 (versionCode 71)
|
||||
|
||||
- **One engine for Android and iOS:** Android now plays through the shared C++
|
||||
|
||||
@@ -7,12 +7,20 @@
|
||||
FOREGROUND_SERVICE : keep the sequencer alive while the app is backgrounded.
|
||||
FOREGROUND_SERVICE_MEDIA_PLAYBACK : Android 14 requires a typed FGS.
|
||||
POST_NOTIFICATIONS : show the media transport notification (Android 13+).
|
||||
BLUETOOTH_CONNECT : Bluetooth MIDI + gamepad on Android 12+. -->
|
||||
BLUETOOTH_CONNECT : Bluetooth MIDI + gamepad on Android 12+.
|
||||
BLUETOOTH_SCAN : finding BLE MIDI controllers (Settings › MIDI inputs) on
|
||||
Android 12+; never used to derive location.
|
||||
BLUETOOTH / _ADMIN / ACCESS_FINE_LOCATION : the same scan on Android 8-11. -->
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"
|
||||
android:usesPermissionFlags="neverForLocation" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="30" />
|
||||
|
||||
<!-- Hardware we can *use* but do not *require* (so the app still installs on
|
||||
devices without them). Code must always feature-detect at runtime. -->
|
||||
@@ -20,6 +28,7 @@
|
||||
<uses-feature android:name="android.software.midi" android:required="false" />
|
||||
<uses-feature android:name="android.hardware.gamepad" android:required="false" />
|
||||
<uses-feature android:name="android.hardware.bluetooth" android:required="false" />
|
||||
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />
|
||||
<uses-feature android:name="android.hardware.microphone" android:required="false" />
|
||||
|
||||
<!-- Lets SongIntents.isTrustedReplace see which app owns a content provider, so
|
||||
|
||||
@@ -57,6 +57,8 @@ class SizzleApp : Application() {
|
||||
val keyboardInput: KeyboardInput by lazy { KeyboardInput(inputRouter) }
|
||||
val gamepadInput: GamepadInput by lazy { GamepadInput(inputRouter) }
|
||||
val midiInput: MidiInput by lazy { MidiInput(this, inputRouter, soundModule) }
|
||||
/** Bluetooth LE MIDI controllers (found, connected and remembered in Settings). */
|
||||
val bleMidi: cc.tiredsysadmin.android.sizzle.input.BleMidi by lazy { cc.tiredsysadmin.android.sizzle.input.BleMidi(this) }
|
||||
|
||||
/** Headless MIDI → engine routing (see [MidiSoundModule]). Lives here, with the
|
||||
* engine, so it keeps playing incoming notes with no Activity or ViewModel. */
|
||||
@@ -141,7 +143,10 @@ class SizzleApp : Application() {
|
||||
}
|
||||
|
||||
fun acquireMidi(owner: String) {
|
||||
if (midiOwners.add(owner) && midiOwners.size == 1) { midiInput.start(); midiClock.start() }
|
||||
if (midiOwners.add(owner) && midiOwners.size == 1) {
|
||||
midiInput.start(); midiClock.start()
|
||||
bleMidi.start(); bleMidi.reconnectRemembered()
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-scan MIDI sources (MainActivity.onResume): opens anything enabled that
|
||||
@@ -149,7 +154,7 @@ class SizzleApp : Application() {
|
||||
fun refreshMidi() { if (midiOwners.isNotEmpty()) midiInput.refresh() }
|
||||
|
||||
fun releaseMidi(owner: String) {
|
||||
if (midiOwners.remove(owner) && midiOwners.isEmpty()) { midiInput.stop(); midiClock.stop() }
|
||||
if (midiOwners.remove(owner) && midiOwners.isEmpty()) { bleMidi.closeAll(); midiInput.stop(); midiClock.stop() }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -207,6 +212,8 @@ class SizzleApp : Application() {
|
||||
_soundModuleEnabled.value = s.soundModule
|
||||
midiInput.restoreDisabled(s.midiSourcesOff)
|
||||
midiInput.onDisabledChanged = { keys -> appScope.launch { settingsStore.saveMidiSourcesOff(keys) } }
|
||||
bleMidi.restoreRemembered(s.bleMidiDevices)
|
||||
bleMidi.onRememberedChanged = { devices -> appScope.launch { settingsStore.saveBleMidiDevices(devices) } }
|
||||
}
|
||||
|
||||
private val appScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package cc.tiredsysadmin.android.sizzle.input
|
||||
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.bluetooth.BluetoothManager
|
||||
import android.bluetooth.le.ScanCallback
|
||||
import android.bluetooth.le.ScanFilter
|
||||
import android.bluetooth.le.ScanResult
|
||||
import android.bluetooth.le.ScanSettings
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.bluetooth.BluetoothDevice
|
||||
import android.media.midi.MidiDevice
|
||||
import android.media.midi.MidiDeviceInfo
|
||||
import android.media.midi.MidiManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.ParcelUuid
|
||||
import android.util.Log
|
||||
import java.util.UUID
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
|
||||
/** A Bluetooth LE MIDI controller Sizzle found or remembers. */
|
||||
data class BleMidiDevice(
|
||||
val address: String,
|
||||
val name: String,
|
||||
val connected: Boolean,
|
||||
val connecting: Boolean,
|
||||
val remembered: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
* Bluetooth LE MIDI controllers: Android lists a BLE MIDI device to MIDI apps only
|
||||
* once some app has connected it, so Settings scans for the BLE MIDI service,
|
||||
* shows what it finds, and connects the one the user picks
|
||||
* ([MidiManager.openBluetoothDevice]). The connection is held here for as long as
|
||||
* Sizzle runs; while it is, the device is an ordinary MIDI source that [MidiInput]
|
||||
* picks up through its device callback (listed, switchable, played).
|
||||
*
|
||||
* Connected devices are remembered ([remembered], persisted by the caller via
|
||||
* [onRememberedChanged]) and connected again by address at the next start
|
||||
* ([reconnectRemembered]) — no scan needed. Main thread.
|
||||
*/
|
||||
class BleMidi(private val context: Context) {
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val midiManager = context.getSystemService(Context.MIDI_SERVICE) as? MidiManager
|
||||
private val adapter = (context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter
|
||||
|
||||
private val found = LinkedHashMap<String, String>() // address -> name, from scans and memory
|
||||
private val open = HashMap<String, MidiDevice>()
|
||||
private val connecting = HashSet<String>()
|
||||
|
||||
/** Addresses of the controllers to connect again at start ("address|name" when saved). */
|
||||
var remembered: Map<String, String> = emptyMap()
|
||||
private set
|
||||
var onRememberedChanged: ((Map<String, String>) -> Unit)? = null
|
||||
|
||||
private val _devices = MutableStateFlow<List<BleMidiDevice>>(emptyList())
|
||||
val devices: StateFlow<List<BleMidiDevice>> = _devices.asStateFlow()
|
||||
private val _scanning = MutableStateFlow(false)
|
||||
val scanning: StateFlow<Boolean> = _scanning.asStateFlow()
|
||||
private val _error = MutableStateFlow<String?>(null)
|
||||
/** Why the last scan or connection failed, for Settings; null when fine. */
|
||||
val error: StateFlow<String?> = _error.asStateFlow()
|
||||
|
||||
/** This device can do BLE MIDI at all (BLE + the MIDI API). */
|
||||
val supported: Boolean
|
||||
get() = adapter != null && midiManager != null &&
|
||||
context.packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)
|
||||
|
||||
/** Runtime permissions a scan needs (Android 12+: scan + connect; before: location). */
|
||||
fun requiredPermissions(): Array<String> =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT)
|
||||
} else {
|
||||
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
}
|
||||
|
||||
fun hasPermissions(): Boolean = requiredPermissions().all {
|
||||
context.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
|
||||
private fun canConnect(): Boolean = Build.VERSION.SDK_INT < Build.VERSION_CODES.S ||
|
||||
context.checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
private var callbackRegistered = false
|
||||
|
||||
/** Watch for connections that drop on their own (out of range, switched off). */
|
||||
fun start() {
|
||||
val mm = midiManager ?: return
|
||||
if (callbackRegistered) return
|
||||
callbackRegistered = true
|
||||
@Suppress("DEPRECATION")
|
||||
mm.registerDeviceCallback(object : MidiManager.DeviceCallback() {
|
||||
override fun onDeviceRemoved(device: MidiDeviceInfo) {
|
||||
if (device.type != MidiDeviceInfo.TYPE_BLUETOOTH) return
|
||||
@Suppress("DEPRECATION")
|
||||
val bt = device.properties.getParcelable<BluetoothDevice>(MidiDeviceInfo.PROPERTY_BLUETOOTH_DEVICE)
|
||||
bt?.address?.let(::deviceRemoved)
|
||||
}
|
||||
}, handler)
|
||||
}
|
||||
|
||||
fun restoreRemembered(saved: Map<String, String>) {
|
||||
remembered = saved
|
||||
found.putAll(saved)
|
||||
publish()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- scanning
|
||||
private val callback = object : ScanCallback() {
|
||||
@SuppressLint("MissingPermission")
|
||||
override fun onScanResult(callbackType: Int, result: ScanResult) {
|
||||
val address = result.device.address ?: return
|
||||
val name = result.scanRecord?.deviceName ?: runCatching { result.device.name }.getOrNull() ?: "BLE MIDI device"
|
||||
if (found[address] != name) { found[address] = name; publish() }
|
||||
}
|
||||
|
||||
override fun onScanFailed(errorCode: Int) {
|
||||
_error.value = "Bluetooth scan failed (error $errorCode)."
|
||||
_scanning.value = false
|
||||
}
|
||||
}
|
||||
|
||||
private val stopScanLater = Runnable { stopScan() }
|
||||
|
||||
/** Look for BLE MIDI controllers for [SCAN_MS]. Needs [hasPermissions] and Bluetooth on. */
|
||||
@SuppressLint("MissingPermission")
|
||||
fun startScan() {
|
||||
_error.value = null
|
||||
if (!supported) { _error.value = "This device has no Bluetooth LE MIDI support."; return }
|
||||
if (!hasPermissions()) { _error.value = "Sizzle needs the Bluetooth permission to look for controllers."; return }
|
||||
val scanner = adapter?.takeIf { it.isEnabled }?.bluetoothLeScanner
|
||||
if (scanner == null) { _error.value = "Bluetooth is off. Turn it on, then scan again."; return }
|
||||
if (_scanning.value) return
|
||||
val filter = ScanFilter.Builder().setServiceUuid(ParcelUuid(MIDI_SERVICE)).build()
|
||||
val settings = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build()
|
||||
runCatching { scanner.startScan(listOf(filter), settings, callback) }
|
||||
.onFailure { _error.value = "Couldn't start the Bluetooth scan: ${it.message}"; return }
|
||||
_scanning.value = true
|
||||
handler.postDelayed(stopScanLater, SCAN_MS)
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
fun stopScan() {
|
||||
handler.removeCallbacks(stopScanLater)
|
||||
if (!_scanning.value) return
|
||||
runCatching { adapter?.bluetoothLeScanner?.stopScan(callback) }
|
||||
_scanning.value = false
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- connecting
|
||||
/** Connect the controller at [address]; it then appears among the MIDI inputs. */
|
||||
@SuppressLint("MissingPermission")
|
||||
fun connect(address: String) {
|
||||
val mm = midiManager ?: return
|
||||
if (address in open || address in connecting) return
|
||||
if (!canConnect()) { _error.value = "Sizzle needs the Bluetooth permission to connect."; return }
|
||||
val device = runCatching { adapter?.getRemoteDevice(address) }.getOrNull() ?: return
|
||||
stopScan() // scanning slows connecting down
|
||||
connecting += address
|
||||
publish()
|
||||
mm.openBluetoothDevice(device, { midi ->
|
||||
connecting -= address
|
||||
if (midi == null) {
|
||||
_error.value = "Couldn't connect to ${found[address] ?: address}. Is it on and nearby?"
|
||||
} else {
|
||||
_error.value = null
|
||||
open[address] = midi
|
||||
remember(address, found[address] ?: midi.info.properties.getString(MidiDeviceInfo.PROPERTY_NAME) ?: address)
|
||||
Log.i(TAG, "${found[address]}: connected")
|
||||
}
|
||||
publish()
|
||||
}, handler)
|
||||
}
|
||||
|
||||
/** Disconnect the controller at [address]; [forget] also stops reconnecting it at start. */
|
||||
fun disconnect(address: String, forget: Boolean) {
|
||||
open.remove(address)?.let { runCatching { it.close() } }
|
||||
if (forget && address in remembered) {
|
||||
remembered = remembered - address
|
||||
onRememberedChanged?.invoke(remembered)
|
||||
}
|
||||
publish()
|
||||
}
|
||||
|
||||
/** Connect every remembered controller (at start and when Settings opens). */
|
||||
fun reconnectRemembered() {
|
||||
for (address in remembered.keys) if (address !in open) connect(address)
|
||||
}
|
||||
|
||||
/** A connection dropped on its own (out of range, switched off): forget the handle. */
|
||||
fun deviceRemoved(address: String) {
|
||||
open.remove(address)?.let { runCatching { it.close() } }
|
||||
publish()
|
||||
}
|
||||
|
||||
/** Close every connection (Sizzle shutting down MIDI). */
|
||||
fun closeAll() {
|
||||
stopScan()
|
||||
open.values.forEach { runCatching { it.close() } }
|
||||
open.clear()
|
||||
publish()
|
||||
}
|
||||
|
||||
private fun remember(address: String, name: String) {
|
||||
if (remembered[address] == name) return
|
||||
remembered = remembered + (address to name)
|
||||
onRememberedChanged?.invoke(remembered)
|
||||
}
|
||||
|
||||
private fun publish() {
|
||||
_devices.value = found.map { (address, name) ->
|
||||
BleMidiDevice(address, name, address in open, address in connecting, address in remembered)
|
||||
}.sortedWith(compareByDescending<BleMidiDevice> { it.connected }.thenBy { it.name.lowercase() })
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SizzleBleMidi"
|
||||
/** The BLE MIDI service (Apple's / the MMA's BLE-MIDI specification). */
|
||||
val MIDI_SERVICE: UUID = UUID.fromString("03B80E5A-EDE8-4B33-A751-6CE34EC4C700")
|
||||
private const val SCAN_MS = 15_000L
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,8 @@ data class AppSettings(
|
||||
val soundModule: Boolean = false,
|
||||
/** MIDI sources the user switched off in Setup ([cc.tiredsysadmin.android.sizzle.input.MidiSourceKey]). */
|
||||
val midiSourcesOff: Set<String> = emptySet(),
|
||||
/** Bluetooth LE MIDI controllers to connect at start: address -> name. */
|
||||
val bleMidiDevices: Map<String, String> = emptyMap(),
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -65,6 +67,10 @@ class SettingsStore(private val context: Context) {
|
||||
receiveMidiClock = prefs[MIDI_CLOCK_RECV] ?: false,
|
||||
soundModule = prefs[SOUND_MODULE] ?: false,
|
||||
midiSourcesOff = prefs[MIDI_SOURCES_OFF] ?: emptySet(),
|
||||
// "address|name" each (a BLE address never contains '|').
|
||||
bleMidiDevices = (prefs[BLE_MIDI] ?: emptySet()).associate {
|
||||
it.substringBefore('|') to it.substringAfter('|', it.substringBefore('|'))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -114,6 +120,11 @@ class SettingsStore(private val context: Context) {
|
||||
context.settingsDataStore.edit { prefs -> prefs[MIDI_SOURCES_OFF] = keys }
|
||||
}
|
||||
|
||||
/** Persist the remembered Bluetooth LE MIDI controllers. */
|
||||
suspend fun saveBleMidiDevices(devices: Map<String, String>) {
|
||||
context.settingsDataStore.edit { prefs -> prefs[BLE_MIDI] = devices.map { (a, n) -> "$a|$n" }.toSet() }
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val PALETTE = stringPreferencesKey("palette")
|
||||
val RECORD_DIR = stringPreferencesKey("recordDirUri")
|
||||
@@ -125,5 +136,6 @@ class SettingsStore(private val context: Context) {
|
||||
val MIDI_CLOCK_RECV = booleanPreferencesKey("midiClockRecv")
|
||||
val SOUND_MODULE = booleanPreferencesKey("soundModule")
|
||||
val MIDI_SOURCES_OFF = stringSetPreferencesKey("midiSourcesOff")
|
||||
val BLE_MIDI = stringSetPreferencesKey("bleMidiDevices")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,6 +160,9 @@ class AppViewModel(
|
||||
/** Close and reopen every MIDI source (e.g. after the sending app restarted). */
|
||||
fun reconnectMidi() = midiInput.reconnect()
|
||||
|
||||
/** Bluetooth LE MIDI controllers: scan, connect, forget (Settings › MIDI inputs). */
|
||||
val bleMidi: cc.tiredsysadmin.android.sizzle.input.BleMidi get() = sizzleApp.bleMidi
|
||||
|
||||
// ----- 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. */
|
||||
|
||||
@@ -574,6 +574,89 @@ private fun MidiInputsList(vm: AppViewModel) {
|
||||
src.enabled,
|
||||
) { vm.setMidiSourceEnabled(src.key, it) }
|
||||
}
|
||||
HorizontalDivider()
|
||||
BluetoothMidiList(vm)
|
||||
}
|
||||
|
||||
/**
|
||||
* Bluetooth LE MIDI controllers: SCAN looks for them for 15 s (asking for the
|
||||
* Bluetooth permission first), CONNECT opens one, and from then on it is one of
|
||||
* the MIDI inputs above, connected again at every start until FORGET.
|
||||
*/
|
||||
@Composable
|
||||
private fun BluetoothMidiList(vm: AppViewModel) {
|
||||
val ble = vm.bleMidi
|
||||
val devices by ble.devices.collectAsState()
|
||||
val scanning by ble.scanning.collectAsState()
|
||||
val error by ble.error.collectAsState()
|
||||
val askPermission = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.RequestMultiplePermissions(),
|
||||
) { ble.startScan() } // without the permission it reports what is missing
|
||||
|
||||
Row(
|
||||
Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("Bluetooth MIDI", style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
if (!ble.supported) "This device has no Bluetooth LE MIDI support."
|
||||
else "Find Bluetooth LE MIDI controllers and connect them. Connected ones are listed " +
|
||||
"with the MIDI inputs and reconnect at every start.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
if (ble.supported) {
|
||||
OutlinedButton(onClick = {
|
||||
when {
|
||||
scanning -> ble.stopScan()
|
||||
ble.hasPermissions() -> ble.startScan()
|
||||
else -> askPermission.launch(ble.requiredPermissions())
|
||||
}
|
||||
}) { Text(if (scanning) "Stop" else "Scan") }
|
||||
}
|
||||
}
|
||||
if (scanning) {
|
||||
Text(
|
||||
"Scanning… switch the controller on (or into pairing mode) nearby.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
error?.let {
|
||||
Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
for (d in devices) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(d.name, style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
when {
|
||||
d.connecting -> "Connecting…"
|
||||
d.connected -> "Connected"
|
||||
d.remembered -> "Remembered — not connected"
|
||||
else -> "Found"
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
when {
|
||||
d.connecting -> {}
|
||||
d.connected -> OutlinedButton(onClick = { ble.disconnect(d.address, forget = false) }) { Text("Disconnect") }
|
||||
else -> OutlinedButton(onClick = { ble.connect(d.address) }) { Text("Connect") }
|
||||
}
|
||||
if (d.remembered) {
|
||||
TextButton(onClick = { ble.disconnect(d.address, forget = true) }) { Text("Forget") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A labelled switch row (title + supporting text + trailing Switch). */
|
||||
|
||||
@@ -418,6 +418,27 @@ to draw (wavetable frames, Grain Cloud source peaks, sample decoding).
|
||||
**Parity rule:** every feature or fix lands in both apps in the same change, with
|
||||
one shared version bump. Engine and DSP work goes into `core/` only.
|
||||
|
||||
### 5.4.3 Bluetooth LE MIDI controllers (0.38.0)
|
||||
|
||||
Android lists a BLE MIDI device to MIDI apps only after some app has connected
|
||||
it. `input/BleMidi.kt` scans for the BLE MIDI service
|
||||
(`03B80E5A-EDE8-4B33-A751-6CE34EC4C700`, 15 s, low-latency mode), connects the
|
||||
chosen device with `MidiManager.openBluetoothDevice` and holds that `MidiDevice`
|
||||
open while Sizzle's MIDI runs; the device then reaches `MidiInput` through the
|
||||
ordinary device callback, so it is listed and played like USB gear. Connected
|
||||
addresses are remembered (`SettingsStore.bleMidiDevices`) and reopened by
|
||||
address at start, without a scan. Permissions: `BLUETOOTH_SCAN`
|
||||
(`neverForLocation`) + `BLUETOOTH_CONNECT` on Android 12+, `ACCESS_FINE_LOCATION`
|
||||
(and the legacy `BLUETOOTH` / `BLUETOOTH_ADMIN`) on 8-11, asked for when SCAN is
|
||||
first tapped. The emulator has no usable Bluetooth radio (its Bluetooth service
|
||||
crashes on a scan); test on a phone.
|
||||
|
||||
iOS (`ios/app/Host/BluetoothMidi.swift`): the system panel
|
||||
(`CABTMIDICentralViewController`) finds and connects; when it closes, the
|
||||
connected BLE MIDI peripherals are remembered and reconnected at launch through
|
||||
CoreBluetooth (best effort: iOS decides whether that brings the CoreMIDI source
|
||||
back without the panel).
|
||||
|
||||
### 5.5 Sizzle as a background MIDI sound module
|
||||
|
||||
Goal: another app (Mikro Seq, a DAW, a controller app) plays Sizzle's mixer over
|
||||
|
||||
@@ -5,6 +5,14 @@ Sizzle for iOS/iPadOS (`cc.tiredsysadmin.ios.sizzle`). One entry per version in
|
||||
is shared with Android, continuing Android's numbering, and both apps ship the
|
||||
same features; the Android side of each version is in `../CHANGELOG.md`.
|
||||
|
||||
## 0.38.0 (build 72)
|
||||
|
||||
- Bluetooth LE MIDI controllers: Setup › MIDI Sync › Bluetooth MIDI › Find
|
||||
controllers opens the system Bluetooth MIDI panel to find and connect them; a
|
||||
connected controller is one of the MIDI inputs. Controllers connected there are
|
||||
remembered and connected again at launch (through CoreBluetooth) until Forget.
|
||||
(Android has the same in 0.38.0.)
|
||||
|
||||
## 0.37.0 (build 71)
|
||||
|
||||
- Same version as Android from now on (iOS 0.6.0 build 11 → 0.37.0 build 71).
|
||||
|
||||
+1
-1
@@ -138,7 +138,7 @@ SNAPDIR ?= build/screens
|
||||
# Mac snapshots of the app's tabs with the demo song (SizzleSession runs on macOS
|
||||
# too, without audio). Screens must stay SwiftUI-only (no UIKit) to render here.
|
||||
SCREEN_SWIFT := $(EDITOR_SWIFT) app/Host/AppModel.swift app/Host/RootView.swift app/Host/SlotDeviceModel.swift \
|
||||
app/Host/KeyboardView.swift app/Host/SlotDataSource.swift app/Host/SampleRecorder.swift app/Host/AppSettings.swift app/Host/AppBoot.swift app/Host/ThemeLibrary.swift \
|
||||
app/Host/KeyboardView.swift app/Host/SlotDataSource.swift app/Host/SampleRecorder.swift app/Host/AppSettings.swift app/Host/AppBoot.swift app/Host/ThemeLibrary.swift app/Host/BluetoothMidi.swift \
|
||||
$(shell find app/Host/Screens app/Host/Bespoke app/Host/Input -name '*.swift')
|
||||
$(SNAPDIR)/libsizzlescreens.dylib: $(AU_SRC) $(wildcard app/Host/SizzleSession*.mm app/Host/SizzleSession*.h) app/Host/SizzleMidi.mm app/Host/SizzleMidi.h app/tests/SnapshotComponents.mm $(CORE_SRC) $(CORE_HDR)
|
||||
mkdir -p $(SNAPDIR)
|
||||
|
||||
@@ -25,6 +25,7 @@ enum AppBoot {
|
||||
midi.onNote = { on, ch, note, vel in input.midiNote(on: on, channel: ch, note: note, velocity: vel) }
|
||||
midi.onControl = { cc, value in input.midiControl(cc, value) }
|
||||
midi.start(withDisabledKeys: settings.midiSourcesOff)
|
||||
BluetoothMidi.shared.reconnectRemembered()
|
||||
}
|
||||
|
||||
/// Leaving the foreground: save, and unless Sizzle stays on as a sound module
|
||||
|
||||
@@ -29,6 +29,10 @@ final class AppSettings: ObservableObject {
|
||||
@Published var soundModule: Bool { didSet { d.set(soundModule, forKey: "soundModule") } }
|
||||
/// MIDI sources the user switched off (MidiSourceKey).
|
||||
@Published var midiSourcesOff: Set<String> { didSet { d.set(Array(midiSourcesOff).sorted(), forKey: "midiSourcesOff") } }
|
||||
/// Bluetooth LE MIDI controllers to connect at launch: peripheral id -> name.
|
||||
@Published var bleMidiDevices: [String: String] {
|
||||
didSet { d.set(bleMidiDevices.map { "\($0.key)|\($0.value)" }.sorted(), forKey: "bleMidiDevices") }
|
||||
}
|
||||
/// Input bindings, one `code=actionId` line each (gamepad: `modifier:code=actionId`);
|
||||
/// nil until the user changes them (the defaults apply).
|
||||
@Published var keyboardBindings: String? { didSet { d.set(keyboardBindings, forKey: "bindKeyboard") } }
|
||||
@@ -45,6 +49,10 @@ final class AppSettings: ObservableObject {
|
||||
receiveMidiClock = d.bool(forKey: "midiClockRecv")
|
||||
soundModule = d.bool(forKey: "soundModule")
|
||||
midiSourcesOff = Set(d.stringArray(forKey: "midiSourcesOff") ?? [])
|
||||
bleMidiDevices = Dictionary((d.stringArray(forKey: "bleMidiDevices") ?? []).map { e -> (String, String) in
|
||||
let parts = e.split(separator: "|", maxSplits: 1).map(String.init)
|
||||
return (parts[0], parts.count > 1 ? parts[1] : parts[0])
|
||||
}, uniquingKeysWith: { a, _ in a })
|
||||
keyboardBindings = d.string(forKey: "bindKeyboard")
|
||||
gamepadBindings = d.string(forKey: "bindGamepad")
|
||||
midiBindings = d.string(forKey: "bindMidi")
|
||||
@@ -53,7 +61,8 @@ final class AppSettings: ObservableObject {
|
||||
// MARK: Backup text
|
||||
|
||||
private static let keys = ["palette", "recordTailBars", "kbdChannel", "kbdOctave", "vuMeters", "midiClockSend",
|
||||
"midiClockRecv", "soundModule", "midiSourcesOff", "bindKeyboard", "bindGamepad", "bindMidi"]
|
||||
"midiClockRecv", "soundModule", "midiSourcesOff", "bleMidiDevices", "bindKeyboard",
|
||||
"bindGamepad", "bindMidi"]
|
||||
|
||||
/// Every setting as `key=value` lines; multi-line values (bindings, the source
|
||||
/// list) are escaped (`\n` → `\\n`).
|
||||
@@ -92,6 +101,12 @@ final class AppSettings: ObservableObject {
|
||||
if let v = map["midiClockRecv"] { receiveMidiClock = v == "true" }
|
||||
if let v = map["soundModule"] { soundModule = v == "true" }
|
||||
if let v = map["midiSourcesOff"] { midiSourcesOff = Set(v.split(separator: "\n").map(String.init)) }
|
||||
if let v = map["bleMidiDevices"] {
|
||||
bleMidiDevices = Dictionary(v.split(separator: "\n").map { e -> (String, String) in
|
||||
let parts = e.split(separator: "|", maxSplits: 1).map(String.init)
|
||||
return (parts[0], parts.count > 1 ? parts[1] : parts[0])
|
||||
}, uniquingKeysWith: { a, _ in a })
|
||||
}
|
||||
if let v = map["bindKeyboard"] { keyboardBindings = v }
|
||||
if let v = map["bindGamepad"] { gamepadBindings = v }
|
||||
if let v = map["bindMidi"] { midiBindings = v }
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
#if os(iOS)
|
||||
import CoreBluetooth
|
||||
#endif
|
||||
|
||||
/// Bluetooth LE MIDI controllers (the Android app's BleMidi). Discovery and
|
||||
/// connecting go through the system's Bluetooth MIDI panel (CABTMIDICentralViewController,
|
||||
/// Setup › MIDI Sync › Find controllers); once connected a controller is an
|
||||
/// ordinary CoreMIDI source, listed and played like the others.
|
||||
///
|
||||
/// When the panel closes, the connected BLE MIDI peripherals are remembered
|
||||
/// (identifier and name, in AppSettings); at the next launch Sizzle connects them
|
||||
/// again through CoreBluetooth, so they come back without opening the panel.
|
||||
/// Bluetooth is only touched once something is remembered or the panel is used,
|
||||
/// so the permission prompt doesn't appear for people without BLE controllers.
|
||||
@MainActor
|
||||
final class BluetoothMidi: ObservableObject {
|
||||
static let shared = BluetoothMidi()
|
||||
|
||||
/// Peripheral identifier -> name.
|
||||
@Published private(set) var remembered: [String: String]
|
||||
|
||||
private init() {
|
||||
remembered = AppSettings.shared.bleMidiDevices
|
||||
}
|
||||
|
||||
func forget(_ id: String) {
|
||||
remembered[id] = nil
|
||||
AppSettings.shared.bleMidiDevices = remembered
|
||||
#if os(iOS)
|
||||
if let uuid = UUID(uuidString: id), let p = central?.retrievePeripherals(withIdentifiers: [uuid]).first {
|
||||
central?.cancelPeripheralConnection(p)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
static let midiService = CBUUID(string: "03B80E5A-EDE8-4B33-A751-6CE34EC4C700")
|
||||
private var central: CBCentralManager?
|
||||
private var pending: [() -> Void] = []
|
||||
private lazy var delegate = CentralDelegate { [weak self] in self?.poweredOn() }
|
||||
|
||||
/// Run [action] once Bluetooth is on (creating the central manager on first use).
|
||||
private func whenPoweredOn(_ action: @escaping () -> Void) {
|
||||
if let c = central, c.state == .poweredOn { action(); return }
|
||||
pending.append(action)
|
||||
if central == nil { central = CBCentralManager(delegate: delegate, queue: .main) }
|
||||
}
|
||||
|
||||
/// At launch: connect every remembered controller.
|
||||
func reconnectRemembered() {
|
||||
guard !remembered.isEmpty else { return }
|
||||
whenPoweredOn { [self] in
|
||||
let ids = remembered.keys.compactMap(UUID.init(uuidString:))
|
||||
for p in central?.retrievePeripherals(withIdentifiers: ids) ?? [] where p.state == .disconnected {
|
||||
central?.connect(p, options: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Bluetooth MIDI panel closed: remember what is connected now.
|
||||
func panelClosed() {
|
||||
whenPoweredOn { [self] in
|
||||
for p in central?.retrieveConnectedPeripherals(withServices: [Self.midiService]) ?? [] {
|
||||
remembered[p.identifier.uuidString] = p.name ?? "Bluetooth MIDI"
|
||||
}
|
||||
AppSettings.shared.bleMidiDevices = remembered
|
||||
}
|
||||
}
|
||||
private func poweredOn() {
|
||||
let actions = pending
|
||||
pending.removeAll()
|
||||
actions.forEach { $0() }
|
||||
}
|
||||
#else
|
||||
func reconnectRemembered() {}
|
||||
func panelClosed() {}
|
||||
#endif
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
/// The central manager's delegate, kept out of the Objective-C header (which
|
||||
/// doesn't import CoreBluetooth).
|
||||
private final class CentralDelegate: NSObject, CBCentralManagerDelegate {
|
||||
private let onPoweredOn: @MainActor () -> Void
|
||||
init(_ onPoweredOn: @escaping @MainActor () -> Void) { self.onPoweredOn = onPoweredOn }
|
||||
|
||||
func centralManagerDidUpdateState(_ central: CBCentralManager) {
|
||||
guard central.state == .poweredOn else { return }
|
||||
Task { @MainActor in self.onPoweredOn() }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -20,6 +20,8 @@
|
||||
<string>1</string>
|
||||
<key>LSSupportsOpeningDocumentsInPlace</key>
|
||||
<true/>
|
||||
<key>NSBluetoothAlwaysUsageDescription</key>
|
||||
<string>Sizzle connects Bluetooth MIDI controllers and reconnects them when it starts.</string>
|
||||
<key>NSMicrophoneUsageDescription</key>
|
||||
<string>Sizzle records the microphone or an audio interface's input into samples.</string>
|
||||
<key>UIBackgroundModes</key>
|
||||
|
||||
@@ -148,6 +148,8 @@ struct MidiSyncCard: View {
|
||||
SizzleMidi.shared.setSourceKey(src.key, enabled: on)
|
||||
}
|
||||
}
|
||||
SetupDivider()
|
||||
BluetoothMidiSection()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -195,3 +197,35 @@ struct BackupCard: View {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bluetooth LE MIDI controllers (the Android app's Bluetooth MIDI list): the
|
||||
/// system panel finds and connects them; connected ones join the MIDI inputs
|
||||
/// above and are remembered, to reconnect at every launch until forgotten.
|
||||
struct BluetoothMidiSection: View {
|
||||
@ObservedObject var ble = BluetoothMidi.shared
|
||||
|
||||
var body: some View {
|
||||
HStack {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text("Bluetooth MIDI").font(.system(size: 15, weight: .medium)).foregroundColor(Theme.text)
|
||||
Text("Find Bluetooth LE MIDI controllers and connect them. Connected ones are listed with the " +
|
||||
"MIDI inputs and reconnect at every launch.")
|
||||
.font(.system(size: 12)).foregroundColor(Theme.dim).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
Spacer()
|
||||
SetupButton(title: "Find controllers", icon: "antenna.radiowaves.left.and.right") {
|
||||
BluetoothMidiPanel.present { ble.panelClosed() }
|
||||
}
|
||||
}
|
||||
ForEach(ble.remembered.sorted { $0.value < $1.value }, id: \.key) { id, name in
|
||||
HStack {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(name).font(.system(size: 15)).foregroundColor(Theme.text)
|
||||
Text("Remembered — reconnects at launch").font(.system(size: 12)).foregroundColor(Theme.dim)
|
||||
}
|
||||
Spacer()
|
||||
SetupButton(title: "Forget") { ble.forget(id) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import SwiftUI
|
||||
|
||||
#if canImport(UIKit)
|
||||
import AVKit
|
||||
import CoreAudioKit
|
||||
import UIKit
|
||||
|
||||
enum ShareSheet {
|
||||
@@ -119,8 +120,42 @@ struct AudioRouteView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// The system's Bluetooth MIDI panel (find, connect, disconnect BLE MIDI
|
||||
/// controllers) in a sheet with Done; [done] runs however it closes.
|
||||
enum BluetoothMidiPanel {
|
||||
@MainActor static func present(done: @escaping () -> Void) {
|
||||
let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
|
||||
let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first
|
||||
var top = scene?.windows.first { $0.isKeyWindow }?.rootViewController
|
||||
while let p = top?.presentedViewController { top = p }
|
||||
guard let host = top else { return }
|
||||
let panel = CABTMIDICentralViewController()
|
||||
let nav = UINavigationController(rootViewController: panel)
|
||||
let closer = Closer(done)
|
||||
panel.navigationItem.rightBarButtonItem = UIBarButtonItem(systemItem: .done, primaryAction: UIAction { [weak nav] _ in
|
||||
nav?.dismiss(animated: true) { closer.fire() }
|
||||
})
|
||||
nav.modalPresentationStyle = .formSheet
|
||||
nav.presentationController?.delegate = closer
|
||||
objc_setAssociatedObject(nav, &Closer.key, closer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
|
||||
host.present(nav, animated: true)
|
||||
}
|
||||
|
||||
private final class Closer: NSObject, UIAdaptivePresentationControllerDelegate {
|
||||
static var key = 0
|
||||
private var done: (() -> Void)?
|
||||
init(_ done: @escaping () -> Void) { self.done = done }
|
||||
func fire() { done?(); done = nil }
|
||||
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { fire() }
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
enum BluetoothMidiPanel {
|
||||
@MainActor static func present(done: @escaping () -> Void) { done() }
|
||||
}
|
||||
|
||||
struct AudioRouteView: View {
|
||||
var body: some View {
|
||||
Text("Output: Speaker\nInput: Microphone").font(.system(size: 14)).foregroundColor(Theme.text)
|
||||
|
||||
@@ -53,6 +53,7 @@ targets:
|
||||
properties:
|
||||
UIBackgroundModes: [audio]
|
||||
NSMicrophoneUsageDescription: Sizzle records the microphone or an audio interface's input into samples.
|
||||
NSBluetoothAlwaysUsageDescription: Sizzle connects Bluetooth MIDI controllers and reconnects them when it starts.
|
||||
# Documents (songs, samples, recordings, backups) shows in the Files app.
|
||||
UIFileSharingEnabled: true
|
||||
LSSupportsOpeningDocumentsInPlace: true
|
||||
@@ -77,6 +78,7 @@ targets:
|
||||
- sdk: CoreAudioKit.framework
|
||||
- sdk: CoreMIDI.framework
|
||||
- sdk: GameController.framework
|
||||
- sdk: CoreBluetooth.framework
|
||||
settings:
|
||||
base:
|
||||
PRODUCT_BUNDLE_IDENTIFIER: cc.tiredsysadmin.ios.sizzle
|
||||
|
||||
+2
-2
@@ -12,8 +12,8 @@
|
||||
# or polish. versionCode is monotonic and bumps by 1 on every release,
|
||||
# because F-Droid and the Android package manager order installs by it alone.
|
||||
|
||||
versionName = 0.37.0
|
||||
versionCode = 71
|
||||
versionName = 0.38.0
|
||||
versionCode = 72
|
||||
|
||||
# Namespace for every platform: cc.tiredsysadmin.<os>.sizzle. Android:
|
||||
# cc.tiredsysadmin.android.sizzle (app/), iOS/iPadOS: cc.tiredsysadmin.ios.sizzle
|
||||
|
||||
Reference in New Issue
Block a user