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