Compare commits

..
4 Commits
Author SHA1 Message Date
ReactorcoremeltdownandClaude Opus 5.5 2d59b0429d Morph Pad instrument: FRASIL's drone voice ported to Kotlin (0.30.0)
A new instrument for evolving pads and drones, ported from FRASIL 3.3
(Styves Goupil, an M-VAVE FM-1 firmware, MPL-2.0): a detuned saw choir,
eight drifting additive partials and noise through resonators, an
Ornstein-Uhlenbeck MOTION walk and a shared TIDE. Morph toward any of
FRASIL's 36 drone sounds by hand, by MIDI LFO or over a set time while a
note is held. Played by SynthVoice (so the tracker, live MIDI and audition
pools all get it); the frasil/ package stays MPL-2.0, LICENSES/MPL-2.0.txt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:04:31 +01:00
ReactorcoremeltdownandClaude Opus 5.5 dae8ac46ac Sound-module mode ignores clock Start/Stop for Sizzle's own song (v0.29.2)
With "Receive MIDI clock" on, Mikro Seq's Start also started Sizzle's
sequencer, so a song imported from Mikro Seq played along with the live
notes, doubling parts that Mikro Seq's mutes could not reach. While
sound-module mode is on, Start/Stop are now ignored (traced as such);
tempo is still followed. Verified on the emulator with MidiTrace, plus a
control run with the mode off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 23:04:41 +01:00
ReactorcoremeltdownandClaude Opus 5.5 3c248028c9 MIDI trace, spaced block names survive save/load, clearer clock-receive text (v0.29.1)
- input/MidiTrace: optional (setprop log.tag.SizzleMidiTrace VERBOSE) log of
  every received packet with lateness and every note handed to the engine
  with the mixer strips it reaches; flags Sizzle's own transport playing and
  clock Start/Stop acting on it. AudioEngine.describeBusTargets backs it.
- ProjectIo percent-encodes spaces/%/] in [PATTERN name=...], so "C1 muted"
  no longer comes back as "C1"; old files load unchanged.
- "Receive MIDI clock" explains that it starts Sizzle's own song, which then
  plays along with incoming notes (the cause of "mutes don't work / only C2"
  reports when used as a sound module with an imported Mikro Seq song).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 23:00:39 +01:00
ReactorcoremeltdownandClaude Opus 5.5 df64af8c9b MIDI inputs list with per-source switches; reconnect dead virtual sources (v0.29.0)
- Setup -> MIDI Sync lists every MIDI source that can send to Sizzle with a
  switch and its state (Listening / Not connected / Off) plus Reconnect.
  Off-choices persist by a stable MidiSourceKey (Android ids change).
- When the app behind a virtual source dies/restarts, Android keeps the
  device and our connection, drops the service binding and sends no callback,
  so Sizzle went deaf to e.g. a restarted Mikro Seq. A worker thread now
  probes open virtual sources every 3 s (openOutputPort is null from a dead
  server) and reopens dead ones; resume re-scans; zero-open port status is
  also treated as dead.
- Verified on an Android 15 emulator: force-stop + restart Mikro Seq ->
  reconnected within ~3 s, notes flowing with both apps in background.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 22:32:04 +01:00
27 changed files with 2270 additions and 56 deletions
+42
View File
@@ -4,6 +4,48 @@ Sizzletracker for Android (`cc.tiredsysadmin.android.sizzle`). One entry per
version in `versions.properties`; versions before 0.28.0 are described in the git
log (one commit per version).
## 0.30.0 (versionCode 61)
- **Morph Pad**, a new instrument for evolving pads and drones: the drone voice of
FRASIL (a custom firmware for the M-VAVE FM-1 by Styves Goupil), ported to
Kotlin. A detuned saw choir, eight drifting additive partials and noise through
resonators, slow random motion and a shared tide on the timbre. Morph toward
any of the 36 factory sounds by hand, by MIDI LFO or over a set time while a
note is held. Plays from the tracker, the toolbox keyboard and live MIDI
(including sound-module mode).
- The ported files (`frasil/`) are MPL-2.0, as FRASIL is; the licence text is in
`LICENSES/MPL-2.0.txt`. The rest of Sizzle stays GPL-3.0-or-later.
## 0.29.2 (versionCode 60)
- While Sizzle runs as a MIDI sound module, another app's clock Start/Stop no
longer starts or stops Sizzle's own song (tempo is still followed). Before, a
song opened from Mikro Seq played along with Mikro Seq's live notes, doubling
parts that Mikro Seq's mutes couldn't silence.
## 0.29.1 (versionCode 59)
- **MIDI trace** for checking what reaches Sizzle and what it plays: every
received packet (bytes, lateness) and every note with the mixer strips it
reaches, flagged when Sizzle's own transport is also playing. Off by default;
`adb shell setprop log.tag.SizzleMidiTrace VERBOSE`, then
`adb logcat -s SizzleMidiTrace`.
- Block names with spaces (e.g. Mikro Seq's "C1 muted") survive the autosave and
project save/load (they were cut at the first space).
- "Receive MIDI clock" now says that it starts Sizzle's own song, which then
plays along with the notes another app sends.
## 0.29.0 (versionCode 58)
- **MIDI inputs list** (Setup → MIDI Sync): every MIDI source Sizzle can hear
(controllers, other apps' virtual ports such as Mikro Seq), each with a switch
and its state (Listening / Not connected / Off), plus a **Reconnect** button.
The choice is saved; new sources are on by default.
- **Automatic reconnect** when the app behind a virtual source restarts (crash,
update, force stop). Android gives no signal for that and left Sizzle holding a
dead connection, so Mikro Seq could play into nothing. Sizzle now checks open
virtual sources every 3 s and reopens a dead one, and re-scans on every resume.
## 0.28.0 (versionCode 57)
- **Background MIDI sound module.** New setting "Keep running as MIDI sound
+373
View File
@@ -0,0 +1,373 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
+5
View File
@@ -80,3 +80,8 @@ the terms of the **GNU General Public License v3.0 or later**
source file carries an SPDX `GPL-3.0-or-later` header.
Copyright © 2026 Reactorcoremeltdown
The Morph Pad instrument (`app/src/main/java/cc/tiredsysadmin/android/sizzle/frasil/`)
is ported from [FRASIL](https://github.com/styvesgoupil/frasil), Copyright © 2026
Styves Goupil, and those files remain under the **Mozilla Public License 2.0**
([`LICENSES/MPL-2.0.txt`](LICENSES/MPL-2.0.txt)).
@@ -129,6 +129,8 @@ class MainActivity : ComponentActivity() {
// Sound-module mode: (re)start its foreground service while we are allowed
// to — a start from the background would be refused.
if (app.soundModuleEnabled.value) SoundModuleService.start(this)
// Pick up MIDI sources that appeared or whose app restarted while we were away.
app.refreshMidi()
}
override fun onStop() {
@@ -13,6 +13,7 @@ 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.input.MidiTrace
import cc.tiredsysadmin.android.sizzle.io.PresetLibrary
import cc.tiredsysadmin.android.sizzle.io.ProjectStore
import cc.tiredsysadmin.android.sizzle.io.SettingsStore
@@ -61,9 +62,18 @@ class SizzleApp : Application() {
* 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) =
override fun busNoteOn(channel: Int, note: Int, velocity: Int) {
if (MidiTrace.on) MidiTrace.log(
"engine ON ch=$channel ${MidiTrace.note(note)} v=$velocity -> " +
audioEngine.describeBusTargets(channel, note) +
if (audioEngine.transport.value.isPlaying) " [Sizzle transport PLAYING]" else "",
)
audioEngine.busNoteOn(channel, note, velocity)
override fun busNoteOff(channel: Int, note: Int) = audioEngine.busNoteOff(channel, note)
}
override fun busNoteOff(channel: Int, note: Int) {
if (MidiTrace.on) MidiTrace.log("engine OFF ch=$channel ${MidiTrace.note(note)}")
audioEngine.busNoteOff(channel, note)
}
})
}
@@ -130,6 +140,10 @@ class SizzleApp : Application() {
if (midiOwners.add(owner) && midiOwners.size == 1) { midiInput.start(); midiClock.start() }
}
/** Re-scan MIDI sources (MainActivity.onResume): opens anything enabled that
* isn't open, e.g. after a source's app was reinstalled. */
fun refreshMidi() { if (midiOwners.isNotEmpty()) midiInput.refresh() }
fun releaseMidi(owner: String) {
if (midiOwners.remove(owner) && midiOwners.isEmpty()) { midiInput.stop(); midiClock.stop() }
}
@@ -154,14 +168,35 @@ class SizzleApp : Application() {
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() } }
// As a sound module, Sizzle plays the notes another app sends; if that app's
// clock Start also started Sizzle's own song, the song would play along
// (doubled parts that the sender's mutes can't reach). So Start/Stop drive
// the transport only while sound-module mode is off. Tempo is still followed
// (tempo-synced LFOs, delays and arpeggiators use it).
midiClock.onReceiveStart = {
if (_soundModuleEnabled.value) {
if (MidiTrace.on) MidiTrace.log("clock Start ignored: sound-module mode is on")
} else {
if (MidiTrace.on) MidiTrace.log("clock Start -> Sizzle's own sequencer plays the loaded song")
main.post { if (!audioEngine.transport.value.isPlaying) audioEngine.play() }
}
}
midiClock.onReceiveStop = {
if (_soundModuleEnabled.value) {
if (MidiTrace.on) MidiTrace.log("clock Stop ignored: sound-module mode is on")
} else {
if (MidiTrace.on) MidiTrace.log("clock Stop -> Sizzle's own sequencer pauses")
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
midiInput.restoreDisabled(s.midiSourcesOff)
midiInput.onDisabledChanged = { keys -> appScope.launch { settingsStore.saveMidiSourcesOff(keys) } }
}
private val appScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
@@ -6,6 +6,8 @@ package cc.tiredsysadmin.android.sizzle.audio
import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioTrack
import cc.tiredsysadmin.android.sizzle.frasil.FrasilClock
import cc.tiredsysadmin.android.sizzle.frasil.FrasilPatch
import cc.tiredsysadmin.android.sizzle.model.Arrangement
import cc.tiredsysadmin.android.sizzle.model.Pattern
import cc.tiredsysadmin.android.sizzle.model.Project
@@ -610,6 +612,7 @@ class AudioEngine(
*/
fun fillBlock(out: FloatArray, frames: Int) {
val proj = project
FrasilClock.advance(frames, sampleRate) // the Morph Pad's shared TIDE runs on it
// Per-block param housekeeping: LFOs modulate targets first, then effects
// read their (possibly modulated) parameters.
if (proj != null) {
@@ -1264,7 +1267,7 @@ class AudioEngine(
if (slot?.type == ToolboxType.SAMPLER) return
// Remember which slot is being auditioned so refreshSynthPatches pushes live
// knob turns into the held preview note.
if (slot?.type == ToolboxType.NES_SYNTH) auditionSlotIdx = slotIndex
if (hasSynthPatch(slot?.type)) auditionSlotIdx = slotIndex
val v = liveVoices.firstOrNull { !it.isActive } ?: liveVoices[0].also { it.kill() }
v.noteOn(midi, 110, patchForSlot(slot, project?.tempoBpm ?: 120f))
}
@@ -1327,6 +1330,27 @@ class AudioEngine(
return pool[base].also { it.kill() }
}
/** For the MIDI trace only: what [busNoteOn] would do with [midi] on
* [midiChannel], e.g. "strip2 SAMPLER pad2 | strip4 NES_SYNTH" or "no strip". */
fun describeBusTargets(midiChannel: Int, midi: Int): String {
val proj = project ?: return "no project"
val parts = ArrayList<String>()
for (ch in 0 until Pattern.TRACK_COUNT) {
if (proj.mixer.channels[ch].midiChannel != midiChannel) continue
val slot = proj.toolbox.getOrNull(proj.mixer.channels[ch].instrumentSlot)
val type = slot?.type
parts += "strip${ch + 1} " + when {
type == null -> "no instrument (silent)"
type == ToolboxType.SAMPLER -> {
val pad = SamplerPads.padFor(midi)
if (voiceSample(slot, midi) != null) "SAMPLER pad${pad + 1}" else "SAMPLER pad${pad + 1} empty (silent)"
}
else -> type.name + if (voiceSample(slot, midi) == null && type == ToolboxType.SOUNDFONT) " no sample" else ""
}
}
return if (parts.isEmpty()) "no strip on channel $midiChannel" else parts.joinToString(" | ")
}
/** Release [midi] on every mixer channel listening on [midiChannel]. */
fun busNoteOff(midiChannel: Int, midi: Int) {
val proj = project ?: return
@@ -1430,8 +1454,14 @@ class AudioEngine(
/** Parse a slot's synth patch (default init patch if it isn't an NES synth).
* Allocates one [SynthPatch] — used only for the first audition note; the
* sequencer/bus paths use the per-block cache in [refreshSynthPatches]. */
private fun patchForSlot(slot: ToolboxSlot?, tempoBpm: Float): SynthPatch =
if (slot?.type == ToolboxType.NES_SYNTH) SynthPatch.from(slot, tempoBpm) else SynthPatch.DEFAULT
private fun patchForSlot(slot: ToolboxSlot?, tempoBpm: Float): SynthPatch = when (slot?.type) {
ToolboxType.NES_SYNTH -> SynthPatch.from(slot, tempoBpm)
ToolboxType.MORPH_PAD -> SynthPatch.forPad(FrasilPatch.from(slot))
else -> SynthPatch.DEFAULT
}
/** The slot types whose notes a [SynthVoice] plays with a parsed [SynthPatch]. */
private fun hasSynthPatch(type: ToolboxType?) = type == ToolboxType.NES_SYNTH || type == ToolboxType.MORPH_PAD
/**
* Once per block: refresh each bus's cached synth patch (reparsing only when the
@@ -1445,9 +1475,9 @@ class AudioEngine(
val tempo = proj.tempoBpm
for (ch in 0 until Pattern.TRACK_COUNT) {
val slot = proj.toolbox.getOrNull(proj.mixer.channels[ch].instrumentSlot)
if (slot?.type != ToolboxType.NES_SYNTH) { synthPatch[ch] = null; synthPatchVer[ch] = -1; continue }
if (slot == null || !hasSynthPatch(slot.type)) { synthPatch[ch] = null; synthPatchVer[ch] = -1; continue }
if (synthPatch[ch] == null || slot.version != synthPatchVer[ch] || tempo != synthPatchTempo[ch]) {
synthPatch[ch] = SynthPatch.from(slot, tempo)
synthPatch[ch] = patchForSlot(slot, tempo)
synthPatchVer[ch] = slot.version
synthPatchTempo[ch] = tempo
}
@@ -1459,9 +1489,9 @@ class AudioEngine(
}
// Editor audition voices follow the slot currently being previewed.
val aslot = proj.toolbox.getOrNull(auditionSlotIdx)
if (aslot?.type == ToolboxType.NES_SYNTH) {
if (aslot != null && hasSynthPatch(aslot.type)) {
if (auditionPatch == null || aslot.version != auditionPatchVer || tempo != auditionPatchTempo) {
auditionPatch = SynthPatch.from(aslot, tempo)
auditionPatch = patchForSlot(aslot, tempo)
auditionPatchVer = aslot.version
auditionPatchTempo = tempo
}
@@ -3,6 +3,7 @@
package cc.tiredsysadmin.android.sizzle.audio
import cc.tiredsysadmin.android.sizzle.frasil.FrasilPatch
import cc.tiredsysadmin.android.sizzle.model.SynthDefs
import cc.tiredsysadmin.android.sizzle.model.TimeDivision
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
@@ -41,6 +42,9 @@ class SynthPatch(
val modSrc: IntArray, // index into MOD_SRC (0 == Off)
val modDst: IntArray, // index into MOD_DST
val modAmt: FloatArray, // -1..1
/** Set for a Morph Pad slot: the voice then plays FRASIL's drone voice from this
* instead of the subtractive path (see [SynthVoice]); everything above is unused. */
val pad: FrasilPatch? = null,
) {
companion object {
const val OSC_COUNT = SynthDefs.OSC_COUNT
@@ -96,5 +100,11 @@ class SynthPatch(
/** A plain default patch (for generic live audition not tied to a synth slot). */
val DEFAULT: SynthPatch = from(null, 120f)
/** A Morph Pad patch: the default synth fields, carrying [pad]. */
fun forPad(pad: FrasilPatch): SynthPatch = with(DEFAULT) {
SynthPatch(oscWave, oscOct, oscSemi, oscFine, oscLevel, noiseLevel, cutoff, resonance, keytrack,
filterEnvAmt, fA, fD, fS, fR, aA, aD, aS, aR, lfoWave, lfoHz, lfoPhase, modSrc, modDst, modAmt, pad)
}
}
}
@@ -3,6 +3,7 @@
package cc.tiredsysadmin.android.sizzle.audio
import cc.tiredsysadmin.android.sizzle.frasil.FrasilVoice
import kotlin.math.abs
import kotlin.math.exp
import kotlin.math.sin
@@ -71,15 +72,30 @@ class SynthVoice(private val sampleRate: Int) {
private val ampEnv = Adsr()
private val filtEnv = Adsr()
val isActive: Boolean get() = ampEnv.active
// A Morph Pad note plays FRASIL's drone voice instead of the subtractive path. It
// lives inside this class so every synth pool (sequencer, mix-bus, audition) can
// play a pad with no change to how voices are allocated, stolen or released.
private val pad = FrasilVoice(sampleRate)
private var padMode = false
val isActive: Boolean get() = if (padMode) pad.isActive else ampEnv.active
/** Gate is still open (attack/decay/sustain) — the note is *held*. A voice in its
* release tail is still [isActive] but no longer gated; distinguishing the two
* lets a note-off target the held voice instead of one that's already ringing
* out (which otherwise leaves the held note stuck under rapid re-tapping). */
val isGated: Boolean get() = ampEnv.gateOpen
val isGated: Boolean get() = if (padMode) pad.isGated else ampEnv.gateOpen
/** Start (or steal-and-restart) this voice with the given [patch]. */
fun noteOn(midi: Int, velocity: Int, patch: SynthPatch) {
val padPatch = patch.pad
if (padPatch != null) {
if (!padMode) { ampEnv.kill(); filtEnv.kill(); padMode = true }
this.patch = patch
pitch = midi
pad.noteOn(midi, velocity / 127f, padPatch)
return
}
if (padMode) { pad.kill(); padMode = false }
this.patch = patch
pitch = midi
this.velocity = (velocity / 127f).coerceIn(0f, 1f)
@@ -98,11 +114,12 @@ class SynthVoice(private val sampleRate: Int) {
computeTuning()
}
fun noteOff() { ampEnv.gateOff(); filtEnv.gateOff() }
fun noteOff() { if (padMode) pad.noteOff() else { ampEnv.gateOff(); filtEnv.gateOff() } }
/** Hard stop with no release tail (transport stop / voice steal). */
fun kill() {
ampEnv.kill(); filtEnv.kill()
pad.kill()
pitch = -1
ownerTrack = -1
icB = 0f; icL = 0f
@@ -114,6 +131,13 @@ class SynthVoice(private val sampleRate: Int) {
* turns (cutoff, levels, mod…) without clicking or retriggering. */
fun setPatch(p: SynthPatch) {
if (p === patch) return
val padPatch = p.pad
if (padMode || padPatch != null) {
// Only within the same kind: a pad note follows pad edits, a synth note synth
// edits; a slot switched between the two takes effect on the next note.
if (padMode && padPatch != null) { patch = p; pad.setPatch(padPatch) }
return
}
patch = p
lfoInc = p.lfoHz.toDouble() / sampleRate
computeTuning()
@@ -130,6 +154,7 @@ class SynthVoice(private val sampleRate: Int) {
}
fun render(): Float {
if (padMode) return pad.render()
if (!ampEnv.active) return 0f
val dt = 1f / sampleRate
val ampE = ampEnv.advance(dt)
@@ -0,0 +1,230 @@
// SPDX-FileCopyrightText: 2026 Styves Goupil (FRASIL)
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown (Kotlin port for Sizzle)
// SPDX-License-Identifier: MPL-2.0
//
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
// If a copy of the MPL was not distributed with this file, You can obtain one at
// https://mozilla.org/MPL/2.0/ (also in LICENSES/MPL-2.0.txt of this repository).
//
// Ported from FRASIL 3.3 (https://github.com/styvesgoupil/frasil, commit e7a8fb2):
// engine/params.c (the drone's settings, their ranges, the 36 drone presets).
package cc.tiredsysadmin.android.sizzle.frasil
import cc.tiredsysadmin.android.sizzle.model.ParamSpec
/**
* The Morph Pad's settings and factory sounds, taken from FRASIL's drone (its
* CHOEUR / PARTIELS / SOUFFLE layers, MOTION and TIDE) and its 36 drone presets.
*
* Every slider is stored 0..1 exactly as FRASIL's 0..127 settings divided by 127;
* [engineFrom] turns them into the engine's units (FRASIL params.c
* `params_to_engine`). Three settings are choices (INTERVAL, TYPE, PITCH).
*
* Left out, because Sizzle's channels are mono or Sizzle has its own: SPREAD (the
* voices across the stereo field), SPACE (FRASIL's own reverb: put an Ambience on
* the channel instead), PRESSURE, TUNE, GLINT / BASS / LEAD and the master effects.
*
* Added for Sizzle: MORPH. FRASIL glides a whole scene to another over 1..120 s;
* here a pad morphs toward one of the factory sounds ([MORPH_TO]), by hand
* ([MORPH], an LFO can move it) and, with [MORPH_TIME], on its own while a note is
* held: each note starts at MORPH and arrives at the target after MORPH TIME.
*/
object FrasilDefs {
const val MORPH_TO = "morphTo"
const val MORPH = "morph"
const val MORPH_TIME = "mtime"
val INTERVALS = listOf("Unison", "-12", "+7", "+12")
private val INTERVAL_RATIO = floatArrayOf(1f, 0.5f, 1.4983071f, 2f)
val FILTER_TYPES = listOf("Low", "Band", "High")
val BREATH_PITCHES = listOf("-12", "Unison", "+12", "+19", "+24")
private val BREATH_RATIO = floatArrayOf(0.5f, 1f, 2f, 2.9966142f, 4f)
// ---- engine parameter indices (FrasilPatch arrays; all glide, as FRASIL's floats do) ----
const val CHOIR = 0
const val PARTIALS = 1
const val BREATH = 2
const val WARMTH = 3
const val DETUNE = 4
const val CUTOFF = 5
const val TILT = 6
const val ODD = 7
const val STRETCH = 8
const val RESONANCE = 9
const val COLOR = 10
const val ATTACK = 11
const val RELEASE = 12
const val MOTION = 13
const val MOTION_RATE = 14
const val TIDE = 15
const val TIDE_RATE = 16
const val TIMBRE = 17
const val SHAPE = 18
const val CH_RESO = 19
const val EVOLVE = 20
const val BEAT = 21
const val FORMANT = 22 // log2 of the harmonic, 0..3
const val PEAK = 23
const val GRAIN = 24
const val TONE = 25 // -1 dark .. 1 bright
const val AIR = 26
const val SOFT = 27
const val VELOCITY = 28
const val BODY = 29 // FRASIL's FULLNESS
const val INTERVAL = 30 // the centre saw's ratio
const val BR_PITCH = 31 // the resonators' ratio
const val N = 32
/** The slider/choice parameters, in editor order. Defaults: FRASIL's MIST. */
val PARAMS: List<ParamSpec> by lazy { listOf(
ParamSpec(MORPH_TO, "Morph To", choices = listOf("Off") + PRESET_NAMES()),
ParamSpec(MORPH, "Morph", 0f, 0f, 1f),
ParamSpec(MORPH_TIME, "Morph Time s", 0f, 0f, 120f),
ParamSpec("choir", "Choir", r(76)), ParamSpec("partials", "Partials", r(89)),
ParamSpec("breath", "Breath", r(32)), ParamSpec("timbre", "Timbre", r(64)),
ParamSpec("warmth", "Warmth", r(19)), ParamSpec("body", "Body", 1f),
ParamSpec("attack", "Attack", r(89)), ParamSpec("release", "Release", r(83)),
ParamSpec("velsens", "Velocity", r(38)),
ParamSpec("motion", "Motion", r(44)), ParamSpec("mrate", "Motion Rate", r(51)),
ParamSpec("tide", "Tide", r(25)), ParamSpec("tperiod", "Tide Speed", r(38)),
ParamSpec("detune", "Detune", r(51)), ParamSpec("cfilter", "Filter", r(44)),
ParamSpec("shape", "Shape", 0f), ParamSpec("interval", "Interval", choices = INTERVALS),
ParamSpec("creso", "Resonance", 0f), ParamSpec("ctype", "Filter Type", choices = FILTER_TYPES),
ParamSpec("soft", "Soft", 0f),
ParamSpec("tilt", "Tilt", r(57)), ParamSpec("odd", "Odd", r(25)),
ParamSpec("stretch", "Stretch", 0f), ParamSpec("evolve", "Evolve", 0f),
ParamSpec("beat", "Beat", 0f), ParamSpec("formant", "Formant", r(85)),
ParamSpec("peak", "Peak", 0f),
ParamSpec("bres", "Glass", r(70)), ParamSpec("color", "Color", 0f),
ParamSpec("grain", "Grain", 0f), ParamSpec("bpitch", "Pitch", choices = BREATH_PITCHES),
ParamSpec("btone", "Tone", r(64)), ParamSpec("air", "Air", 0f),
) }
/** The editor's pages: (title, keys). */
val SECTIONS: List<Pair<String, List<String>>> = listOf(
"Morph" to listOf(MORPH_TO, MORPH, MORPH_TIME),
"Layers" to listOf("choir", "partials", "breath", "timbre", "warmth", "body"),
"Shape" to listOf("attack", "release", "velsens"),
"Motion" to listOf("motion", "mrate", "tide", "tperiod"),
"Choir" to listOf("detune", "cfilter", "shape", "interval", "creso", "ctype", "soft"),
"Partials" to listOf("tilt", "odd", "stretch", "evolve", "beat", "formant", "peak"),
"Breath" to listOf("bres", "color", "grain", "bpitch", "btone", "air"),
)
private fun r(v: Int) = v / 127f
/**
* A sound's engine values from its stored settings: [num] reads a slider (0..1,
* its default if absent), [choice] a choice's label. Returns the float array
* and the choir filter's TYPE (0 low, 1 band, 2 high).
*/
fun engineFrom(num: (String, Float) -> Float, choice: (String, String) -> String): Pair<FloatArray, Int> {
val e = FloatArray(N)
fun u(key: String, def: Float) = num(key, def).coerceIn(0f, 1f)
e[CHOIR] = u("choir", r(76)); e[PARTIALS] = u("partials", r(89)); e[BREATH] = u("breath", r(32))
e[WARMTH] = u("warmth", r(19)); e[DETUNE] = u("detune", r(51)); e[CUTOFF] = u("cfilter", r(44))
e[TILT] = u("tilt", r(57)); e[ODD] = u("odd", r(25)); e[STRETCH] = u("stretch", 0f)
e[RESONANCE] = u("bres", r(70)); e[COLOR] = u("color", 0f)
e[ATTACK] = u("attack", r(89)); e[RELEASE] = u("release", r(83))
e[MOTION] = u("motion", r(44)); e[MOTION_RATE] = u("mrate", r(51))
e[TIDE] = u("tide", r(25)); e[TIDE_RATE] = u("tperiod", r(38)); e[TIMBRE] = u("timbre", r(64))
e[SHAPE] = u("shape", 0f); e[CH_RESO] = u("creso", 0f)
e[EVOLVE] = u("evolve", 0f); e[BEAT] = u("beat", 0f)
e[FORMANT] = 3f * u("formant", r(85)); e[PEAK] = u("peak", 0f)
e[GRAIN] = u("grain", 0f)
val tn = u("btone", r(64)) * 127f
e[TONE] = if (tn >= 126.5f) 1f else (tn - 64f) / 63f
e[AIR] = u("air", 0f); e[SOFT] = u("soft", 0f)
e[VELOCITY] = u("velsens", r(38)); e[BODY] = u("body", 1f)
e[INTERVAL] = INTERVAL_RATIO[INTERVALS.indexOf(choice("interval", INTERVALS[0])).coerceAtLeast(0)]
e[BR_PITCH] = BREATH_RATIO[BREATH_PITCHES.indexOf(choice("bpitch", BREATH_PITCHES[1])).let { if (it < 0) 1 else it }]
val type = FILTER_TYPES.indexOf(choice("ctype", FILTER_TYPES[0])).coerceAtLeast(0)
return e to type
}
// ---------------------------------------------------------------- presets ---
class Preset(val name: String, val values: Map<String, String>)
/** FRASIL's 36 drone presets, each as the slot values it sets (params.c DRONE_PRESET). */
val FACTORY: List<Preset> by lazy {
RAW.map { (name, row) ->
val m = LinkedHashMap<String, String>()
for (c in COLS.indices) {
val key = COLS[c] ?: continue
m[key] = when (key) {
"interval" -> INTERVALS[row[c] % 4]
"ctype" -> FILTER_TYPES[row[c] % 3]
"bpitch" -> BREATH_PITCHES[row[c] % 5]
else -> (row[c] / 127f).toString()
}
}
// Sizzle's own, not in FRASIL's preset: as FRASIL's defaults, no morph.
m["velsens"] = r(38).toString(); m["body"] = "1.0"
m[MORPH_TO] = "Off"; m[MORPH] = "0.0"; m[MORPH_TIME] = "0.0"
Preset(name, m)
}
}
/** A factory sound's engine values by its name (MORPH TO's target), or null. */
fun factoryEngine(name: String): Pair<FloatArray, Int>? = engineByName[name]
private val engineByName: Map<String, Pair<FloatArray, Int>> by lazy {
FACTORY.associate { p ->
p.name to engineFrom({ k, d -> p.values[k]?.toFloatOrNull() ?: d }, { k, d -> p.values[k] ?: d })
}
}
// CHO PAR SOU WAR DET FIL TIL ODD STR BRES COL SPR ATT REL MOT RAT TID PER TIM SPA SHP INT CRES TYP EVO BEAT
// FORM PEAK GRN PIT TONE AIR SOFT. SPREAD and SPACE (null) are FRASIL's stereo field and reverb.
private val COLS: Array<String?> = arrayOf(
"choir", "partials", "breath", "warmth", "detune", "cfilter", "tilt", "odd", "stretch", "bres", "color",
null, "attack", "release", "motion", "mrate", "tide", "tperiod", "timbre", null, "shape", "interval",
"creso", "ctype", "evolve", "beat", "formant", "peak", "grain", "bpitch", "btone", "air", "soft",
)
private fun PRESET_NAMES(): List<String> = RAW.map { it.first }
private val RAW: List<Pair<String, IntArray>> by lazy {
listOf(
"Mist" to intArrayOf(76, 89, 32, 19, 51, 44, 57, 25, 0, 70, 0, 89, 89, 83, 44, 51, 25, 38, 64, 57, 0, 0, 0, 0, 0, 0, 85, 0, 0, 1, 64, 0, 0),
"Cathedral" to intArrayOf(110, 50, 20, 25, 85, 55, 60, 30, 0, 60, 0, 110, 100, 100, 60, 40, 20, 50, 60, 95, 0, 1, 20, 0, 10, 0, 85, 0, 0, 1, 64, 0, 0),
"Glacier" to intArrayOf(20, 100, 70, 5, 30, 60, 35, 50, 60, 115, 127, 100, 80, 110, 40, 30, 30, 40, 80, 90, 0, 0, 0, 0, 40, 15, 100, 30, 20, 2, 80, 0, 0),
"Abyss" to intArrayOf(90, 70, 25, 50, 70, 20, 90, 40, 0, 50, 0, 70, 100, 105, 50, 25, 50, 25, 40, 70, 30, 1, 40, 0, 20, 0, 60, 0, 0, 0, 30, 0, 0),
"Aurora" to intArrayOf(60, 105, 40, 15, 45, 65, 40, 15, 10, 85, 60, 115, 90, 105, 55, 45, 45, 50, 75, 95, 0, 0, 0, 0, 70, 25, 90, 35, 0, 2, 75, 10, 0),
"Ember" to intArrayOf(100, 55, 20, 80, 40, 40, 70, 60, 0, 50, 30, 80, 70, 80, 35, 40, 20, 40, 55, 50, 64, 0, 50, 0, 10, 0, 70, 0, 0, 1, 50, 0, 0),
"Tide" to intArrayOf(80, 80, 45, 25, 60, 45, 55, 30, 10, 75, 40, 100, 95, 100, 70, 30, 110, 60, 60, 70, 0, 0, 30, 0, 30, 0, 85, 0, 0, 1, 64, 0, 0),
"Dust" to intArrayOf(25, 40, 85, 20, 40, 50, 60, 30, 20, 100, 60, 120, 60, 90, 50, 50, 30, 40, 60, 75, 0, 0, 0, 0, 30, 0, 85, 0, 90, 2, 85, 40, 0),
"Wind" to intArrayOf(0, 20, 85, 0, 40, 50, 60, 30, 0, 20, 30, 127, 80, 95, 90, 80, 50, 70, 64, 80, 0, 0, 0, 0, 0, 0, 85, 0, 0, 1, 75, 50, 0),
"Organ" to intArrayOf(40, 115, 10, 30, 10, 50, 45, 0, 0, 60, 0, 60, 40, 60, 15, 40, 10, 40, 64, 50, 0, 2, 0, 0, 0, 0, 85, 0, 0, 1, 64, 0, 0),
"Hollow" to intArrayOf(105, 80, 25, 20, 35, 50, 50, 110, 0, 70, 64, 90, 80, 90, 40, 45, 25, 40, 60, 65, 64, 0, 40, 1, 15, 0, 85, 0, 0, 1, 60, 0, 0),
"Vowel" to intArrayOf(65, 125, 15, 10, 30, 55, 30, 20, 0, 70, 0, 85, 90, 95, 45, 35, 60, 45, 64, 70, 0, 0, 60, 1, 20, 0, 95, 105, 0, 1, 64, 0, 0),
"Shimmer" to intArrayOf(45, 100, 50, 10, 55, 75, 25, 20, 15, 100, 90, 120, 85, 110, 50, 55, 30, 40, 85, 100, 0, 3, 0, 0, 40, 50, 100, 20, 10, 3, 90, 20, 0),
"Chanter" to intArrayOf(105, 45, 15, 40, 30, 55, 60, 70, 0, 60, 30, 70, 50, 70, 30, 45, 15, 40, 60, 45, 110, 0, 35, 1, 0, 0, 85, 0, 0, 1, 64, 0, 0),
"Ensemble" to intArrayOf(115, 40, 20, 30, 75, 60, 55, 25, 0, 60, 0, 115, 95, 90, 55, 55, 20, 40, 65, 75, 90, 0, 15, 0, 0, 0, 85, 0, 0, 1, 64, 0, 0),
"Bells" to intArrayOf(15, 115, 45, 5, 25, 50, 30, 20, 95, 110, 127, 95, 40, 110, 30, 40, 20, 40, 75, 85, 0, 0, 0, 0, 30, 30, 85, 0, 0, 2, 80, 0, 0),
"Nocturne" to intArrayOf(90, 60, 30, 35, 55, 25, 85, 30, 0, 55, 0, 90, 110, 115, 45, 20, 40, 20, 45, 85, 20, 1, 70, 0, 25, 0, 70, 0, 0, 0, 35, 0, 0),
"Haze" to intArrayOf(85, 50, 60, 10, 60, 70, 50, 25, 0, 40, 30, 120, 100, 105, 60, 50, 30, 50, 70, 90, 0, 3, 20, 2, 20, 0, 85, 0, 0, 2, 80, 30, 0),
"Pulse" to intArrayOf(50, 95, 25, 20, 30, 50, 45, 30, 0, 70, 20, 100, 60, 80, 30, 50, 20, 40, 64, 65, 0, 0, 0, 0, 15, 100, 85, 0, 0, 1, 64, 0, 0),
"Rime" to intArrayOf(30, 110, 70, 0, 20, 80, 20, 40, 30, 120, 100, 110, 70, 100, 35, 60, 20, 40, 90, 90, 0, 3, 0, 2, 30, 20, 110, 40, 40, 4, 100, 15, 0),
"Deep" to intArrayOf(100, 100, 0, 40, 25, 25, 100, 20, 0, 50, 0, 60, 90, 95, 25, 30, 20, 30, 40, 45, 0, 1, 10, 0, 0, 0, 40, 0, 0, 0, 30, 0, 0),
"Spectral" to intArrayOf(20, 120, 15, 5, 20, 50, 20, 10, 0, 70, 0, 90, 90, 100, 50, 40, 80, 50, 64, 80, 0, 0, 0, 0, 50, 10, 85, 127, 0, 1, 64, 0, 0),
"Rust" to intArrayOf(80, 50, 40, 100, 50, 45, 65, 60, 20, 80, 40, 80, 60, 80, 40, 55, 25, 40, 55, 55, 70, 0, 80, 1, 20, 15, 75, 0, 60, 1, 45, 20, 0),
"Still" to intArrayOf(0, 125, 0, 0, 0, 50, 127, 0, 0, 50, 0, 60, 100, 100, 5, 20, 0, 40, 50, 70, 0, 0, 0, 0, 0, 0, 85, 0, 0, 1, 64, 0, 0),
"Velvet" to intArrayOf(95, 45, 10, 15, 35, 40, 85, 20, 0, 50, 0, 100, 105, 110, 35, 30, 20, 45, 52, 70, 0, 0, 10, 0, 0, 0, 85, 0, 0, 1, 50, 0, 120),
"Chrome" to intArrayOf(35, 115, 15, 35, 15, 75, 15, 120, 45, 90, 80, 85, 60, 90, 35, 55, 15, 40, 85, 60, 64, 3, 85, 2, 20, 35, 110, 70, 0, 3, 95, 0, 0),
"Swarm" to intArrayOf(120, 75, 30, 30, 120, 60, 40, 30, 0, 60, 20, 127, 70, 85, 110, 100, 40, 15, 70, 60, 120, 0, 40, 1, 40, 70, 85, 0, 30, 2, 70, 20, 0),
"Foghorn" to intArrayOf(127, 60, 15, 70, 20, 22, 95, 90, 0, 40, 0, 50, 120, 120, 20, 20, 60, 70, 35, 65, 64, 1, 60, 0, 0, 0, 40, 30, 0, 0, 30, 0, 30),
"Solar" to intArrayOf(70, 105, 45, 20, 55, 90, 15, 15, 5, 80, 30, 120, 100, 110, 60, 50, 70, 35, 100, 90, 10, 3, 15, 2, 60, 25, 120, 40, 0, 3, 110, 30, 0),
"Cave" to intArrayOf(55, 40, 95, 30, 30, 18, 110, 30, 0, 100, 60, 70, 110, 120, 30, 20, 45, 60, 30, 100, 0, 1, 50, 0, 10, 0, 40, 0, 50, 0, 18, 5, 60),
"Glass Harp" to intArrayOf(10, 120, 20, 0, 12, 60, 30, 10, 25, 100, 90, 110, 50, 120, 25, 30, 15, 55, 90, 95, 0, 3, 0, 0, 45, 40, 120, 110, 0, 4, 100, 0, 127),
"Monk" to intArrayOf(110, 85, 10, 25, 30, 38, 70, 40, 0, 60, 0, 70, 100, 100, 30, 25, 30, 65, 50, 80, 0, 1, 55, 1, 15, 0, 62, 90, 0, 1, 50, 0, 90),
"Static" to intArrayOf(35, 40, 127, 15, 40, 70, 40, 50, 0, 110, 90, 127, 40, 70, 80, 110, 20, 20, 80, 55, 30, 0, 30, 2, 0, 0, 85, 0, 85, 3, 100, 40, 0),
"Lullaby" to intArrayOf(85, 70, 8, 10, 22, 45, 100, 10, 0, 60, 0, 80, 110, 120, 20, 15, 35, 80, 55, 85, 0, 2, 0, 0, 10, 8, 85, 20, 0, 1, 64, 0, 110),
"Storm" to intArrayOf(80, 40, 110, 90, 70, 28, 90, 40, 0, 70, 40, 127, 90, 110, 100, 85, 120, 25, 40, 75, 30, 1, 70, 0, 50, 20, 60, 0, 70, 0, 35, 60, 20),
"Prism" to intArrayOf(50, 120, 25, 10, 40, 65, 25, 60, 15, 90, 50, 120, 85, 105, 60, 45, 50, 40, 80, 90, 0, 3, 20, 1, 100, 30, 105, 80, 0, 2, 85, 10, 40),
)
}
}
@@ -0,0 +1,59 @@
// SPDX-FileCopyrightText: 2026 Styves Goupil (FRASIL)
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown (Kotlin port for Sizzle)
// SPDX-License-Identifier: MPL-2.0
//
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
// If a copy of the MPL was not distributed with this file, You can obtain one at
// https://mozilla.org/MPL/2.0/ (also in LICENSES/MPL-2.0.txt of this repository).
package cc.tiredsysadmin.android.sizzle.frasil
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
/**
* An immutable snapshot of a Morph Pad slot, parsed off the audio thread's hot path
* (once per slot change, like the synth's patch): the sound's engine values [a] and
* its filter type, and when MORPH TO names a factory sound, that sound's [b] to
* morph toward.
*/
class FrasilPatch(
val a: FloatArray,
val aType: Int,
val b: FloatArray?,
val bType: Int,
/** Where a note starts between [a] (0) and [b] (1). */
val morph: Float,
/** Seconds a held note takes from [morph] to [b]; 0 stays at [morph]. */
val morphTime: Float,
) {
companion object {
fun from(slot: ToolboxSlot?): FrasilPatch {
val (a, at) = FrasilDefs.engineFrom(
{ k, d -> slot?.float(k, d) ?: d },
{ k, d -> slot?.string(k, d) ?: d },
)
val target = slot?.string(FrasilDefs.MORPH_TO, "Off") ?: "Off"
val b = if (target == "Off") null else FrasilDefs.factoryEngine(target)
return FrasilPatch(
a, at, b?.first, b?.second ?: at,
morph = (slot?.float(FrasilDefs.MORPH, 0f) ?: 0f).coerceIn(0f, 1f),
morphTime = (slot?.float(FrasilDefs.MORPH_TIME, 0f) ?: 0f).coerceIn(0f, 120f),
)
}
val DEFAULT: FrasilPatch by lazy { from(null) }
}
}
/**
* FRASIL's TIDE is one slow sine shared by every voice (a chord brightens and darkens
* together). Sizzle renders voice by voice, so the shared part is the time it runs
* on: the audio engine advances this clock once a block, and each voice reads its
* tide from it at its own TIDE SPEED. Audio thread only.
*/
object FrasilClock {
var seconds = 0.0
private set
fun advance(frames: Int, sampleRate: Int) { seconds += frames.toDouble() / sampleRate }
}
@@ -0,0 +1,667 @@
// SPDX-FileCopyrightText: 2026 Styves Goupil (FRASIL)
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown (Kotlin port for Sizzle)
// SPDX-License-Identifier: MPL-2.0
//
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
// If a copy of the MPL was not distributed with this file, You can obtain one at
// https://mozilla.org/MPL/2.0/ (also in LICENSES/MPL-2.0.txt of this repository).
//
// Ported from FRASIL 3.3 (https://github.com/styvesgoupil/frasil, commit e7a8fb2):
// engine/dsp/frasil.c, its drone voice (voice_start, drift, voice_block, choir_run,
// ch_svf, ch_lp, blepi, partial_ramp, partials_chunk, souffle_chunk, breath_noise,
// render_part) and the mix's DC blocker, warmth and FULLNESS high-pass.
package cc.tiredsysadmin.android.sizzle.frasil
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.AIR
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.ATTACK
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.BEAT
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.BODY
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.BREATH
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.BR_PITCH
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.CHOIR
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.CH_RESO
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.COLOR
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.CUTOFF
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.DETUNE
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.EVOLVE
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.FORMANT
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.GRAIN
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.INTERVAL
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.MOTION
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.MOTION_RATE
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.ODD
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.PARTIALS
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.PEAK
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.RELEASE
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.RESONANCE
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.SHAPE
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.SOFT
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.STRETCH
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.TIDE
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.TIDE_RATE
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.TILT
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.TIMBRE
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.TONE
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.VELOCITY
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.WARMTH
import kotlin.math.cos
import kotlin.math.exp
import kotlin.math.floor
import kotlin.math.ln
import kotlin.math.pow
import kotlin.math.sin
import kotlin.math.sqrt
import kotlin.math.tan
import kotlin.math.tanh
/**
* One note of the Morph Pad: FRASIL's drone voice, three layers summed and slowly
* drifting while the note is held.
*
* - CHOIR: three PolyBLEP saws (centre at INTERVAL, the sides detuned ±), SHAPE
* turns each toward a swaying pulse, SOFT integrates it toward a triangle or a
* sine; two one-pole low-passes, or with RESONANCE / TYPE a TPT state-variable
* filter, the cutoff in harmonics of the note.
* - PARTIALS: eight additive partials as "magic circle" oscillators, tilt, odd,
* stretch, a formant, each one's level and tuning drifting (EVOLVE), BEAT pulsing.
* - BREATH (FRASIL's SOUFFLE): noise or sparse grains through three resonators at
* the note times harmonic / odd / bell ratios, Q from air to glass.
*
* MOTION is an Ornstein-Uhlenbeck random walk per drifting thing (a step a block),
* TIDE one slow sine on the timbre ([FrasilClock]). Then, per voice, FRASIL's mix
* stages: a DC blocker, WARMTH (tanh) and the BODY high-pass.
*
* Differences from FRASIL, all because Sizzle's voices are mono and per note: the
* stereo buses are summed (centre + sides at -3 dB), there is no pan, no pressure,
* no voice shedding, the noise is the voice's own, warmth and the DC blocker run on
* each voice instead of the mix, every parameter glides toward its patch value per
* block (FRASIL glides them globally), and the partials' levels are always ramped
* over the block. Rendering is FRASIL's: a block of [BLOCK] frames sets the voice
* up, chunks of [CH] frames are computed at once and handed out a sample at a time
* by [render]. Allocation-free after construction.
*/
class FrasilVoice(private val fs: Int) {
private val invFs = 1f / fs
private val r44 = 44100f / fs // FRASIL's per-step constants were made at 44.1 kHz
private val nyq = 0.45f * fs
var note = -1; private set
private var gate = false
private var vel = 0f
private var env = 0f
private var lvl = 0f
private var patch: FrasilPatch = FrasilPatch.DEFAULT
private var prime = true
private val cur = FloatArray(FrasilDefs.N)
private var type = 0
private var ageFrames = 0L
private var tideV = 0f
private var rng: Int = nextSeed()
// drift, each about -1..1
private val ouC = FloatArray(3)
private var ouCut = 0f
private val ouPa = FloatArray(NP)
private val ouPf = FloatArray(NP)
private val ouR = FloatArray(NR)
// CHOIR
private val cph = FloatArray(3)
private val cdt = FloatArray(3)
private val cid = FloatArray(3)
private val cw = FloatArray(3)
private val cpw = FloatArray(3)
private var csh = 0f
private var sc0 = 0f; private var sc1 = 0f; private var sc2 = 1f
private var sp0 = 0f; private var sp1 = 0f; private var sp2 = 1f
private val clp = FloatArray(4)
private var ca = 0f
private var sa1 = 0f; private var sa2 = 0f; private var sa3 = 0f
private var cgain = 1f
private val cint = FloatArray(6)
private var csvf = false
// PARTIALS
private val px = FloatArray(NP); private val py = FloatArray(NP); private val pa = FloatArray(NP)
private val ps = FloatArray(NP); private val pc = FloatArray(NP)
private val pac = FloatArray(NP); private val pda = FloatArray(NP); private val pbt = FloatArray(NP)
private var np = 0
// BREATH
private val r1 = FloatArray(NR); private val r2 = FloatArray(NR)
private val rb1 = FloatArray(NR); private val rb2 = FloatArray(NR); private val rg = FloatArray(NR)
private var nlp = 0f
// the voice's output stages
private var dcState = 0f
private var thinState = 0f
private var ka = 0f; private var kr = 0f
private var dk = 1f; private var dmake = 1f; private var driveOn = false
private var thinA = 0f; private var thin = false
private val kdc = brK(0.0014f)
private val glideK = brK(0.2f)
private val tideK = 1f - exp(-BLOCK.toFloat() / (fs * TIDE_SMOOTH_S))
// chunk buffers
private val bc = FloatArray(CH); private val ba = FloatArray(CH); private val bb = FloatArray(CH)
private val x0 = FloatArray(CH); private val x1 = FloatArray(CH); private val xc = FloatArray(CH)
private val nz = FloatArray(CH)
private val out = FloatArray(CH)
private var pos = CH
private var chunk = 0
private var ending = false
val isActive: Boolean get() = note >= 0
val isGated: Boolean get() = note >= 0 && gate
/** Start [midi] at [velocity] (0..1). A voice still sounding goes on from where it
* is (FRASIL's same-note / steal rule: its phases continue, no click). */
fun noteOn(midi: Int, velocity: Float, p: FrasilPatch) {
val fresh = note < 0
note = midi
gate = true
vel = velocity.coerceIn(0f, 1f)
patch = p
ageFrames = 0
ending = false
chunk = 0 // the new pitch from the next chunk on
if (fresh) start()
}
fun noteOff() { gate = false }
/** Silence now, no tail. */
fun kill() {
note = -1; gate = false; env = 0f; lvl = 0f; pos = CH; ending = false
}
/** A gliding engine value now (a [FrasilDefs] index), for tests. */
internal fun valueForTest(i: Int): Float = cur[i]
/** Follow edits while sounding: the values glide there over ~25 ms. */
fun setPatch(p: FrasilPatch) { patch = p }
fun render(): Float {
if (pos >= CH) {
if (note < 0) return 0f
if (ending) { note = -1; ending = false; return 0f }
renderChunk()
pos = 0
}
return out[pos++]
}
// ------------------------------------------------------------------- start ---
private fun start() {
env = 0f; lvl = 0f; pos = CH; prime = true
dcState = 0f; thinState = 0f; nlp = 0f
for (k in 0 until 3) {
cph[k] = urand()
cpw[k] = k * 0.33f
ouC[k] = randf() * 0.5f
}
clp.fill(0f); cint.fill(0f); csvf = false
for (k in 0 until NP) { // random phases: no peak where they all start together
val ph = urand() * TWO_PI
px[k] = cos(ph); py[k] = sin(ph)
ps[k] = 0f; pc[k] = 1f
ouPa[k] = randf() * 0.5f; ouPf[k] = randf() * 0.5f
pac[k] = 0f; pda[k] = 0f
pbt[k] = urand()
}
for (k in 0 until NR) { r1[k] = 0f; r2[k] = 0f; ouR[k] = randf() * 0.5f }
ouCut = randf() * 0.5f
}
// ------------------------------------------------------------------- block ---
private fun block() {
val p = patch
val b = p.b
val m = if (b == null) 0f else morphPosition(p)
val gk = if (prime) 1f else glideK
for (i in 0 until FrasilDefs.N) {
val t = if (b == null) p.a[i] else p.a[i] + (b[i] - p.a[i]) * m
cur[i] += (t - cur[i]) * gk
}
type = if (b != null && m >= 0.5f) p.bType else p.aType
val period = 300f * (1f / 30f).pow(cur[TIDE_RATE])
val ph = FrasilClock.seconds / period
val tideT = sin(TWO_PI * (ph - floor(ph)).toFloat())
tideV = if (prime) tideT else tideV + (tideT - tideV) * tideK
val wasPrime = prime
prime = false
ageFrames += BLOCK
drift()
voiceBlock(wasPrime)
// envelope: a one-pole a chunk to the target, a third of the time a time constant
ka = 1f - exp(-CH * invFs * 3f / (0.005f * 6000f.pow(cur[ATTACK])))
kr = 1f - exp(-CH * invFs * 3f / (0.05f * 1200f.pow(cur[RELEASE])))
val full = cur[BODY]
dk = 1f + 5f * cur[WARMTH] * full
dmake = 1f / tanh(dk * 0.35f) * 0.35f
driveOn = cur[WARMTH] * full > 0.001f
thin = full < 0.995f
thinA = 1f - exp(-TWO_PI * 20f * 20f.pow(1f - full) * invFs)
}
/** Where this note is between the sound (0) and MORPH TO's (1): MORPH, then with
* MORPH TIME a smoothstep from there to 1 while the note is held. */
private fun morphPosition(p: FrasilPatch): Float {
if (p.morphTime <= 0f) return p.morph
val x = ((ageFrames.toFloat() * invFs) / p.morphTime).coerceIn(0f, 1f)
return p.morph + (1f - p.morph) * x * x * (3f - 2f * x)
}
/** One Ornstein-Uhlenbeck step: back toward 0 by th, a kick of s (unit variance:
* three uniforms). */
private fun ou(x: Float, th: Float, s: Float): Float =
(x - th * x + s * (randf() + randf() + randf())).coerceIn(-1.5f, 1.5f)
private fun drift() {
val tau = 20f * 0.025f.pow(cur[MOTION_RATE]) // 20 s .. 0.5 s
val th = BLOCK * invFs / tau
val s = 0.6f * sqrt(2f * th)
val te = th * (1f + 3f * cur[EVOLVE])
val se = 0.6f * sqrt(2f * te)
for (k in 0 until 3) ouC[k] = ou(ouC[k], th, s)
for (k in 0 until NP) { ouPa[k] = ou(ouPa[k], te, se); ouPf[k] = ou(ouPf[k], th, s) }
for (k in 0 until NR) ouR[k] = ou(ouR[k], th, s)
ouCut = ou(ouCut, th, s)
}
private fun voiceBlock(fresh: Boolean) {
val c = cur
val f = 440f * 2f.pow((note - 69) / 12f)
val m = c[MOTION]
val mw = m * (1f + 2f * m) // MOTION's wander: twice as wide half-way, three times at the top
val bright = (c[TIMBRE] - 0.5f) + tideV * c[TIDE] * 0.5f
val full = c[BODY]
// CHOIR: the saws' tunings, SHAPE's widths, the low-pass, RESONANCE's state-variable
if (c[CHOIR] > 0.001f) {
val dc = c[DETUNE] * c[DETUNE] * 40f * (0.2f + 0.8f * full)
val sh = c[SHAPE]
val a = if (sh < 0.5f) 2f * sh else 1f
val w = if (sh < 0.5f) 0.5f else 0.5f - 0.8f * (sh - 0.5f)
val sw = if (sh > 0.5f) 0.03f + 0.18f * (sh - 0.5f) else 0.03f * a
for (j in 0 until 3) {
val cents = SIDE[j] * dc + mw * 7f * ouC[j]
cdt[j] = (f * (if (j == 0) c[INTERVAL] else 1f) * 2f.pow(cents / 1200f) * invFs).coerceIn(1e-6f, 0.45f)
cid[j] = 1f / cdt[j]
cpw[j] += PWR[j] * BLOCK * invFs
cpw[j] -= floor(cpw[j])
cw[j] = (w + sw * sin(TWO_PI * cpw[j]) + 0.1f * mw * ouC[j] * a).coerceIn(0.04f, 0.96f)
}
csh = a
val ce = (c[CUTOFF] + bright * 0.6f + mw * 0.2f * ouCut).coerceIn(0f, 1f)
val hc = 1f + 39f * ce * ce
val fc = (f * hc).coerceIn(20f, minOf(16000f, nyq))
ca = 1f - exp(-TWO_PI * fc * invFs)
val pv = (1f + a * a) / 3f - 2f * a * (1f / 3f - 2f * w * (1f - w)) // a saw minus a of it w on: its power
cgain = sqrt((1f / 3f) / (if (pv > 0.05f) pv else 0.05f))
if (c[CH_RESO] > 0.002f || type != 0) {
val g = tan(PI * fc * invFs)
val q = 0.5f * 40f.pow(c[CH_RESO])
val k = 1f / q
sa1 = 1f / (1f + g * (g + k)); sa2 = g * sa1; sa3 = g * sa2
when (type) {
1 -> { sc0 = 0f; sc1 = k * (1.4f + 0.12f * sqrt(hc)) * sqrt(q); sc2 = 0f } // band, peak at 1
2 -> { // high, made up
val mk = sqrt(0.75f * hc).coerceIn(1f, 4f)
sc0 = mk; sc1 = -k * mk; sc2 = -mk
}
else -> { sc0 = 0f; sc1 = 0f; sc2 = 1f }
}
cgain *= 1f / sqrt(1f + 0.22f * (q - 0.5f))
}
if (fresh) { sp0 = sc0; sp1 = sc1; sp2 = sc2 }
}
// PARTIALS: frequencies (stretched, drifting), amplitudes (tilt, odd, drift), levelled
if (c[PARTIALS] > 0.001f) {
val pe = (c[TILT] - bright * 0.7f).coerceIn(0f, 1f)
val pw = 0.3f + 2.7f * pe
val sx = 1f + 0.12f * c[STRETCH]
val fnp = 2f + 6f * full
var nmax = fnp.toInt()
var top = fnp - nmax
if (top > 0.001f) nmax++ else top = 1f
if (nmax > NP) nmax = NP
var sum2 = 0f
var n = 0
for (j in 0 until nmax) {
val fk = f * 2f.pow(sx * LOG2K[j] + mw * 5f * ouPf[j] / 1200f)
if (fk > minOf(15000f, nyq)) break
val w = TWO_PI * fk * invFs
// the oscillator: back to its phasor, renormalised, on with this block's step (a half-angle rotation)
val cw0 = cos(w); val sn = sin(w)
val q = sqrt(2f * (1f + cw0))
var x = px[j]
var y = (py[j] - x * ps[j]) * pc[j]
val gn = 1.5f - 0.5f * (x * x + y * y)
val shh = sn / q
val chh = (1f + cw0) / q
x *= gn; y *= gn
ps[j] = shh
pc[j] = q / (1f + cw0)
px[j] = x
py[j] = y * chh + x * shh
var a = 2f.pow(-pw * LOG2K[j] + 1.6f * (m + 2.5f * c[EVOLVE]) * ouPa[j])
if (j and 1 == 1) a *= 1f - c[ODD] // the even harmonics (2, 4 ...)
val pk = c[PEAK]
if (pk > 0.001f) { // the formant
val d = (sx * LOG2K[j] - c[FORMANT]) * (1.5f + 4f * pk)
val fl = 1f - 0.97f * pk
a *= fl + (1f + 7f * pk - fl) / (1f + d * d)
}
if (j + 1 == nmax) a *= top
pa[j] = a
sum2 += a * a
n++
}
np = n
val norm = 0.6f / sqrt(sum2 + 1e-9f)
for (j in 0 until n) pa[j] *= norm
if (c[BEAT] > 0.001f) { // BEAT: each one pulsing at its own pace
val bt = c[BEAT]
val dep = minOf(1f, bt * 1.4f)
val hz = 0.15f + 5f * bt * bt
for (j in 0 until n) {
pbt[j] += hz * BEAT_SPREAD[j] * BLOCK * invFs
pbt[j] -= floor(pbt[j])
pa[j] *= (1f - dep * (0.5f + 0.5f * sin(TWO_PI * pbt[j]))) / (1f - 0.5f * dep)
}
}
for (j in 0 until n) pda[j] = (pa[j] - pac[j]) / BLOCK
for (j in n until NP) { pac[j] = 0f; pda[j] = 0f }
}
// BREATH: resonators at the note x ratios (COLOR between the sets), levelled so
// the loudness follows neither Q nor pitch: y = g x + b1 y1 - b2 y2
if (c[BREATH] > 0.001f) {
var col = c[COLOR].coerceIn(0f, 1f) * 2f
val lo = col < 1f
val ra = RATIO_L2[if (lo) 0 else 1]
val rb = RATIO_L2[if (lo) 1 else 2]
if (!lo) col -= 1f
val q = 2f * 300f.pow((c[RESONANCE] + mw * 0.1f * ouR[0]).coerceIn(0f, 1f))
val sb = (0.55f + bright * 0.8f).coerceIn(0.05f, 1f)
for (j in 0 until NR) {
val l2 = ra[j] + (rb[j] - ra[j]) * col + mw * 12f * ouR[j] / 1200f
val fr = (f * c[BR_PITCH] * 2f.pow(l2)).coerceIn(20f, minOf(16000f, nyq))
val r = exp(-PI * fr / q * invFs).toDouble()
val b1 = 2.0 * r * cos(TWO_PI * fr * invFs).toDouble()
val b2 = r * r
val ng = (1.0 + b2) / ((1.0 - b2) * ((1.0 + b2) * (1.0 + b2) - b1 * b1)) // the sum of h^2
rb1[j] = b1.toFloat(); rb2[j] = b2.toFloat()
rg[j] = (0.4 * sqrt(3.0 / ng)).toFloat() * (if (j == 0) 1f else sb * (if (j == 2) sb else 1f))
}
}
}
// ------------------------------------------------------------------- chunk ---
private fun renderChunk() {
if (chunk == 0) block()
chunk = (chunk + 1) % (BLOCK / CH)
val c = cur
env += ((if (gate) 1f else 0f) - env) * (if (gate) ka else kr)
val level = (1f - c[VELOCITY] + c[VELOCITY] * vel) * VOICE_G
val g1 = if (!gate && env < TAIL_END) 0f else level * env * env
var g = lvl
lvl = g1
val dg = (g1 - g) / CH
bc.fill(0f); ba.fill(0f); bb.fill(0f)
val full = c[BODY]
if (c[CHOIR] > 0.001f) choirChunk(0.35f * c[CHOIR] * (0.3f + 0.7f * full))
if (c[PARTIALS] > 0.001f) partialsChunk(c[PARTIALS] * (0.7f + 0.3f * full))
if (c[BREATH] > 0.001f) { breathNoise(); souffleChunk(c[BREATH] * full * full) }
// a guard: a voice gone wild or not a number never reaches the mix; it starts again
val z = bc[CH - 1] + ba[CH - 1] + bb[CH - 1] + bc[CH / 2] + ba[CH / 2] + bb[CH / 2]
if (!(z > -1e4f && z < 1e4f)) {
bc.fill(0f); ba.fill(0f); bb.fill(0f)
start()
prime = false
}
var dcs = dcState
var th = thinState
for (i in 0 until CH) {
g += dg
var x = (bc[i] + SIDE_GAIN * (ba[i] + bb[i])) * g
dcs += kdc * (x - dcs)
x -= dcs
if (driveOn) x = tanh(x * dk) * dmake
if (thin) { th += thinA * (x - th); x -= th }
out[i] = x * OUT_GAIN
}
dcState = flush(dcs)
thinState = if (thin) flush(th) else 0f
if (g1 == 0f && !gate && env < TAIL_END) ending = true
}
/** CHOIR's saws into the two sides (left: centre + -detune, right: centre + +detune),
* then their filters into [ba] / [bb] at [g0]. */
private fun choirChunk(g0: Float) {
val svf = cur[CH_RESO] > 0.002f || type != 0
val sq = cur[SHAPE] > 0.002f
val soft = cur[SOFT] > 0.002f
if (svf != csvf) { // the other filter: the low-pass's state carried over
clp[0] = if (svf) 0f else clp[1]
clp[2] = if (svf) 0f else clp[3]
csvf = svf
}
val g = g0 * cgain
var p0 = cph[0]; var p1 = cph[1]; var p2 = cph[2]
val d0 = cdt[0]; val d1 = cdt[1]; val d2 = cdt[2]
val i0 = cid[0]; val i1 = cid[1]; val i2 = cid[2]
val sh = csh; val w0 = cw[0]; val w1 = cw[1]; val w2 = cw[2]
for (i in 0 until CH) {
p0 += d0; if (p0 >= 1f) p0 -= 1f
p1 += d1; if (p1 >= 1f) p1 -= 1f
p2 += d2; if (p2 >= 1f) p2 -= 1f
var s0 = 2f * p0 - 1f - blep(p0, d0, i0)
var s1 = 2f * p1 - 1f - blep(p1, d1, i1)
var s2 = 2f * p2 - 1f - blep(p2, d2, i2)
if (sq) { // each minus its share of itself a width on: a pulse
var q0 = p0 + w0; if (q0 >= 1f) q0 -= 1f
var q1 = p1 + w1; if (q1 >= 1f) q1 -= 1f
var q2 = p2 + w2; if (q2 >= 1f) q2 -= 1f
s0 -= sh * (2f * q0 - 1f - blep(q0, d0, i0))
s1 -= sh * (2f * q1 - 1f - blep(q1, d1, i1))
s2 -= sh * (2f * q2 - 1f - blep(q2, d2, i2))
}
if (soft) { xc[i] = s0; x0[i] = s1; x1[i] = s2 } else { x0[i] = s0 + s1; x1[i] = s0 + s2 }
}
cph[0] = p0; cph[1] = p1; cph[2] = p2
if (soft) {
// SOFT: integrated once (the square a triangle), then twice (near a sine), each saw at
// its own gain (its fundamental kept), a leak at a sixth of it; crossfaded by quarter turns
val kc = TWO_PI * d0; val ks = TWO_PI * d1
val lc = 1f - 0.15f * kc; val ls = 1f - 0.15f * ks
val u = cur[SOFT]
val a0: Float; val a1: Float; val a2: Float
if (u < 0.5f) { a0 = cos(PI * u); a1 = sin(PI * u); a2 = 0f }
else { a0 = 0f; a1 = cos(PI * (u - 0.5f)); a2 = sin(PI * (u - 0.5f)) }
val c1 = a1 * kc; val c2 = a2 * kc * kc; val e1 = a1 * ks; val e2 = a2 * ks * ks
var cA = cint[0]; var cB = cint[1]; var l1 = cint[2]; var l2 = cint[3]; var q1 = cint[4]; var q2 = cint[5]
for (j in 0 until CH) {
val vc = xc[j]; val vl = x0[j]; val vr = x1[j]
cA = lc * cA + vc; cB = lc * cB + cA
l1 = ls * l1 + vl; l2 = ls * l2 + l1
q1 = ls * q1 + vr; q2 = ls * q2 + q1
val cc = a0 * vc + c1 * cA + c2 * cB
x0[j] = cc + a0 * vl + e1 * l1 + e2 * l2
x1[j] = cc + a0 * vr + e1 * q1 + e2 * q2
}
if (!(cB > -1e9f && cB < 1e9f && l2 > -1e9f && l2 < 1e9f && q2 > -1e9f && q2 < 1e9f)) {
cA = 0f; cB = 0f; l1 = 0f; l2 = 0f; q1 = 0f; q2 = 0f
}
cint[0] = cA; cint[1] = cB; cint[2] = l1; cint[3] = l2; cint[4] = q1; cint[5] = q2
} else {
cint.fill(0f)
}
if (svf) { // the type's mix, gliding to sc over the chunk
val o0 = sp0 * g; val o1 = sp1 * g; val o2 = sp2 * g
val e0 = (sc0 - sp0) * g / CH; val e1 = (sc1 - sp1) * g / CH; val e2 = (sc2 - sp2) * g / CH
svfRun(ba, x0, 0, o0, o1, o2, e0, e1, e2)
svfRun(bb, x1, 2, o0, o1, o2, e0, e1, e2)
} else {
val a = ca
var l1 = clp[0]; var l2 = clp[1]; var q1 = clp[2]; var q2 = clp[3]
for (i in 0 until CH) {
l1 += a * (x0[i] - l1); l2 += a * (l1 - l2)
q1 += a * (x1[i] - q1); q2 += a * (q1 - q2)
ba[i] += l2 * g; bb[i] += q2 * g
}
clp[0] = l1; clp[1] = l2; clp[2] = q1; clp[3] = q2
}
sp0 = sc0; sp1 = sc1; sp2 = sc2
}
private fun svfRun(b: FloatArray, x: FloatArray, s: Int, o0i: Float, o1i: Float, o2i: Float,
e0: Float, e1: Float, e2: Float) {
var s1 = clp[s]; var s2 = clp[s + 1]
var o0 = o0i; var o1 = o1i; var o2 = o2i
val a1 = sa1; val a2 = sa2; val a3 = sa3
for (i in 0 until CH) {
val v = x[i] - s2
val t1 = a1 * s1 + a2 * v
val t2 = s2 + a2 * s1 + a3 * v
s1 = 2f * t1 - s1
s2 = 2f * t2 - s2
b[i] += o0 * x[i] + o1 * t1 + o2 * t2
o0 += e0; o1 += e1; o2 += e2
}
clp[s] = s1; clp[s + 1] = s2
}
/** The fundamental in the centre; harmonics 2, 4, 6, 8 to one side, 3, 5, 7 to the other. */
private fun partialsChunk(g: Float) {
for (j in 0 until np) {
val bus = when (j) { 0 -> bc; 1, 3, 5, 7 -> ba; else -> bb }
var x = px[j]; var y = py[j]
val e = 2f * ps[j]
var a = pac[j] * g
val d = pda[j] * g
for (i in 0 until CH) {
x -= e * y
y += e * x
bus[i] += a * x
a += d
}
px[j] = x; py[j] = y
pac[j] += pda[j] * CH
}
}
/** BREATH's source for the chunk: a hiss (white, variance 1/3) or GRAIN's sparse
* grains (as loud on average); TONE darker (a low-pass) or brighter (a high-pass). */
private fun breathNoise() {
val grain = cur[GRAIN]
if (grain < 0.002f) {
for (i in 0 until CH) nz[i] = randf()
} else {
val p = 2f.pow(-13f * grain) * r44
val amp = minOf(16f, sqrt(1f / (3f * 0.5833f * p)))
val th = (p * 16777216f).toInt()
for (i in 0 until CH) {
val r = nextRand()
val a = amp * (0.5f + (r and 255) * (0.5f / 255f))
nz[i] = if ((r ushr 8) < th) (if (r and 256 != 0) a else -a) else 0f
}
}
val t = cur[TONE]
if (t < -0.01f) {
val fc = 16000f * (300f / 16000f).pow(-t)
val a = 1f - exp(-TWO_PI * minOf(fc, nyq) * invFs)
val gn = sqrt((2f - a) / a)
var l = nlp
for (i in 0 until CH) { l += a * (nz[i] - l); nz[i] = l * gn }
nlp = flush(l)
} else if (t > 0.01f) {
val fc = 20f * 150f.pow(t)
val a = 1f - exp(-TWO_PI * fc * invFs)
val gn = 1f / sqrt(1f + a / (2f - a) - 2f * a)
var l = nlp
for (i in 0 until CH) { l += a * (nz[i] - l); nz[i] = (nz[i] - l) * gn }
nlp = flush(l)
}
}
private fun souffleChunk(g: Float) {
val air = cur[AIR]
val ga = air * 0.7f * g
for (j in 0 until NR) {
val bus = when (j) { 0 -> bc; 1 -> ba; else -> bb }
var y1 = r1[j]; var y2 = r2[j]
val b1 = rb1[j]; val b2 = rb2[j]; val gg = rg[j] * g
val withAir = j == 0 && air > 0.001f
for (i in 0 until CH) {
val y = gg * nz[i] + b1 * y1 - b2 * y2
y2 = y1; y1 = y
bus[i] += if (withAir) y + ga * nz[i] else y
}
if (y1 > -1e-20f && y1 < 1e-20f && y2 > -1e-20f && y2 < 1e-20f) { y1 = 0f; y2 = 0f }
r1[j] = y1; r2[j] = y2
}
}
// ----------------------------------------------------------------- helpers ---
private fun brK(k: Float): Float = 1f - (1f - k).pow(r44)
/** 32-bit xorshift: the noise and the drift. */
private fun nextRand(): Int {
var x = rng
x = x xor (x shl 13)
x = x xor (x ushr 17)
x = x xor (x shl 5)
rng = x
return x
}
private fun randf(): Float = nextRand() * (1f / 2147483648f) // -1..1
private fun urand(): Float = (nextRand() ushr 8) * (1f / 16777216f) // 0..1
companion object {
const val NP = 8
const val NR = 3
const val CH = 64
const val BLOCK = 256
private const val VOICE_G = 0.2f
private const val TAIL_END = 0.01f // a released voice ends here: its gain (env^2) 80 dB down
private const val SIDE_GAIN = 0.70710678f // the stereo sides summed into mono at -3 dB
/** Brings a held FRASIL voice to about the level of a Sizzle synth note. */
private const val OUT_GAIN = 2.2f
private const val TIDE_SMOOTH_S = 0.5f
private const val PI = 3.14159265f
private const val TWO_PI = 6.2831853f
private val SIDE = floatArrayOf(0f, -1f, 1f)
private val PWR = floatArrayOf(0.21f, 0.29f, 0.37f) // the widths' sways, Hz
private val LOG2K = floatArrayOf(0f, 1f, 1.5849625f, 2f, 2.3219281f, 2.5849625f, 2.8073549f, 3f)
private val BEAT_SPREAD = floatArrayOf(0.55f, 1.25f, 0.8f, 1.45f, 0.65f, 1.1f, 0.95f, 1.35f)
/** BREATH's ratios (log2), COLOR across them: harmonic, odd, bell (a free bar's modes). */
private val RATIO_L2: Array<FloatArray> = arrayOf(
floatArrayOf(1f, 2f, 3f), floatArrayOf(1f, 3f, 5f), floatArrayOf(1f, 2.756f, 5.404f),
).map { r -> FloatArray(NR) { (ln(r[it].toDouble()) / ln(2.0)).toFloat() } }.toTypedArray()
private var seeds = 0x2545F491
private fun nextSeed(): Int {
seeds += 0x6D2B79F5
return if (seeds == 0) 0x2545F491 else seeds
}
/** A blep with the step's inverse. */
private fun blep(t0: Float, dt: Float, idt: Float): Float {
if (t0 < dt) { val t = t0 * idt; return t + t - t * t - 1f }
if (t0 > 1f - dt) { val t = (t0 - 1f) * idt; return t * t + t + t + 1f }
return 0f
}
private fun flush(x: Float): Float = if (x > -1e-20f && x < 1e-20f) 0f else x
}
}
@@ -4,31 +4,59 @@
package cc.tiredsysadmin.android.sizzle.input
import android.content.Context
import android.content.pm.ServiceInfo
import android.media.midi.MidiDevice
import android.media.midi.MidiDeviceInfo
import android.media.midi.MidiDeviceStatus
import android.media.midi.MidiManager
import android.media.midi.MidiOutputPort
import android.media.midi.MidiReceiver
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.Log
import cc.tiredsysadmin.android.sizzle.playback.MidiSoundModule
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
/** One MIDI source as the Setup screen lists it. [key] is stable across restarts
* (unlike Android's device id), so the on/off choice can be saved. */
data class MidiSource(val key: String, val name: String, val enabled: Boolean, val connected: Boolean)
/**
* Bridges hardware and virtual MIDI sources (USB, Bluetooth, and other apps'
* virtual devices such as Mikro Seq; Android lists all of them through the same
* [MidiManager]) into the app.
*
* Every source gets its own [MidiByteParser] (running status is per stream).
* Every source that can send to us is listed in [sources]. Each is listened to
* unless the user switched it off in Setup ([setEnabled]; the off-keys are
* persisted by the caller via [onDisabledChanged]), so a new controller or app
* works with no setup.
*
* Every open source gets its own [MidiByteParser] (running status is per stream).
* Notes, all-notes-off and real-time bytes go to the [module], the headless sound
* module that plays them on the engine whether or not the UI exists. Control
* Change (CC) messages the module does not consume are matched against
* [ccBindings] so any knob/pad can drive navigation or transport; unmatched CCs
* are forwarded as [InputAction.RawControl] so the Settings screen can "learn" them.
*
* A source that goes away (unplugged, or removed by the system) is closed and its
* held notes are released through [MidiSoundModule.sourceDisconnected].
* Reconnecting: a virtual source's app can die and restart (crash, update, force
* stop, the system reclaiming it) without Android removing its device or telling
* its clients anything: our MidiDevice keeps pointing at the dead process and no
* callback fires (verified on Android 15). So every [PROBE_MS] a worker thread asks
* each open virtual source for an output port: a live one answers (the probe port
* is closed at once), a dead one fails, and that source is closed (releasing its
* held notes) and opened again, which makes Android rebind the app's MIDI service.
* A port-status report of "nobody has the output open" while we think we do is
* treated the same way. [refresh] (every Activity resume) probes at once and opens
* anything enabled that isn't open; [reconnect] (the Setup button) closes and
* reopens everything as a last resort. A source that goes away is
* closed and its held notes are released through [MidiSoundModule.sourceDisconnected].
*
* Note: this handles MIDI *input*. Sending MIDI out lives in [MidiClock].
* Main thread for everything except the parsers (each port's own thread).
*/
class MidiInput(
context: Context,
@@ -40,64 +68,240 @@ class MidiInput(
private val midiManager = context.getSystemService(Context.MIDI_SERVICE) as? MidiManager
private val handler = Handler(Looper.getMainLooper())
/** Open sources by [MidiDeviceInfo.getId]. Touched only on the main thread. */
/** Every device that can send to us, by [MidiDeviceInfo.getId]. */
private val known = LinkedHashMap<Int, MidiDeviceInfo>()
/** Open sources by device id. */
private val open = HashMap<Int, Pair<MidiDevice, MidiOutputPort>>()
/** Device ids with an [MidiManager.openDevice] in flight. */
private val opening = HashSet<Int>()
private var callback: MidiManager.DeviceCallback? = null
/** When we last opened or closed each device id, to ignore the port-status
* echoes of our own actions (see [onStatus]). */
private val lastChange = HashMap<Int, Long>()
/** Start listening. Opens every currently-attached device that can send to us
* and watches for hot-plug events. Idempotent; safe if the device has no MIDI.
* Main thread. */
/** Keys of the sources the user switched off. Set before [start]. */
var disabledKeys: Set<String> = emptySet()
private set
/** Called with the new off-set when the user changes it, to persist it. */
var onDisabledChanged: ((Set<String>) -> Unit)? = null
private val _sources = MutableStateFlow<List<MidiSource>>(emptyList())
/** All sources that can send to us, for the Setup screen. */
val sources: StateFlow<List<MidiSource>> = _sources.asStateFlow()
fun restoreDisabled(keys: Set<String>) { disabledKeys = keys; publish() }
/** Start listening: open every enabled device that can send to us and watch for
* hot-plug and status events. Idempotent; safe if the device has no MIDI. */
fun start() {
val mm = midiManager ?: return
if (callback != null) return
val cb = object : MidiManager.DeviceCallback() {
override fun onDeviceAdded(device: MidiDeviceInfo) = openDevice(device)
override fun onDeviceRemoved(device: MidiDeviceInfo) = closeDevice(device.id)
override fun onDeviceAdded(device: MidiDeviceInfo) = add(device)
override fun onDeviceRemoved(device: MidiDeviceInfo) {
known.remove(device.id)
closeDevice(device.id)
publish()
}
override fun onDeviceStatusChanged(status: MidiDeviceStatus) = onStatus(status)
}
callback = cb
mm.devices.forEach(::openDevice)
mm.registerDeviceCallback(cb, handler)
allDevices(mm).forEach(::add)
registerCallback(mm, cb)
handler.postDelayed(probeTick, PROBE_MS)
}
/** Close every source (releasing their held notes). Main thread. */
/** Close every source (releasing their held notes). */
fun stop() {
callback?.let { cb -> runCatching { midiManager?.unregisterDeviceCallback(cb) } }
callback = null
handler.removeCallbacks(probeTick)
open.keys.toList().forEach(::closeDevice)
opening.clear()
known.clear()
publish()
}
/** Pick up anything missed: new devices, and enabled ones that aren't open. */
fun refresh() {
val mm = midiManager ?: return
if (callback == null) return
allDevices(mm).forEach(::add)
probe()
}
/** Close and reopen every enabled source (Setup's Reconnect button). */
fun reconnect() {
if (callback == null) return
open.keys.toList().forEach(::closeDevice)
known.clear()
refresh()
publish()
}
/** Listen to the source with [key], or stop listening to it. */
fun setEnabled(key: String, enabled: Boolean) {
disabledKeys = if (enabled) disabledKeys - key else disabledKeys + key
onDisabledChanged?.invoke(disabledKeys)
for ((id, info) in known) {
if (keyOf(info) != key) continue
if (enabled) openDevice(info) else closeDevice(id)
}
publish()
}
private fun add(info: MidiDeviceInfo) {
// We want devices that can SEND to us (they expose output ports).
if (info.outputPortCount == 0) return
known[info.id] = info
if (keyOf(info) !in disabledKeys) openDevice(info)
publish()
}
/** Port status from Android. If nobody holds the output open while we believe we
* do, the app behind it restarted and our connection is dead: reopen it. */
private fun onStatus(status: MidiDeviceStatus) {
val info = status.deviceInfo
val id = info.id
if (id !in open || info.outputPortCount == 0) return
val sinceOwnChange = SystemClock.uptimeMillis() - (lastChange[id] ?: 0L)
if (sinceOwnChange < STATUS_SETTLE_MS) return
if (status.getOutputPortOpenCount(0) == 0) {
Log.i(TAG, "${nameOf(info)}: connection lost, reopening")
closeDevice(id)
openDevice(info)
publish()
}
}
private val probeTick = object : Runnable {
override fun run() {
if (callback == null) return
probe()
handler.postDelayed(this, PROBE_MS)
}
}
/** Off-main-thread liveness check of every open virtual source (see the class
* doc). A hung source app can't stall the UI this way. */
private fun probe() {
val targets = open.entries
.filter { (_, dp) -> dp.first.info.type == MidiDeviceInfo.TYPE_VIRTUAL }
.map { (id, dp) -> id to dp.first }
if (targets.isEmpty() || probing) return
probing = true
probeExecutor.execute {
val dead = targets.filter { (_, device) ->
val port = runCatching { device.openOutputPort(0) }.getOrNull()
port?.let { runCatching { it.close() } }
port == null
}
handler.post {
probing = false
for ((id, device) in dead) {
// Still the same connection? (It may have been closed or replaced meanwhile.)
if (open[id]?.first !== device) continue
val info = device.info
Log.i(TAG, "${nameOf(info)}: connection lost, reopening")
closeDevice(id)
openDevice(info)
}
if (dead.isNotEmpty()) publish()
}
}
}
private var probing = false
private val probeExecutor = java.util.concurrent.Executors.newSingleThreadExecutor { r ->
Thread(r, "sizzle-midi-probe").apply { isDaemon = true }
}
private fun openDevice(info: MidiDeviceInfo) {
// We want devices that can SEND to us (they expose output ports).
if (info.outputPortCount == 0 || info.id in open) return
midiManager?.openDevice(info, { device ->
device ?: return@openDevice
// stop() ran (or the same device was opened twice) while this was pending.
if (callback == null || info.id in open) { runCatching { device.close() }; return@openDevice }
val port = device.openOutputPort(0) ?: run { runCatching { device.close() }; return@openDevice }
val source = info.id
val id = info.id
if (id in open || id in opening) return
val mm = midiManager ?: return
opening += id
mm.openDevice(info, { device ->
opening -= id
device ?: run { Log.w(TAG, "${nameOf(info)}: could not open"); publish(); return@openDevice }
// stop() ran, the device was opened twice, or the user switched it off
// while this was pending.
if (callback == null || id in open || keyOf(info) in disabledKeys) {
runCatching { device.close() }; return@openDevice
}
val port = device.openOutputPort(0)
?: run { runCatching { device.close() }; publish(); return@openDevice }
val parser = MidiByteParser(
onChannel = { status, d1, d2 ->
val consumed = module.onChannelMessage(source, status, d1, d2)
val consumed = module.onChannelMessage(id, status, d1, d2)
if (!consumed && (status and 0xF0) == 0xB0) handleCc(d1, d2)
},
onRealtime = module::onRealtime,
)
port.connect(object : MidiReceiver() {
override fun onSend(data: ByteArray, offset: Int, count: Int, timestamp: Long) =
override fun onSend(data: ByteArray, offset: Int, count: Int, timestamp: Long) {
if (MidiTrace.on) MidiTrace.packet(nameOf(info), data, offset, count, timestamp)
parser.feed(data, offset, count)
}
})
open[source] = device to port
module.sourceConnected(source)
open[id] = device to port
lastChange[id] = SystemClock.uptimeMillis()
module.sourceConnected(id)
Log.i(TAG, "${nameOf(info)}: listening")
publish()
}, handler)
}
private fun closeDevice(id: Int) {
val (device, port) = open.remove(id) ?: return
lastChange[id] = SystemClock.uptimeMillis()
runCatching { port.close() }
runCatching { device.close() }
module.sourceDisconnected(id)
}
private fun publish() {
_sources.value = known.values
.map { MidiSource(keyOf(it), nameOf(it), keyOf(it) !in disabledKeys, it.id in open) }
.distinctBy { it.key }
}
@Suppress("DEPRECATION") // getDevices / the Handler overload: still the only way below API 33
private fun allDevices(mm: MidiManager): List<MidiDeviceInfo> = mm.devices.toList()
@Suppress("DEPRECATION")
private fun registerCallback(mm: MidiManager, cb: MidiManager.DeviceCallback) =
mm.registerDeviceCallback(cb, handler)
private fun keyOf(info: MidiDeviceInfo): String {
val p = info.properties
@Suppress("DEPRECATION")
val service = if (Build.VERSION.SDK_INT >= 33) {
p.getParcelable(PROPERTY_SERVICE_INFO, ServiceInfo::class.java)
} else {
p.getParcelable(PROPERTY_SERVICE_INFO)
}
@Suppress("DEPRECATION")
val bluetooth = p.getParcelable<android.os.Parcelable>(MidiDeviceInfo.PROPERTY_BLUETOOTH_DEVICE)
return MidiSourceKey.of(
type = info.type,
manufacturer = p.getString(MidiDeviceInfo.PROPERTY_MANUFACTURER),
product = p.getString(MidiDeviceInfo.PROPERTY_PRODUCT),
name = p.getString(MidiDeviceInfo.PROPERTY_NAME),
service = service?.let { "${it.packageName}/${it.name}" },
bluetooth = bluetooth?.toString(),
)
}
private fun nameOf(info: MidiDeviceInfo): String = info.properties.let { p ->
MidiSourceKey.displayName(
p.getString(MidiDeviceInfo.PROPERTY_MANUFACTURER),
p.getString(MidiDeviceInfo.PROPERTY_PRODUCT),
p.getString(MidiDeviceInfo.PROPERTY_NAME),
)
}
private fun handleCc(cc: Int, value: Int) {
val actionId = ccBindings[cc]
if (actionId == null) {
@@ -133,4 +337,14 @@ class MidiInput(
}
action?.let(router::dispatch)
}
private companion object {
const val TAG = "SizzleMidi"
/** MidiDeviceInfo.PROPERTY_SERVICE_INFO: set on virtual devices, but @hide in the SDK. */
const val PROPERTY_SERVICE_INFO = "service_info"
/** How often open virtual sources are checked for a dead app behind them. */
const val PROBE_MS = 3000L
/** Port-status events this soon after our own open/close are its echo. */
const val STATUS_SETTLE_MS = 1000L
}
}
@@ -0,0 +1,29 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.input
/**
* Stable identity and display name for a MIDI source. Android's device id changes
* on every reconnect and reboot, so the user's on/off choice is keyed on what the
* device says about itself instead: its type, maker/product/name, the service
* that publishes it (virtual devices from other apps) or its Bluetooth address.
* Pure Kotlin, unit-tested.
*/
object MidiSourceKey {
fun of(
type: Int,
manufacturer: String?,
product: String?,
name: String?,
service: String?,
bluetooth: String?,
): String = listOf(type.toString(), manufacturer, product, name, service, bluetooth)
.joinToString("|") { it.orEmpty().replace("|", "/") }
/** What the device calls itself: its name, else its product ("Mikro Seq"),
* else its maker. */
fun displayName(manufacturer: String?, product: String?, name: String?): String =
listOf(name, product, manufacturer).firstOrNull { !it.isNullOrBlank() } ?: "MIDI device"
}
@@ -0,0 +1,66 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.input
import android.util.Log
/**
* Optional MIDI trace for checking what reaches Sizzle and what it plays. Off by
* default and free when off; switch it on from a computer:
*
* adb shell setprop log.tag.SizzleMidiTrace VERBOSE # on (takes effect at once)
* adb shell setprop log.tag.SizzleMidiTrace INFO # off
* adb logcat -s SizzleMidiTrace
*
* Logs every received packet (source, bytes, how late it arrived against its
* timestamp) and every note the sound module hands the engine with the mixer
* strips it reaches. Real-time bytes (clock) are left out of packet lines unless
* they come with other data, to keep the log readable.
*/
object MidiTrace {
const val TAG = "SizzleMidiTrace"
private var checkedAt = 0L
private var cached = false
/** Re-reads the property at most every 500 ms (setprop applies without a restart). */
val on: Boolean
get() {
val now = System.nanoTime()
if (now - checkedAt > 500_000_000L) {
cached = Log.isLoggable(TAG, Log.VERBOSE)
checkedAt = now
}
return cached
}
fun log(msg: String) { Log.v(TAG, msg) }
fun packet(source: String, data: ByteArray, offset: Int, count: Int, timestamp: Long) {
if (count == 1 && (data[offset].toInt() and 0xFF) == 0xF8) return // clock tick
val hex = (offset until offset + count).joinToString(" ") { "%02X".format(data[it]) }
val lateMs = if (timestamp > 0) (System.nanoTime() - timestamp) / 1_000_000.0 else Double.NaN
log("recv $source [$hex] ${describe(data, offset, count)} late=${"%.1f".format(lateMs)}ms")
}
private fun describe(data: ByteArray, offset: Int, count: Int): String {
val s = data[offset].toInt() and 0xFF
val d1 = if (count > 1) data[offset + 1].toInt() and 0x7F else 0
val d2 = if (count > 2) data[offset + 2].toInt() and 0x7F else 0
val ch = (s and 0x0F) + 1
return when (s and 0xF0) {
0x90 -> if (d2 > 0) "NoteOn ch=$ch ${note(d1)} v=$d2" else "NoteOn(v0=Off) ch=$ch ${note(d1)}"
0x80 -> "NoteOff ch=$ch ${note(d1)}"
0xB0 -> "CC ch=$ch #$d1=$d2"
0xC0 -> "Program ch=$ch $d1"
0xF0 -> when (s) { 0xFA -> "Start"; 0xFB -> "Continue"; 0xFC -> "Stop"; else -> "System %02X".format(s) }
else -> "status %02X".format(s)
}
}
private val NAMES = arrayOf("C-", "C#", "D-", "D#", "E-", "F-", "F#", "G-", "G#", "A-", "A#", "B-")
/** "36(C-2)", in this app's naming (60 = C-4). */
fun note(n: Int): String = "$n(${NAMES[n % 12]}${n / 12 - 1})"
}
@@ -4,6 +4,7 @@
package cc.tiredsysadmin.android.sizzle.io
import cc.tiredsysadmin.android.sizzle.audio.SampleStore
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs
import cc.tiredsysadmin.android.sizzle.model.AmbiencePresets
import cc.tiredsysadmin.android.sizzle.model.MixTightenerPresets
import cc.tiredsysadmin.android.sizzle.model.NesSynthPresets
@@ -52,6 +53,9 @@ class PresetLibrary(private val baseDir: File) {
seedType(ToolboxType.NES_SYNTH, NesSynthPresets.FACTORY.map { it.name }) { slot, name ->
NesSynthPresets.apply(slot, NesSynthPresets.FACTORY.first { it.name == name })
}
seedType(ToolboxType.MORPH_PAD, FrasilDefs.FACTORY.map { it.name }) { slot, name ->
FrasilDefs.FACTORY.first { it.name == name }.values.forEach { (k, v) -> slot.set(k, v) }
}
seedType(ToolboxType.MIX_TIGHTENER, MixTightenerPresets.FACTORY.map { it.name }) { slot, name ->
MixTightenerPresets.apply(slot, MixTightenerPresets.FACTORY.first { it.name == name })
}
@@ -38,7 +38,7 @@ object ProjectIo {
appendLine("ACTIVE=${project.activePatternId}")
project.patterns.forEach { p ->
appendLine("[PATTERN id=${p.id} name=${p.name} len=${p.length}]")
appendLine("[PATTERN id=${p.id} name=${encodeName(p.name)} len=${p.length}]")
for (t in 0 until Pattern.TRACK_COUNT) {
for (line in 0 until p.length) {
val cell = p.cell(t, line)
@@ -109,7 +109,7 @@ object ProjectIo {
val attrs = parseAttrs(line)
current = Pattern(
id = attrs["id"]?.toIntOrNull() ?: project.patterns.size,
name = attrs["name"] ?: "PTN",
name = attrs["name"]?.let(::decodeName) ?: "PTN",
length = attrs["len"]?.toIntOrNull() ?: 16,
).also { project.patterns.add(it) }
section = "PATTERN"
@@ -232,4 +232,19 @@ object ProjectIo {
}
}
}
/** Block names may contain spaces ("C1 muted" from a Mikro Seq import), but the
* `[PATTERN …]` header is split on whitespace: escape space, `%` and `]`. */
internal fun encodeName(name: String): String = buildString {
for (c in name) when (c) {
'%' -> append("%25"); ' ' -> append("%20"); ']' -> append("%5D")
'\t', '\n', '\r' -> append("%20")
else -> append(c)
}
}
/** Inverse of [encodeName]; anything that isn't one of its escapes (older files,
* a literal "50%") is kept as written. */
internal fun decodeName(text: String): String = text
.replace("%20", " ").replace("%5D", "]").replace("%25", "%")
}
@@ -10,6 +10,7 @@ import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.core.stringSetPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.first
@@ -36,6 +37,8 @@ data class AppSettings(
/** Keep a foreground service up so incoming MIDI plays with the app in the
* background ("Keep running as MIDI sound module"). */
val soundModule: Boolean = false,
/** MIDI sources the user switched off in Setup ([cc.tiredsysadmin.android.sizzle.input.MidiSourceKey]). */
val midiSourcesOff: Set<String> = emptySet(),
)
/**
@@ -61,6 +64,7 @@ class SettingsStore(private val context: Context) {
sendMidiClock = prefs[MIDI_CLOCK_SEND] ?: false,
receiveMidiClock = prefs[MIDI_CLOCK_RECV] ?: false,
soundModule = prefs[SOUND_MODULE] ?: false,
midiSourcesOff = prefs[MIDI_SOURCES_OFF] ?: emptySet(),
)
}
@@ -105,6 +109,11 @@ class SettingsStore(private val context: Context) {
context.settingsDataStore.edit { prefs -> prefs[SOUND_MODULE] = enabled }
}
/** Persist the MIDI sources switched off in Setup. */
suspend fun saveMidiSourcesOff(keys: Set<String>) {
context.settingsDataStore.edit { prefs -> prefs[MIDI_SOURCES_OFF] = keys }
}
private companion object {
val PALETTE = stringPreferencesKey("palette")
val RECORD_DIR = stringPreferencesKey("recordDirUri")
@@ -115,5 +124,6 @@ class SettingsStore(private val context: Context) {
val MIDI_CLOCK_SEND = booleanPreferencesKey("midiClockSend")
val MIDI_CLOCK_RECV = booleanPreferencesKey("midiClockRecv")
val SOUND_MODULE = booleanPreferencesKey("soundModule")
val MIDI_SOURCES_OFF = stringSetPreferencesKey("midiSourcesOff")
}
}
@@ -3,6 +3,8 @@
package cc.tiredsysadmin.android.sizzle.model
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs
/**
* The third tab is a toolbox of 16 slots. Every slot can hold one instrument OR
* one effect. Rather than a separate class per device (which would be a lot of
@@ -113,6 +115,12 @@ enum class ToolboxType(
),
),
// FRASIL's drone voice (MPL-2.0, see the frasil package): three layers (a detuned
// saw choir, drifting additive partials, noise through resonators) that evolve
// while held, morphing toward one of FRASIL's 36 drone sounds. Rendered by
// FrasilVoice inside SynthVoice; edited by the paged editor in ToolboxScreen.
MORPH_PAD(ToolboxKind.INSTRUMENT, "Morph Pad", FrasilDefs.PARAMS),
// ---------- Effects ----------
ARPEGGIATOR(
ToolboxKind.EFFECT, "MIDI Arpeggiator",
@@ -148,6 +148,15 @@ class AppViewModel(
fun updateSoundModuleMode(enabled: Boolean) = sizzleApp.setSoundModuleEnabled(enabled)
/** Every MIDI source that can send to Sizzle, with whether it is listened to. */
val midiInputSources: StateFlow<List<cc.tiredsysadmin.android.sizzle.input.MidiSource>>
get() = midiInput.sources
fun setMidiSourceEnabled(key: String, enabled: Boolean) = midiInput.setEnabled(key, enabled)
/** Close and reopen every MIDI source (e.g. after the sending app restarted). */
fun reconnectMidi() = midiInput.reconnect()
// ----- A song opened from another app (VIEW / SEND intent) -----
/** Waiting for the user to confirm replacing the current song, or to read why
* it can't be opened. */
@@ -518,19 +518,61 @@ private fun MidiSyncCard(vm: AppViewModel) {
HorizontalDivider()
ToggleRow(
"Receive MIDI clock",
"Follow an external clock's tempo, and start/stop with it.",
"Follow an external clock's tempo, and start/stop Sizzle's own song with it " +
"(tempo only while Sizzle runs as a MIDI sound module).",
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.",
"use it as its synth), with a notification while on. Sizzle's own song " +
"doesn't start from the other app's clock meanwhile.",
module,
) { vm.updateSoundModuleMode(it) }
HorizontalDivider()
MidiInputsList(vm)
}
}
/** The MIDI sources Sizzle can listen to (controllers, other apps' virtual ports),
* each with a switch, plus Reconnect for a source whose app restarted. */
@Composable
private fun MidiInputsList(vm: AppViewModel) {
val sources by vm.midiInputSources.collectAsState()
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text("MIDI inputs", style = MaterialTheme.typography.bodyMedium)
Text(
"Sources Sizzle listens to. Each mixer track plays the notes on its MIDI channel.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
OutlinedButton(onClick = { vm.reconnectMidi() }) { Text("Reconnect") }
}
if (sources.isEmpty()) {
Text(
"No MIDI sources found.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
for (src in sources) {
ToggleRow(
src.name,
when {
!src.enabled -> "Off"
src.connected -> "Listening"
else -> "Not connected (tap Reconnect)"
},
src.enabled,
) { vm.setMidiSourceEnabled(src.key, it) }
}
}
@@ -53,9 +53,11 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.FileProvider
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs
import cc.tiredsysadmin.android.sizzle.model.ParamSpec
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
import cc.tiredsysadmin.android.sizzle.model.ToolboxType
@@ -294,7 +296,8 @@ private fun ParamEditor(vm: AppViewModel, slot: ToolboxSlot, onClose: () -> Unit
// The SoundFont and synth editors pin an audition keyboard at the bottom (same as
// the toolbox / tracker keyboards), so their controls scroll in a weighted region
// above the keyboard rather than the whole editor scrolling as one.
val pinnedKeyboard = type == ToolboxType.SOUNDFONT || type == ToolboxType.NES_SYNTH
val pinnedKeyboard = type == ToolboxType.SOUNDFONT || type == ToolboxType.NES_SYNTH ||
type == ToolboxType.MORPH_PAD
// The Sampler pins its 16-pad grid at the bottom in that same region, so the
// playable pads are the same height as the keyboards across every instrument editor.
val pinnedBottom = pinnedKeyboard || type == ToolboxType.SAMPLER
@@ -340,6 +343,7 @@ private fun ParamEditor(vm: AppViewModel, slot: ToolboxSlot, onClose: () -> Unit
ToolboxType.SOUNDFONT -> SoundFontEditor(vm, slot)
ToolboxType.DELAY -> DelayEditor(vm, slot)
ToolboxType.AMBIENCE -> AmbiencePager(vm, slot)
ToolboxType.MORPH_PAD -> SectionPager(vm, slot, FrasilDefs.SECTIONS, 300.dp)
ToolboxType.LFO -> {
ParamGrid(vm, slot, type.params)
LfoTargetPicker(vm, slot)
@@ -465,25 +469,30 @@ internal fun ParamGrid(vm: AppViewModel, slot: ToolboxSlot, params: List<ParamSp
* dot pagination below. Each page uses the same two-column [ParamGrid]. Works the
* same in portrait and landscape (the editor overlay is full-width in both). */
@Composable
private fun AmbiencePager(vm: AppViewModel, slot: ToolboxSlot) {
private fun AmbiencePager(vm: AppViewModel, slot: ToolboxSlot) =
SectionPager(vm, slot, AMBIENCE_SECTIONS.map { it.title to it.keys }, 210.dp)
/** A device's parameters as swipeable pages of (title, keys), with dot pagination. */
@Composable
private fun SectionPager(vm: AppViewModel, slot: ToolboxSlot, sections: List<Pair<String, List<String>>>, height: Dp) {
val c = LocalRetro.current
val byKey = (slot.type ?: return).params.associateBy { it.key }
val pagerState = rememberPagerState(pageCount = { AMBIENCE_SECTIONS.size })
val pagerState = rememberPagerState(pageCount = { sections.size })
val scope = rememberCoroutineScope()
Column(Modifier.fillMaxWidth()) {
HorizontalPager(
state = pagerState,
modifier = Modifier.fillMaxWidth().height(210.dp),
modifier = Modifier.fillMaxWidth().height(height),
pageSpacing = 12.dp,
) { page ->
val section = AMBIENCE_SECTIONS[page]
val (title, keys) = sections[page]
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(
section.title, color = c.accent,
title, color = c.accent,
fontFamily = FontFamily.Monospace, fontSize = 12.sp,
)
ParamGrid(vm, slot, section.keys.mapNotNull { byKey[it] })
ParamGrid(vm, slot, keys.mapNotNull { byKey[it] })
}
}
// Dot pagination: tap a dot (or swipe the page) to jump to that section.
@@ -491,7 +500,7 @@ private fun AmbiencePager(vm: AppViewModel, slot: ToolboxSlot) {
Modifier.fillMaxWidth().padding(top = 8.dp),
horizontalArrangement = Arrangement.Center,
) {
for (i in AMBIENCE_SECTIONS.indices) {
for (i in sections.indices) {
val active = i == pagerState.currentPage
Box(
Modifier
@@ -0,0 +1,130 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.frasil
import cc.tiredsysadmin.android.sizzle.audio.SynthPatch
import cc.tiredsysadmin.android.sizzle.audio.SynthVoice
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
import cc.tiredsysadmin.android.sizzle.model.ToolboxType
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.math.abs
import kotlin.math.sqrt
class FrasilVoiceTest {
private val fs = 48_000
private fun slot(preset: String? = null, vararg extra: Pair<String, String>): ToolboxSlot =
ToolboxSlot(0).apply {
fill(ToolboxType.MORPH_PAD)
preset?.let { n -> FrasilDefs.FACTORY.first { it.name == n }.values.forEach { (k, v) -> set(k, v) } }
extra.forEach { (k, v) -> set(k, v) }
}
private class Stats(val rms: Float, val peak: Float, val finite: Boolean)
private fun render(v: FrasilVoice, frames: Int): Stats {
var sum = 0.0; var peak = 0f; var finite = true
repeat(frames) {
val x = v.render()
if (!x.isFinite()) finite = false
sum += x * x; peak = maxOf(peak, abs(x))
}
return Stats(sqrt(sum / frames).toFloat(), peak, finite)
}
@Test fun everyFactorySoundPlaysFiniteBoundedAndFreesAfterRelease() {
assertEquals(36, FrasilDefs.FACTORY.size)
for (p in FrasilDefs.FACTORY) {
val v = FrasilVoice(fs)
v.noteOn(48, 0.8f, FrasilPatch.from(slot(p.name)))
val held = render(v, fs * 3)
assertTrue("${p.name} finite", held.finite)
assertTrue("${p.name} sounds (rms ${held.rms})", held.rms > 0.003f)
// Sparse GRAIN clicks ring the resonators past the steady level (FRASIL's crackle);
// the master limiter takes those. The body of every sound stays well under.
assertTrue("${p.name} peak ${held.peak}", held.peak < 1.5f)
assertTrue("${p.name} rms ${held.rms}", held.rms < 0.5f)
println("${p.name}: rms ${"%.3f".format(held.rms)} peak ${"%.3f".format(held.peak)}")
v.noteOff()
// RELEASE tops out at 60 s (a time constant a third of it): the tail ends well inside 70 s.
var frames = 0
while (v.isActive && frames < fs * 70) { v.render(); frames++ }
assertFalse("${p.name} frees after its release", v.isActive)
}
}
@Test fun pitchFollowsTheNote() {
// STILL: partials alone, darkest tilt: nearly a sine at the note.
val v = FrasilVoice(fs)
v.noteOn(69, 1f, FrasilPatch.from(slot("Still", "motion" to "0.0")))
render(v, fs) // past the attack
var prev = v.render(); var crossings = 0; val n = fs * 2
repeat(n) { val x = v.render(); if (prev < 0f && x >= 0f) crossings++; prev = x }
assertEquals(440.0, crossings / 2.0, 3.0)
}
@Test fun morphTimeCarriesAHeldNoteToTheTarget() {
val glacier = FrasilDefs.factoryEngine("Glacier")!!.first
val v = FrasilVoice(fs)
v.noteOn(60, 1f, FrasilPatch.from(slot("Mist", FrasilDefs.MORPH_TO to "Glacier", FrasilDefs.MORPH_TIME to "1.0")))
render(v, fs / 100)
assertEquals(76 / 127f, v.valueForTest(FrasilDefs.CHOIR), 0.02f) // starts at Mist
render(v, fs + fs / 5)
assertEquals(glacier[FrasilDefs.CHOIR], v.valueForTest(FrasilDefs.CHOIR), 0.01f)
assertEquals(glacier[FrasilDefs.STRETCH], v.valueForTest(FrasilDefs.STRETCH), 0.01f)
}
@Test fun manualMorphSitsBetweenTheTwo() {
val glacier = FrasilDefs.factoryEngine("Glacier")!!.first
val v = FrasilVoice(fs)
v.noteOn(60, 1f, FrasilPatch.from(slot("Mist", FrasilDefs.MORPH_TO to "Glacier", FrasilDefs.MORPH to "0.5")))
render(v, fs / 2)
assertEquals((76 / 127f + glacier[FrasilDefs.CHOIR]) / 2f, v.valueForTest(FrasilDefs.CHOIR), 0.01f)
}
@Test fun aHeldPadIsAboutAsLoudAsASynthNote() {
val pad = SynthVoice(fs).apply { noteOn(60, 100, SynthPatch.forPad(FrasilPatch.from(slot("Mist")))) }
val syn = SynthVoice(fs).apply { noteOn(60, 100, SynthPatch.DEFAULT) }
fun rms(v: SynthVoice): Float {
repeat(fs * 2) { v.render() }
var s = 0.0; repeat(fs) { val x = v.render(); s += x * x }
return sqrt(s / fs).toFloat()
}
val ratio = rms(pad) / rms(syn)
println("pad/synth rms ratio $ratio")
assertTrue("pad/synth level ratio $ratio within -6..+6 dB", ratio in 0.5f..2f)
}
@Test fun synthVoicePlaysPadThenSynthAgain() {
val v = SynthVoice(fs)
v.noteOn(57, 100, SynthPatch.forPad(FrasilPatch.from(slot("Organ"))))
assertTrue(v.isActive && v.isGated)
var e = 0.0; repeat(fs) { val x = v.render(); e += x * x }
assertTrue(e > 0.0)
v.noteOff()
assertFalse(v.isGated)
v.noteOn(57, 100, SynthPatch.DEFAULT) // the slot became a synth
var e2 = 0.0; repeat(fs / 4) { val x = v.render(); e2 += x * x }
assertTrue(e2 > 0.0)
v.kill()
assertFalse(v.isActive)
}
@Test fun cpuBudgetForFullPolyphony() {
// 4 channels x 8 voices of the heaviest kind of sound (all three layers, SOFT, BEAT, a resonant filter).
val p = FrasilPatch.from(slot("Prism", "choir" to "1.0", "creso" to "0.5", "soft" to "0.5", "breath" to "0.8"))
val voices = Array(32) { FrasilVoice(fs).also { v -> v.noteOn(36 + it, 0.9f, p) } }
repeat(fs / 2) { for (v in voices) v.render() } // warm up the JIT
val seconds = 2
val t0 = System.nanoTime()
repeat(fs * seconds) { for (v in voices) v.render() }
val load = (System.nanoTime() - t0) / 1e9 / seconds
println("32 Morph Pad voices: ${"%.1f".format(load * 100)} % of real time on this host")
assertTrue("32 voices must render faster than real time on the host ($load)", load < 1.0)
}
}
@@ -0,0 +1,49 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.input
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Test
class MidiSourceKeyTest {
private val mikroSeq = MidiSourceKey.of(
2, "tiredsysadmin", "Mikro Seq", null,
"cc.tiredsysadmin.android.mikroseq/cc.tiredsysadmin.android.mikroseq.SeqMidiService", null,
)
@Test fun sameDeviceSameKeyRegardlessOfAndroidId() {
val again = MidiSourceKey.of(
2, "tiredsysadmin", "Mikro Seq", null,
"cc.tiredsysadmin.android.mikroseq/cc.tiredsysadmin.android.mikroseq.SeqMidiService", null,
)
assertEquals(mikroSeq, again)
}
@Test fun differentDevicesDiffer() {
val usb = MidiSourceKey.of(1, "Android", "USB Peripheral Port", "Android USB Peripheral Port", null, null)
val sunvox = MidiSourceKey.of(2, "NightRadio", "SunVox", null, "nightradio.sunvox/x.MidiService", null)
assertNotEquals(mikroSeq, usb)
assertNotEquals(mikroSeq, sunvox)
val bt1 = MidiSourceKey.of(3, null, null, "WIDI", null, "AA:BB")
val bt2 = MidiSourceKey.of(3, null, null, "WIDI", null, "AA:CC")
assertNotEquals(bt1, bt2)
}
@Test fun separatorInsideAFieldCannotForgeAnotherKey() {
assertNotEquals(
MidiSourceKey.of(1, "a|b", null, null, null, null),
MidiSourceKey.of(1, "a", "b", null, null, null),
)
}
@Test fun displayNamePrefersNameThenProductThenMaker() {
assertEquals("Android USB Peripheral Port",
MidiSourceKey.displayName("Android", "USB Peripheral Port", "Android USB Peripheral Port"))
assertEquals("Mikro Seq", MidiSourceKey.displayName("tiredsysadmin", "Mikro Seq", null))
assertEquals("tiredsysadmin", MidiSourceKey.displayName("tiredsysadmin", " ", ""))
assertEquals("MIDI device", MidiSourceKey.displayName(null, null, null))
}
}
@@ -0,0 +1,25 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.io
import cc.tiredsysadmin.android.sizzle.model.Project
import org.junit.Assert.assertEquals
import org.junit.Test
/** Block names with spaces survive the project save/load (the autosave). */
class ProjectIoNameTest {
@Test fun namesWithSpacesAndEscapesRoundTrip() {
val names = listOf("C1 muted", "50% ]x", "%20 literal", "plain")
val p = Project()
names.forEachIndexed { i, n -> p.patterns[i].name = n }
val back = ProjectIo.loadInto(Project(), ProjectIo.save(p))
assertEquals(names, back.patterns.take(names.size).map { it.name })
}
@Test fun olderFilesWithoutEscapesLoadAsWritten() {
assertEquals("50%", ProjectIo.decodeName("50%"))
assertEquals("C1", ProjectIo.decodeName("C1"))
}
}
+103 -2
View File
@@ -206,11 +206,13 @@ cc.tiredsysadmin.android.sizzle
│ ├── GamepadInput.kt KeyEvent/MotionEvent -> InputAction (rebindable)
│ ├── MidiByteParser.kt MIDI byte stream -> messages (running status, split packets, realtime, SysEx)
│ ├── MidiClock.kt MIDI clock send / follow
│ └── MidiInput.kt Opens MIDI sources (USB, BLE, other apps' virtual ports) -> MidiSoundModule / CC bindings
│ ├── MidiSourceKey.kt Stable key + display name for a MIDI source (persisted on/off choice)
│ ├── MidiTrace.kt Optional receive/engine trace (setprop log.tag.SizzleMidiTrace VERBOSE)
│ └── MidiInput.kt Lists/opens MIDI sources (USB, BLE, other apps' virtual ports), reconnects dead ones -> MidiSoundModule / CC bindings
│
├── audio/ The real-time sound engine (own thread)
│ ├── Transport.kt TransportState snapshot published to the UI
│ ├── SynthVoice.kt One NES-style voice: pulse/triangle/noise + ADSR
│ ├── SynthVoice.kt One synth note (3-osc subtractive), or a Morph Pad note via FrasilVoice
│ ├── SampleVoice.kt Pitched + sliced playback of a decoded sample
│ ├── SampleStore.kt Process-wide decoded-PCM cache + WAV encode/decode
│ ├── SampleRecorder.kt Ad-hoc mic/USB capture into a sample
@@ -221,6 +223,11 @@ cc.tiredsysadmin.android.sizzle
│ ├── NativeAudioBridge.kt JNI bridge to the Oboe callback (calls fillBlock)
│ └── AudioEngine.kt Oboe/AudioTrack + sample-accurate sequencer + voice/FX mixing
│
├── frasil/ MPL-2.0 (not GPL): the Morph Pad, ported from FRASIL (see §5.7)
│ ├── FrasilDefs.kt Its settings, editor pages, engine-unit mapping, the 36 drone presets
│ ├── FrasilPatch.kt Parsed slot snapshot (+ morph target); FrasilClock (the shared TIDE time)
│ └── FrasilVoice.kt One pad note: choir + partials + breath, drift, tide, warmth
│
├── cpp/native_audio.cpp Low-latency Oboe stream; RT callback pulls audio via JNI
│
├── io/ Human-readable text persistence
@@ -343,10 +350,49 @@ foreground on pause, and its notification manager re-derives that state from
- The MIDI clock follow (Start/Stop/tempo) and the clock sender's providers are
wired in `SizzleApp.wireMidi`, not the ViewModel, and the clock toggles are
restored there; the ViewModel only redraws on `MidiClock.followedTempo`.
While sound-module mode is on, clock Start/Stop are ignored (0.29.2): the
sender's notes already play, and starting Sizzle's own song too doubled them
(e.g. a song just imported from Mikro Seq) out of reach of the sender's mutes.
Tempo is still followed.
- Punch-in recording stays UI-driven: the module mirrors notes onto
`InputRouter` as `NoteOn(…, sounded = true)`, which the ViewModel records but
does not play again. With no UI collecting, the router drops them.
**Which sources, and staying connected (0.29.0).** `MidiInput` keeps every
device that can send to us in `sources` (a `StateFlow<List<MidiSource>>` the
Setup screen lists with a switch each). Sources are listened to unless switched
off; the off-set is persisted as `MidiSourceKey`s (type + maker/product/name +
publishing service or Bluetooth address), because Android's device id changes on
every reconnect. The trap this solves: when the app behind a *virtual* source
dies and restarts (crash, update, force stop), Android keeps the device, keeps
our connection record, drops its service binding, and tells clients nothing:
no `onDeviceRemoved`, no `onDeviceStatusChanged` (checked on Android 15:
`dumpsys midi` shows `Status: null … mServiceConnection: null`). Our
`MidiOutputPort` just goes silent. So a worker thread probes each open virtual
source every 3 s with `MidiDevice.openOutputPort(0)` (null from a dead server;
a live one's probe port is closed at once) and reopens dead ones through
`MidiManager.openDevice`, which makes Android rebind the app's MIDI service.
`refresh()` runs on every Activity resume and the Setup "Reconnect" button closes
and reopens everything. A status report of zero open output ports while we hold
one is treated as dead too (events within 1 s of our own open/close are ignored).
USB and Bluetooth sources are not probed: Android reports their removal.
`MidiInput` logs connects/reconnects under the `SizzleMidi` tag.
**Tracing (0.29.1).** `input/MidiTrace` logs, when switched on with
`adb shell setprop log.tag.SizzleMidiTrace VERBOSE` (re-read every 500 ms, free
when off), every received packet (`recv <source> [bytes] <decoded> late=…ms`), each
note handed to the engine with the strips it reaches (`AudioEngine.describeBusTargets`:
"strip1 SAMPLER pad3", "no strip on channel 10", "pad empty (silent)") and a
`[Sizzle transport PLAYING]` flag, and clock Start/Stop acting on the transport.
Mikro Seq's debug builds log what they send under `MidiOut`, so
`adb logcat -s MidiOut SizzleMidiTrace` lines the two up. Checked this way on the
Android 15 emulator (Mikro Seq 0.13.0): 666 note messages, sent = received byte for
byte and in order, median 0.6 ms late; 243 notes over 20 s all balanced; muting a
Mikro Seq track stops its notes at the sender. The trap found: with "Receive MIDI
clock" on, Mikro Seq's Start also starts Sizzle's *own* sequencer, so a song
imported from Mikro Seq plays along with the live notes, and Mikro Seq's mutes can't
reach it.
**Verifying.** With the setting on and the app backgrounded, `adb shell dumpsys
activity processes` must not show `isFrozen=true` for the Sizzle process, and
another app's notes must keep sounding. Opening a virtual port binds the other
@@ -366,6 +412,61 @@ than songs. The ViewModel then holds an `incomingSong`, and `App.kt` asks before
stay); the intent is consumed so a rotation can't offer it twice. Mikro Seq's "Open
in Sizzle" sends its exported `.sng` this way with a FileProvider URI.
### 5.7 The Morph Pad (FRASIL port, MPL-2.0)
The **Morph Pad** instrument (`ToolboxType.MORPH_PAD`) is the drone voice of
[FRASIL](https://github.com/styvesgoupil/frasil) 3.3 (commit `e7a8fb2`), a
custom firmware for the M-VAVE FM-1 by Styves Goupil, translated from C to Kotlin.
It was chosen from the FM-1 firmware hub (thefirmwarehub.com) because it was the
cleanest evolving-pad engine there and its licence fits.
**Licence boundary.** FRASIL is MPL-2.0, which is file-level copyleft. The three
files in `frasil/` are derived from FRASIL's files, so they **stay MPL-2.0**: they
keep FRASIL's copyright line and the MPL header, and their source must stay
published. MPL-2.0 §3.3 lets them live in a GPL program (none of FRASIL's files is
marked "Incompatible With Secondary Licenses"); the rest of Sizzle stays
GPL-3.0-or-later. The text is in `LICENSES/MPL-2.0.txt`. Keep FRASIL-derived code
in that package. Glue code that only uses it (`SynthVoice`, `AudioEngine`, the
editor) is Sizzle's own and stays GPL. Most other firmwares on the hub are
GPL-3.0-*only*; porting from those would make the whole app GPL-3.0-only, so that
was avoided.
**What was ported** (`engine/dsp/frasil.c`, `engine/params.c`): the voice's three
layers (CHOIR: three PolyBLEP saws with SHAPE/SOFT and a one-pole or TPT SVF
filter; PARTIALS: eight magic-circle partials with tilt, odd, stretch, formant,
EVOLVE and BEAT; BREATH: noise or grains through three resonators), MOTION
(an Ornstein-Uhlenbeck walk per drifting value, a step per 256-frame block),
TIDE, the mix's DC blocker, warmth and the BODY high-pass, and the 36 drone
presets. **Left out:** GLINT, BASS, LEAD, the NUAGE reverb (use an Ambience insert),
the master effects, stereo SPREAD, pressure and FRASIL's load shedding.
**Where it plugs in.** A Morph Pad note is played by a `SynthVoice` whose
`SynthPatch.pad` is set: the voice then forwards everything to its embedded
`FrasilVoice`. That way every existing synth pool (sequencer, mix-bus/MIDI
sound-module, editor audition) plays pads with no change to allocation, stealing
or note-off. `AudioEngine.patchForSlot`/`refreshSynthPatches` build the patch
(`FrasilPatch.from(slot)`) only when the slot version changes, so knob turns and
MIDI-LFO moves reach held notes; `FrasilVoice` glides every value to the new patch
over ~25 ms (FRASIL glides its parameters the same way).
**Rendering.** `FrasilVoice.render()` is per sample, as Sizzle's voices are, but
internally FRASIL's structure is kept: a 256-frame block recomputes frequencies,
filter coefficients and drift; 64-frame chunks are computed at once and handed out
a sample at a time. FRASIL's 44.1 kHz per-step constants are rescaled with its own
`br_k` rule (`1 - (1 - k)^(44100/fs)`). The mono mix is centre + sides at -3 dB.
TIDE is one shared sine in FRASIL; here `FrasilClock` (advanced once per
`fillBlock`) is the shared time, so the voices of a chord swell together.
**Morph** is Sizzle's addition. FRASIL morphs whole scenes over 1–120 s. Here a
pad names one factory sound as **MORPH TO**; **MORPH** sets where a note starts
between the slot's own sound and that one (an LFO can move it), and **MORPH TIME**
(seconds) carries each held note the rest of the way on a smoothstep. Float values
are interpolated; the choir filter TYPE switches at the halfway point.
**Cost.** On a desktop JVM, 32 voices of the heaviest setting run at about 7 % of
real time (`FrasilVoiceTest.cpuBudgetForFullPolyphony`). The level of a held pad
is matched to a synth note (`aHeldPadIsAboutAsLoudAsASynthNote`).
---
## 6. How to extend
+25
View File
@@ -249,6 +249,25 @@ or FastTracker (`.xi`) file, pitched across the keyboard from its root note.
It has a volume **ADSR envelope** and an optional **LOOP** (sustains the sample
until note‑off) with an adjustable crossfade (**XFADE**) to smooth the loop seam.
**Morph Pad** — evolving pads and drones, ported from FRASIL (a custom firmware
for the M‑VAVE FM‑1 by Styves Goupil). Each note has three layers: **Choir**
(three detuned saws, shapeable toward pulses, through a filter), **Partials**
(eight additive overtones that wander on their own) and **Breath** (noise or
grains ringing through resonators tuned to the note). The sound keeps moving
while you hold it: **Motion** sets how far its parts drift and **Motion Rate** how
quickly, **Tide** slowly brightens and darkens every note together (**Tide Speed**:
one turn in 5 minutes up to 10 seconds). **Body** thins the sound out, **Warmth**
saturates it.
To **morph**, pick a factory sound in **Morph To**. **Morph** places the pad between
its own sound (0) and that one (1); turn it by hand or let a MIDI LFO move it.
**Morph Time** (seconds) makes every held note travel to the target on its own:
start a long chord and it slowly becomes the other sound. The editor is paged:
**Morph**, **Layers**, **Shape**, **Motion**, **Choir**, **Partials**, **Breath**.
The 36 factory presets are FRASIL's drone sounds (Mist, Cathedral, Glacier,
Abyss, …). The pad is dry: put an **Ambience** reverb on its channel for the
spacious sound FRASIL is known for.
### Effects
Insert effects (assign them to a channel's FX slots in the Mix tab):
@@ -303,6 +322,12 @@ you delete stay deleted.
DAW) can use it as its synth. A notification shows while it is on; its
**Stop** button turns it off. Each mixer track plays the notes on its MIDI
channel.
- **MIDI Sync → MIDI inputs** — every MIDI source Sizzle can hear (controllers,
and other apps such as Mikro Seq), each with a switch. New sources are on. If a
source shows "Not connected", or an app you play from stopped being heard, tap
**Reconnect** (Sizzle also reconnects by itself within a few seconds when the
sending app restarts). Remember to give each mixer track a MIDI channel and an
instrument, or incoming notes have nowhere to sound.
- **Audio Devices** — route **Output** and **Input** to USB or built‑in.
- **Color Theme** — pick a palette, or **Export / Import `.szt`** themes. Stock
themes can't be deleted; imported ones join the list.
+2 -2
View File
@@ -8,8 +8,8 @@
# or polish. android.versionCode is monotonic and bumps by 1 on every release,
# because F-Droid and the Android package manager order installs by it alone.
android.versionName = 0.28.0
android.versionCode = 57
android.versionName = 0.30.0
android.versionCode = 61
# No desktop builds exist yet. These lines are the agreed slots so a port starts
# with a version instead of inventing one; `-` means "not built on this