Compare commits
2
Commits
2d59b0429d
...
c8d760ed17
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8d760ed17 | ||
|
|
aa023d1f01 |
@@ -4,6 +4,26 @@ Sizzletracker for Android (`cc.tiredsysadmin.android.sizzle`). One entry per
|
|||||||
version in `versions.properties`; versions before 0.28.0 are described in the git
|
version in `versions.properties`; versions before 0.28.0 are described in the git
|
||||||
log (one commit per version).
|
log (one commit per version).
|
||||||
|
|
||||||
|
## 0.32.0 (versionCode 63)
|
||||||
|
|
||||||
|
- **Wavetable**, a new two-oscillator wavetable synth: twelve built-in tables
|
||||||
|
(Classic, PWM, Vowels, Harmonic Sweep, Sync, FM, Organ, Fold, Digital, Glass,
|
||||||
|
Odd Even, Comb), Serum / WaveEdit WAV import, position swept by its own envelope
|
||||||
|
and a tempo-synced LFO, phase bend, up to 4-voice unison, sub, noise, drive and a
|
||||||
|
low/band/high filter. Band-limited per octave, so high notes don't alias. 12
|
||||||
|
factory presets. Written for Sizzle (GPL-3.0-or-later), not ported.
|
||||||
|
|
||||||
|
## 0.31.0 (versionCode 62)
|
||||||
|
|
||||||
|
- **Grain Cloud**, a new granular drone instrument: ECHOFIELD's grain engine (by
|
||||||
|
Philip Bos, an M-VAVE FM-1 firmware) ported to Kotlin. Six modes (Cloud, Dust,
|
||||||
|
Tape, Bloom, Pulse, Drift), up to 32 grains per channel, held notes pitch the
|
||||||
|
grains, freeze, and an auto-level that keeps every sound at one loudness. Ten
|
||||||
|
built-in sources synthesised by Sizzle, or load / record your own (kept across
|
||||||
|
restarts). 14 factory presets. Plays from the tracker, the toolbox keyboard and
|
||||||
|
live MIDI.
|
||||||
|
- The ported files (`echofield/`) are MIT, as ECHOFIELD is (`LICENSES/MIT.txt`).
|
||||||
|
|
||||||
## 0.30.0 (versionCode 61)
|
## 0.30.0 (versionCode 61)
|
||||||
|
|
||||||
- **Morph Pad**, a new instrument for evolving pads and drones: the drone voice of
|
- **Morph Pad**, a new instrument for evolving pads and drones: the drone voice of
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Philip Bos
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -85,3 +85,8 @@ The Morph Pad instrument (`app/src/main/java/cc/tiredsysadmin/android/sizzle/fra
|
|||||||
is ported from [FRASIL](https://github.com/styvesgoupil/frasil), Copyright © 2026
|
is ported from [FRASIL](https://github.com/styvesgoupil/frasil), Copyright © 2026
|
||||||
Styves Goupil, and those files remain under the **Mozilla Public License 2.0**
|
Styves Goupil, and those files remain under the **Mozilla Public License 2.0**
|
||||||
([`LICENSES/MPL-2.0.txt`](LICENSES/MPL-2.0.txt)).
|
([`LICENSES/MPL-2.0.txt`](LICENSES/MPL-2.0.txt)).
|
||||||
|
|
||||||
|
The Grain Cloud instrument (`app/src/main/java/cc/tiredsysadmin/android/sizzle/echofield/`)
|
||||||
|
is ported from [ECHOFIELD FM-1](https://github.com/Philip-Bos/echofield-fm1),
|
||||||
|
Copyright © 2026 Philip Bos, and those files remain under the **MIT License**
|
||||||
|
([`LICENSES/MIT.txt`](LICENSES/MIT.txt)).
|
||||||
|
|||||||
@@ -102,6 +102,10 @@ class SizzleApp : Application() {
|
|||||||
|
|
||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
|
// The Grain Cloud's built-in sources are synthesised, not shipped: render them
|
||||||
|
// in the background now so they're ready before anyone plays one.
|
||||||
|
cc.tiredsysadmin.android.sizzle.audio.GrainSources.prewarm()
|
||||||
|
cc.tiredsysadmin.android.sizzle.wavetable.WaveTables.prewarm()
|
||||||
// Crash recovery: restore the last autosaved project before the engine or
|
// Crash recovery: restore the last autosaved project before the engine or
|
||||||
// UI read it, so a crash / process-death resumes where the user left off.
|
// UI read it, so a crash / process-death resumes where the user left off.
|
||||||
projectStore.restore(project)
|
projectStore.restore(project)
|
||||||
|
|||||||
@@ -6,8 +6,11 @@ package cc.tiredsysadmin.android.sizzle.audio
|
|||||||
import android.media.AudioAttributes
|
import android.media.AudioAttributes
|
||||||
import android.media.AudioFormat
|
import android.media.AudioFormat
|
||||||
import android.media.AudioTrack
|
import android.media.AudioTrack
|
||||||
|
import cc.tiredsysadmin.android.sizzle.echofield.GrainCloud
|
||||||
|
import cc.tiredsysadmin.android.sizzle.echofield.GrainPatch
|
||||||
import cc.tiredsysadmin.android.sizzle.frasil.FrasilClock
|
import cc.tiredsysadmin.android.sizzle.frasil.FrasilClock
|
||||||
import cc.tiredsysadmin.android.sizzle.frasil.FrasilPatch
|
import cc.tiredsysadmin.android.sizzle.frasil.FrasilPatch
|
||||||
|
import cc.tiredsysadmin.android.sizzle.wavetable.WavePatch
|
||||||
import cc.tiredsysadmin.android.sizzle.model.Arrangement
|
import cc.tiredsysadmin.android.sizzle.model.Arrangement
|
||||||
import cc.tiredsysadmin.android.sizzle.model.Pattern
|
import cc.tiredsysadmin.android.sizzle.model.Pattern
|
||||||
import cc.tiredsysadmin.android.sizzle.model.Project
|
import cc.tiredsysadmin.android.sizzle.model.Project
|
||||||
@@ -103,6 +106,18 @@ class AudioEngine(
|
|||||||
private val moutNote = IntArray(Arrangement.LANE_COUNT * Pattern.TRACK_COUNT) { -1 }
|
private val moutNote = IntArray(Arrangement.LANE_COUNT * Pattern.TRACK_COUNT) { -1 }
|
||||||
private val moutCh = IntArray(Arrangement.LANE_COUNT * Pattern.TRACK_COUNT)
|
private val moutCh = IntArray(Arrangement.LANE_COUNT * Pattern.TRACK_COUNT)
|
||||||
|
|
||||||
|
// Grain Cloud (ECHOFIELD port): one shared cloud per mixer channel, held notes
|
||||||
|
// pitch its grains; plus one for the editor's audition keyboard. A cloud renders
|
||||||
|
// only while its channel's instrument is a Grain Cloud (cloudOn).
|
||||||
|
private val clouds = Array(Pattern.TRACK_COUNT) { GrainCloud(sampleRate) }
|
||||||
|
private val cloudOn = BooleanArray(Pattern.TRACK_COUNT)
|
||||||
|
private val cloudVer = IntArray(Pattern.TRACK_COUNT) { -1 }
|
||||||
|
private val cloudTempo = FloatArray(Pattern.TRACK_COUNT) { Float.NaN }
|
||||||
|
private val auditionCloud = GrainCloud(sampleRate)
|
||||||
|
private var auditionCloudVer = -1
|
||||||
|
private var auditionCloudTempo = Float.NaN
|
||||||
|
private var auditionCloudActive = false
|
||||||
|
|
||||||
// Cached subtractive-synth patch per bus, reparsed only when the slot changes
|
// Cached subtractive-synth patch per bus, reparsed only when the slot changes
|
||||||
// (version) or tempo changes — so note triggers don't allocate a patch each time,
|
// (version) or tempo changes — so note triggers don't allocate a patch each time,
|
||||||
// and active voices can be refreshed per block for live parameter feedback.
|
// and active voices can be refreshed per block for live parameter feedback.
|
||||||
@@ -147,6 +162,7 @@ class AudioEngine(
|
|||||||
|
|
||||||
/** Release (fade out) every active voice on [bus] — a note-off cell on its channel. */
|
/** Release (fade out) every active voice on [bus] — a note-off cell on its channel. */
|
||||||
private fun releaseBus(bus: Int) {
|
private fun releaseBus(bus: Int) {
|
||||||
|
clouds[bus].releaseSequenced()
|
||||||
val base = bus * POLYPHONY
|
val base = bus * POLYPHONY
|
||||||
for (i in 0 until POLYPHONY) {
|
for (i in 0 until POLYPHONY) {
|
||||||
seqVoices[base + i].noteOff()
|
seqVoices[base + i].noteOff()
|
||||||
@@ -552,6 +568,8 @@ class AudioEngine(
|
|||||||
* tick.
|
* tick.
|
||||||
*/
|
*/
|
||||||
fun panic() {
|
fun panic() {
|
||||||
|
clouds.forEach { it.kill() }
|
||||||
|
auditionCloud.kill()
|
||||||
seqVoices.forEach { it.kill() }
|
seqVoices.forEach { it.kill() }
|
||||||
sampleVoices.forEach { it.kill() }
|
sampleVoices.forEach { it.kill() }
|
||||||
liveVoices.forEach { it.kill() }
|
liveVoices.forEach { it.kill() }
|
||||||
@@ -641,6 +659,7 @@ class AudioEngine(
|
|||||||
for (i in busVoices.indices) if (busVoices[i].isActive) actBus[actBusN++] = i
|
for (i in busVoices.indices) if (busVoices[i].isActive) actBus[actBusN++] = i
|
||||||
for (i in busSampleVoices.indices) if (busSampleVoices[i].isActive) actBSmp[actBSmpN++] = i
|
for (i in busSampleVoices.indices) if (busSampleVoices[i].isActive) actBSmp[actBSmpN++] = i
|
||||||
for (i in liveVoices.indices) if (liveVoices[i].isActive) actLive[actLiveN++] = i
|
for (i in liveVoices.indices) if (liveVoices[i].isActive) actLive[actLiveN++] = i
|
||||||
|
auditionCloudActive = auditionCloud.isActive
|
||||||
for (i in auditionSampleVoices.indices) if (auditionSampleVoices[i].isActive) actASmp[actASmpN++] = i
|
for (i in auditionSampleVoices.indices) if (auditionSampleVoices[i].isActive) actASmp[actASmpN++] = i
|
||||||
|
|
||||||
for (i in 0 until frames) {
|
for (i in 0 until frames) {
|
||||||
@@ -658,6 +677,7 @@ class AudioEngine(
|
|||||||
for (k in 0 until actSmpN) { val vi = actSmp[k]; channelSum[vi / POLYPHONY] += sampleVoices[vi].render() }
|
for (k in 0 until actSmpN) { val vi = actSmp[k]; channelSum[vi / POLYPHONY] += sampleVoices[vi].render() }
|
||||||
for (k in 0 until actBusN) { val vi = actBus[k]; channelSum[vi / BUS_POLYPHONY] += busVoices[vi].render() }
|
for (k in 0 until actBusN) { val vi = actBus[k]; channelSum[vi / BUS_POLYPHONY] += busVoices[vi].render() }
|
||||||
for (k in 0 until actBSmpN) { val vi = actBSmp[k]; channelSum[vi / BUS_POLYPHONY] += busSampleVoices[vi].render() }
|
for (k in 0 until actBSmpN) { val vi = actBSmp[k]; channelSum[vi / BUS_POLYPHONY] += busSampleVoices[vi].render() }
|
||||||
|
for (ch in 0 until Pattern.TRACK_COUNT) if (cloudOn[ch]) channelSum[ch] += clouds[ch].render()
|
||||||
for (ch in 0 until Pattern.TRACK_COUNT) {
|
for (ch in 0 until Pattern.TRACK_COUNT) {
|
||||||
val mc = proj.mixer.channels[ch]
|
val mc = proj.mixer.channels[ch]
|
||||||
var s = if (mc.audible(anySolo)) channelSum[ch] * mc.volume else 0f
|
var s = if (mc.audible(anySolo)) channelSum[ch] * mc.volume else 0f
|
||||||
@@ -677,6 +697,7 @@ class AudioEngine(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (k in 0 until actLiveN) { val v = liveVoices[actLive[k]].render() * LIVE_GAIN; mixL += v; mixR += v }
|
for (k in 0 until actLiveN) { val v = liveVoices[actLive[k]].render() * LIVE_GAIN; mixL += v; mixR += v }
|
||||||
|
if (auditionCloudActive) { val v = auditionCloud.render() * LIVE_GAIN; mixL += v; mixR += v }
|
||||||
for (k in 0 until actASmpN) { val v = auditionSampleVoices[actASmp[k]].render() * LIVE_GAIN; mixL += v; mixR += v }
|
for (k in 0 until actASmpN) { val v = auditionSampleVoices[actASmp[k]].render() * LIVE_GAIN; mixL += v; mixR += v }
|
||||||
// Makeup gain (lifts instruments to media loudness) into a look-ahead
|
// Makeup gain (lifts instruments to media loudness) into a look-ahead
|
||||||
// brickwall limiter that guarantees the output stays under the ceiling.
|
// brickwall limiter that guarantees the output stays under the ceiling.
|
||||||
@@ -1012,6 +1033,7 @@ class AudioEngine(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun releaseTrackVoices(trackKey: Int) {
|
private fun releaseTrackVoices(trackKey: Int) {
|
||||||
|
for (c in clouds) c.releaseOwner(trackKey)
|
||||||
for (v in seqVoices) if (v.ownerTrack == trackKey && v.isGated) v.noteOff()
|
for (v in seqVoices) if (v.ownerTrack == trackKey && v.isGated) v.noteOff()
|
||||||
for (v in sampleVoices) if (v.ownerTrack == trackKey && v.isGated) v.noteOff()
|
for (v in sampleVoices) if (v.ownerTrack == trackKey && v.isGated) v.noteOff()
|
||||||
}
|
}
|
||||||
@@ -1041,6 +1063,8 @@ class AudioEngine(
|
|||||||
// Empty bus (no instrument — e.g. the default channel 0) or a Sampler
|
// Empty bus (no instrument — e.g. the default channel 0) or a Sampler
|
||||||
// with an empty pad → silent, matching the live audition path.
|
// with an empty pad → silent, matching the live audition path.
|
||||||
slot?.type == null || slot.type == ToolboxType.SAMPLER -> {}
|
slot?.type == null || slot.type == ToolboxType.SAMPLER -> {}
|
||||||
|
slot.type == ToolboxType.GRAIN_CLOUD ->
|
||||||
|
clouds[bus].noteOn(note, velocity, if (ownerTrack >= 0) ownerTrack else GrainCloud.OWNER_SEQ)
|
||||||
// NES synth, or a SoundFont with nothing loaded → the tone generator.
|
// NES synth, or a SoundFont with nothing loaded → the tone generator.
|
||||||
else -> {
|
else -> {
|
||||||
allocSynthVoice(bus).also { it.ownerTrack = ownerTrack }
|
allocSynthVoice(bus).also { it.ownerTrack = ownerTrack }
|
||||||
@@ -1265,6 +1289,15 @@ class AudioEngine(
|
|||||||
// note-off, so a sustaining synth voice would ring forever). A SoundFont
|
// note-off, so a sustaining synth voice would ring forever). A SoundFont
|
||||||
// with nothing loaded still falls through to the synth preview below.
|
// with nothing loaded still falls through to the synth preview below.
|
||||||
if (slot?.type == ToolboxType.SAMPLER) return
|
if (slot?.type == ToolboxType.SAMPLER) return
|
||||||
|
if (slot?.type == ToolboxType.GRAIN_CLOUD) {
|
||||||
|
if (auditionSlotIdx != slotIndex || slot.version != auditionCloudVer) {
|
||||||
|
auditionCloud.setPatch(GrainPatch.from(slot, project?.tempoBpm ?: 120f))
|
||||||
|
auditionCloudVer = slot.version
|
||||||
|
}
|
||||||
|
auditionSlotIdx = slotIndex
|
||||||
|
auditionCloud.noteOn(midi, 110, GrainCloud.OWNER_LIVE)
|
||||||
|
return
|
||||||
|
}
|
||||||
// Remember which slot is being auditioned so refreshSynthPatches pushes live
|
// Remember which slot is being auditioned so refreshSynthPatches pushes live
|
||||||
// knob turns into the held preview note.
|
// knob turns into the held preview note.
|
||||||
if (hasSynthPatch(slot?.type)) auditionSlotIdx = slotIndex
|
if (hasSynthPatch(slot?.type)) auditionSlotIdx = slotIndex
|
||||||
@@ -1277,6 +1310,7 @@ class AudioEngine(
|
|||||||
* ringing out its release tail — otherwise rapid re-tapping / chord-tapping the same
|
* ringing out its release tail — otherwise rapid re-tapping / chord-tapping the same
|
||||||
* key lands the note-off on the releasing voice and leaves the held one stuck. */
|
* key lands the note-off on the releasing voice and leaves the held one stuck. */
|
||||||
fun auditionSlotOff(midi: Int) {
|
fun auditionSlotOff(midi: Int) {
|
||||||
|
auditionCloud.noteOff(midi)
|
||||||
(liveVoices.firstOrNull { it.pitch == midi && it.isGated }
|
(liveVoices.firstOrNull { it.pitch == midi && it.isGated }
|
||||||
?: liveVoices.firstOrNull { it.isActive && it.pitch == midi })?.noteOff()
|
?: liveVoices.firstOrNull { it.isActive && it.pitch == midi })?.noteOff()
|
||||||
(auditionSampleVoices.firstOrNull { it.pitch == midi && it.isGated }
|
(auditionSampleVoices.firstOrNull { it.pitch == midi && it.isGated }
|
||||||
@@ -1307,6 +1341,7 @@ class AudioEngine(
|
|||||||
}
|
}
|
||||||
// Sampler with an empty pad → silent (no synth fallback).
|
// Sampler with an empty pad → silent (no synth fallback).
|
||||||
type == ToolboxType.SAMPLER -> {}
|
type == ToolboxType.SAMPLER -> {}
|
||||||
|
type == ToolboxType.GRAIN_CLOUD -> clouds[ch].noteOn(midi, velocity, GrainCloud.OWNER_LIVE)
|
||||||
else -> {
|
else -> {
|
||||||
val v = freeBusVoice(busVoices, base)
|
val v = freeBusVoice(busVoices, base)
|
||||||
v.noteOn(midi, velocity, synthPatch[ch] ?: patchForSlot(slot, proj.tempoBpm))
|
v.noteOn(midi, velocity, synthPatch[ch] ?: patchForSlot(slot, proj.tempoBpm))
|
||||||
@@ -1356,6 +1391,7 @@ class AudioEngine(
|
|||||||
val proj = project ?: return
|
val proj = project ?: return
|
||||||
for (ch in 0 until Pattern.TRACK_COUNT) {
|
for (ch in 0 until Pattern.TRACK_COUNT) {
|
||||||
if (proj.mixer.channels[ch].midiChannel != midiChannel) continue
|
if (proj.mixer.channels[ch].midiChannel != midiChannel) continue
|
||||||
|
clouds[ch].noteOff(midi)
|
||||||
val base = ch * BUS_POLYPHONY
|
val base = ch * BUS_POLYPHONY
|
||||||
for (i in 0 until BUS_POLYPHONY) {
|
for (i in 0 until BUS_POLYPHONY) {
|
||||||
busVoices[base + i].takeIf { it.isActive && it.pitch == midi }?.noteOff()
|
busVoices[base + i].takeIf { it.isActive && it.pitch == midi }?.noteOff()
|
||||||
@@ -1457,11 +1493,13 @@ class AudioEngine(
|
|||||||
private fun patchForSlot(slot: ToolboxSlot?, tempoBpm: Float): SynthPatch = when (slot?.type) {
|
private fun patchForSlot(slot: ToolboxSlot?, tempoBpm: Float): SynthPatch = when (slot?.type) {
|
||||||
ToolboxType.NES_SYNTH -> SynthPatch.from(slot, tempoBpm)
|
ToolboxType.NES_SYNTH -> SynthPatch.from(slot, tempoBpm)
|
||||||
ToolboxType.MORPH_PAD -> SynthPatch.forPad(FrasilPatch.from(slot))
|
ToolboxType.MORPH_PAD -> SynthPatch.forPad(FrasilPatch.from(slot))
|
||||||
|
ToolboxType.WAVETABLE -> SynthPatch.forWave(WavePatch.from(slot, tempoBpm))
|
||||||
else -> SynthPatch.DEFAULT
|
else -> SynthPatch.DEFAULT
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The slot types whose notes a [SynthVoice] plays with a parsed [SynthPatch]. */
|
/** 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
|
private fun hasSynthPatch(type: ToolboxType?) =
|
||||||
|
type == ToolboxType.NES_SYNTH || type == ToolboxType.MORPH_PAD || type == ToolboxType.WAVETABLE
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Once per block: refresh each bus's cached synth patch (reparsing only when the
|
* Once per block: refresh each bus's cached synth patch (reparsing only when the
|
||||||
@@ -1475,6 +1513,17 @@ class AudioEngine(
|
|||||||
val tempo = proj.tempoBpm
|
val tempo = proj.tempoBpm
|
||||||
for (ch in 0 until Pattern.TRACK_COUNT) {
|
for (ch in 0 until Pattern.TRACK_COUNT) {
|
||||||
val slot = proj.toolbox.getOrNull(proj.mixer.channels[ch].instrumentSlot)
|
val slot = proj.toolbox.getOrNull(proj.mixer.channels[ch].instrumentSlot)
|
||||||
|
if (slot?.type == ToolboxType.GRAIN_CLOUD) {
|
||||||
|
if (!cloudOn[ch] || slot.version != cloudVer[ch] || tempo != cloudTempo[ch]) {
|
||||||
|
clouds[ch].setPatch(GrainPatch.from(slot, tempo))
|
||||||
|
cloudVer[ch] = slot.version
|
||||||
|
cloudTempo[ch] = tempo
|
||||||
|
}
|
||||||
|
cloudOn[ch] = true
|
||||||
|
} else if (cloudOn[ch]) {
|
||||||
|
cloudOn[ch] = false
|
||||||
|
clouds[ch].kill()
|
||||||
|
}
|
||||||
if (slot == null || !hasSynthPatch(slot.type)) { 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]) {
|
if (synthPatch[ch] == null || slot.version != synthPatchVer[ch] || tempo != synthPatchTempo[ch]) {
|
||||||
synthPatch[ch] = patchForSlot(slot, tempo)
|
synthPatch[ch] = patchForSlot(slot, tempo)
|
||||||
@@ -1489,6 +1538,12 @@ class AudioEngine(
|
|||||||
}
|
}
|
||||||
// Editor audition voices follow the slot currently being previewed.
|
// Editor audition voices follow the slot currently being previewed.
|
||||||
val aslot = proj.toolbox.getOrNull(auditionSlotIdx)
|
val aslot = proj.toolbox.getOrNull(auditionSlotIdx)
|
||||||
|
if (aslot?.type == ToolboxType.GRAIN_CLOUD &&
|
||||||
|
(aslot.version != auditionCloudVer || tempo != auditionCloudTempo)) {
|
||||||
|
auditionCloud.setPatch(GrainPatch.from(aslot, tempo))
|
||||||
|
auditionCloudVer = aslot.version
|
||||||
|
auditionCloudTempo = tempo
|
||||||
|
}
|
||||||
if (aslot != null && hasSynthPatch(aslot.type)) {
|
if (aslot != null && hasSynthPatch(aslot.type)) {
|
||||||
if (auditionPatch == null || aslot.version != auditionPatchVer || tempo != auditionPatchTempo) {
|
if (auditionPatch == null || aslot.version != auditionPatchVer || tempo != auditionPatchTempo) {
|
||||||
auditionPatch = patchForSlot(aslot, tempo)
|
auditionPatch = patchForSlot(aslot, tempo)
|
||||||
@@ -1503,6 +1558,7 @@ class AudioEngine(
|
|||||||
sampleRate * (60.0 / proj.tempoBpm) / proj.timeSignature.linesPerBeat
|
sampleRate * (60.0 / proj.tempoBpm) / proj.timeSignature.linesPerBeat
|
||||||
|
|
||||||
private fun allSeqVoicesOff() {
|
private fun allSeqVoicesOff() {
|
||||||
|
clouds.forEach { it.releaseSequenced() }
|
||||||
seqVoices.forEach { it.noteOff() }
|
seqVoices.forEach { it.noteOff() }
|
||||||
sampleVoices.forEach { it.noteOff() }
|
sampleVoices.forEach { it.noteOff() }
|
||||||
arps.forEach { it.stop() }
|
arps.forEach { it.stop() }
|
||||||
|
|||||||
@@ -0,0 +1,296 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
package cc.tiredsysadmin.android.sizzle.audio
|
||||||
|
|
||||||
|
import kotlin.math.PI
|
||||||
|
import kotlin.math.exp
|
||||||
|
import kotlin.math.max
|
||||||
|
import kotlin.math.pow
|
||||||
|
import kotlin.math.sin
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Grain Cloud's built-in sources: ten short recordings synthesised here, so the
|
||||||
|
* app ships no audio files. Each is about six seconds at [RATE], mono, its pitched
|
||||||
|
* material on C (a note C4 plays a source at its own pitch). Deterministic: the same
|
||||||
|
* code makes the same sound on every device.
|
||||||
|
*
|
||||||
|
* ECHOFIELD's own factory sounds come from a generator outside its public
|
||||||
|
* repository; these are new sounds after its names (felt piano, bowed glass, music
|
||||||
|
* box …), not copies.
|
||||||
|
*
|
||||||
|
* Generated off the audio thread: [prewarm] at startup renders them all in the
|
||||||
|
* background (about a second of CPU); [get] never blocks and returns null until a
|
||||||
|
* sound is ready, so the audio thread can ask every block.
|
||||||
|
*/
|
||||||
|
object GrainSources {
|
||||||
|
|
||||||
|
const val RATE = 24_000
|
||||||
|
private const val SECONDS = 6.0
|
||||||
|
private val N = (RATE * SECONDS).toInt()
|
||||||
|
|
||||||
|
private val cache = java.util.concurrent.ConcurrentHashMap<String, SampleStore.Sample>()
|
||||||
|
@Volatile private var started = false
|
||||||
|
|
||||||
|
fun get(name: String): SampleStore.Sample? = cache[name]
|
||||||
|
|
||||||
|
/** Render every source on a background thread (once). */
|
||||||
|
fun prewarm() {
|
||||||
|
if (started) return
|
||||||
|
started = true
|
||||||
|
Thread({ prewarmBlocking() }, "sizzle-grain-sources").apply { priority = Thread.MIN_PRIORITY; isDaemon = true }.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Render every source now, on this thread (tests, or a caller already off the UI). */
|
||||||
|
fun prewarmBlocking() {
|
||||||
|
for ((name, make) in RECIPES) if (!cache.containsKey(name)) cache[name] = SampleStore.Sample(normalize(make()), RATE)
|
||||||
|
}
|
||||||
|
|
||||||
|
private val RECIPES: List<Pair<String, () -> FloatArray>> = listOf(
|
||||||
|
"Felt Piano" to ::feltPiano, "Bowed Glass" to ::bowedGlass, "Music Box" to ::musicBox,
|
||||||
|
"Warm Pad" to ::warmPad, "Strings" to ::strings, "Low Drone" to ::lowDrone,
|
||||||
|
"Rain Field" to ::rainField, "Kalimba" to ::kalimba, "Breath Choir" to ::breathChoir,
|
||||||
|
"Glass Tines" to ::glassTines,
|
||||||
|
)
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ helpers ---
|
||||||
|
private const val C4 = 261.6256
|
||||||
|
private fun hz(semisFromC4: Int) = C4 * 2.0.pow(semisFromC4 / 12.0)
|
||||||
|
private const val TAU = 2 * PI
|
||||||
|
|
||||||
|
/** A struck note: partials (ratio, level, decay per second) from [t0] with a soft
|
||||||
|
* [attack], each partial's decay scaled by its ratio for brighter-dies-first. */
|
||||||
|
private fun strike(out: FloatArray, t0: Double, f: Double, partials: Array<DoubleArray>, attack: Double, gain: Double) {
|
||||||
|
val start = (t0 * RATE).toInt()
|
||||||
|
for (p in partials) {
|
||||||
|
val fr = f * p[0]
|
||||||
|
if (fr > RATE * 0.45) continue
|
||||||
|
val w = TAU * fr / RATE
|
||||||
|
var ph = (p[0] * 1.7) % TAU
|
||||||
|
for (i in start until N) {
|
||||||
|
val t = (i - start).toDouble() / RATE
|
||||||
|
val env = (if (t < attack) t / attack else 1.0) * exp(-p[2] * t)
|
||||||
|
if (env < 1e-4 && t > attack) break
|
||||||
|
out[i] += (gain * p[1] * env * sin(ph)).toFloat()
|
||||||
|
ph += w
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A band-limited saw by its harmonics, with a slow vibrato. */
|
||||||
|
private fun saw(out: FloatArray, f: Double, gain: Double, vibHz: Double, vibCents: Double, phase: Double, ampEnv: (Double) -> Double) {
|
||||||
|
val maxK = max(1, ((RATE * 0.45) / f).toInt()).coerceAtMost(40)
|
||||||
|
val phs = DoubleArray(maxK) { phase * (it + 1) }
|
||||||
|
for (i in 0 until N) {
|
||||||
|
val t = i.toDouble() / RATE
|
||||||
|
val fm = f * 2.0.pow(vibCents * sin(TAU * vibHz * t + phase) / 1200.0)
|
||||||
|
var s = 0.0
|
||||||
|
for (k in 1..maxK) {
|
||||||
|
phs[k - 1] += TAU * fm * k / RATE
|
||||||
|
s += sin(phs[k - 1]) / k
|
||||||
|
}
|
||||||
|
out[i] += (gain * ampEnv(t) * s).toFloat()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Rng(var s: Int) {
|
||||||
|
fun next(): Int { var x = s; x = x xor (x shl 13); x = x xor (x ushr 17); x = x xor (x shl 5); s = x; return x }
|
||||||
|
fun f(): Double = (next() ushr 8) / 16777216.0
|
||||||
|
fun b(): Double = f() * 2 - 1
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A two-pole resonant band-pass (RBJ, constant peak gain) run over [x]. */
|
||||||
|
private fun bandpass(x: FloatArray, f: Double, q: Double): FloatArray {
|
||||||
|
val w = TAU * f / RATE
|
||||||
|
val alpha = sin(w) / (2 * q)
|
||||||
|
val a0 = 1 + alpha
|
||||||
|
val b0 = alpha / a0; val b2 = -alpha / a0
|
||||||
|
val a1 = -2 * kotlin.math.cos(w) / a0; val a2 = (1 - alpha) / a0
|
||||||
|
val y = FloatArray(x.size)
|
||||||
|
var x1 = 0.0; var x2 = 0.0; var y1 = 0.0; var y2 = 0.0
|
||||||
|
for (i in x.indices) {
|
||||||
|
val v = b0 * x[i] + b2 * x2 - a1 * y1 - a2 * y2
|
||||||
|
x2 = x1; x1 = x[i].toDouble(); y2 = y1; y1 = v
|
||||||
|
y[i] = v.toFloat()
|
||||||
|
}
|
||||||
|
return y
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun lowpass(x: FloatArray, f: Double) {
|
||||||
|
val a = 1 - exp(-TAU * f / RATE)
|
||||||
|
var z = 0.0
|
||||||
|
for (i in x.indices) { z += a * (x[i] - z); x[i] = z.toFloat() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun normalize(x: FloatArray): FloatArray {
|
||||||
|
var pk = 1e-9f
|
||||||
|
for (v in x) pk = max(pk, kotlin.math.abs(v))
|
||||||
|
val g = 0.89f / pk
|
||||||
|
val fade = RATE / 50
|
||||||
|
for (i in x.indices) {
|
||||||
|
var e = 1f
|
||||||
|
if (i < fade) e = i.toFloat() / fade
|
||||||
|
if (i > x.size - fade) e = (x.size - i).toFloat() / fade
|
||||||
|
x[i] *= g * e
|
||||||
|
}
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ recipes ---
|
||||||
|
private val PENT = intArrayOf(0, 2, 4, 7, 9, 12, 14, 16, 19, 21, 24)
|
||||||
|
|
||||||
|
private fun feltPiano(): FloatArray {
|
||||||
|
val out = FloatArray(N)
|
||||||
|
val partials = Array(8) { k -> doubleArrayOf(k + 1.0 + 0.0008 * (k + 1) * (k + 1), 1.0 / (k + 1).toDouble().pow(1.6), 0.9 + 0.7 * k) }
|
||||||
|
val melody = intArrayOf(0, 7, 4, 11, 2, 9, 7, 16, 12, 4, 14, 7)
|
||||||
|
for ((n, st) in melody.withIndex()) strike(out, 0.05 + n * 0.48, hz(st), partials, 0.006, 0.6)
|
||||||
|
lowpass(out, 3200.0)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun bowedGlass(): FloatArray {
|
||||||
|
val out = FloatArray(N)
|
||||||
|
val ratios = doubleArrayOf(1.0, 2.32, 4.25, 6.63)
|
||||||
|
val levels = doubleArrayOf(1.0, 0.45, 0.22, 0.1)
|
||||||
|
for (k in ratios.indices) {
|
||||||
|
val f = hz(12) * ratios[k]
|
||||||
|
var ph = k * 0.9
|
||||||
|
for (i in 0 until N) {
|
||||||
|
val t = i.toDouble() / RATE
|
||||||
|
val env = (1 - exp(-t / 1.2)) * (0.85 + 0.15 * sin(TAU * 0.23 * t + k))
|
||||||
|
val vib = 1 + 0.0015 * sin(TAU * 4.6 * t)
|
||||||
|
ph += TAU * f * vib / RATE
|
||||||
|
out[i] += (levels[k] * env * sin(ph)).toFloat()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun musicBox(): FloatArray {
|
||||||
|
val out = FloatArray(N)
|
||||||
|
val partials = arrayOf(doubleArrayOf(1.0, 1.0, 1.4), doubleArrayOf(3.01, 0.32, 3.5), doubleArrayOf(5.4, 0.14, 6.0), doubleArrayOf(8.9, 0.05, 9.0))
|
||||||
|
val melody = intArrayOf(12, 16, 19, 24, 21, 19, 16, 14, 12, 19, 16, 24, 26, 24)
|
||||||
|
for ((n, st) in melody.withIndex()) strike(out, 0.04 + n * 0.41, hz(st), partials, 0.002, 0.5)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun kalimba(): FloatArray {
|
||||||
|
val out = FloatArray(N)
|
||||||
|
val partials = arrayOf(doubleArrayOf(1.0, 1.0, 1.1), doubleArrayOf(5.93, 0.22, 7.0), doubleArrayOf(13.4, 0.06, 14.0))
|
||||||
|
val rng = Rng(0x51A1)
|
||||||
|
var t = 0.03
|
||||||
|
while (t < SECONDS - 0.8) {
|
||||||
|
strike(out, t, hz(PENT[(rng.f() * 8).toInt()]), partials, 0.003, 0.55)
|
||||||
|
t += 0.28 + 0.3 * rng.f()
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun glassTines(): FloatArray {
|
||||||
|
val out = FloatArray(N)
|
||||||
|
val partials = arrayOf(doubleArrayOf(1.0, 1.0, 0.8), doubleArrayOf(2.756, 0.4, 1.6), doubleArrayOf(5.404, 0.18, 2.8), doubleArrayOf(8.93, 0.07, 4.0))
|
||||||
|
val rng = Rng(0x7123)
|
||||||
|
var t = 0.02
|
||||||
|
while (t < SECONDS - 0.6) {
|
||||||
|
strike(out, t, hz(12 + PENT[(rng.f() * 9).toInt()]), partials, 0.002, 0.4)
|
||||||
|
t += 0.17 + 0.25 * rng.f()
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun warmPad(): FloatArray {
|
||||||
|
val out = FloatArray(N)
|
||||||
|
val chord = intArrayOf(-12, 0, 4, 7, 11, 14)
|
||||||
|
for ((n, st) in chord.withIndex()) for (d in 0 until 2) {
|
||||||
|
val det = if (d == 0) -6.0 else 6.0
|
||||||
|
saw(out, hz(st) * 2.0.pow(det / 1200), 0.18, 0.2 + 0.05 * n, 4.0, n * 0.7 + d, { t -> (1 - exp(-t / 0.8)) })
|
||||||
|
}
|
||||||
|
// a slow opening low-pass: three passes at a cutoff that rises over the sound
|
||||||
|
val a = FloatArray(N); System.arraycopy(out, 0, a, 0, N)
|
||||||
|
var z1 = 0.0; var z2 = 0.0
|
||||||
|
for (i in 0 until N) {
|
||||||
|
val t = i.toDouble() / RATE
|
||||||
|
val fc = 500 + 1800 * (0.5 - 0.5 * kotlin.math.cos(TAU * t / SECONDS))
|
||||||
|
val k = 1 - exp(-TAU * fc / RATE)
|
||||||
|
z1 += k * (a[i] - z1); z2 += k * (z1 - z2)
|
||||||
|
out[i] = z2.toFloat()
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun strings(): FloatArray {
|
||||||
|
val out = FloatArray(N)
|
||||||
|
val voices = intArrayOf(-12, -5, 0, 4, 7)
|
||||||
|
for ((n, st) in voices.withIndex()) for (d in 0 until 3) {
|
||||||
|
val det = (d - 1) * 7.0
|
||||||
|
saw(out, hz(st) * 2.0.pow(det / 1200), 0.14, 5.1 + 0.4 * d, 9.0, n * 1.3 + d * 0.5,
|
||||||
|
{ t -> (1 - exp(-t / 0.45)) * (0.8 + 0.2 * sin(TAU * 0.3 * t + n)) })
|
||||||
|
}
|
||||||
|
lowpass(out, 2600.0); lowpass(out, 5000.0)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun lowDrone(): FloatArray {
|
||||||
|
val out = FloatArray(N)
|
||||||
|
val parts = arrayOf(doubleArrayOf(hz(-24), 1.0), doubleArrayOf(hz(-24) * 2.003, 0.5), doubleArrayOf(hz(-17), 0.55),
|
||||||
|
doubleArrayOf(hz(-17) * 2.0, 0.25), doubleArrayOf(hz(-12) * 1.002, 0.3), doubleArrayOf(hz(-24) * 3.0, 0.18))
|
||||||
|
for ((n, p) in parts.withIndex()) {
|
||||||
|
var ph = n * 1.1
|
||||||
|
for (i in 0 until N) {
|
||||||
|
val t = i.toDouble() / RATE
|
||||||
|
ph += TAU * p[0] / RATE
|
||||||
|
val am = 0.75 + 0.25 * sin(TAU * (0.11 + 0.07 * n) * t + n)
|
||||||
|
out[i] += (p[1] * am * (sin(ph) + 0.15 * sin(2 * ph))).toFloat()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun breathChoir(): FloatArray {
|
||||||
|
val rng = Rng(0x0B2E)
|
||||||
|
val noise = FloatArray(N) { rng.b().toFloat() }
|
||||||
|
// a voiced source under the breath: a soft buzz at C4 and its fifth
|
||||||
|
val buzz = FloatArray(N)
|
||||||
|
saw(buzz, hz(0), 0.25, 5.0, 8.0, 0.0, { t -> 1 - exp(-t / 0.6) })
|
||||||
|
saw(buzz, hz(7), 0.18, 4.6, 8.0, 1.0, { t -> 1 - exp(-t / 0.9) })
|
||||||
|
val src = FloatArray(N) { noise[it] * 0.6f + buzz[it] }
|
||||||
|
// "ah" formants drifting toward "oh"
|
||||||
|
val f1 = bandpass(src, 750.0, 6.0); val f2 = bandpass(src, 1150.0, 8.0); val f3 = bandpass(src, 2600.0, 10.0)
|
||||||
|
val g1 = bandpass(src, 500.0, 6.0); val g2 = bandpass(src, 900.0, 8.0)
|
||||||
|
val out = FloatArray(N)
|
||||||
|
for (i in 0 until N) {
|
||||||
|
val t = i.toDouble() / RATE
|
||||||
|
val m = 0.5 - 0.5 * kotlin.math.cos(TAU * t / SECONDS)
|
||||||
|
val swell = (1 - exp(-t / 0.7)) * (0.7 + 0.3 * sin(TAU * 0.4 * t))
|
||||||
|
out[i] = (swell * ((1 - m) * (f1[i] + 0.7 * f2[i]) + m * (g1[i] + 0.6 * g2[i]) + 0.3 * f3[i])).toFloat()
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun rainField(): FloatArray {
|
||||||
|
val out = FloatArray(N)
|
||||||
|
val rng = Rng(0x2A1F)
|
||||||
|
// the bed: soft filtered noise
|
||||||
|
var z = 0.0; var z2 = 0.0
|
||||||
|
for (i in 0 until N) {
|
||||||
|
z += 0.08 * (rng.b() - z); z2 += 0.3 * (z - z2)
|
||||||
|
out[i] = (0.5 * (z - 0.6 * z2)).toFloat()
|
||||||
|
}
|
||||||
|
// drops: short pitched blips at random
|
||||||
|
var t = 0.0
|
||||||
|
while (t < SECONDS - 0.1) {
|
||||||
|
val f = 900 + 3200 * rng.f()
|
||||||
|
val start = (t * RATE).toInt()
|
||||||
|
val a = 0.15 + 0.35 * rng.f()
|
||||||
|
var ph = 0.0
|
||||||
|
for (i in start until minOf(N, start + RATE / 10)) {
|
||||||
|
val tt = (i - start).toDouble() / RATE
|
||||||
|
ph += TAU * f * (1 + 0.6 * exp(-tt * 60)) / RATE
|
||||||
|
out[i] += (a * exp(-tt * 55) * sin(ph)).toFloat()
|
||||||
|
}
|
||||||
|
t += 0.01 + 0.08 * rng.f().pow(2.0)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
package cc.tiredsysadmin.android.sizzle.audio
|
package cc.tiredsysadmin.android.sizzle.audio
|
||||||
|
|
||||||
import cc.tiredsysadmin.android.sizzle.frasil.FrasilPatch
|
import cc.tiredsysadmin.android.sizzle.frasil.FrasilPatch
|
||||||
|
import cc.tiredsysadmin.android.sizzle.wavetable.WavePatch
|
||||||
import cc.tiredsysadmin.android.sizzle.model.SynthDefs
|
import cc.tiredsysadmin.android.sizzle.model.SynthDefs
|
||||||
import cc.tiredsysadmin.android.sizzle.model.TimeDivision
|
import cc.tiredsysadmin.android.sizzle.model.TimeDivision
|
||||||
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
|
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
|
||||||
@@ -45,6 +46,8 @@ class SynthPatch(
|
|||||||
/** Set for a Morph Pad slot: the voice then plays FRASIL's drone voice from this
|
/** 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. */
|
* instead of the subtractive path (see [SynthVoice]); everything above is unused. */
|
||||||
val pad: FrasilPatch? = null,
|
val pad: FrasilPatch? = null,
|
||||||
|
/** Set for a Wavetable slot: the voice plays [WaveVoice] from this. */
|
||||||
|
val wave: WavePatch? = null,
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
const val OSC_COUNT = SynthDefs.OSC_COUNT
|
const val OSC_COUNT = SynthDefs.OSC_COUNT
|
||||||
@@ -106,5 +109,11 @@ class SynthPatch(
|
|||||||
SynthPatch(oscWave, oscOct, oscSemi, oscFine, oscLevel, noiseLevel, cutoff, resonance, keytrack,
|
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)
|
filterEnvAmt, fA, fD, fS, fR, aA, aD, aS, aR, lfoWave, lfoHz, lfoPhase, modSrc, modDst, modAmt, pad)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A Wavetable patch: the default synth fields, carrying [wave]. */
|
||||||
|
fun forWave(wave: WavePatch): 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, null, wave)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
package cc.tiredsysadmin.android.sizzle.audio
|
package cc.tiredsysadmin.android.sizzle.audio
|
||||||
|
|
||||||
import cc.tiredsysadmin.android.sizzle.frasil.FrasilVoice
|
import cc.tiredsysadmin.android.sizzle.frasil.FrasilVoice
|
||||||
|
import cc.tiredsysadmin.android.sizzle.wavetable.WaveVoice
|
||||||
import kotlin.math.abs
|
import kotlin.math.abs
|
||||||
import kotlin.math.exp
|
import kotlin.math.exp
|
||||||
import kotlin.math.sin
|
import kotlin.math.sin
|
||||||
@@ -72,30 +73,43 @@ class SynthVoice(private val sampleRate: Int) {
|
|||||||
private val ampEnv = Adsr()
|
private val ampEnv = Adsr()
|
||||||
private val filtEnv = Adsr()
|
private val filtEnv = Adsr()
|
||||||
|
|
||||||
// A Morph Pad note plays FRASIL's drone voice instead of the subtractive path. It
|
// A Morph Pad note plays FRASIL's drone voice, a Wavetable note the wavetable
|
||||||
// lives inside this class so every synth pool (sequencer, mix-bus, audition) can
|
// voice, instead of the subtractive path. They live inside this class so every
|
||||||
// play a pad with no change to how voices are allocated, stolen or released.
|
// synth pool (sequencer, mix-bus, audition) plays them with no change to how
|
||||||
|
// voices are allocated, stolen or released. [mode]: MODE_SYNTH / _PAD / _WAVE.
|
||||||
private val pad = FrasilVoice(sampleRate)
|
private val pad = FrasilVoice(sampleRate)
|
||||||
private var padMode = false
|
private val wave = WaveVoice(sampleRate)
|
||||||
|
private var mode = MODE_SYNTH
|
||||||
|
private val padMode get() = mode == MODE_PAD
|
||||||
|
|
||||||
val isActive: Boolean get() = if (padMode) pad.isActive else ampEnv.active
|
val isActive: Boolean get() = when (mode) { MODE_PAD -> pad.isActive; MODE_WAVE -> wave.isActive; else -> ampEnv.active }
|
||||||
/** Gate is still open (attack/decay/sustain) — the note is *held*. A voice in its
|
/** 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
|
* 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
|
* 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). */
|
* out (which otherwise leaves the held note stuck under rapid re-tapping). */
|
||||||
val isGated: Boolean get() = if (padMode) pad.isGated else ampEnv.gateOpen
|
val isGated: Boolean get() = when (mode) { MODE_PAD -> pad.isGated; MODE_WAVE -> wave.isGated; else -> ampEnv.gateOpen }
|
||||||
|
|
||||||
/** Start (or steal-and-restart) this voice with the given [patch]. */
|
/** Start (or steal-and-restart) this voice with the given [patch]. */
|
||||||
fun noteOn(midi: Int, velocity: Int, patch: SynthPatch) {
|
fun noteOn(midi: Int, velocity: Int, patch: SynthPatch) {
|
||||||
val padPatch = patch.pad
|
val padPatch = patch.pad
|
||||||
|
val wavePatch = patch.wave
|
||||||
|
val want = if (padPatch != null) MODE_PAD else if (wavePatch != null) MODE_WAVE else MODE_SYNTH
|
||||||
|
if (want != mode) { // a slot switched kinds: the old engine stops
|
||||||
|
ampEnv.kill(); filtEnv.kill(); pad.kill(); wave.kill()
|
||||||
|
mode = want
|
||||||
|
}
|
||||||
if (padPatch != null) {
|
if (padPatch != null) {
|
||||||
if (!padMode) { ampEnv.kill(); filtEnv.kill(); padMode = true }
|
|
||||||
this.patch = patch
|
this.patch = patch
|
||||||
pitch = midi
|
pitch = midi
|
||||||
pad.noteOn(midi, velocity / 127f, padPatch)
|
pad.noteOn(midi, velocity / 127f, padPatch)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (padMode) { pad.kill(); padMode = false }
|
if (wavePatch != null) {
|
||||||
|
this.patch = patch
|
||||||
|
pitch = midi
|
||||||
|
wave.noteOn(midi, velocity / 127f, wavePatch)
|
||||||
|
return
|
||||||
|
}
|
||||||
this.patch = patch
|
this.patch = patch
|
||||||
pitch = midi
|
pitch = midi
|
||||||
this.velocity = (velocity / 127f).coerceIn(0f, 1f)
|
this.velocity = (velocity / 127f).coerceIn(0f, 1f)
|
||||||
@@ -114,12 +128,15 @@ class SynthVoice(private val sampleRate: Int) {
|
|||||||
computeTuning()
|
computeTuning()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun noteOff() { if (padMode) pad.noteOff() else { ampEnv.gateOff(); filtEnv.gateOff() } }
|
fun noteOff() {
|
||||||
|
when (mode) { MODE_PAD -> pad.noteOff(); MODE_WAVE -> wave.noteOff(); else -> { ampEnv.gateOff(); filtEnv.gateOff() } }
|
||||||
|
}
|
||||||
|
|
||||||
/** Hard stop with no release tail (transport stop / voice steal). */
|
/** Hard stop with no release tail (transport stop / voice steal). */
|
||||||
fun kill() {
|
fun kill() {
|
||||||
ampEnv.kill(); filtEnv.kill()
|
ampEnv.kill(); filtEnv.kill()
|
||||||
pad.kill()
|
pad.kill()
|
||||||
|
wave.kill()
|
||||||
pitch = -1
|
pitch = -1
|
||||||
ownerTrack = -1
|
ownerTrack = -1
|
||||||
icB = 0f; icL = 0f
|
icB = 0f; icL = 0f
|
||||||
@@ -132,10 +149,12 @@ class SynthVoice(private val sampleRate: Int) {
|
|||||||
fun setPatch(p: SynthPatch) {
|
fun setPatch(p: SynthPatch) {
|
||||||
if (p === patch) return
|
if (p === patch) return
|
||||||
val padPatch = p.pad
|
val padPatch = p.pad
|
||||||
if (padMode || padPatch != null) {
|
val wavePatch = p.wave
|
||||||
// Only within the same kind: a pad note follows pad edits, a synth note synth
|
if (mode != MODE_SYNTH || padPatch != null || wavePatch != null) {
|
||||||
// edits; a slot switched between the two takes effect on the next note.
|
// Only within the same kind: a pad note follows pad edits, a wavetable note
|
||||||
if (padMode && padPatch != null) { patch = p; pad.setPatch(padPatch) }
|
// wavetable edits; a slot switched between kinds takes effect on the next note.
|
||||||
|
if (mode == MODE_PAD && padPatch != null) { patch = p; pad.setPatch(padPatch) }
|
||||||
|
if (mode == MODE_WAVE && wavePatch != null) { patch = p; wave.setPatch(wavePatch) }
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
patch = p
|
patch = p
|
||||||
@@ -154,7 +173,8 @@ class SynthVoice(private val sampleRate: Int) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun render(): Float {
|
fun render(): Float {
|
||||||
if (padMode) return pad.render()
|
if (mode == MODE_PAD) return pad.render()
|
||||||
|
if (mode == MODE_WAVE) return wave.render()
|
||||||
if (!ampEnv.active) return 0f
|
if (!ampEnv.active) return 0f
|
||||||
val dt = 1f / sampleRate
|
val dt = 1f / sampleRate
|
||||||
val ampE = ampEnv.advance(dt)
|
val ampE = ampEnv.advance(dt)
|
||||||
@@ -346,6 +366,9 @@ class SynthVoice(private val sampleRate: Int) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
private const val MODE_SYNTH = 0
|
||||||
|
private const val MODE_PAD = 1
|
||||||
|
private const val MODE_WAVE = 2
|
||||||
private const val OUT_GAIN = 0.5f
|
private const val OUT_GAIN = 0.5f
|
||||||
private const val CTRL_INTERVAL = 16 // samples between cutoff recomputes
|
private const val CTRL_INTERVAL = 16 // samples between cutoff recomputes
|
||||||
/** One-pole time constant for amp modulation. Long enough to band-limit a
|
/** One-pole time constant for amp modulation. Long enough to band-limit a
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Philip Bos (ECHOFIELD)
|
||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown (Kotlin port for Sizzle)
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
//
|
||||||
|
// Ported from ECHOFIELD FM-1 (https://github.com/Philip-Bos/echofield-fm1, commit 4734e97):
|
||||||
|
// app/params.c (the parameters, their ranges and defaults) and app/presets.c (the
|
||||||
|
// factory presets). The MIT licence text is in LICENSES/MIT.txt of this repository.
|
||||||
|
|
||||||
|
package cc.tiredsysadmin.android.sizzle.echofield
|
||||||
|
|
||||||
|
import cc.tiredsysadmin.android.sizzle.model.ParamSpec
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Grain Cloud's settings and factory presets, taken from ECHOFIELD's granular
|
||||||
|
* engine. Keys are ECHOFIELD's own parameter names.
|
||||||
|
*
|
||||||
|
* Left out (Sizzle has its own, or they need stereo): ECHOFIELD's effects (filter,
|
||||||
|
* drive, echo, reverb + shimmer, tape), WIDTH, the DRIFT ORACLE (it plays notes by
|
||||||
|
* itself while no key is held), LATCH and the performance effects. Kept as a
|
||||||
|
* setting: FREEZE. Added for Sizzle: SOURCE (a built-in sound or your own sample).
|
||||||
|
*/
|
||||||
|
object EchofieldDefs {
|
||||||
|
|
||||||
|
val MODES = listOf("Cloud", "Dust", "Tape", "Bloom", "Pulse", "Drift")
|
||||||
|
val WINDOWS = listOf("Auto", "Hann", "Tukey", "Perc", "Swell", "Gauss")
|
||||||
|
const val CUSTOM = "Custom"
|
||||||
|
|
||||||
|
/** The built-in sources (synthesised by Sizzle, see GrainSources), then your own. */
|
||||||
|
val SOURCES = listOf(
|
||||||
|
"Felt Piano", "Bowed Glass", "Music Box", "Warm Pad", "Strings",
|
||||||
|
"Low Drone", "Rain Field", "Kalimba", "Breath Choir", "Glass Tines", CUSTOM,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Where a custom sample's id and its file live: the same keys the SF2/XI loader
|
||||||
|
* uses, so the preset library, project bundles and startup rehydration carry it. */
|
||||||
|
const val SAMPLE_KEY = "sfSample"
|
||||||
|
|
||||||
|
val PARAMS: List<ParamSpec> by lazy {
|
||||||
|
listOf(
|
||||||
|
ParamSpec("source", "Source", choices = SOURCES),
|
||||||
|
ParamSpec("mode", "Mode", choices = MODES),
|
||||||
|
ParamSpec("position", "Position", 0.35f, 0f, 1f),
|
||||||
|
ParamSpec("texture", "Texture", 0.72f, 0f, 1f),
|
||||||
|
ParamSpec("scatter", "Scatter", 0.45f, 0f, 1f),
|
||||||
|
ParamSpec("drift", "Drift", 0.35f, 0f, 1f),
|
||||||
|
ParamSpec("motion", "Evolve", 0.35f, 0f, 1f),
|
||||||
|
ParamSpec("pitch", "Pitch", 0f, -24f, 24f, isInt = true),
|
||||||
|
ParamSpec("harmony", "Harmony", 0.30f, 0f, 1f),
|
||||||
|
ParamSpec("size_mul", "Size", 0f, -2f, 2f),
|
||||||
|
ParamSpec("dens_mul", "Density", 0f, -2f, 2f),
|
||||||
|
ParamSpec("scan", "Scan", 0f, -1f, 1f),
|
||||||
|
ParamSpec("reverse", "Reverse", 0.10f, 0f, 1f),
|
||||||
|
ParamSpec("pitch_rand", "Pitch Rnd", 0f, 0f, 12f),
|
||||||
|
ParamSpec("size_rand", "Size Rnd", 0.3f, 0f, 1f),
|
||||||
|
ParamSpec("window", "Envelope", choices = WINDOWS),
|
||||||
|
ParamSpec("grain_tone", "Tone", -0.1f, -1f, 1f),
|
||||||
|
ParamSpec("attack", "Attack", 0.15f, 0f, 1f),
|
||||||
|
ParamSpec("release", "Release", 0.45f, 0f, 1f),
|
||||||
|
ParamSpec("velo", "Velocity", 0.5f, 0f, 1f),
|
||||||
|
ParamSpec("start", "Start", 0f, 0f, 1f),
|
||||||
|
ParamSpec("end", "End", 1f, 0f, 1f),
|
||||||
|
ParamSpec("freeze", "Freeze", choices = listOf("Off", "On")),
|
||||||
|
ParamSpec("level", "Level", 0.75f, 0f, 1f),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The editor's pages: (title, keys). */
|
||||||
|
val SECTIONS: List<Pair<String, List<String>>> = listOf(
|
||||||
|
"Cloud" to listOf("source", "mode", "position", "texture", "scatter", "drift"),
|
||||||
|
"Play" to listOf("motion", "pitch", "harmony", "freeze", "level"),
|
||||||
|
"Grain" to listOf("size_mul", "dens_mul", "scan", "reverse", "window", "grain_tone"),
|
||||||
|
"Random" to listOf("pitch_rand", "size_rand"),
|
||||||
|
"Keys" to listOf("attack", "release", "velo"),
|
||||||
|
"Region" to listOf("start", "end"),
|
||||||
|
)
|
||||||
|
|
||||||
|
class Preset(val name: String, val values: Map<String, String>)
|
||||||
|
|
||||||
|
/** ECHOFIELD's 14 factory presets (presets.c FACTORY) on Sizzle's built-in sources;
|
||||||
|
* their effect settings are left out with the effects. */
|
||||||
|
val FACTORY: List<Preset> by lazy {
|
||||||
|
fun p(name: String, source: String, mode: Int, vararg v: Pair<String, Float>): Preset {
|
||||||
|
val m = LinkedHashMap<String, String>()
|
||||||
|
for (spec in PARAMS) m[spec.key] = if (spec.isEnum) spec.choices[0] else spec.default.toString()
|
||||||
|
m["source"] = source
|
||||||
|
m["mode"] = MODES[mode]
|
||||||
|
for ((k, x) in v) m[k] = x.toString()
|
||||||
|
return Preset(name, m)
|
||||||
|
}
|
||||||
|
listOf(
|
||||||
|
p("Felt Clouds", "Felt Piano", 0, "texture" to 0.78f, "scatter" to 0.50f, "drift" to 0.35f, "motion" to 0.30f, "harmony" to 0.35f),
|
||||||
|
p("Glass Choir", "Bowed Glass", 3, "texture" to 0.70f, "scatter" to 0.40f, "drift" to 0.30f, "motion" to 0.35f, "harmony" to 0.50f),
|
||||||
|
p("Dust Lights", "Music Box", 1, "texture" to 0.45f, "scatter" to 0.70f, "drift" to 0.30f, "motion" to 0.40f, "harmony" to 0.30f),
|
||||||
|
p("Warm Tide", "Warm Pad", 5, "texture" to 0.70f, "scatter" to 0.45f, "drift" to 0.55f, "motion" to 0.40f, "harmony" to 0.25f),
|
||||||
|
p("Slow Tapes", "Strings", 2, "texture" to 0.60f, "scatter" to 0.25f, "drift" to 0.40f, "motion" to 0.35f, "harmony" to 0.15f),
|
||||||
|
p("Deep Water", "Low Drone", 0, "texture" to 0.85f, "scatter" to 0.40f, "drift" to 0.40f, "motion" to 0.25f, "harmony" to 0.40f),
|
||||||
|
p("Rain Cathedral", "Rain Field", 0, "texture" to 0.88f, "scatter" to 0.60f, "drift" to 0.40f, "motion" to 0.30f, "harmony" to 0.45f),
|
||||||
|
p("Kalimba Steps", "Kalimba", 4, "texture" to 0.40f, "scatter" to 0.60f, "drift" to 0.30f, "motion" to 0.30f, "harmony" to 0.20f),
|
||||||
|
p("Hymn", "Breath Choir", 0, "texture" to 0.85f, "scatter" to 0.45f, "drift" to 0.35f, "motion" to 0.30f, "harmony" to 0.40f),
|
||||||
|
p("Breath Choir", "Breath Choir", 3, "texture" to 0.75f, "scatter" to 0.50f, "drift" to 0.40f, "motion" to 0.40f, "harmony" to 0.35f),
|
||||||
|
p("Night Current", "Low Drone", 5, "texture" to 0.65f, "scatter" to 0.40f, "drift" to 0.60f, "motion" to 0.40f),
|
||||||
|
p("Glass Rain", "Glass Tines", 1, "texture" to 0.35f, "scatter" to 0.55f, "drift" to 0.20f, "motion" to 0.50f, "pitch" to 12f, "reverse" to 0.20f, "grain_tone" to 0.40f),
|
||||||
|
p("Broken Stars", "Kalimba", 3, "texture" to 0.60f, "scatter" to 0.70f, "drift" to 0.50f, "motion" to 0.50f),
|
||||||
|
p("Far Broadcast", "Rain Field", 2, "texture" to 0.50f, "scatter" to 0.20f, "drift" to 0.40f, "motion" to 0.40f),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,702 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Philip Bos (ECHOFIELD)
|
||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown (Kotlin port for Sizzle)
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
//
|
||||||
|
// Ported from ECHOFIELD FM-1 (https://github.com/Philip-Bos/echofield-fm1, commit 4734e97):
|
||||||
|
// app/dsp/engine.c, its granular core (ef_window, compute_ctl, notes_track, note_pitch,
|
||||||
|
// spawn, render_grains_part, schedule, ef_render's gate and source fade, auto_level).
|
||||||
|
// The MIT licence text is in LICENSES/MIT.txt of this repository.
|
||||||
|
|
||||||
|
package cc.tiredsysadmin.android.sizzle.echofield
|
||||||
|
|
||||||
|
import cc.tiredsysadmin.android.sizzle.audio.GrainSources
|
||||||
|
import cc.tiredsysadmin.android.sizzle.audio.SampleStore
|
||||||
|
import kotlin.math.abs
|
||||||
|
import kotlin.math.cos
|
||||||
|
import kotlin.math.exp
|
||||||
|
import kotlin.math.floor
|
||||||
|
import kotlin.math.max
|
||||||
|
import kotlin.math.min
|
||||||
|
import kotlin.math.pow
|
||||||
|
import kotlin.math.sin
|
||||||
|
import kotlin.math.sqrt
|
||||||
|
|
||||||
|
/** A parsed Grain Cloud slot: its smoothed settings' targets, the source to read,
|
||||||
|
* and the song's tempo (PULSE steps on it). Built off the hot path, per slot change. */
|
||||||
|
class GrainPatch(
|
||||||
|
val p: FloatArray,
|
||||||
|
/** The built-in source's name, or null for the custom sample [sampleId]. */
|
||||||
|
val sourceName: String?,
|
||||||
|
val sampleId: String,
|
||||||
|
val tempoBpm: Float,
|
||||||
|
) {
|
||||||
|
companion object {
|
||||||
|
fun from(slot: cc.tiredsysadmin.android.sizzle.model.ToolboxSlot?, tempoBpm: Float): GrainPatch {
|
||||||
|
val p = FloatArray(GrainCloud.P_COUNT)
|
||||||
|
fun f(i: Int, key: String, def: Float) { p[i] = slot?.float(key, def) ?: def }
|
||||||
|
f(GrainCloud.P_POSITION, "position", 0.35f); f(GrainCloud.P_TEXTURE, "texture", 0.72f)
|
||||||
|
f(GrainCloud.P_SCATTER, "scatter", 0.45f); f(GrainCloud.P_DRIFT, "drift", 0.35f)
|
||||||
|
f(GrainCloud.P_MOTION, "motion", 0.35f); f(GrainCloud.P_PITCH, "pitch", 0f)
|
||||||
|
f(GrainCloud.P_HARMONY, "harmony", 0.30f); f(GrainCloud.P_SIZE_MUL, "size_mul", 0f)
|
||||||
|
f(GrainCloud.P_DENS_MUL, "dens_mul", 0f); f(GrainCloud.P_SCAN, "scan", 0f)
|
||||||
|
f(GrainCloud.P_REVERSE, "reverse", 0.10f); f(GrainCloud.P_PITCH_RAND, "pitch_rand", 0f)
|
||||||
|
f(GrainCloud.P_SIZE_RAND, "size_rand", 0.3f); f(GrainCloud.P_GRAIN_TONE, "grain_tone", -0.1f)
|
||||||
|
f(GrainCloud.P_ATTACK, "attack", 0.15f); f(GrainCloud.P_RELEASE, "release", 0.45f)
|
||||||
|
f(GrainCloud.P_VELO, "velo", 0.5f); f(GrainCloud.P_START, "start", 0f); f(GrainCloud.P_END, "end", 1f)
|
||||||
|
f(GrainCloud.P_LEVEL, "level", 0.75f)
|
||||||
|
p[GrainCloud.P_MODE] = EchofieldDefs.MODES.indexOf(slot?.string("mode", "Cloud") ?: "Cloud").coerceAtLeast(0).toFloat()
|
||||||
|
p[GrainCloud.P_WINDOW] = EchofieldDefs.WINDOWS.indexOf(slot?.string("window", "Auto") ?: "Auto").coerceAtLeast(0).toFloat()
|
||||||
|
p[GrainCloud.P_FREEZE] = if (slot?.string("freeze", "Off") == "On") 1f else 0f
|
||||||
|
val src = slot?.string("source", EchofieldDefs.SOURCES[0]) ?: EchofieldDefs.SOURCES[0]
|
||||||
|
return GrainPatch(
|
||||||
|
p, if (src == EchofieldDefs.CUSTOM) null else src,
|
||||||
|
slot?.string(EchofieldDefs.SAMPLE_KEY, "") ?: "", tempoBpm,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One mixer channel's grain cloud: ECHOFIELD's granular engine. A note doesn't get a
|
||||||
|
* voice of its own; held notes (up to [MAX_NOTES]) are handed to new grains in turn,
|
||||||
|
* and a new note fires two grains at once so the key answers. One gate (ATTACK /
|
||||||
|
* RELEASE) opens while any note is held.
|
||||||
|
*
|
||||||
|
* Six modes shape the cloud: CLOUD (long grains melting into a pad), DUST (tiny
|
||||||
|
* specks, stutters, leaps), TAPE (three loop heads at three speeds), BLOOM (slow
|
||||||
|
* swells with overtones), PULSE (soft notes on a euclidean 16-step clock, on the
|
||||||
|
* song's tempo) and DRIFT (everything wanders). Up to [MAX_GRAINS] grains, each
|
||||||
|
* with a window, a reverse chance, a colour filter and its pitch drawn at birth;
|
||||||
|
* the level follows ECHOFIELD's auto-level, so density and source don't change it.
|
||||||
|
*
|
||||||
|
* Differences from ECHOFIELD: Sizzle's channels are mono (grains are not panned),
|
||||||
|
* the source is float PCM (no ADPCM blocks), the rate is Sizzle's, PULSE follows
|
||||||
|
* the song's tempo (no clock phase), and the effects, oracle and performance
|
||||||
|
* effects are not part of it. Control runs every [SUB] frames as in ECHOFIELD;
|
||||||
|
* [render] hands out a sample at a time. Allocation-free after construction.
|
||||||
|
*/
|
||||||
|
class GrainCloud(private val fs: Int) {
|
||||||
|
|
||||||
|
private val fsf = fs.toFloat()
|
||||||
|
private var patch: GrainPatch? = null
|
||||||
|
private val sm = FloatArray(P_COUNT)
|
||||||
|
private var smPrimed = false
|
||||||
|
private val smoothA = 1f - exp(-SUB / (0.04f * fs))
|
||||||
|
private val playK = 1f - 0.99f.pow(44100f / fs)
|
||||||
|
|
||||||
|
// grains
|
||||||
|
private val gOn = BooleanArray(MAX_GRAINS)
|
||||||
|
private val gWin = IntArray(MAX_GRAINS)
|
||||||
|
private val gRev = BooleanArray(MAX_GRAINS)
|
||||||
|
private val gTone = IntArray(MAX_GRAINS)
|
||||||
|
private val gPos = DoubleArray(MAX_GRAINS)
|
||||||
|
private val gInc = DoubleArray(MAX_GRAINS)
|
||||||
|
private val gLen = IntArray(MAX_GRAINS)
|
||||||
|
private val gAge = IntArray(MAX_GRAINS)
|
||||||
|
private val gDelay = IntArray(MAX_GRAINS)
|
||||||
|
private val gWph = FloatArray(MAX_GRAINS)
|
||||||
|
private val gWstep = FloatArray(MAX_GRAINS)
|
||||||
|
private val gAmp = FloatArray(MAX_GRAINS)
|
||||||
|
private val gToneA = FloatArray(MAX_GRAINS)
|
||||||
|
private val gZ = FloatArray(MAX_GRAINS)
|
||||||
|
private val gLoad = FloatArray(MAX_GRAINS)
|
||||||
|
private var loadNow = 0f
|
||||||
|
|
||||||
|
// the source and its swap fade
|
||||||
|
private var src: SampleStore.Sample? = null
|
||||||
|
private var fadeGain = 1f
|
||||||
|
|
||||||
|
// modes
|
||||||
|
private var rng = nextSeed()
|
||||||
|
private var spawnWait = 0f; private var scan = 0f
|
||||||
|
private var walkPos = 0f; private var walkPitch = 0f; private var walkV1 = 0f; private var walkV2 = 0f
|
||||||
|
private var walkSize = 0f
|
||||||
|
private var lfo1 = 0f; private var lfo2Cur = 0f; private var lfo2Tgt = 0f; private var lfo2T = 0f
|
||||||
|
private var tapeHead = 0f; private var tapeSpeed = 1f; private var tapeStop = 0f; private var tapeK = 0
|
||||||
|
private var stutterLeft = 0; private var stutterPos = 0f
|
||||||
|
private var pulseStep = 0; private var pulseRot = 0; private var pulseAcc = 0f
|
||||||
|
private val stepPos = FloatArray(16) { rndf() }
|
||||||
|
private val stepOct = IntArray(16)
|
||||||
|
private var env = 0f
|
||||||
|
private var playGain = 0f
|
||||||
|
private var agcMs = 0f
|
||||||
|
private var agcGain = 1f
|
||||||
|
|
||||||
|
// notes: those held now (owner: the tracker track, or -1 for live input)
|
||||||
|
private val noteNum = IntArray(MAX_NOTES)
|
||||||
|
private val noteVel = IntArray(MAX_NOTES)
|
||||||
|
private val noteOwner = IntArray(MAX_NOTES)
|
||||||
|
private var nNotes = 0
|
||||||
|
private var noteSeq = 0; private var noteSeqSeen = 0
|
||||||
|
// the notes grains are born on: the ones held, or while the release sounds the last ones held
|
||||||
|
private val heldNote = IntArray(MAX_NOTES)
|
||||||
|
private val heldVel = IntArray(MAX_NOTES)
|
||||||
|
private var heldN = 0
|
||||||
|
private var noteRr = 0
|
||||||
|
|
||||||
|
// control values (ECHOFIELD's ctl_t), recomputed each sub-block
|
||||||
|
private var cSize = 0f; private var cDensity = 0f; private var cJitter = 0f; private var cCenter = 0f
|
||||||
|
private var cScatter = 0f; private var cPitchRand = 0f; private var cRevProb = 0f; private var cAmp = 1f
|
||||||
|
private var cTone = 0f; private var cToneRand = 0f; private var cWin = 0; private var cClocked = false
|
||||||
|
private var cTape = false; private var cTapeSpeed = 1f
|
||||||
|
|
||||||
|
private val bus = FloatArray(SUB)
|
||||||
|
private var pos = SUB
|
||||||
|
|
||||||
|
/** Sounding: a note held, the gate's release still open, or a grain still playing. */
|
||||||
|
val isActive: Boolean
|
||||||
|
get() {
|
||||||
|
if (nNotes > 0 || env > 0.0005f || playGain > 0.0005f) return true
|
||||||
|
for (k in 0 until MAX_GRAINS) if (gOn[k]) return true
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setPatch(p: GrainPatch) { patch = p }
|
||||||
|
|
||||||
|
fun noteOn(note: Int, velocity: Int, owner: Int = -1) {
|
||||||
|
for (k in 0 until nNotes) if (noteNum[k] == note) { noteVel[k] = velocity; noteOwner[k] = owner; noteSeq++; return }
|
||||||
|
if (nNotes == MAX_NOTES) removeAt(0) // the oldest makes room
|
||||||
|
noteNum[nNotes] = note; noteVel[nNotes] = velocity; noteOwner[nNotes] = owner
|
||||||
|
nNotes++
|
||||||
|
noteSeq++
|
||||||
|
}
|
||||||
|
|
||||||
|
fun noteOff(note: Int) {
|
||||||
|
var k = 0
|
||||||
|
while (k < nNotes) if (noteNum[k] == note) removeAt(k) else k++
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Let go of every note tracker track [owner] holds (its next note replaces them). */
|
||||||
|
fun releaseOwner(owner: Int) {
|
||||||
|
var k = 0
|
||||||
|
while (k < nNotes) if (noteOwner[k] == owner) removeAt(k) else k++
|
||||||
|
}
|
||||||
|
|
||||||
|
fun releaseAll() { nNotes = 0 }
|
||||||
|
|
||||||
|
/** Let go of the sequencer's notes ([owner] >= 0 or [OWNER_SEQ]), keeping live ones. */
|
||||||
|
fun releaseSequenced() {
|
||||||
|
var k = 0
|
||||||
|
while (k < nNotes) if (noteOwner[k] != OWNER_LIVE) removeAt(k) else k++
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Silence now: every grain off, no tail. */
|
||||||
|
fun kill() {
|
||||||
|
nNotes = 0; heldN = 0; env = 0f; playGain = 0f
|
||||||
|
gOn.fill(false); loadNow = 0f; pos = SUB
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun removeAt(k: Int) {
|
||||||
|
for (i in k until nNotes - 1) { noteNum[i] = noteNum[i + 1]; noteVel[i] = noteVel[i + 1]; noteOwner[i] = noteOwner[i + 1] }
|
||||||
|
nNotes--
|
||||||
|
}
|
||||||
|
|
||||||
|
fun render(): Float {
|
||||||
|
if (pos >= SUB) { block(); pos = 0 }
|
||||||
|
return bus[pos++]
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------- block ---
|
||||||
|
private fun block() {
|
||||||
|
val pt = patch
|
||||||
|
if (pt == null) { bus.fill(0f); return }
|
||||||
|
val dt = SUB / fsf
|
||||||
|
for (i in 0 until P_COUNT) {
|
||||||
|
val t = pt.p[i]
|
||||||
|
sm[i] = if (!smPrimed || i == P_MODE || i == P_WINDOW || i == P_FREEZE) t else sm[i] + (t - sm[i]) * smoothA
|
||||||
|
}
|
||||||
|
smPrimed = true
|
||||||
|
|
||||||
|
// a new source: fade out, swap, fade in
|
||||||
|
val want = (if (pt.sourceName != null) GrainSources.get(pt.sourceName) else SampleStore.get(pt.sampleId))
|
||||||
|
?.takeIf { it.data.size >= 512 }
|
||||||
|
if (want !== src) {
|
||||||
|
if (src == null || fadeGain <= 0f) {
|
||||||
|
src = want
|
||||||
|
gOn.fill(false); loadNow = 0f
|
||||||
|
tapeHead = 0f
|
||||||
|
fadeGain = 0f
|
||||||
|
} else {
|
||||||
|
fadeGain = max(0f, fadeGain - SUB / (0.02f * fsf))
|
||||||
|
}
|
||||||
|
} else if (fadeGain < 1f) {
|
||||||
|
fadeGain = min(1f, fadeGain + SUB / (0.02f * fsf))
|
||||||
|
}
|
||||||
|
|
||||||
|
// the gate: keys open it with their attack, release closes it
|
||||||
|
val atk = 0.005f * 800f.pow(sm[P_ATTACK])
|
||||||
|
val rel = 0.01f * 800f.pow(sm[P_RELEASE])
|
||||||
|
val envTarget = if (nNotes > 0) 1f else 0f
|
||||||
|
env += (envTarget - env) * min(1f, dt / (if (envTarget > env) atk else rel))
|
||||||
|
|
||||||
|
computeCtl(dt)
|
||||||
|
val s = src
|
||||||
|
if (cTape && s != null && !frozen()) {
|
||||||
|
val a = min(sm[P_START], sm[P_END]); val b = max(sm[P_START], sm[P_END])
|
||||||
|
val rlen = max(512f, (b - a) * s.data.size)
|
||||||
|
tapeHead += cTapeSpeed * SUB * (s.sampleRate / fsf) / rlen
|
||||||
|
tapeHead -= floor(tapeHead)
|
||||||
|
}
|
||||||
|
bus.fill(0f)
|
||||||
|
if (want === src) schedule()
|
||||||
|
renderGrains()
|
||||||
|
for (i in 0 until SUB) {
|
||||||
|
playGain += (env - playGain) * playK
|
||||||
|
bus[i] *= playGain * fadeGain
|
||||||
|
}
|
||||||
|
autoLevel()
|
||||||
|
val level = sm[P_LEVEL] * OUT_GAIN
|
||||||
|
for (i in 0 until SUB) {
|
||||||
|
val y = bus[i] * level
|
||||||
|
bus[i] = if (y.isFinite()) y else 0f
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun frozen() = sm[P_FREEZE] >= 0.5f
|
||||||
|
|
||||||
|
private fun regionSeconds(): Float {
|
||||||
|
val s = src ?: return 1f
|
||||||
|
val a = min(sm[P_START], sm[P_END]); val b = max(sm[P_START], sm[P_END])
|
||||||
|
return (b - a) * s.data.size / s.sampleRate
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun computeCtl(dt: Float) {
|
||||||
|
val mode = sm[P_MODE].toInt()
|
||||||
|
val t = sm[P_TEXTURE]; val sc = sm[P_SCATTER]; val d = sm[P_DRIFT]; val m = sm[P_MOTION]
|
||||||
|
val sizeMul = 2f.pow(sm[P_SIZE_MUL]); val densMul = 2f.pow(sm[P_DENS_MUL])
|
||||||
|
if (!frozen()) {
|
||||||
|
lfo1 += dt * (0.03f + 0.3f * m)
|
||||||
|
if (lfo1 > 1f) lfo1 -= 1f
|
||||||
|
lfo2T += dt * (0.1f + 1.5f * m)
|
||||||
|
if (lfo2T >= 1f) { lfo2T -= 1f; lfo2Tgt = rndb() }
|
||||||
|
lfo2Cur += (lfo2Tgt - lfo2Cur) * min(1f, dt * (0.5f + 3f * m))
|
||||||
|
val wr = (if (mode == MODE_DRIFT) 0.25f + 1.2f * m else 0.08f + 0.4f * m) * dt
|
||||||
|
walkV1 += rndb() * wr * 2f - walkV1 * wr * 2f
|
||||||
|
walkPos = (walkPos + walkV1 * wr * 4f - walkPos * wr * 0.3f).coerceIn(-1f, 1f)
|
||||||
|
walkV2 += rndb() * wr * 2f - walkV2 * wr * 2f
|
||||||
|
walkPitch = (walkPitch + walkV2 * wr * 4f - walkPitch * wr * 0.3f).coerceIn(-1f, 1f)
|
||||||
|
walkSize += (rndb() - walkSize) * dt * 0.3f
|
||||||
|
if (src != null) {
|
||||||
|
scan += sm[P_SCAN] * dt / max(0.05f, abs(regionSeconds()))
|
||||||
|
scan -= floor(scan)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val lfo = sin(TWO_PI * lfo1)
|
||||||
|
val pos0 = sm[P_POSITION]
|
||||||
|
cJitter = 0.5f
|
||||||
|
cPitchRand = sm[P_PITCH_RAND] + 0.08f + d * 0.3f
|
||||||
|
cRevProb = sm[P_REVERSE]
|
||||||
|
cAmp = 1f
|
||||||
|
cTone = sm[P_GRAIN_TONE]
|
||||||
|
cToneRand = 0f
|
||||||
|
cWin = WIN_HANN
|
||||||
|
cClocked = false
|
||||||
|
cTape = false
|
||||||
|
cTapeSpeed = 1f
|
||||||
|
val wander = d * 0.3f * walkPos
|
||||||
|
when (mode) {
|
||||||
|
MODE_DUST -> {
|
||||||
|
cSize = 0.02f * (200f / 20f).pow(t)
|
||||||
|
cDensity = (6f + 24f * (1f - t * 0.5f)) * (0.5f + sc)
|
||||||
|
cJitter = 0.7f + 0.3f * sc
|
||||||
|
cCenter = pos0 + 0.1f * m * lfo + wander
|
||||||
|
cScatter = 0.1f + 0.85f * sc
|
||||||
|
cRevProb += 0.2f + 0.3f * sc
|
||||||
|
cWin = WIN_GAUSS
|
||||||
|
cAmp = 0.85f
|
||||||
|
cTone = (sm[P_GRAIN_TONE] + 0.25f).coerceIn(-1f, 1f)
|
||||||
|
cToneRand = 0.3f
|
||||||
|
}
|
||||||
|
MODE_TAPE -> {
|
||||||
|
var target = semis(sm[P_PITCH]) * lerp(1f, 0.3f, t.pow(1.2f))
|
||||||
|
target *= 1f + 0.03f * m * lfo2Cur + 0.02f * d * walkPitch
|
||||||
|
if (!frozen() && tapeStop <= 0f && rndf() < m * 0.02f * dt) tapeStop = 1.6f
|
||||||
|
if (tapeStop > 0f) {
|
||||||
|
tapeStop -= dt
|
||||||
|
val ph = 1.6f - tapeStop
|
||||||
|
target *= if (ph < 0.8f) 1f - ph / 0.8f else (ph - 0.8f) / 0.8f
|
||||||
|
target = max(target, 0.02f)
|
||||||
|
}
|
||||||
|
tapeSpeed += (target - tapeSpeed) * min(1f, dt * 6f)
|
||||||
|
cTape = true
|
||||||
|
cTapeSpeed = tapeSpeed
|
||||||
|
cSize = 0.18f * (1f + t)
|
||||||
|
cDensity = 4f / cSize
|
||||||
|
cJitter = 0.15f
|
||||||
|
cCenter = tapeHead
|
||||||
|
cScatter = 0.002f + sc * 0.03f
|
||||||
|
cPitchRand = sm[P_PITCH_RAND]
|
||||||
|
}
|
||||||
|
MODE_BLOOM -> {
|
||||||
|
cSize = 0.6f * (2.5f / 0.6f).pow(t)
|
||||||
|
cDensity = (3f + 3f * t) / cSize * (1f + 0.5f * m * lfo2Cur)
|
||||||
|
cJitter = 0.9f
|
||||||
|
cCenter = pos0 + 0.2f * m * lfo + wander
|
||||||
|
cScatter = 0.08f + 0.5f * sc
|
||||||
|
cRevProb += 0.25f
|
||||||
|
cTone = (sm[P_GRAIN_TONE] + 0.15f).coerceIn(-1f, 1f)
|
||||||
|
cToneRand = 0.25f
|
||||||
|
cWin = if (rndf() < 0.5f) WIN_HANN else WIN_GAUSS
|
||||||
|
cAmp = 0.95f
|
||||||
|
}
|
||||||
|
MODE_PULSE -> {
|
||||||
|
cClocked = true
|
||||||
|
cSize = 0.06f * (1200f / 60f).pow(t)
|
||||||
|
cDensity = 0f
|
||||||
|
cCenter = pos0 + wander
|
||||||
|
cScatter = sc
|
||||||
|
cWin = if (t > 0.6f) WIN_HANN else WIN_PERC
|
||||||
|
cJitter = 0f
|
||||||
|
}
|
||||||
|
MODE_DRIFT -> {
|
||||||
|
cSize = 0.1f * 12f.pow(t) * (1f + 0.5f * walkSize)
|
||||||
|
cDensity = (2f + 4f * t) * (1f + 0.5f * lfo) / cSize
|
||||||
|
cJitter = 0.8f
|
||||||
|
cCenter = pos0 + walkPos * (0.1f + 0.5f * sc)
|
||||||
|
cScatter = 0.03f + 0.3f * sc
|
||||||
|
cPitchRand = sm[P_PITCH_RAND] + d * 0.5f
|
||||||
|
cRevProb += 0.15f
|
||||||
|
cWin = WIN_GAUSS
|
||||||
|
}
|
||||||
|
else -> { // CLOUD
|
||||||
|
cSize = 0.12f * (1500f / 120f).pow(t)
|
||||||
|
cDensity = (4f + 8f * t) / cSize * (1f + 0.4f * m * lfo2Cur)
|
||||||
|
cJitter = 0.4f + 0.6f * sc
|
||||||
|
cCenter = pos0 + 0.15f * m * lfo + wander
|
||||||
|
cScatter = 0.03f + 0.6f * sc.pow(1.3f)
|
||||||
|
cRevProb += sc * 0.1f
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cSize *= sizeMul
|
||||||
|
cDensity *= densMul
|
||||||
|
val wsel = sm[P_WINDOW].toInt()
|
||||||
|
if (wsel > 0) cWin = wsel - 1
|
||||||
|
cRevProb = cRevProb.coerceIn(0f, 1f)
|
||||||
|
cSize = cSize.coerceIn(0.004f, 2.5f)
|
||||||
|
cDensity = cDensity.coerceIn(0f, 400f)
|
||||||
|
cScatter = cScatter.coerceIn(0f, 1f)
|
||||||
|
if (!cTape) { val cc = cCenter + scan; cCenter = cc - floor(cc) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ grains ---
|
||||||
|
private fun notesTrack() {
|
||||||
|
if (nNotes == 0) return
|
||||||
|
for (k in 0 until nNotes) { heldNote[k] = noteNum[k] - 60; heldVel[k] = noteVel[k] }
|
||||||
|
heldN = nNotes
|
||||||
|
}
|
||||||
|
|
||||||
|
private var ampScale = 1f
|
||||||
|
private fun notePitch(): Float {
|
||||||
|
if (heldN == 0) return 0f
|
||||||
|
val k = (noteRr++ and 0x7FFFFFFF) % heldN
|
||||||
|
val velo = sm[P_VELO]
|
||||||
|
ampScale *= (1f - velo) + velo * heldVel[k] / 127f
|
||||||
|
return heldNote[k].toFloat()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun spawn(offset: Int, amp0: Float, extraPitch: Float, posOverride: Float) {
|
||||||
|
val s = src ?: return
|
||||||
|
val frames = s.data.size
|
||||||
|
var g = -1
|
||||||
|
var active = 0
|
||||||
|
for (i in 0 until MAX_GRAINS) if (gOn[i]) active++ else if (g < 0) g = i
|
||||||
|
if (g < 0 || active >= MAX_GRAINS) return
|
||||||
|
val ra = min(sm[P_START], sm[P_END]); val rb = max(sm[P_START], sm[P_END])
|
||||||
|
var rs = ra * frames; var re = rb * frames
|
||||||
|
if (re - rs < 512f) { re = min(frames - 1f, rs + 512f); rs = max(0f, re - 512f) }
|
||||||
|
re = min(re, frames - 2f)
|
||||||
|
val rlen = re - rs
|
||||||
|
if (rlen < 64f) return
|
||||||
|
|
||||||
|
val size = cSize * (1f + rndb() * sm[P_SIZE_RAND] * 0.7f * (if (cTape) 0.3f else 1f))
|
||||||
|
var len = (max(size, 0.003f) * fsf).toInt()
|
||||||
|
ampScale = amp0
|
||||||
|
val pitch = sm[P_PITCH] + notePitch()
|
||||||
|
var harm = 0f
|
||||||
|
if (rndf() < sm[P_HARMONY] * 0.65f) {
|
||||||
|
harm = HARMONY_IV[nextRand() and 7]
|
||||||
|
ampScale *= 0.7f
|
||||||
|
}
|
||||||
|
var step: Float
|
||||||
|
if (cTape) {
|
||||||
|
val head = tapeK
|
||||||
|
tapeK = (tapeK + 1) % 3
|
||||||
|
step = cTapeSpeed * TAPE_HR[head] * semis(harm + (pitch - sm[P_PITCH]))
|
||||||
|
ampScale *= TAPE_HA[head]
|
||||||
|
tapeGrainHead = head
|
||||||
|
} else {
|
||||||
|
val st = (pitch + harm + extraPitch + rndb() * cPitchRand + walkPitch * sm[P_DRIFT] * 2f).coerceIn(-48f, 36f)
|
||||||
|
step = semis(st)
|
||||||
|
}
|
||||||
|
step *= s.sampleRate / fsf
|
||||||
|
step = step.coerceIn(1f / 64f, STEP_MAX)
|
||||||
|
if (loadNow + 1f + step > LOAD_MAX) return
|
||||||
|
if (len < 64) len = 64
|
||||||
|
var span = len * step
|
||||||
|
if (span > rlen * 0.98f) { len = (rlen * 0.98f / step).toInt(); span = len * step }
|
||||||
|
if (len < 32) return
|
||||||
|
val rev = rndf() < cRevProb
|
||||||
|
var center = if (posOverride >= 0f) posOverride else cCenter + rndb() * cScatter * 0.5f
|
||||||
|
if (cTape) center = cCenter + tapeGrainHead / 3f + rndb() * cScatter
|
||||||
|
center -= floor(center)
|
||||||
|
val cpos = rs + center * rlen
|
||||||
|
val start = if (!rev) (cpos - span * 0.5f).coerceIn(rs, re - span) else (cpos + span * 0.5f).coerceIn(rs + span, re - 1f)
|
||||||
|
gPos[g] = max(start, 0f).toDouble()
|
||||||
|
gInc[g] = step.toDouble()
|
||||||
|
gRev[g] = rev
|
||||||
|
gLen[g] = len
|
||||||
|
gAge[g] = 0
|
||||||
|
gDelay[g] = offset
|
||||||
|
gWin[g] = cWin.coerceIn(0, WIN_COUNT - 1)
|
||||||
|
gWph[g] = 0f
|
||||||
|
gWstep[g] = WIN_N.toFloat() / len
|
||||||
|
gLoad[g] = 1f + step
|
||||||
|
val overlap = max(1f, cDensity * cSize)
|
||||||
|
gAmp[g] = (cAmp * ampScale * 0.75f / sqrt(overlap)).coerceIn(0f, 1.9f)
|
||||||
|
val tone = (cTone + rndb() * cToneRand).coerceIn(-1f, 1f)
|
||||||
|
when {
|
||||||
|
abs(tone) < 0.02f -> gTone[g] = 0
|
||||||
|
tone < 0f -> { gTone[g] = 1; gToneA[g] = onepole(min(18000f * 0.02f.pow(-tone), min(20000f, 0.45f * fsf))) }
|
||||||
|
else -> { gTone[g] = 2; gToneA[g] = onepole(150f * 30f.pow(tone)) }
|
||||||
|
}
|
||||||
|
gZ[g] = 0f
|
||||||
|
gOn[g] = true
|
||||||
|
loadNow += gLoad[g]
|
||||||
|
}
|
||||||
|
|
||||||
|
private var tapeGrainHead = 0
|
||||||
|
|
||||||
|
private fun renderGrains() {
|
||||||
|
val s = src ?: run { gOn.fill(false); loadNow = 0f; return }
|
||||||
|
val data = s.data
|
||||||
|
val last = data.size - 1
|
||||||
|
var load = 0f
|
||||||
|
for (k in 0 until MAX_GRAINS) {
|
||||||
|
if (!gOn[k]) continue
|
||||||
|
val w = WIN_TAB[gWin[k]]
|
||||||
|
var i = gDelay[k]
|
||||||
|
gDelay[k] = 0
|
||||||
|
var p = gPos[k]
|
||||||
|
val inc = gInc[k]
|
||||||
|
val rev = gRev[k]
|
||||||
|
val tone = gTone[k]
|
||||||
|
val ta = gToneA[k]
|
||||||
|
var z = gZ[k]
|
||||||
|
var wph = gWph[k]
|
||||||
|
val wstep = gWstep[k]
|
||||||
|
val amp = gAmp[k]
|
||||||
|
var left = gLen[k] - gAge[k]
|
||||||
|
if (left > SUB - i) left = SUB - i
|
||||||
|
gAge[k] += left
|
||||||
|
while (left > 0) {
|
||||||
|
val idx = p.toInt()
|
||||||
|
if (p < 0.0 || idx >= last) { gAge[k] = gLen[k]; break }
|
||||||
|
val fr = (p - idx).toFloat()
|
||||||
|
var x = data[idx] + (data[idx + 1] - data[idx]) * fr
|
||||||
|
if (tone != 0) { z += (x - z) * ta; x = if (tone == 1) z else x - z }
|
||||||
|
val wi = wph.toInt().coerceAtMost(WIN_N)
|
||||||
|
val wv = w[wi] + (w[wi + 1] - w[wi]) * (wph - wi)
|
||||||
|
bus[i] += x * wv * amp
|
||||||
|
p = if (rev) p - inc else p + inc
|
||||||
|
wph = min(wph + wstep, WIN_N.toFloat())
|
||||||
|
i++; left--
|
||||||
|
}
|
||||||
|
gPos[k] = p; gWph[k] = wph; gZ[k] = flush(z)
|
||||||
|
if (gAge[k] >= gLen[k]) gOn[k] = false else load += gLoad[k]
|
||||||
|
}
|
||||||
|
loadNow = load
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun schedule() {
|
||||||
|
notesTrack()
|
||||||
|
if (src == null || (env <= 0.0005f && nNotes == 0)) return
|
||||||
|
if (noteSeq != noteSeqSeen) { // a new key: two grains at once, so the key answers
|
||||||
|
noteSeqSeen = noteSeq
|
||||||
|
if (!cClocked && nNotes > 0) { spawn(0, 1f, 0f, -1f); spawn(0, 0.8f, 0f, -1f) }
|
||||||
|
}
|
||||||
|
if (cClocked) {
|
||||||
|
// PULSE: on the song's tempo, its 1/16, 1/8 or 1/4, whichever is nearest ECHOFIELD's own pace
|
||||||
|
val own = 30f + 90f * sm[P_MOTION]
|
||||||
|
val ext = patch?.tempoBpm ?: 0f
|
||||||
|
var bpm = own
|
||||||
|
if (ext > 0f) {
|
||||||
|
var best = 1e9f
|
||||||
|
var dv = 1
|
||||||
|
while (dv <= 4) {
|
||||||
|
val r = ext / dv
|
||||||
|
val e = if (r > own) r / own else own / r
|
||||||
|
if (e < best) { best = e; bpm = r }
|
||||||
|
dv = dv shl 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val stepSamples = fsf * 60f / bpm / 4f
|
||||||
|
val kk = (5f + sm[P_DENS_MUL] * 2.5f + 0.5f).coerceIn(1f, 16f).toInt()
|
||||||
|
val pat = euclid(kk, 16, pulseRot)
|
||||||
|
for (i in 0 until SUB) {
|
||||||
|
pulseAcc -= 1f
|
||||||
|
if (pulseAcc <= 0f) {
|
||||||
|
val st = pulseStep
|
||||||
|
pulseAcc += stepSamples * (1f + (if (pulseStep and 1 == 1) 0.08f else -0.08f) * sm[P_DRIFT])
|
||||||
|
pulseStep = (pulseStep + 1) and 15
|
||||||
|
if (st == 0 && !frozen() && rndf() < sm[P_MOTION] * 0.35f) {
|
||||||
|
val j = (rndf() * 16f).toInt() and 15
|
||||||
|
stepPos[j] = rndf()
|
||||||
|
stepOct[j] = if (rndf() < sm[P_DRIFT] * 0.5f) (if (rndf() < 0.5f) 12 else 7) else 0
|
||||||
|
if (rndf() < sm[P_MOTION] * 0.3f) pulseRot = (pulseRot + 1) and 15
|
||||||
|
}
|
||||||
|
if ((pat shr st) and 1 == 1) {
|
||||||
|
var p = cCenter + (stepPos[st] - 0.5f) * cScatter
|
||||||
|
p -= floor(p)
|
||||||
|
spawn(i, if (st % 4 == 0) 1.1f else 0.77f, stepOct[st].toFloat(), p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (cDensity <= 0f) return
|
||||||
|
val mean = fsf / cDensity
|
||||||
|
val mode = sm[P_MODE].toInt()
|
||||||
|
for (i in 0 until SUB) {
|
||||||
|
spawnWait -= 1f
|
||||||
|
if (spawnWait > 0f) continue
|
||||||
|
spawnWait += mean * (1f - cJitter + cJitter * 2f * rndf())
|
||||||
|
if (spawnWait < 1f) spawnWait = 1f
|
||||||
|
when (mode) {
|
||||||
|
MODE_DUST -> {
|
||||||
|
if (stutterLeft > 0) { stutterLeft--; spawn(i, 1f, 0f, stutterPos); continue }
|
||||||
|
if (rndf() < sm[P_MOTION] * 0.05f) {
|
||||||
|
stutterLeft = 2 + (rndf() * 4f).toInt()
|
||||||
|
stutterPos = cCenter + rndb() * cScatter * 0.5f
|
||||||
|
stutterPos -= floor(stutterPos)
|
||||||
|
}
|
||||||
|
val sp = if (rndf() < sm[P_SCATTER] * 0.35f) DUST_LEAP[(rndf() * 5f).toInt() % 5] else 0f
|
||||||
|
spawn(i, 1f, sp, -1f)
|
||||||
|
}
|
||||||
|
MODE_BLOOM -> {
|
||||||
|
val r = rndf()
|
||||||
|
val k = if (r < 0.55f) 0 else if (r < 0.75f) 1 else if (r < 0.9f) 2 else 3
|
||||||
|
spawn(i, 0.5f + 0.5f * rndf(), BLOOM_PART[k], -1f)
|
||||||
|
}
|
||||||
|
else -> spawn(i, 1f, 0f, -1f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** ECHOFIELD's auto-level: the cloud held near one loudness whatever its density or
|
||||||
|
* source; a tail that dies away is never pulled back up. */
|
||||||
|
private fun autoLevel() {
|
||||||
|
val blk = SUB / fsf
|
||||||
|
var ms = 0f
|
||||||
|
for (i in 0 until SUB) ms += bus[i] * bus[i]
|
||||||
|
ms /= SUB
|
||||||
|
val g0 = agcGain
|
||||||
|
agcMs += (ms - agcMs) * (1f - exp(-blk / 2.5f))
|
||||||
|
var target = agcGain
|
||||||
|
if (agcMs > 1e-6f) target = (AGC_TARGET / sqrt(agcMs)).coerceIn(0.5f, 4f)
|
||||||
|
if (env <= 0.5f && target > agcGain) target = agcGain
|
||||||
|
val tc = if (target < agcGain) 0.4f else 2.5f
|
||||||
|
agcGain += (target - agcGain) * (1f - exp(-blk / tc))
|
||||||
|
for (i in 0 until SUB) bus[i] *= g0 + (agcGain - g0) * i / SUB
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------- helpers ---
|
||||||
|
private fun onepole(hz: Float) = 1f - exp(-TWO_PI * hz / fsf)
|
||||||
|
|
||||||
|
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 rndf(): Float = (nextRand() ushr 8) * (1f / 16777216f)
|
||||||
|
private fun rndb(): Float = rndf() * 2f - 1f
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val P_POSITION = 0; const val P_TEXTURE = 1; const val P_SCATTER = 2; const val P_DRIFT = 3
|
||||||
|
const val P_MOTION = 4; const val P_PITCH = 5; const val P_HARMONY = 6; const val P_SIZE_MUL = 7
|
||||||
|
const val P_DENS_MUL = 8; const val P_SCAN = 9; const val P_REVERSE = 10; const val P_PITCH_RAND = 11
|
||||||
|
const val P_SIZE_RAND = 12; const val P_WINDOW = 13; const val P_GRAIN_TONE = 14; const val P_ATTACK = 15
|
||||||
|
const val P_RELEASE = 16; const val P_VELO = 17; const val P_START = 18; const val P_END = 19
|
||||||
|
const val P_MODE = 20; const val P_FREEZE = 21; const val P_LEVEL = 22
|
||||||
|
const val P_COUNT = 23
|
||||||
|
|
||||||
|
/** A note from live input (keys, MIDI); [OWNER_SEQ] one the sequencer played with no track (an arpeggio). */
|
||||||
|
const val OWNER_LIVE = -1
|
||||||
|
const val OWNER_SEQ = -2
|
||||||
|
|
||||||
|
const val SUB = 64
|
||||||
|
const val MAX_GRAINS = 32
|
||||||
|
const val MAX_NOTES = 8
|
||||||
|
private const val WIN_N = 256
|
||||||
|
private const val STEP_MAX = 4f
|
||||||
|
private const val LOAD_MAX = 56f
|
||||||
|
private const val AGC_TARGET = 0.126f
|
||||||
|
/** Brings the auto-levelled cloud to about the level of a Sizzle synth note. */
|
||||||
|
private const val OUT_GAIN = 1.0f
|
||||||
|
private const val TWO_PI = 6.2831853f
|
||||||
|
private const val PI = 3.14159265f
|
||||||
|
|
||||||
|
const val MODE_CLOUD = 0; const val MODE_DUST = 1; const val MODE_TAPE = 2
|
||||||
|
const val MODE_BLOOM = 3; const val MODE_PULSE = 4; const val MODE_DRIFT = 5
|
||||||
|
private const val WIN_HANN = 0; private const val WIN_TUKEY = 1; private const val WIN_PERC = 2
|
||||||
|
private const val WIN_SWELL = 3; private const val WIN_GAUSS = 4; private const val WIN_COUNT = 5
|
||||||
|
|
||||||
|
private val HARMONY_IV = floatArrayOf(12f, 12f, -12f, 7f, 19f, 24f, -5f, 7f)
|
||||||
|
private val TAPE_HR = floatArrayOf(1f, 0.5f, 2f)
|
||||||
|
private val TAPE_HA = floatArrayOf(1f, 0.8f, 0.4f)
|
||||||
|
private val DUST_LEAP = floatArrayOf(12f, 19f, 24f, 7f, -12f)
|
||||||
|
private val BLOOM_PART = floatArrayOf(0f, 12f, 7f, -12f)
|
||||||
|
|
||||||
|
/** The grain windows (ef_window), 0..1 over [WIN_N] + 2 points. */
|
||||||
|
fun window(w: Int, x0: Float): Float {
|
||||||
|
val x = x0.coerceIn(0f, 1f)
|
||||||
|
return when (w) {
|
||||||
|
WIN_TUKEY -> {
|
||||||
|
val a = 0.3f
|
||||||
|
when {
|
||||||
|
x < a * 0.5f -> 0.5f - 0.5f * cos(TWO_PI * x / a)
|
||||||
|
x > 1f - a * 0.5f -> 0.5f - 0.5f * cos(TWO_PI * (1f - x) / a)
|
||||||
|
else -> 1f
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WIN_PERC -> {
|
||||||
|
val att = 0.03f
|
||||||
|
var v = if (x < att) sin(0.5f * PI * x / att) else exp(-5f * (x - att) / (1f - att))
|
||||||
|
if (x > 0.92f) v *= 0.5f + 0.5f * cos(PI * (x - 0.92f) / 0.08f)
|
||||||
|
v
|
||||||
|
}
|
||||||
|
WIN_SWELL -> window(WIN_PERC, 1f - x)
|
||||||
|
WIN_GAUSS -> {
|
||||||
|
val d = (x - 0.5f) / 0.16f
|
||||||
|
val g = exp(-0.5f * d * d)
|
||||||
|
val e = 0.00752f
|
||||||
|
((g - e) / (1f - e)).coerceIn(0f, 1f)
|
||||||
|
}
|
||||||
|
else -> 0.5f - 0.5f * cos(TWO_PI * x)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val WIN_TAB: Array<FloatArray> = Array(WIN_COUNT) { w ->
|
||||||
|
FloatArray(WIN_N + 2) { i -> window(w, i.toFloat() / WIN_N) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun euclid(k: Int, n: Int, rot: Int): Int {
|
||||||
|
var pat = 0
|
||||||
|
if (k <= 0) return 0
|
||||||
|
for (i in 0 until n) if ((i * k) % n < k) pat = pat or (1 shl ((i + rot) % n))
|
||||||
|
return pat
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun semis(st: Float): Float = 2f.pow(st / 12f)
|
||||||
|
private fun lerp(a: Float, b: Float, t: Float) = a + (b - a) * t
|
||||||
|
private fun flush(x: Float) = if (x > -1e-20f && x < 1e-20f) 0f else x
|
||||||
|
|
||||||
|
private var seeds = 0x1234567
|
||||||
|
private fun nextSeed(): Int {
|
||||||
|
seeds += 0x6D2B79F5
|
||||||
|
return if (seeds == 0) 0x1234567 else seeds
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,9 @@
|
|||||||
package cc.tiredsysadmin.android.sizzle.io
|
package cc.tiredsysadmin.android.sizzle.io
|
||||||
|
|
||||||
import cc.tiredsysadmin.android.sizzle.audio.SampleStore
|
import cc.tiredsysadmin.android.sizzle.audio.SampleStore
|
||||||
|
import cc.tiredsysadmin.android.sizzle.echofield.EchofieldDefs
|
||||||
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs
|
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs
|
||||||
|
import cc.tiredsysadmin.android.sizzle.wavetable.WaveDefs
|
||||||
import cc.tiredsysadmin.android.sizzle.model.AmbiencePresets
|
import cc.tiredsysadmin.android.sizzle.model.AmbiencePresets
|
||||||
import cc.tiredsysadmin.android.sizzle.model.MixTightenerPresets
|
import cc.tiredsysadmin.android.sizzle.model.MixTightenerPresets
|
||||||
import cc.tiredsysadmin.android.sizzle.model.NesSynthPresets
|
import cc.tiredsysadmin.android.sizzle.model.NesSynthPresets
|
||||||
@@ -56,6 +58,12 @@ class PresetLibrary(private val baseDir: File) {
|
|||||||
seedType(ToolboxType.MORPH_PAD, FrasilDefs.FACTORY.map { it.name }) { slot, 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) }
|
FrasilDefs.FACTORY.first { it.name == name }.values.forEach { (k, v) -> slot.set(k, v) }
|
||||||
}
|
}
|
||||||
|
seedType(ToolboxType.GRAIN_CLOUD, EchofieldDefs.FACTORY.map { it.name }) { slot, name ->
|
||||||
|
EchofieldDefs.FACTORY.first { it.name == name }.values.forEach { (k, v) -> slot.set(k, v) }
|
||||||
|
}
|
||||||
|
seedType(ToolboxType.WAVETABLE, WaveDefs.FACTORY.map { it.name }) { slot, name ->
|
||||||
|
WaveDefs.FACTORY.first { it.name == name }.values.forEach { (k, v) -> slot.set(k, v) }
|
||||||
|
}
|
||||||
seedType(ToolboxType.MIX_TIGHTENER, MixTightenerPresets.FACTORY.map { it.name }) { slot, name ->
|
seedType(ToolboxType.MIX_TIGHTENER, MixTightenerPresets.FACTORY.map { it.name }) { slot, name ->
|
||||||
MixTightenerPresets.apply(slot, MixTightenerPresets.FACTORY.first { it.name == name })
|
MixTightenerPresets.apply(slot, MixTightenerPresets.FACTORY.first { it.name == name })
|
||||||
}
|
}
|
||||||
@@ -143,6 +151,18 @@ class PresetLibrary(private val baseDir: File) {
|
|||||||
}
|
}
|
||||||
preset.writeText(exportSoundFont(slot, rel))
|
preset.writeText(exportSoundFont(slot, rel))
|
||||||
}
|
}
|
||||||
|
ToolboxType.GRAIN_CLOUD, ToolboxType.WAVETABLE -> {
|
||||||
|
// A custom grain source or wavetable travels with the preset as a WAV, like the SF2/XI
|
||||||
|
// loader's; the built-in sources need nothing.
|
||||||
|
val sample = SampleStore.get(slot.string("sfSample"))
|
||||||
|
if (sample != null) {
|
||||||
|
File(dir, "${safe}_sf.wav").writeBytes(SampleStore.encodeWav(sample))
|
||||||
|
slot.set("sfFile", "${safe}_sf.wav")
|
||||||
|
} else {
|
||||||
|
slot.values.remove("sfFile")
|
||||||
|
}
|
||||||
|
preset.writeText(PresetIo.export(slot))
|
||||||
|
}
|
||||||
else -> preset.writeText(PresetIo.export(slot))
|
else -> preset.writeText(PresetIo.export(slot))
|
||||||
}
|
}
|
||||||
return preset
|
return preset
|
||||||
@@ -165,7 +185,7 @@ class PresetLibrary(private val baseDir: File) {
|
|||||||
}
|
}
|
||||||
if (type == ToolboxType.SAMPLER) {
|
if (type == ToolboxType.SAMPLER) {
|
||||||
for (p in 0 until SamplerPads.COUNT) File(dir, "${base}_pad$p.wav").delete()
|
for (p in 0 until SamplerPads.COUNT) File(dir, "${base}_pad$p.wav").delete()
|
||||||
} else if (type == ToolboxType.SOUNDFONT) {
|
} else if (type == ToolboxType.SOUNDFONT || type == ToolboxType.GRAIN_CLOUD || type == ToolboxType.WAVETABLE) {
|
||||||
File(dir, "${base}_sf.wav").delete()
|
File(dir, "${base}_sf.wav").delete()
|
||||||
}
|
}
|
||||||
return preset.delete()
|
return preset.delete()
|
||||||
@@ -182,7 +202,7 @@ class PresetLibrary(private val baseDir: File) {
|
|||||||
project.toolbox.forEach { slot ->
|
project.toolbox.forEach { slot ->
|
||||||
when (slot.type) {
|
when (slot.type) {
|
||||||
ToolboxType.SAMPLER -> resolvePads(slot, typeDir(ToolboxType.SAMPLER))
|
ToolboxType.SAMPLER -> resolvePads(slot, typeDir(ToolboxType.SAMPLER))
|
||||||
ToolboxType.SOUNDFONT -> resolveSoundFont(slot, typeDir(ToolboxType.SOUNDFONT))
|
ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD, ToolboxType.WAVETABLE -> resolveSoundFont(slot, typeDir(ToolboxType.SOUNDFONT))
|
||||||
else -> {}
|
else -> {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -197,7 +217,7 @@ class PresetLibrary(private val baseDir: File) {
|
|||||||
val dir = file.parentFile ?: typeDir(type)
|
val dir = file.parentFile ?: typeDir(type)
|
||||||
when (slot.type) {
|
when (slot.type) {
|
||||||
ToolboxType.SAMPLER -> resolvePads(slot, dir)
|
ToolboxType.SAMPLER -> resolvePads(slot, dir)
|
||||||
ToolboxType.SOUNDFONT -> resolveSoundFont(slot, dir)
|
ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD, ToolboxType.WAVETABLE -> resolveSoundFont(slot, dir)
|
||||||
else -> {}
|
else -> {}
|
||||||
}
|
}
|
||||||
true
|
true
|
||||||
@@ -214,7 +234,7 @@ class PresetLibrary(private val baseDir: File) {
|
|||||||
val type = slot.type ?: return false
|
val type = slot.type ?: return false
|
||||||
when (type) {
|
when (type) {
|
||||||
ToolboxType.SAMPLER -> resolvePads(slot, typeDir(type))
|
ToolboxType.SAMPLER -> resolvePads(slot, typeDir(type))
|
||||||
ToolboxType.SOUNDFONT -> resolveSoundFont(slot, typeDir(type))
|
ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD, ToolboxType.WAVETABLE -> resolveSoundFont(slot, typeDir(type))
|
||||||
else -> {}
|
else -> {}
|
||||||
}
|
}
|
||||||
save(slot, slot.name.ifBlank { type.displayName })
|
save(slot, slot.name.ifBlank { type.displayName })
|
||||||
@@ -255,7 +275,7 @@ class PresetLibrary(private val baseDir: File) {
|
|||||||
if (!PresetIo.import(slot, text)) return false
|
if (!PresetIo.import(slot, text)) return false
|
||||||
when (slot.type) {
|
when (slot.type) {
|
||||||
ToolboxType.SAMPLER -> resolvePads(slot, scratch)
|
ToolboxType.SAMPLER -> resolvePads(slot, scratch)
|
||||||
ToolboxType.SOUNDFONT -> resolveSoundFont(slot, scratch)
|
ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD, ToolboxType.WAVETABLE -> resolveSoundFont(slot, scratch)
|
||||||
else -> {}
|
else -> {}
|
||||||
}
|
}
|
||||||
// Persist a self-contained copy into the real library folder.
|
// Persist a self-contained copy into the real library folder.
|
||||||
@@ -272,7 +292,9 @@ class PresetLibrary(private val baseDir: File) {
|
|||||||
fun bundleForShare(type: ToolboxType, name: String): File? {
|
fun bundleForShare(type: ToolboxType, name: String): File? {
|
||||||
val preset = File(typeDir(type), sanitize(name) + PRESET_EXT)
|
val preset = File(typeDir(type), sanitize(name) + PRESET_EXT)
|
||||||
if (!preset.exists()) return null
|
if (!preset.exists()) return null
|
||||||
if (type != ToolboxType.SAMPLER && type != ToolboxType.SOUNDFONT) return preset
|
if (type != ToolboxType.SAMPLER && type != ToolboxType.SOUNDFONT && type != ToolboxType.GRAIN_CLOUD &&
|
||||||
|
type != ToolboxType.WAVETABLE
|
||||||
|
) return preset
|
||||||
|
|
||||||
val bundles = File(baseDir, BUNDLE_DIR).apply { mkdirs() }
|
val bundles = File(baseDir, BUNDLE_DIR).apply { mkdirs() }
|
||||||
val zip = File(bundles, sanitize(name) + ".zip")
|
val zip = File(bundles, sanitize(name) + ".zip")
|
||||||
|
|||||||
@@ -112,7 +112,7 @@ object ProjectBundleIo {
|
|||||||
ToolboxType.SAMPLER -> for (p in 0 until SamplerPads.COUNT) {
|
ToolboxType.SAMPLER -> for (p in 0 until SamplerPads.COUNT) {
|
||||||
idToPath[slot.string(SamplerPads.key(p))]?.let { slot.set("pad${p}File", it) }
|
idToPath[slot.string(SamplerPads.key(p))]?.let { slot.set("pad${p}File", it) }
|
||||||
}
|
}
|
||||||
ToolboxType.SOUNDFONT -> idToPath[slot.string("sfSample")]?.let { slot.set("sfFile", it) }
|
ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD, ToolboxType.WAVETABLE -> idToPath[slot.string("sfSample")]?.let { slot.set("sfFile", it) }
|
||||||
else -> {}
|
else -> {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -127,7 +127,8 @@ object ProjectBundleIo {
|
|||||||
ToolboxType.SAMPLER -> for (p in 0 until SamplerPads.COUNT) {
|
ToolboxType.SAMPLER -> for (p in 0 until SamplerPads.COUNT) {
|
||||||
slot.string(SamplerPads.key(p)).takeIf { it.isNotBlank() }?.let { ids.add(it) }
|
slot.string(SamplerPads.key(p)).takeIf { it.isNotBlank() }?.let { ids.add(it) }
|
||||||
}
|
}
|
||||||
ToolboxType.SOUNDFONT -> slot.string("sfSample").takeIf { it.isNotBlank() }?.let { ids.add(it) }
|
ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD, ToolboxType.WAVETABLE ->
|
||||||
|
slot.string("sfSample").takeIf { it.isNotBlank() }?.let { ids.add(it) }
|
||||||
else -> {}
|
else -> {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,9 @@
|
|||||||
|
|
||||||
package cc.tiredsysadmin.android.sizzle.model
|
package cc.tiredsysadmin.android.sizzle.model
|
||||||
|
|
||||||
|
import cc.tiredsysadmin.android.sizzle.echofield.EchofieldDefs
|
||||||
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs
|
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs
|
||||||
|
import cc.tiredsysadmin.android.sizzle.wavetable.WaveDefs
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The third tab is a toolbox of 16 slots. Every slot can hold one instrument OR
|
* The third tab is a toolbox of 16 slots. Every slot can hold one instrument OR
|
||||||
@@ -120,6 +122,16 @@ enum class ToolboxType(
|
|||||||
// while held, morphing toward one of FRASIL's 36 drone sounds. Rendered by
|
// while held, morphing toward one of FRASIL's 36 drone sounds. Rendered by
|
||||||
// FrasilVoice inside SynthVoice; edited by the paged editor in ToolboxScreen.
|
// FrasilVoice inside SynthVoice; edited by the paged editor in ToolboxScreen.
|
||||||
MORPH_PAD(ToolboxKind.INSTRUMENT, "Morph Pad", FrasilDefs.PARAMS),
|
MORPH_PAD(ToolboxKind.INSTRUMENT, "Morph Pad", FrasilDefs.PARAMS),
|
||||||
|
// ECHOFIELD's granular engine (MIT, see the echofield package): one cloud of up to
|
||||||
|
// 32 grains per mixer channel, read from a built-in source (audio/GrainSources)
|
||||||
|
// or your own sample ("sfSample", as the SF2/XI loader keeps it); held notes pitch
|
||||||
|
// the grains. Rendered by GrainCloud in AudioEngine; edited by GrainCloudEditor.
|
||||||
|
GRAIN_CLOUD(ToolboxKind.INSTRUMENT, "Grain Cloud", EchofieldDefs.PARAMS),
|
||||||
|
// A two-oscillator wavetable synth (Sizzle's own, see the wavetable package): 12
|
||||||
|
// generated tables or an imported Serum / WaveEdit WAV ("sfSample"), band-limited
|
||||||
|
// per octave, position swept by an envelope and LFO, unison, SVF filter. Rendered
|
||||||
|
// by WaveVoice inside SynthVoice; edited by WavetableEditor + the paged list.
|
||||||
|
WAVETABLE(ToolboxKind.INSTRUMENT, "Wavetable", WaveDefs.PARAMS),
|
||||||
|
|
||||||
// ---------- Effects ----------
|
// ---------- Effects ----------
|
||||||
ARPEGGIATOR(
|
ARPEGGIATOR(
|
||||||
|
|||||||
@@ -1068,6 +1068,74 @@ class AppViewModel(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Give a Grain Cloud [slot] a source of its own from [bytes] (an uncompressed WAV,
|
||||||
|
* or an SF2/XI's sample). A copy is kept in the preset library's folder and the
|
||||||
|
* slot points at it by path (`sfFile`), so the source comes back after a restart
|
||||||
|
* without saving a preset. Switches SOURCE to "Custom".
|
||||||
|
*/
|
||||||
|
fun loadGrainSample(slot: cc.tiredsysadmin.android.sizzle.model.ToolboxSlot, bytes: ByteArray): Boolean {
|
||||||
|
val sample = cc.tiredsysadmin.android.sizzle.audio.SampleStore.decodeWav(bytes)
|
||||||
|
?: cc.tiredsysadmin.android.sizzle.audio.SoundFontLoader.load(bytes)?.sample
|
||||||
|
?: return false
|
||||||
|
setGrainSample(slot, sample)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stop the recorder and make the take the Grain Cloud [slot]'s source. */
|
||||||
|
fun stopRecordingIntoGrain(slot: cc.tiredsysadmin.android.sizzle.model.ToolboxSlot) {
|
||||||
|
val sample = recorder.stop()
|
||||||
|
isRecording = false
|
||||||
|
if (sample != null) setGrainSample(slot, sample)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun setGrainSample(
|
||||||
|
slot: cc.tiredsysadmin.android.sizzle.model.ToolboxSlot,
|
||||||
|
sample: cc.tiredsysadmin.android.sizzle.audio.SampleStore.Sample,
|
||||||
|
) {
|
||||||
|
storeSlotSample(slot, sample, cc.tiredsysadmin.android.sizzle.model.ToolboxType.GRAIN_CLOUD)
|
||||||
|
slot.set("source", cc.tiredsysadmin.android.sizzle.echofield.EchofieldDefs.CUSTOM)
|
||||||
|
touched()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keep [sample] as [slot]'s own sound: a WAV copy in [type]'s preset folder, the
|
||||||
|
* slot pointing at it by id (`sfSample`) and path (`sfFile`). Returns the id. */
|
||||||
|
private fun storeSlotSample(
|
||||||
|
slot: cc.tiredsysadmin.android.sizzle.model.ToolboxSlot,
|
||||||
|
sample: cc.tiredsysadmin.android.sizzle.audio.SampleStore.Sample,
|
||||||
|
type: cc.tiredsysadmin.android.sizzle.model.ToolboxType,
|
||||||
|
): String {
|
||||||
|
val store = cc.tiredsysadmin.android.sizzle.audio.SampleStore
|
||||||
|
val dir = java.io.File(presetLibrary.typeDir(type), "sources").apply { mkdirs() }
|
||||||
|
val file = java.io.File(dir, "source-${System.currentTimeMillis()}.wav")
|
||||||
|
runCatching { file.writeBytes(store.encodeWav(sample)) }
|
||||||
|
val id = "file:" + file.absolutePath
|
||||||
|
store.put(id, sample)
|
||||||
|
slot.set("sfSample", id)
|
||||||
|
if (file.exists()) slot.set("sfFile", file.absolutePath)
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load a wavetable WAV into Wavetable [slot]: Serum's (its `clm ` chunk gives the
|
||||||
|
* frame length), WaveEdit's (64 x 256) or any file of power-of-two frames. The
|
||||||
|
* table is built here (off the audio thread) and oscillator 1 switches to it.
|
||||||
|
*/
|
||||||
|
fun loadWavetable(slot: cc.tiredsysadmin.android.sizzle.model.ToolboxSlot, bytes: ByteArray): Boolean {
|
||||||
|
val tables = cc.tiredsysadmin.android.sizzle.wavetable.WaveTables
|
||||||
|
val defs = cc.tiredsysadmin.android.sizzle.wavetable.WaveDefs
|
||||||
|
val sample = cc.tiredsysadmin.android.sizzle.audio.SampleStore.decodeWav(bytes) ?: return false
|
||||||
|
if (sample.data.size < 64) return false
|
||||||
|
val frameLen = tables.detectFrameLength(bytes, sample.data.size)
|
||||||
|
val label = frameLen.toString().takeIf { it in defs.FRAME_SIZES } ?: defs.FRAME_SIZES[0]
|
||||||
|
val id = storeSlotSample(slot, sample, cc.tiredsysadmin.android.sizzle.model.ToolboxType.WAVETABLE)
|
||||||
|
slot.set("wtframe", label)
|
||||||
|
tables.buildForSample(id, label.toIntOrNull() ?: 0)
|
||||||
|
slot.set("o1table", tables.CUSTOM)
|
||||||
|
touched()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
/** Point an LFO slot at another device's parameter, capturing that param's
|
/** Point an LFO slot at another device's parameter, capturing that param's
|
||||||
* current value as the modulation centre. Pass targetSlotIndex < 0 to clear. */
|
* current value as the modulation centre. Pass targetSlotIndex < 0 to clear. */
|
||||||
fun setLfoTarget(
|
fun setLfoTarget(
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
package cc.tiredsysadmin.android.sizzle.ui.toolbox
|
||||||
|
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.foundation.Canvas
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.geometry.Offset
|
||||||
|
import androidx.compose.ui.geometry.Size
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.font.FontFamily
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import cc.tiredsysadmin.android.sizzle.audio.GrainSources
|
||||||
|
import cc.tiredsysadmin.android.sizzle.audio.SampleStore
|
||||||
|
import cc.tiredsysadmin.android.sizzle.echofield.EchofieldDefs
|
||||||
|
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
|
||||||
|
import cc.tiredsysadmin.android.sizzle.ui.AppViewModel
|
||||||
|
import cc.tiredsysadmin.android.sizzle.ui.components.RetroButton
|
||||||
|
import cc.tiredsysadmin.android.sizzle.ui.theme.LocalRetro
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Grain Cloud's source strip: load a WAV (or SF2/XI) or record one as the cloud's
|
||||||
|
* own source, and see the source with its START..END region lit. The settings
|
||||||
|
* themselves are the paged list below it (ToolboxScreen).
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun GrainCloudEditor(vm: AppViewModel, slot: ToolboxSlot) {
|
||||||
|
val c = LocalRetro.current
|
||||||
|
val context = LocalContext.current
|
||||||
|
@Suppress("UNUSED_VARIABLE") val rev = vm.revision
|
||||||
|
|
||||||
|
var importError by remember(slot.index) { mutableStateOf<String?>(null) }
|
||||||
|
val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||||
|
if (uri == null) return@rememberLauncherForActivityResult
|
||||||
|
val bytes = runCatching { context.contentResolver.openInputStream(uri)?.use { readCapped(it) } }.getOrNull()
|
||||||
|
when {
|
||||||
|
bytes == null -> importError =
|
||||||
|
"Couldn't read the file, or it's larger than ${MAX_IMPORT_BYTES / (1024 * 1024)} MB."
|
||||||
|
!vm.loadGrainSample(slot, bytes) -> importError =
|
||||||
|
"Couldn't load this sound. Supported formats are uncompressed .wav, .sf2 and .xi."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val sourceName = slot.string("source", EchofieldDefs.SOURCES[0])
|
||||||
|
val custom = sourceName == EchofieldDefs.CUSTOM
|
||||||
|
val sample = if (custom) SampleStore.get(slot.string(EchofieldDefs.SAMPLE_KEY)) else GrainSources.get(sourceName)
|
||||||
|
val start = slot.float("start", 0f)
|
||||||
|
val end = slot.float("end", 1f)
|
||||||
|
|
||||||
|
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
RetroButton("LOAD WAV") { picker.launch(arrayOf("*/*")) }
|
||||||
|
if (vm.isRecording) {
|
||||||
|
RetroButton("■ STOP REC", active = true) { vm.stopRecordingIntoGrain(slot) }
|
||||||
|
} else {
|
||||||
|
RetroButton("● RECORD") { vm.startRecording() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
when {
|
||||||
|
sample == null && custom -> "Source: your own — load or record a sound."
|
||||||
|
sample == null -> "Source: $sourceName (preparing…)"
|
||||||
|
else -> "Source: ${if (custom) "your own" else sourceName} · " +
|
||||||
|
"%.1f s".format(sample.data.size.toFloat() / sample.sampleRate)
|
||||||
|
},
|
||||||
|
color = c.textDim, fontFamily = FontFamily.Monospace, fontSize = 10.sp,
|
||||||
|
)
|
||||||
|
if (sample != null) {
|
||||||
|
val peaks = remember(sample, sample.data.size) { computePeaks(sample.data, 300) }
|
||||||
|
Canvas(Modifier.fillMaxWidth().height(64.dp).background(c.surface)) {
|
||||||
|
val a = minOf(start, end) * size.width
|
||||||
|
val b = maxOf(start, end) * size.width
|
||||||
|
drawRect(c.accent.copy(alpha = 0.18f), Offset(a, 0f), Size(b - a, size.height))
|
||||||
|
val (mins, maxs) = peaks
|
||||||
|
val bw = size.width / mins.size
|
||||||
|
val mid = size.height / 2f
|
||||||
|
for (i in mins.indices) {
|
||||||
|
val x = i * bw
|
||||||
|
drawLine(c.text, Offset(x, mid - maxs[i] * mid), Offset(x, mid - mins[i] * mid), strokeWidth = 1f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
importError?.let { msg ->
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { importError = null },
|
||||||
|
title = { Text("Import failed") },
|
||||||
|
text = { Text(msg) },
|
||||||
|
confirmButton = { TextButton(onClick = { importError = null }) { Text("OK") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -57,7 +57,9 @@ import androidx.compose.ui.unit.Dp
|
|||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import androidx.core.content.FileProvider
|
import androidx.core.content.FileProvider
|
||||||
|
import cc.tiredsysadmin.android.sizzle.echofield.EchofieldDefs
|
||||||
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs
|
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs
|
||||||
|
import cc.tiredsysadmin.android.sizzle.wavetable.WaveDefs
|
||||||
import cc.tiredsysadmin.android.sizzle.model.ParamSpec
|
import cc.tiredsysadmin.android.sizzle.model.ParamSpec
|
||||||
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
|
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
|
||||||
import cc.tiredsysadmin.android.sizzle.model.ToolboxType
|
import cc.tiredsysadmin.android.sizzle.model.ToolboxType
|
||||||
@@ -297,7 +299,7 @@ private fun ParamEditor(vm: AppViewModel, slot: ToolboxSlot, onClose: () -> Unit
|
|||||||
// the toolbox / tracker keyboards), so their controls scroll in a weighted region
|
// the toolbox / tracker keyboards), so their controls scroll in a weighted region
|
||||||
// above the keyboard rather than the whole editor scrolling as one.
|
// 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
|
type == ToolboxType.MORPH_PAD || type == ToolboxType.GRAIN_CLOUD || type == ToolboxType.WAVETABLE
|
||||||
// The Sampler pins its 16-pad grid at the bottom in that same region, so the
|
// 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.
|
// playable pads are the same height as the keyboards across every instrument editor.
|
||||||
val pinnedBottom = pinnedKeyboard || type == ToolboxType.SAMPLER
|
val pinnedBottom = pinnedKeyboard || type == ToolboxType.SAMPLER
|
||||||
@@ -344,6 +346,14 @@ private fun ParamEditor(vm: AppViewModel, slot: ToolboxSlot, onClose: () -> Unit
|
|||||||
ToolboxType.DELAY -> DelayEditor(vm, slot)
|
ToolboxType.DELAY -> DelayEditor(vm, slot)
|
||||||
ToolboxType.AMBIENCE -> AmbiencePager(vm, slot)
|
ToolboxType.AMBIENCE -> AmbiencePager(vm, slot)
|
||||||
ToolboxType.MORPH_PAD -> SectionPager(vm, slot, FrasilDefs.SECTIONS, 300.dp)
|
ToolboxType.MORPH_PAD -> SectionPager(vm, slot, FrasilDefs.SECTIONS, 300.dp)
|
||||||
|
ToolboxType.WAVETABLE -> {
|
||||||
|
WavetableEditor(vm, slot)
|
||||||
|
SectionPager(vm, slot, WaveDefs.SECTIONS, 300.dp)
|
||||||
|
}
|
||||||
|
ToolboxType.GRAIN_CLOUD -> {
|
||||||
|
GrainCloudEditor(vm, slot)
|
||||||
|
SectionPager(vm, slot, EchofieldDefs.SECTIONS, 300.dp)
|
||||||
|
}
|
||||||
ToolboxType.LFO -> {
|
ToolboxType.LFO -> {
|
||||||
ParamGrid(vm, slot, type.params)
|
ParamGrid(vm, slot, type.params)
|
||||||
LfoTargetPicker(vm, slot)
|
LfoTargetPicker(vm, slot)
|
||||||
@@ -474,7 +484,7 @@ private fun AmbiencePager(vm: AppViewModel, slot: ToolboxSlot) =
|
|||||||
|
|
||||||
/** A device's parameters as swipeable pages of (title, keys), with dot pagination. */
|
/** A device's parameters as swipeable pages of (title, keys), with dot pagination. */
|
||||||
@Composable
|
@Composable
|
||||||
private fun SectionPager(vm: AppViewModel, slot: ToolboxSlot, sections: List<Pair<String, List<String>>>, height: Dp) {
|
internal fun SectionPager(vm: AppViewModel, slot: ToolboxSlot, sections: List<Pair<String, List<String>>>, height: Dp) {
|
||||||
val c = LocalRetro.current
|
val c = LocalRetro.current
|
||||||
val byKey = (slot.type ?: return).params.associateBy { it.key }
|
val byKey = (slot.type ?: return).params.associateBy { it.key }
|
||||||
val pagerState = rememberPagerState(pageCount = { sections.size })
|
val pagerState = rememberPagerState(pageCount = { sections.size })
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
package cc.tiredsysadmin.android.sizzle.ui.toolbox
|
||||||
|
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.foundation.Canvas
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.geometry.Offset
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.font.FontFamily
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
|
||||||
|
import cc.tiredsysadmin.android.sizzle.ui.AppViewModel
|
||||||
|
import cc.tiredsysadmin.android.sizzle.ui.components.RetroButton
|
||||||
|
import cc.tiredsysadmin.android.sizzle.ui.theme.LocalRetro
|
||||||
|
import cc.tiredsysadmin.android.sizzle.wavetable.WaveDefs
|
||||||
|
import cc.tiredsysadmin.android.sizzle.wavetable.WaveTables
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Wavetable's table strip: LOAD TABLE (a Serum / WaveEdit / power-of-two-frame
|
||||||
|
* WAV becomes the "Custom" table) and a view of oscillator 1's table, every frame
|
||||||
|
* stacked back to front with the one at its POSITION lit.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun WavetableEditor(vm: AppViewModel, slot: ToolboxSlot) {
|
||||||
|
val c = LocalRetro.current
|
||||||
|
val context = LocalContext.current
|
||||||
|
@Suppress("UNUSED_VARIABLE") val rev = vm.revision
|
||||||
|
|
||||||
|
var importError by remember(slot.index) { mutableStateOf<String?>(null) }
|
||||||
|
val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||||
|
if (uri == null) return@rememberLauncherForActivityResult
|
||||||
|
val bytes = runCatching { context.contentResolver.openInputStream(uri)?.use { readCapped(it) } }.getOrNull()
|
||||||
|
when {
|
||||||
|
bytes == null -> importError =
|
||||||
|
"Couldn't read the file, or it's larger than ${MAX_IMPORT_BYTES / (1024 * 1024)} MB."
|
||||||
|
!vm.loadWavetable(slot, bytes) -> importError =
|
||||||
|
"Couldn't load this wavetable. Use an uncompressed .wav (Serum, WaveEdit, or frames of 256–2048 samples)."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val name = slot.string("o1table", WaveDefs.TABLES[0])
|
||||||
|
val frame = slot.string("wtframe", WaveDefs.FRAME_SIZES[0]).toIntOrNull() ?: 0
|
||||||
|
val table = if (name == WaveTables.CUSTOM) WaveTables.forSample(slot.string(WaveDefs.SAMPLE_KEY), frame) else WaveTables.factory(name)
|
||||||
|
val pos = slot.float("o1pos", 0f)
|
||||||
|
|
||||||
|
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
RetroButton("LOAD TABLE") { picker.launch(arrayOf("*/*")) }
|
||||||
|
Text(
|
||||||
|
if (table == null) "Osc 1: $name (preparing…)" else "Osc 1: ${if (name == WaveTables.CUSTOM) "your table" else name} · ${table.frames} frames",
|
||||||
|
color = c.textDim, fontFamily = FontFamily.Monospace, fontSize = 10.sp,
|
||||||
|
)
|
||||||
|
if (table != null) {
|
||||||
|
// 128 points of each frame's richest level, stacked; recomputed per table only
|
||||||
|
val curves = remember(table) {
|
||||||
|
val n = table.size(0); val step = maxOf(1, table.frames / 16)
|
||||||
|
(0 until table.frames step step).map { f -> FloatArray(128) { i -> table.data[0][f * n + i * n / 128] } to f }
|
||||||
|
}
|
||||||
|
val lit = (pos * (table.frames - 1) + 0.5f).toInt()
|
||||||
|
Canvas(Modifier.fillMaxWidth().height(110.dp).background(c.surface)) {
|
||||||
|
val k = curves.size
|
||||||
|
val rowH = size.height * 0.45f
|
||||||
|
for ((idx, cf) in curves.withIndex().reversed()) {
|
||||||
|
val (pts, f) = cf
|
||||||
|
val depth = if (k > 1) idx.toFloat() / (k - 1) else 0f
|
||||||
|
val x0 = size.width * 0.04f + depth * size.width * 0.18f
|
||||||
|
val w = size.width * 0.76f
|
||||||
|
val yMid = size.height * 0.72f - depth * size.height * 0.45f
|
||||||
|
val near = kotlin.math.abs(f - lit) * 2 <= maxOf(1, table.frames / curves.size)
|
||||||
|
val col = if (near) c.accent else c.text.copy(alpha = 0.25f)
|
||||||
|
for (i in 1 until pts.size) {
|
||||||
|
drawLine(col,
|
||||||
|
Offset(x0 + w * (i - 1) / pts.size, yMid - pts[i - 1] * rowH * 0.5f),
|
||||||
|
Offset(x0 + w * i / pts.size, yMid - pts[i] * rowH * 0.5f),
|
||||||
|
strokeWidth = if (near) 2f else 1f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
importError?.let { msg ->
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { importError = null },
|
||||||
|
title = { Text("Import failed") },
|
||||||
|
text = { Text(msg) },
|
||||||
|
confirmButton = { TextButton(onClick = { importError = null }) { Text("OK") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
package cc.tiredsysadmin.android.sizzle.wavetable
|
||||||
|
|
||||||
|
import cc.tiredsysadmin.android.sizzle.model.ParamSpec
|
||||||
|
import cc.tiredsysadmin.android.sizzle.model.TimeDivision
|
||||||
|
|
||||||
|
/** The wavetable synth's settings, editor pages and factory presets. */
|
||||||
|
object WaveDefs {
|
||||||
|
|
||||||
|
val TABLES: List<String> = WaveTables.FACTORY_NAMES + WaveTables.CUSTOM
|
||||||
|
val FILTER_TYPES = listOf("Low", "Band", "High")
|
||||||
|
val LFO_WAVES = listOf("Sine", "Tri", "Saw", "Square", "S&H")
|
||||||
|
val FRAME_SIZES = listOf("Auto", "256", "512", "1024", "2048")
|
||||||
|
/** A custom table's WAV lives under the SF2/XI loader's keys, so presets, project
|
||||||
|
* bundles and startup rehydration carry it (see PresetLibrary). */
|
||||||
|
const val SAMPLE_KEY = "sfSample"
|
||||||
|
|
||||||
|
val PARAMS: List<ParamSpec> by lazy {
|
||||||
|
buildList {
|
||||||
|
for (o in 1..2) {
|
||||||
|
add(ParamSpec("o${o}table", "Osc$o Table", choices = TABLES))
|
||||||
|
add(ParamSpec("o${o}pos", "Osc$o Position", if (o == 1) 0f else 0.3f, 0f, 1f))
|
||||||
|
add(ParamSpec("o${o}oct", "Osc$o Oct", 0f, -2f, 2f, isInt = true))
|
||||||
|
add(ParamSpec("o${o}semi", "Osc$o Semi", 0f, -12f, 12f, isInt = true))
|
||||||
|
add(ParamSpec("o${o}fine", "Osc$o Fine", if (o == 1) 0f else 7f, -50f, 50f))
|
||||||
|
add(ParamSpec("o${o}level", "Osc$o Level", if (o == 1) 0.8f else 0f, 0f, 1f))
|
||||||
|
add(ParamSpec("o${o}bend", "Osc$o Bend", 0f, -1f, 1f))
|
||||||
|
}
|
||||||
|
add(ParamSpec("unison", "Unison", 1f, 1f, 4f, isInt = true))
|
||||||
|
add(ParamSpec("spread", "Spread", 0.3f, 0f, 1f))
|
||||||
|
add(ParamSpec("sub", "Sub", 0f, 0f, 1f))
|
||||||
|
add(ParamSpec("noise", "Noise", 0f, 0f, 1f))
|
||||||
|
add(ParamSpec("velsens", "Velocity", 0.5f, 0f, 1f))
|
||||||
|
add(ParamSpec("wtframe", "Frame Size", choices = FRAME_SIZES))
|
||||||
|
add(ParamSpec("ftype", "Filter", choices = FILTER_TYPES))
|
||||||
|
add(ParamSpec("cutoff", "Cutoff", 0.75f, 0f, 1f))
|
||||||
|
add(ParamSpec("reso", "Resonance", 0.15f, 0f, 1f))
|
||||||
|
add(ParamSpec("keytrack", "Key Track", 0.4f, 0f, 1f))
|
||||||
|
add(ParamSpec("fenv", "Env Amount", 0.2f, -1f, 1f))
|
||||||
|
add(ParamSpec("drive", "Drive", 0f, 0f, 1f))
|
||||||
|
add(ParamSpec("attack", "Attack", 0.01f, 0f, 5f))
|
||||||
|
add(ParamSpec("decay", "Decay", 0.3f, 0f, 5f))
|
||||||
|
add(ParamSpec("sustain", "Sustain", 0.8f, 0f, 1f))
|
||||||
|
add(ParamSpec("release", "Release", 0.4f, 0f, 8f))
|
||||||
|
add(ParamSpec("mattack", "Mod Attack", 0.5f, 0f, 10f))
|
||||||
|
add(ParamSpec("mdecay", "Mod Decay", 2f, 0f, 10f))
|
||||||
|
add(ParamSpec("msustain", "Mod Sustain", 0.5f, 0f, 1f))
|
||||||
|
add(ParamSpec("mrelease", "Mod Release", 1f, 0f, 10f))
|
||||||
|
add(ParamSpec("menvpos", "Env > Position", 0.3f, -1f, 1f))
|
||||||
|
add(ParamSpec("lfowave", "LFO Wave", choices = LFO_WAVES))
|
||||||
|
add(ParamSpec("lfodiv", "LFO Sync", 1f, 0f, (TimeDivision.entries.size - 1).toFloat(), isInt = true))
|
||||||
|
add(ParamSpec("lfopos", "LFO > Position", 0.15f, 0f, 1f))
|
||||||
|
add(ParamSpec("lfopitch", "LFO > Pitch", 0f, 0f, 1f))
|
||||||
|
add(ParamSpec("lfocut", "LFO > Cutoff", 0f, 0f, 1f))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val SECTIONS: List<Pair<String, List<String>>> = listOf(
|
||||||
|
"Osc 1" to listOf("o1table", "o1pos", "o1oct", "o1semi", "o1fine", "o1level", "o1bend"),
|
||||||
|
"Osc 2" to listOf("o2table", "o2pos", "o2oct", "o2semi", "o2fine", "o2level", "o2bend"),
|
||||||
|
"Voice" to listOf("unison", "spread", "sub", "noise", "velsens", "wtframe"),
|
||||||
|
"Filter" to listOf("ftype", "cutoff", "reso", "keytrack", "fenv", "drive"),
|
||||||
|
"Amp Env" to listOf("attack", "decay", "sustain", "release"),
|
||||||
|
"Mod Env" to listOf("mattack", "mdecay", "msustain", "mrelease", "menvpos"),
|
||||||
|
"LFO" to listOf("lfowave", "lfodiv", "lfopos", "lfopitch", "lfocut"),
|
||||||
|
)
|
||||||
|
|
||||||
|
class Preset(val name: String, val values: Map<String, String>)
|
||||||
|
|
||||||
|
val FACTORY: List<Preset> by lazy {
|
||||||
|
fun p(name: String, vararg v: Pair<String, Any>): Preset {
|
||||||
|
val m = LinkedHashMap<String, String>()
|
||||||
|
for (spec in PARAMS) m[spec.key] = if (spec.isEnum) spec.choices[0] else spec.default.toString()
|
||||||
|
for ((k, x) in v) m[k] = x.toString()
|
||||||
|
return Preset(name, m)
|
||||||
|
}
|
||||||
|
listOf(
|
||||||
|
p("Morph Lead", "o1table" to "Classic", "o1pos" to 0.4f, "menvpos" to 0.5f, "mattack" to 0.01f, "mdecay" to 0.8f, "msustain" to 0.2f,
|
||||||
|
"cutoff" to 0.8f, "reso" to 0.25f, "lfopitch" to 0.15f, "lfodiv" to 3, "release" to 0.25f),
|
||||||
|
p("Vowel Pad", "o1table" to "Vowels", "o1pos" to 0f, "o2table" to "Vowels", "o2pos" to 0.5f, "o2level" to 0.6f, "o2fine" to 9f,
|
||||||
|
"unison" to 3, "spread" to 0.4f, "attack" to 0.8f, "release" to 2.5f, "mattack" to 3f, "mdecay" to 4f, "msustain" to 0.7f,
|
||||||
|
"menvpos" to 0.6f, "lfopos" to 0.2f, "lfodiv" to 0, "cutoff" to 0.7f),
|
||||||
|
p("PWM Strings", "o1table" to "PWM", "o1pos" to 0.2f, "o2table" to "PWM", "o2pos" to 0.6f, "o2level" to 0.7f, "o2fine" to -8f,
|
||||||
|
"unison" to 2, "spread" to 0.5f, "attack" to 0.4f, "release" to 1.2f, "lfopos" to 0.4f, "lfodiv" to 1, "menvpos" to 0f,
|
||||||
|
"cutoff" to 0.65f, "reso" to 0.1f),
|
||||||
|
p("Sync Sweep", "o1table" to "Sync", "o1pos" to 0f, "menvpos" to 0.9f, "mattack" to 0f, "mdecay" to 0.6f, "msustain" to 0.1f,
|
||||||
|
"cutoff" to 0.85f, "fenv" to 0.3f, "decay" to 0.5f, "sustain" to 0.6f, "release" to 0.2f, "drive" to 0.3f),
|
||||||
|
p("FM Bells", "o1table" to "FM", "o1pos" to 0.6f, "menvpos" to -0.6f, "mattack" to 0f, "mdecay" to 1.5f, "msustain" to 0f,
|
||||||
|
"attack" to 0f, "decay" to 2.5f, "sustain" to 0f, "release" to 2f, "cutoff" to 0.9f, "keytrack" to 0.8f, "fenv" to 0f),
|
||||||
|
p("Glass Keys", "o1table" to "Glass", "o1pos" to 0.2f, "o2table" to "Classic", "o2pos" to 0f, "o2oct" to 1, "o2level" to 0.3f,
|
||||||
|
"attack" to 0.005f, "decay" to 1.2f, "sustain" to 0.3f, "release" to 1f, "menvpos" to 0.4f, "mdecay" to 1.2f, "msustain" to 0.2f,
|
||||||
|
"mattack" to 0f, "cutoff" to 0.75f),
|
||||||
|
p("Organ Drift", "o1table" to "Organ", "o1pos" to 0f, "lfopos" to 0.5f, "lfodiv" to 0, "lfowave" to "Tri", "attack" to 0.02f,
|
||||||
|
"sustain" to 1f, "release" to 0.15f, "menvpos" to 0f, "cutoff" to 0.9f, "reso" to 0f),
|
||||||
|
p("Fold Bass", "o1table" to "Fold", "o1pos" to 0.1f, "o1oct" to -1, "sub" to 0.5f, "menvpos" to 0.7f, "mattack" to 0f,
|
||||||
|
"mdecay" to 0.3f, "msustain" to 0f, "attack" to 0f, "decay" to 0.4f, "sustain" to 0.7f, "release" to 0.15f,
|
||||||
|
"cutoff" to 0.55f, "fenv" to 0.35f, "drive" to 0.4f),
|
||||||
|
p("Digital Grit", "o1table" to "Digital", "o1pos" to 0.3f, "o2table" to "Digital", "o2pos" to 0.9f, "o2level" to 0.5f,
|
||||||
|
"o2semi" to 7, "lfopos" to 0.6f, "lfowave" to "S&H", "lfodiv" to 4, "menvpos" to 0f, "cutoff" to 0.8f, "reso" to 0.3f),
|
||||||
|
p("Comb Choir", "o1table" to "Comb", "o1pos" to 0f, "unison" to 4, "spread" to 0.45f, "attack" to 1.2f, "release" to 3f,
|
||||||
|
"mattack" to 6f, "mdecay" to 6f, "msustain" to 1f, "menvpos" to 1f, "cutoff" to 0.7f, "lfocut" to 0.2f, "lfodiv" to 0),
|
||||||
|
p("Odd Even Pluck", "o1table" to "Odd Even", "o1pos" to 1f, "menvpos" to -1f, "mattack" to 0f, "mdecay" to 0.5f, "msustain" to 0f,
|
||||||
|
"attack" to 0f, "decay" to 0.6f, "sustain" to 0f, "release" to 0.4f, "cutoff" to 0.7f, "fenv" to 0.4f, "reso" to 0.3f),
|
||||||
|
p("Harmonic Rise", "o1table" to "Harmonic Sweep", "o1pos" to 0f, "o2table" to "Harmonic Sweep", "o2pos" to 0f, "o2level" to 0.6f,
|
||||||
|
"o2fine" to 10f, "unison" to 2, "spread" to 0.3f, "attack" to 2f, "release" to 3f, "mattack" to 5f, "mdecay" to 8f,
|
||||||
|
"msustain" to 1f, "menvpos" to 1f, "cutoff" to 0.85f, "reso" to 0.05f),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,333 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
package cc.tiredsysadmin.android.sizzle.wavetable
|
||||||
|
|
||||||
|
import cc.tiredsysadmin.android.sizzle.audio.SampleStore
|
||||||
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
import java.util.concurrent.Executors
|
||||||
|
import kotlin.math.PI
|
||||||
|
import kotlin.math.abs
|
||||||
|
import kotlin.math.cos
|
||||||
|
import kotlin.math.exp
|
||||||
|
import kotlin.math.floor
|
||||||
|
import kotlin.math.max
|
||||||
|
import kotlin.math.min
|
||||||
|
import kotlin.math.pow
|
||||||
|
import kotlin.math.round
|
||||||
|
import kotlin.math.sin
|
||||||
|
import kotlin.math.sqrt
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A wavetable ready to play: [frames] single cycles, each kept as band-limited
|
||||||
|
* copies, one per octave ("mip levels"). Level k holds at most `512 >> k`
|
||||||
|
* harmonics in a cycle of [size]`(k)` samples (at least four samples per top
|
||||||
|
* harmonic, so linear interpolation is clean); the top quarter of each level's
|
||||||
|
* harmonics is faded out with a raised cosine, so moving from one level to the next
|
||||||
|
* as the pitch rises is not heard as a step. The voice picks the level whose top
|
||||||
|
* harmonic stays under Nyquist.
|
||||||
|
*/
|
||||||
|
class WaveTable(val name: String, val frames: Int, /** [level][frame * size(level) + i] */ val data: Array<FloatArray>) {
|
||||||
|
fun size(level: Int) = SIZES[level]
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val MAX_HARMONICS = 512
|
||||||
|
const val LEVELS = 10
|
||||||
|
val SIZES = IntArray(LEVELS) { k -> max(64, 4 * (MAX_HARMONICS shr k)) }
|
||||||
|
/** Harmonics level k carries. */
|
||||||
|
fun harmonics(level: Int) = MAX_HARMONICS shr level
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The wavetable synth's tables: twelve factory tables made here from formulas (no
|
||||||
|
* audio files ship), and tables imported from WAV files (Serum's 2048-sample frames,
|
||||||
|
* WaveEdit's 256, or any power-of-two frame length).
|
||||||
|
*
|
||||||
|
* Everything is built off the audio thread: [prewarm] makes the factory set in the
|
||||||
|
* background at startup; an imported table is built when it is loaded, or — after a
|
||||||
|
* restart, when only its WAV comes back — on a worker the first time a voice asks
|
||||||
|
* ([forSample]). Lookups never block; a table that isn't ready yet is silent.
|
||||||
|
*
|
||||||
|
* All original work for Sizzle: the method (spectra, an inverse FFT per octave with
|
||||||
|
* a taper at the top) is the textbook way to band-limit a wavetable.
|
||||||
|
*/
|
||||||
|
object WaveTables {
|
||||||
|
|
||||||
|
const val FRAMES = 16
|
||||||
|
private const val GEN = 4096 // the cycle length the formulas are sampled at
|
||||||
|
|
||||||
|
val FACTORY_NAMES = listOf(
|
||||||
|
"Classic", "PWM", "Vowels", "Harmonic Sweep", "Sync", "FM",
|
||||||
|
"Organ", "Fold", "Digital", "Glass", "Odd Even", "Comb",
|
||||||
|
)
|
||||||
|
const val CUSTOM = "Custom"
|
||||||
|
|
||||||
|
private val cache = ConcurrentHashMap<String, WaveTable>()
|
||||||
|
private val building = ConcurrentHashMap.newKeySet<String>()
|
||||||
|
private val worker = Executors.newSingleThreadExecutor { r -> Thread(r, "sizzle-wavetables").apply { isDaemon = true; priority = Thread.MIN_PRIORITY } }
|
||||||
|
@Volatile private var started = false
|
||||||
|
|
||||||
|
fun factory(name: String): WaveTable? = cache[name]
|
||||||
|
|
||||||
|
/** The table built from the custom sample [id] cut in [frameLen]-sample frames (0: detect),
|
||||||
|
* or null while it is being built (it is then queued once). */
|
||||||
|
fun forSample(id: String, frameLen: Int): WaveTable? {
|
||||||
|
if (id.isEmpty()) return null
|
||||||
|
val key = "$id#$frameLen"
|
||||||
|
cache[key]?.let { return it }
|
||||||
|
if (building.add(key)) worker.execute {
|
||||||
|
SampleStore.get(id)?.let { s -> cache[key] = fromSamples(CUSTOM, s.data, frameLen) }
|
||||||
|
building.remove(key)
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Build a custom table now (the caller is off the audio thread) and cache it. */
|
||||||
|
fun buildForSample(id: String, frameLen: Int): WaveTable? {
|
||||||
|
val s = SampleStore.get(id) ?: return null
|
||||||
|
return fromSamples(CUSTOM, s.data, frameLen).also { cache["$id#$frameLen"] = it }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun prewarm() {
|
||||||
|
if (started) return
|
||||||
|
started = true
|
||||||
|
worker.execute { prewarmBlocking() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun prewarmBlocking() {
|
||||||
|
for (n in FACTORY_NAMES) if (!cache.containsKey(n)) cache[n] = makeFactory(n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ building ---
|
||||||
|
|
||||||
|
/** A table from cycles given as time-domain samples ([cycles] of equal power-of-two length). */
|
||||||
|
private fun fromCycles(name: String, cycles: List<FloatArray>): WaveTable {
|
||||||
|
val spectra = cycles.map { spectrum(it) }
|
||||||
|
return fromSpectra(name, spectra)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** [spectra]: per frame, cosine and sine amplitudes of harmonics 1..512 (index h-1). */
|
||||||
|
private fun fromSpectra(name: String, spectra: List<Pair<FloatArray, FloatArray>>): WaveTable {
|
||||||
|
val nf = spectra.size
|
||||||
|
val data = Array(WaveTable.LEVELS) { k -> FloatArray(nf * WaveTable.SIZES[k]) }
|
||||||
|
for (k in 0 until WaveTable.LEVELS) {
|
||||||
|
val n = WaveTable.SIZES[k]
|
||||||
|
val hk = WaveTable.harmonics(k)
|
||||||
|
val re = DoubleArray(n); val im = DoubleArray(n)
|
||||||
|
for (f in 0 until nf) {
|
||||||
|
val (c, s) = spectra[f]
|
||||||
|
re.fill(0.0); im.fill(0.0)
|
||||||
|
for (h in 1..min(hk, c.size)) {
|
||||||
|
val taper = taper(h, hk)
|
||||||
|
if (taper <= 0.0) continue
|
||||||
|
re[h] = c[h - 1] * taper
|
||||||
|
im[h] = -s[h - 1] * taper
|
||||||
|
}
|
||||||
|
fft(re, im, inverse = true)
|
||||||
|
val base = f * n
|
||||||
|
for (i in 0 until n) data[k][base + i] = re[i].toFloat()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return WaveTable(name, nf, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The top quarter of a level's harmonics fades out (raised cosine). */
|
||||||
|
private fun taper(h: Int, hk: Int): Double {
|
||||||
|
if (hk <= 4) return if (h <= hk) 1.0 else 0.0
|
||||||
|
val a = 0.75 * hk
|
||||||
|
return when {
|
||||||
|
h <= a -> 1.0
|
||||||
|
h > hk -> 0.0
|
||||||
|
else -> 0.5 + 0.5 * cos(PI * (h - a) / (hk - a + 1))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Harmonics 1..512 of one cycle (any power-of-two length; others are resampled). */
|
||||||
|
private fun spectrum(cycle0: FloatArray): Pair<FloatArray, FloatArray> {
|
||||||
|
val cycle = if (Integer.bitCount(cycle0.size) == 1) cycle0 else resample(cycle0, 2048)
|
||||||
|
val m = cycle.size
|
||||||
|
val re = DoubleArray(m) { cycle[it].toDouble() }
|
||||||
|
val im = DoubleArray(m)
|
||||||
|
fft(re, im, inverse = false)
|
||||||
|
val hn = min(WaveTable.MAX_HARMONICS, m / 2 - 1)
|
||||||
|
val c = FloatArray(WaveTable.MAX_HARMONICS); val s = FloatArray(WaveTable.MAX_HARMONICS)
|
||||||
|
for (h in 1..hn) { c[h - 1] = (2.0 * re[h] / m).toFloat(); s[h - 1] = (-2.0 * im[h] / m).toFloat() }
|
||||||
|
return c to s
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun resample(x: FloatArray, n: Int): FloatArray = FloatArray(n) { i ->
|
||||||
|
val p = i.toDouble() * x.size / n
|
||||||
|
val j = p.toInt(); val fr = (p - j).toFloat()
|
||||||
|
x[j % x.size] + (x[(j + 1) % x.size] - x[j % x.size]) * fr
|
||||||
|
}
|
||||||
|
|
||||||
|
/** In-place radix-2 complex FFT; [inverse] uses e^{+i} and no 1/N (the synthesis sum). */
|
||||||
|
private fun fft(re: DoubleArray, im: DoubleArray, inverse: Boolean) {
|
||||||
|
val n = re.size
|
||||||
|
var j = 0
|
||||||
|
for (i in 1 until n) {
|
||||||
|
var bit = n shr 1
|
||||||
|
while (j and bit != 0) { j = j xor bit; bit = bit shr 1 }
|
||||||
|
j = j xor bit
|
||||||
|
if (i < j) { var t = re[i]; re[i] = re[j]; re[j] = t; t = im[i]; im[i] = im[j]; im[j] = t }
|
||||||
|
}
|
||||||
|
var len = 2
|
||||||
|
while (len <= n) {
|
||||||
|
val ang = 2 * PI / len * (if (inverse) 1 else -1)
|
||||||
|
val wr = cos(ang); val wi = sin(ang)
|
||||||
|
var i = 0
|
||||||
|
while (i < n) {
|
||||||
|
var cr = 1.0; var ci = 0.0
|
||||||
|
for (k in 0 until len / 2) {
|
||||||
|
val ar = re[i + k + len / 2] * cr - im[i + k + len / 2] * ci
|
||||||
|
val ai = re[i + k + len / 2] * ci + im[i + k + len / 2] * cr
|
||||||
|
re[i + k + len / 2] = re[i + k] - ar; im[i + k + len / 2] = im[i + k] - ai
|
||||||
|
re[i + k] += ar; im[i + k] += ai
|
||||||
|
val ncr = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = ncr
|
||||||
|
}
|
||||||
|
i += len
|
||||||
|
}
|
||||||
|
len = len shl 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------- import ---
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The frame length of a wavetable WAV: Serum's `clm ` chunk ("<!>2048 …") when
|
||||||
|
* present, else WaveEdit's 64 x 256 layout, else 2048 or 256 if the length divides,
|
||||||
|
* else the whole file as one cycle (0).
|
||||||
|
*/
|
||||||
|
fun detectFrameLength(wavBytes: ByteArray, frames: Int): Int {
|
||||||
|
val clm = indexOf(wavBytes, "clm ".toByteArray())
|
||||||
|
if (clm >= 0) {
|
||||||
|
val text = String(wavBytes, clm + 8, min(32, wavBytes.size - clm - 8), Charsets.US_ASCII)
|
||||||
|
Regex("<!>(\\d{2,5})").find(text)?.groupValues?.get(1)?.toIntOrNull()?.let { if (it in 16..8192 && frames % it == 0) return it }
|
||||||
|
}
|
||||||
|
return guessFrameLength(frames)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun guessFrameLength(frames: Int): Int = when {
|
||||||
|
frames == 64 * 256 -> 256
|
||||||
|
frames % 2048 == 0 && frames / 2048 in 1..256 -> 2048
|
||||||
|
frames % 256 == 0 && frames / 256 in 1..256 -> 256
|
||||||
|
frames % 1024 == 0 && frames / 1024 in 1..256 -> 1024
|
||||||
|
frames % 512 == 0 && frames / 512 in 1..256 -> 512
|
||||||
|
else -> 0
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun indexOf(h: ByteArray, n: ByteArray): Int {
|
||||||
|
outer@ for (i in 0..h.size - n.size) { for (j in n.indices) if (h[i + j] != n[j]) continue@outer; return i }
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A table from a sample cut into [frameLen0]-sample cycles (0: detect; at most 256 frames). */
|
||||||
|
fun fromSamples(name: String, x: FloatArray, frameLen0: Int): WaveTable {
|
||||||
|
val frameLen = if (frameLen0 > 0) frameLen0 else guessFrameLength(x.size)
|
||||||
|
val cycles = if (frameLen <= 0 || x.size < frameLen) listOf(x.copyOf())
|
||||||
|
else {
|
||||||
|
val n = min(256, x.size / frameLen)
|
||||||
|
val step = (x.size / frameLen).toDouble() / n
|
||||||
|
List(n) { i -> val f = (i * step).toInt(); x.copyOfRange(f * frameLen, (f + 1) * frameLen) }
|
||||||
|
}
|
||||||
|
var pk = 1e-9f
|
||||||
|
for (c in cycles) for (v in c) pk = max(pk, abs(v))
|
||||||
|
val g = 1f / pk
|
||||||
|
return fromCycles(name, cycles.map { c -> FloatArray(c.size) { c[it] * g } })
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- factory ---
|
||||||
|
|
||||||
|
private fun makeFactory(name: String): WaveTable {
|
||||||
|
val cycles = List(FRAMES) { f ->
|
||||||
|
val t = f / (FRAMES - 1.0)
|
||||||
|
val x = DoubleArray(GEN) { i -> sample(name, t, f, i.toDouble() / GEN) }
|
||||||
|
val dc = x.average()
|
||||||
|
var pk = 1e-9
|
||||||
|
for (i in x.indices) { x[i] -= dc; pk = max(pk, abs(x[i])) }
|
||||||
|
FloatArray(GEN) { (x[it] / pk).toFloat() }
|
||||||
|
}
|
||||||
|
return fromCycles(name, cycles)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun saw(p: Double) = 2 * (p - floor(p)) - 1
|
||||||
|
private fun pulse(p: Double, w: Double) = if (p - floor(p) < w) 1.0 else -1.0
|
||||||
|
private fun tri(p: Double) = 1 - 4 * abs((p - floor(p)) - 0.5)
|
||||||
|
private fun sine(p: Double) = sin(2 * PI * p)
|
||||||
|
|
||||||
|
/** Additive: harmonics 1..n with amplitude a(h), all sine phase. */
|
||||||
|
private inline fun additive(p: Double, n: Int, a: (Int) -> Double): Double {
|
||||||
|
var s = 0.0
|
||||||
|
for (h in 1..n) { val v = a(h); if (v != 0.0) s += v * sin(2 * PI * h * p) }
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
private val VOWELS = arrayOf( // formant centre frequencies (Hz): a, e, i, o, u
|
||||||
|
doubleArrayOf(800.0, 1150.0, 2900.0), doubleArrayOf(400.0, 1600.0, 2700.0), doubleArrayOf(300.0, 2300.0, 3000.0),
|
||||||
|
doubleArrayOf(450.0, 800.0, 2830.0), doubleArrayOf(325.0, 700.0, 2530.0),
|
||||||
|
)
|
||||||
|
private val DRAWBARS = arrayOf( // levels of harmonics 1, 2, 3, 4, 6, 8 (and the 16' sub as h1)
|
||||||
|
doubleArrayOf(8.0, 8.0, 8.0, 0.0, 0.0, 0.0), doubleArrayOf(8.0, 0.0, 8.0, 6.0, 0.0, 4.0),
|
||||||
|
doubleArrayOf(6.0, 8.0, 4.0, 8.0, 3.0, 2.0), doubleArrayOf(8.0, 3.0, 0.0, 8.0, 8.0, 8.0),
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Glass: sparse prime and square-ish harmonics at seeded levels, a new set every
|
||||||
|
* four frames, crossfaded between. */
|
||||||
|
private val GLASS: Array<DoubleArray> by lazy {
|
||||||
|
val primes = setOf(1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37)
|
||||||
|
val squares = setOf(1, 2, 4, 6, 9, 12, 16, 20, 25, 30, 36)
|
||||||
|
val sets = Array(FRAMES / 4 + 2) { k ->
|
||||||
|
val rng = java.util.Random(0x61A55L + k)
|
||||||
|
val pick = if (k % 2 == 0) primes else squares
|
||||||
|
DoubleArray(40) { h -> if ((h + 1) in pick) 0.2 + 0.8 * rng.nextDouble() else 0.0 }
|
||||||
|
}
|
||||||
|
Array(FRAMES) { f ->
|
||||||
|
val k = f / 4; val fr = (f % 4) / 4.0
|
||||||
|
DoubleArray(40) { h -> sets[k][h] * (1 - fr) + sets[k + 1][h] * fr }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val CLASSIC: Array<(Double) -> Double> = arrayOf({ q -> sine(q) }, { q -> tri(q) }, { q -> saw(q) },
|
||||||
|
{ q -> pulse(q, 0.5) }, { q -> pulse(q, 0.25) })
|
||||||
|
|
||||||
|
private fun sample(name: String, t: Double, f: Int, p: Double): Double = when (name) {
|
||||||
|
"Classic" -> {
|
||||||
|
val x = t * 4; val i = min(3, x.toInt()); val fr = x - i
|
||||||
|
CLASSIC[i](p) * (1 - fr) + CLASSIC[i + 1](p) * fr
|
||||||
|
}
|
||||||
|
"PWM" -> pulse(p, 0.5 - 0.46 * t)
|
||||||
|
"Vowels" -> {
|
||||||
|
val x = t * 4; val i = min(3, x.toInt()); val fr = x - i
|
||||||
|
additive(p, 60) { h ->
|
||||||
|
val hz = h * 110.0
|
||||||
|
var a = 0.0
|
||||||
|
for (k in 0 until 3) {
|
||||||
|
val fc = VOWELS[i][k] * (1 - fr) + VOWELS[i + 1][k] * fr
|
||||||
|
val bw = 80.0 + 40.0 * k
|
||||||
|
a += exp(-((hz - fc) / bw).pow(2)) * (if (k == 0) 1.0 else 0.6)
|
||||||
|
}
|
||||||
|
(a + 0.02) / sqrt(h.toDouble())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"Harmonic Sweep" -> {
|
||||||
|
val n = 1.0 + 2.0.pow(t * 6)
|
||||||
|
additive(p, 65) { h -> if (h <= n) 1.0 / h else if (h - 1 < n) (n - (h - 1)) / h else 0.0 }
|
||||||
|
}
|
||||||
|
"Sync" -> saw(p * (1 + 7 * t)) * (1 - 0.3 * t * p)
|
||||||
|
"FM" -> sin(2 * PI * p + 7 * t * sin(2 * PI * p) + 1.5 * t * t * sin(4 * PI * p))
|
||||||
|
"Organ" -> {
|
||||||
|
val x = t * 3; val i = min(2, x.toInt()); val fr = x - i
|
||||||
|
val hs = intArrayOf(1, 2, 3, 4, 6, 8)
|
||||||
|
var s = 0.0
|
||||||
|
for (k in hs.indices) s += (DRAWBARS[i][k] * (1 - fr) + DRAWBARS[i + 1][k] * fr) / 8 * sine(hs[k] * p)
|
||||||
|
s
|
||||||
|
}
|
||||||
|
"Fold" -> sin((1 + 7 * t) * sin(2 * PI * p) * PI / 2)
|
||||||
|
"Digital" -> { val steps = 2.0.pow(6 - 5 * t); round(sine(p) * steps) / steps }
|
||||||
|
"Glass" -> additive(p, 40) { h -> GLASS[f][h - 1] / h.toDouble().pow(0.6) }
|
||||||
|
"Odd Even" -> additive(p, 64) { h -> if (h % 2 == 1) (1 - t) / h + t * 0.3 / h else t / h * (if (h == 2) 1.6 else 1.0) }
|
||||||
|
"Comb" -> additive(p, 64) { h -> abs(cos(PI * h * (0.02 + 0.23 * t))) / h }
|
||||||
|
else -> sine(p)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
package cc.tiredsysadmin.android.sizzle.wavetable
|
||||||
|
|
||||||
|
import cc.tiredsysadmin.android.sizzle.model.TimeDivision
|
||||||
|
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
|
||||||
|
import kotlin.math.PI
|
||||||
|
import kotlin.math.ceil
|
||||||
|
import kotlin.math.floor
|
||||||
|
import kotlin.math.ln
|
||||||
|
import kotlin.math.max
|
||||||
|
import kotlin.math.min
|
||||||
|
import kotlin.math.pow
|
||||||
|
import kotlin.math.sin
|
||||||
|
import kotlin.math.sqrt
|
||||||
|
import kotlin.math.tan
|
||||||
|
import kotlin.math.tanh
|
||||||
|
|
||||||
|
/** A parsed Wavetable slot (built once per slot change, off the sample loop). */
|
||||||
|
class WavePatch(
|
||||||
|
val table: Array<String>, val pos: FloatArray, val semis: FloatArray, val level: FloatArray, val bend: FloatArray,
|
||||||
|
val unison: Int, val spread: Float, val sub: Float, val noise: Float, val velSens: Float,
|
||||||
|
val customId: String, val frameLen: Int,
|
||||||
|
val filterType: Int, val cutoff: Float, val reso: Float, val keytrack: Float, val fenv: Float, val drive: Float,
|
||||||
|
val a: Float, val d: Float, val s: Float, val r: Float,
|
||||||
|
val ma: Float, val md: Float, val ms: Float, val mr: Float, val menvPos: Float,
|
||||||
|
val lfoWave: Int, val lfoHz: Float, val lfoPos: Float, val lfoPitch: Float, val lfoCut: Float,
|
||||||
|
) {
|
||||||
|
companion object {
|
||||||
|
fun from(slot: ToolboxSlot?, tempoBpm: Float): WavePatch {
|
||||||
|
fun f(k: String, d: Float) = slot?.float(k, d) ?: d
|
||||||
|
fun c(k: String, choices: List<String>) = choices.indexOf(slot?.string(k, choices[0]) ?: choices[0]).coerceAtLeast(0)
|
||||||
|
val tables = Array(2) { o -> slot?.string("o${o + 1}table", WaveDefs.TABLES[0]) ?: WaveDefs.TABLES[0] }
|
||||||
|
val semis = FloatArray(2) { o ->
|
||||||
|
val n = o + 1
|
||||||
|
f("o${n}oct", 0f).toInt().coerceIn(-2, 2) * 12f + f("o${n}semi", 0f).toInt().coerceIn(-12, 12) +
|
||||||
|
f("o${n}fine", if (n == 1) 0f else 7f).coerceIn(-50f, 50f) / 100f
|
||||||
|
}
|
||||||
|
val frame = WaveDefs.FRAME_SIZES[c("wtframe", WaveDefs.FRAME_SIZES)].toIntOrNull() ?: 0
|
||||||
|
val beat = TimeDivision.fromIndex(f("lfodiv", 1f).toInt()).beatFraction.toFloat()
|
||||||
|
return WavePatch(
|
||||||
|
table = tables,
|
||||||
|
pos = FloatArray(2) { o -> f("o${o + 1}pos", if (o == 0) 0f else 0.3f).coerceIn(0f, 1f) },
|
||||||
|
semis = semis,
|
||||||
|
level = FloatArray(2) { o -> f("o${o + 1}level", if (o == 0) 0.8f else 0f).coerceIn(0f, 1f) },
|
||||||
|
bend = FloatArray(2) { o -> f("o${o + 1}bend", 0f).coerceIn(-1f, 1f) },
|
||||||
|
unison = f("unison", 1f).toInt().coerceIn(1, 4), spread = f("spread", 0.3f).coerceIn(0f, 1f),
|
||||||
|
sub = f("sub", 0f).coerceIn(0f, 1f), noise = f("noise", 0f).coerceIn(0f, 1f), velSens = f("velsens", 0.5f).coerceIn(0f, 1f),
|
||||||
|
customId = slot?.string(WaveDefs.SAMPLE_KEY, "") ?: "", frameLen = frame,
|
||||||
|
filterType = c("ftype", WaveDefs.FILTER_TYPES), cutoff = f("cutoff", 0.75f).coerceIn(0f, 1f),
|
||||||
|
reso = f("reso", 0.15f).coerceIn(0f, 1f), keytrack = f("keytrack", 0.4f).coerceIn(0f, 1f),
|
||||||
|
fenv = f("fenv", 0.2f).coerceIn(-1f, 1f), drive = f("drive", 0f).coerceIn(0f, 1f),
|
||||||
|
a = f("attack", 0.01f), d = f("decay", 0.3f), s = f("sustain", 0.8f).coerceIn(0f, 1f), r = f("release", 0.4f),
|
||||||
|
ma = f("mattack", 0.5f), md = f("mdecay", 2f), ms = f("msustain", 0.5f).coerceIn(0f, 1f), mr = f("mrelease", 1f),
|
||||||
|
menvPos = f("menvpos", 0.3f).coerceIn(-1f, 1f),
|
||||||
|
lfoWave = c("lfowave", WaveDefs.LFO_WAVES),
|
||||||
|
lfoHz = if (beat > 0f) (tempoBpm / 60f) / beat else 1f,
|
||||||
|
lfoPos = f("lfopos", 0.15f).coerceIn(0f, 1f), lfoPitch = f("lfopitch", 0f).coerceIn(0f, 1f),
|
||||||
|
lfoCut = f("lfocut", 0f).coerceIn(0f, 1f),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val DEFAULT: WavePatch by lazy { from(null, 120f) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One note of the wavetable synth:
|
||||||
|
*
|
||||||
|
* 2 wavetable oscillators (each: table, position through its frames, pitch, level,
|
||||||
|
* phase bend, up to 4 unison copies) + a sub sine + noise → drive → state-variable
|
||||||
|
* filter (low / band / high) → amp envelope
|
||||||
|
*
|
||||||
|
* A second envelope and a tempo-synced LFO move the table position, the cutoff and
|
||||||
|
* (LFO) the pitch. Every [CTRL] samples the voice re-reads its tables, positions and
|
||||||
|
* filter, and picks per oscillator the band-limited level whose top harmonic stays
|
||||||
|
* under Nyquist — counting how much BEND steepens the wave — so nothing aliases.
|
||||||
|
* Reads are linear within a cycle (each level keeps four samples per top harmonic)
|
||||||
|
* and linear between the two neighbouring frames.
|
||||||
|
*
|
||||||
|
* BEND is a two-segment phase warp (as in phase-distortion synthesis): the first
|
||||||
|
* half of the cycle is squeezed (bend > 0) or stretched (bend < 0), sharpening the
|
||||||
|
* wave without changing its pitch.
|
||||||
|
*/
|
||||||
|
class WaveVoice(private val fs: Int) {
|
||||||
|
|
||||||
|
private val fsf = fs.toFloat()
|
||||||
|
private var patch = WavePatch.DEFAULT
|
||||||
|
var note = -1; private set
|
||||||
|
private var vel = 0f
|
||||||
|
private var baseHz = 440f
|
||||||
|
|
||||||
|
private val amp = Env()
|
||||||
|
private val mod = Env()
|
||||||
|
|
||||||
|
// oscillators: [osc * MAX_UNISON + u]
|
||||||
|
private val phase = DoubleArray(2 * MAX_UNISON)
|
||||||
|
private val inc = DoubleArray(2 * MAX_UNISON)
|
||||||
|
private val oscTable = arrayOfNulls<WaveTable>(2)
|
||||||
|
private val oscLevel = IntArray(2)
|
||||||
|
private val oscFrame = FloatArray(2)
|
||||||
|
private val oscWarpM = FloatArray(2)
|
||||||
|
private var subPhase = 0.0
|
||||||
|
private var subInc = 0.0
|
||||||
|
|
||||||
|
// filter (topology-preserving SVF)
|
||||||
|
private var s1 = 0f; private var s2 = 0f
|
||||||
|
private var fa1 = 0f; private var fa2 = 0f; private var fa3 = 0f; private var fk = 1f
|
||||||
|
|
||||||
|
private var lfoPh = 0.0
|
||||||
|
private var lfoVal = 0f
|
||||||
|
private var shVal = 0f
|
||||||
|
private var ctrl = 0
|
||||||
|
private var rng = 0x6C8E9CF5
|
||||||
|
|
||||||
|
val isActive: Boolean get() = amp.active
|
||||||
|
val isGated: Boolean get() = amp.gate
|
||||||
|
|
||||||
|
fun noteOn(midi: Int, velocity: Float, p: WavePatch) {
|
||||||
|
val fresh = !amp.active
|
||||||
|
patch = p
|
||||||
|
note = midi
|
||||||
|
vel = velocity.coerceIn(0f, 1f)
|
||||||
|
baseHz = (440.0 * 2.0.pow((midi - 69) / 12.0)).toFloat()
|
||||||
|
amp.on(p.a, p.d, p.s, p.r)
|
||||||
|
mod.on(p.ma, p.md, p.ms, p.mr)
|
||||||
|
if (fresh) {
|
||||||
|
s1 = 0f; s2 = 0f; lfoPh = 0.0
|
||||||
|
for (i in phase.indices) phase[i] = if (i % MAX_UNISON == 0 && p.unison == 1) 0.0 else rand01().toDouble()
|
||||||
|
subPhase = 0.0
|
||||||
|
}
|
||||||
|
ctrl = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
fun noteOff() { amp.off(); mod.off() }
|
||||||
|
|
||||||
|
fun kill() { amp.kill(); mod.kill(); note = -1; s1 = 0f; s2 = 0f }
|
||||||
|
|
||||||
|
fun setPatch(p: WavePatch) { patch = p; amp.retime(p.a, p.d, p.s, p.r); mod.retime(p.ma, p.md, p.ms, p.mr) }
|
||||||
|
|
||||||
|
fun render(): Float {
|
||||||
|
if (!amp.active) return 0f
|
||||||
|
if (ctrl <= 0) { control(); ctrl = CTRL }
|
||||||
|
ctrl--
|
||||||
|
val p = patch
|
||||||
|
var mix = 0f
|
||||||
|
val uni = p.unison
|
||||||
|
val uniGain = 1f / sqrt(uni.toFloat())
|
||||||
|
for (o in 0 until 2) {
|
||||||
|
val t = oscTable[o] ?: continue
|
||||||
|
val lvl = p.level[o]
|
||||||
|
if (lvl <= 0.0001f) continue
|
||||||
|
val lv = oscLevel[o]
|
||||||
|
val size = t.size(lv)
|
||||||
|
val data = t.data[lv]
|
||||||
|
val fpos = oscFrame[o]
|
||||||
|
val f0 = fpos.toInt().coerceAtMost(t.frames - 1)
|
||||||
|
val f1 = min(f0 + 1, t.frames - 1)
|
||||||
|
val ff = fpos - f0
|
||||||
|
val b0 = f0 * size; val b1 = f1 * size
|
||||||
|
val mask = size - 1
|
||||||
|
val m = oscWarpM[o]
|
||||||
|
var acc = 0f
|
||||||
|
for (u in 0 until uni) {
|
||||||
|
val k = o * MAX_UNISON + u
|
||||||
|
var ph = phase[k] + inc[k]
|
||||||
|
if (ph >= 1.0) ph -= 1.0
|
||||||
|
phase[k] = ph
|
||||||
|
// BEND: the cycle's first part squeezed into half (m < 0.5) or stretched (m > 0.5)
|
||||||
|
val pw = if (m == 0.5f) ph.toFloat() else {
|
||||||
|
val q = ph.toFloat()
|
||||||
|
if (q < m) 0.5f * q / m else 0.5f + 0.5f * (q - m) / (1f - m)
|
||||||
|
}
|
||||||
|
val x = pw * size
|
||||||
|
val i0 = x.toInt() and mask
|
||||||
|
val i1 = (i0 + 1) and mask
|
||||||
|
val fr = x - x.toInt()
|
||||||
|
val a0 = data[b0 + i0] + (data[b0 + i1] - data[b0 + i0]) * fr
|
||||||
|
val a1 = data[b1 + i0] + (data[b1 + i1] - data[b1 + i0]) * fr
|
||||||
|
acc += a0 + (a1 - a0) * ff
|
||||||
|
}
|
||||||
|
mix += acc * uniGain * lvl
|
||||||
|
}
|
||||||
|
if (p.sub > 0.0001f) {
|
||||||
|
subPhase += subInc
|
||||||
|
if (subPhase >= 1.0) subPhase -= 1.0
|
||||||
|
mix += p.sub * sin(2.0 * PI * subPhase).toFloat()
|
||||||
|
}
|
||||||
|
if (p.noise > 0.0001f) mix += p.noise * 0.5f * (rand01() * 2f - 1f)
|
||||||
|
if (p.drive > 0.001f) { val g = 1f + 4f * p.drive; mix = tanh(mix * g) / tanh(g) }
|
||||||
|
|
||||||
|
// the state-variable filter (Zavalishin / Simper TPT form)
|
||||||
|
val v3 = mix - s2
|
||||||
|
val v1 = fa1 * s1 + fa2 * v3
|
||||||
|
val v2 = s2 + fa2 * s1 + fa3 * v3
|
||||||
|
s1 = 2f * v1 - s1
|
||||||
|
s2 = 2f * v2 - s2
|
||||||
|
val y = when (p.filterType) { 1 -> v1; 2 -> mix - fk * v1 - v2; else -> v2 }
|
||||||
|
|
||||||
|
val e = amp.next(1f / fsf)
|
||||||
|
mod.next(1f / fsf)
|
||||||
|
val out = y * e * (1f - p.velSens + p.velSens * vel) * OUT_GAIN
|
||||||
|
return if (out.isFinite()) out else { kill(); 0f }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun control() {
|
||||||
|
val p = patch
|
||||||
|
val dt = CTRL / fsf
|
||||||
|
// LFO
|
||||||
|
lfoPh += p.lfoHz * dt
|
||||||
|
if (lfoPh >= 1.0) { lfoPh -= floor(lfoPh); shVal = rand01() * 2f - 1f }
|
||||||
|
val ph = lfoPh.toFloat()
|
||||||
|
lfoVal = when (p.lfoWave) {
|
||||||
|
1 -> 1f - 4f * kotlin.math.abs(ph - 0.5f)
|
||||||
|
2 -> 2f * ph - 1f
|
||||||
|
3 -> if (ph < 0.5f) 1f else -1f
|
||||||
|
4 -> shVal
|
||||||
|
else -> sin(2f * PI.toFloat() * ph)
|
||||||
|
}
|
||||||
|
val menv = mod.level
|
||||||
|
val vibCents = p.lfoPitch * 50f * lfoVal // up to ±50 cents
|
||||||
|
for (o in 0 until 2) {
|
||||||
|
val t = if (p.table[o] == WaveTables.CUSTOM) WaveTables.forSample(p.customId, p.frameLen) else WaveTables.factory(p.table[o])
|
||||||
|
oscTable[o] = t
|
||||||
|
if (t == null) continue
|
||||||
|
val pos = (p.pos[o] + p.menvPos * menv + p.lfoPos * 0.5f * lfoVal).coerceIn(0f, 1f)
|
||||||
|
oscFrame[o] = pos * (t.frames - 1)
|
||||||
|
val b = p.bend[o]
|
||||||
|
val m = if (b >= 0f) 0.5f * (1f - 0.9f * b) else 0.5f * (1f + 0.9f * -b)
|
||||||
|
oscWarpM[o] = m
|
||||||
|
val slope = 0.5f / min(m, 1f - m)
|
||||||
|
val hz = baseHz * 2f.pow((p.semis[o] + vibCents / 100f) / 12f)
|
||||||
|
val uni = p.unison
|
||||||
|
var top = hz
|
||||||
|
for (u in 0 until uni) {
|
||||||
|
val cents = if (uni == 1) 0f else p.spread * 30f * (2f * u / (uni - 1) - 1f)
|
||||||
|
val f = hz * 2f.pow(cents / 1200f)
|
||||||
|
inc[o * MAX_UNISON + u] = (f / fsf).toDouble()
|
||||||
|
if (f > top) top = f
|
||||||
|
}
|
||||||
|
// the band-limited level: its top harmonic (times BEND's steepening) under 0.45 fs
|
||||||
|
val hmax = 0.45f * fsf / (top * slope)
|
||||||
|
oscLevel[o] = if (hmax >= WaveTable.MAX_HARMONICS) 0
|
||||||
|
else ceil(ln(WaveTable.MAX_HARMONICS / max(1f, hmax)) / LN2).toInt().coerceIn(0, WaveTable.LEVELS - 1)
|
||||||
|
}
|
||||||
|
subInc = (baseHz * 0.5f * 2f.pow(p.semis[0] / 12f) / fsf).toDouble()
|
||||||
|
// filter: cutoff 20 Hz .. 20 kHz on an exponential scale, key tracking around C4
|
||||||
|
val c = p.cutoff + p.keytrack * (note - 60) / 120f + p.fenv * menv * 0.6f + p.lfoCut * 0.3f * lfoVal
|
||||||
|
val fc = (20f * 1000f.pow(c.coerceIn(0f, 1f))).coerceAtMost(0.45f * fsf)
|
||||||
|
val g = tan(PI.toFloat() * fc / fsf)
|
||||||
|
fk = 2f - 1.96f * p.reso
|
||||||
|
fa1 = 1f / (1f + g * (g + fk)); fa2 = g * fa1; fa3 = g * fa2
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun rand01(): Float {
|
||||||
|
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 ushr 8) * (1f / 16777216f)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Linear ADSR, levels 0..1; a release reaches 0 in its time from any level. */
|
||||||
|
private class Env {
|
||||||
|
private var stage = 0 // 0 idle, 1 attack, 2 decay, 3 sustain, 4 release
|
||||||
|
var level = 0f; private set
|
||||||
|
private var a = 0.01f; private var d = 0.1f; private var s = 0.7f; private var r = 0.2f
|
||||||
|
val active get() = stage != 0
|
||||||
|
val gate get() = stage in 1..3
|
||||||
|
fun on(aa: Float, dd: Float, ss: Float, rr: Float) { retime(aa, dd, ss, rr); stage = 1 }
|
||||||
|
fun retime(aa: Float, dd: Float, ss: Float, rr: Float) { a = max(aa, 0.0005f); d = max(dd, 0.001f); s = ss; r = max(rr, 0.001f) }
|
||||||
|
fun off() { if (stage != 0) stage = 4 }
|
||||||
|
fun kill() { stage = 0; level = 0f }
|
||||||
|
fun next(dt: Float): Float {
|
||||||
|
when (stage) {
|
||||||
|
1 -> { level += dt / a; if (level >= 1f) { level = 1f; stage = 2 } }
|
||||||
|
2 -> { level -= dt / d * (1f - s); if (level <= s) { level = s; stage = 3 } }
|
||||||
|
4 -> { level -= dt / r; if (level <= 0f) { level = 0f; stage = 0 } }
|
||||||
|
}
|
||||||
|
return level
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val MAX_UNISON = 4
|
||||||
|
private const val CTRL = 16
|
||||||
|
private const val OUT_GAIN = 0.45f
|
||||||
|
private val LN2 = ln(2f)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
package cc.tiredsysadmin.android.sizzle.echofield
|
||||||
|
|
||||||
|
import cc.tiredsysadmin.android.sizzle.audio.GrainSources
|
||||||
|
import cc.tiredsysadmin.android.sizzle.audio.SampleStore
|
||||||
|
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.assertNotNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.BeforeClass
|
||||||
|
import org.junit.Test
|
||||||
|
import kotlin.math.PI
|
||||||
|
import kotlin.math.abs
|
||||||
|
import kotlin.math.sin
|
||||||
|
import kotlin.math.sqrt
|
||||||
|
|
||||||
|
class GrainCloudTest {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
@JvmStatic @BeforeClass fun sources() = GrainSources.prewarmBlocking()
|
||||||
|
}
|
||||||
|
|
||||||
|
private val fs = 48_000
|
||||||
|
|
||||||
|
private fun slot(preset: String? = null, vararg extra: Pair<String, String>): ToolboxSlot =
|
||||||
|
ToolboxSlot(0).apply {
|
||||||
|
fill(ToolboxType.GRAIN_CLOUD)
|
||||||
|
preset?.let { n -> EchofieldDefs.FACTORY.first { it.name == n }.values.forEach { (k, v) -> set(k, v) } }
|
||||||
|
extra.forEach { (k, v) -> set(k, v) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun cloud(s: ToolboxSlot, tempo: Float = 120f) = GrainCloud(fs).apply { setPatch(GrainPatch.from(s, tempo)) }
|
||||||
|
|
||||||
|
private class Stats(val rms: Float, val peak: Float, val finite: Boolean)
|
||||||
|
|
||||||
|
private fun render(c: GrainCloud, frames: Int): Stats {
|
||||||
|
var sum = 0.0; var peak = 0f; var finite = true
|
||||||
|
repeat(frames) { val x = c.render(); if (!x.isFinite()) finite = false; sum += x * x; peak = maxOf(peak, abs(x)) }
|
||||||
|
return Stats(sqrt(sum / frames).toFloat(), peak, finite)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun builtInSourcesAreReady() {
|
||||||
|
for (name in EchofieldDefs.SOURCES.filter { it != EchofieldDefs.CUSTOM }) {
|
||||||
|
val s = assertNotNull(name, GrainSources.get(name)).let { GrainSources.get(name)!! }
|
||||||
|
assertEquals(name, GrainSources.RATE, s.sampleRate)
|
||||||
|
assertTrue(name, s.data.size >= GrainSources.RATE * 5)
|
||||||
|
assertTrue(name, s.data.all { it.isFinite() && abs(it) <= 0.9f })
|
||||||
|
assertTrue("$name not silent", s.data.maxOf { abs(it) } > 0.5f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun everyFactoryPresetPlaysAndFreesAfterRelease() {
|
||||||
|
assertEquals(14, EchofieldDefs.FACTORY.size)
|
||||||
|
for (p in EchofieldDefs.FACTORY) {
|
||||||
|
val c = cloud(slot(p.name))
|
||||||
|
c.noteOn(60, 100)
|
||||||
|
val held = render(c, fs * 4)
|
||||||
|
println("${p.name}: rms ${"%.3f".format(held.rms)} peak ${"%.3f".format(held.peak)}")
|
||||||
|
assertTrue("${p.name} finite", held.finite)
|
||||||
|
assertTrue("${p.name} sounds (rms ${held.rms})", held.rms > 0.01f)
|
||||||
|
assertTrue("${p.name} rms ${held.rms}", held.rms < 0.6f)
|
||||||
|
c.noteOff(60)
|
||||||
|
var frames = 0
|
||||||
|
while (c.isActive && frames < fs * 15) { c.render(); frames++ }
|
||||||
|
assertFalse("${p.name} frees after its release", c.isActive)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun grainsFollowTheNote() {
|
||||||
|
// a pure C4 sine as the source: A4 must come out at 440 Hz
|
||||||
|
val n = 48_000 * 4
|
||||||
|
SampleStore.put("test:sine", SampleStore.Sample(FloatArray(n) { (0.8 * sin(2 * PI * 261.6256 * it / 48_000)).toFloat() }, 48_000))
|
||||||
|
val c = cloud(slot(null, "source" to EchofieldDefs.CUSTOM, EchofieldDefs.SAMPLE_KEY to "test:sine",
|
||||||
|
"drift" to "0.0", "harmony" to "0.0", "reverse" to "0.0", "scatter" to "0.0", "grain_tone" to "0.0", "motion" to "0.0"))
|
||||||
|
c.noteOn(69, 127)
|
||||||
|
render(c, fs)
|
||||||
|
var prev = c.render(); var crossings = 0
|
||||||
|
repeat(fs * 2) { val x = c.render(); if (prev < 0f && x >= 0f) crossings++; prev = x }
|
||||||
|
assertEquals(440.0, crossings / 2.0, 6.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun aCloudIsAboutAsLoudAsASynthNote() {
|
||||||
|
val c = cloud(slot("Felt Clouds")).apply { noteOn(60, 100) }
|
||||||
|
render(c, fs * 3)
|
||||||
|
val cloud = render(c, fs).rms
|
||||||
|
val syn = SynthVoice(fs).apply { noteOn(60, 100, SynthPatch.DEFAULT) }
|
||||||
|
repeat(fs) { syn.render() }
|
||||||
|
var s = 0.0; repeat(fs) { val x = syn.render(); s += x * x }
|
||||||
|
val ratio = cloud / sqrt(s / fs).toFloat()
|
||||||
|
println("cloud/synth rms ratio $ratio")
|
||||||
|
assertTrue("cloud/synth level $ratio within -6..+6 dB", ratio in 0.5f..2f)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun ownersReleaseOnlyTheirNotes() {
|
||||||
|
val c = cloud(slot("Felt Clouds"))
|
||||||
|
c.noteOn(60, 100, owner = 3)
|
||||||
|
c.noteOn(64, 100, owner = GrainCloud.OWNER_LIVE)
|
||||||
|
c.noteOn(67, 100, owner = GrainCloud.OWNER_SEQ)
|
||||||
|
c.releaseOwner(3)
|
||||||
|
render(c, fs)
|
||||||
|
assertTrue(c.isActive)
|
||||||
|
c.releaseSequenced() // the arpeggio's note goes, the live one stays
|
||||||
|
render(c, fs * 2)
|
||||||
|
assertTrue("live note still held", c.isActive)
|
||||||
|
c.noteOff(64)
|
||||||
|
var frames = 0
|
||||||
|
while (c.isActive && frames < fs * 15) { c.render(); frames++ }
|
||||||
|
assertFalse(c.isActive)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun pulseModeFollowsTheTempo() {
|
||||||
|
val c = cloud(slot("Kalimba Steps"), tempo = 120f)
|
||||||
|
c.noteOn(60, 100)
|
||||||
|
val s = render(c, fs * 3)
|
||||||
|
assertTrue(s.finite && s.rms > 0.005f)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun cpuBudgetForFourDenseClouds() {
|
||||||
|
val clouds = Array(4) { cloud(slot("Glass Choir", "dens_mul" to "2.0", "size_mul" to "1.0")).apply { noteOn(48 + it * 5, 100) } }
|
||||||
|
repeat(fs) { for (c in clouds) c.render() }
|
||||||
|
val seconds = 2
|
||||||
|
val t0 = System.nanoTime()
|
||||||
|
repeat(fs * seconds) { for (c in clouds) c.render() }
|
||||||
|
val load = (System.nanoTime() - t0) / 1e9 / seconds
|
||||||
|
println("4 dense Grain Clouds: ${"%.1f".format(load * 100)} % of real time on this host")
|
||||||
|
assertTrue(load < 1.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
|
||||||
|
package cc.tiredsysadmin.android.sizzle.wavetable
|
||||||
|
|
||||||
|
import cc.tiredsysadmin.android.sizzle.audio.SampleStore
|
||||||
|
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.BeforeClass
|
||||||
|
import org.junit.Test
|
||||||
|
import kotlin.math.PI
|
||||||
|
import kotlin.math.abs
|
||||||
|
import kotlin.math.cos
|
||||||
|
import kotlin.math.round
|
||||||
|
import kotlin.math.sin
|
||||||
|
import kotlin.math.sqrt
|
||||||
|
|
||||||
|
class WavetableTest {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
@JvmStatic @BeforeClass fun tables() = WaveTables.prewarmBlocking()
|
||||||
|
}
|
||||||
|
|
||||||
|
private val fs = 48_000
|
||||||
|
|
||||||
|
private fun slot(preset: String? = null, vararg extra: Pair<String, String>): ToolboxSlot =
|
||||||
|
ToolboxSlot(0).apply {
|
||||||
|
fill(ToolboxType.WAVETABLE)
|
||||||
|
preset?.let { n -> WaveDefs.FACTORY.first { it.name == n }.values.forEach { (k, v) -> set(k, v) } }
|
||||||
|
extra.forEach { (k, v) -> set(k, v) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun voice(s: ToolboxSlot, note: Int, vel: Float = 0.8f) =
|
||||||
|
WaveVoice(fs).apply { noteOn(note, vel, WavePatch.from(s, 120f)) }
|
||||||
|
|
||||||
|
/** |DFT|^2 of x (Hann-windowed) at bins 0..n/2. */
|
||||||
|
private fun power(x: FloatArray): DoubleArray {
|
||||||
|
val n = x.size
|
||||||
|
val w = DoubleArray(n) { x[it] * (0.5 - 0.5 * cos(2 * PI * it / n)) }
|
||||||
|
return DoubleArray(n / 2) { k ->
|
||||||
|
var re = 0.0; var im = 0.0
|
||||||
|
val a = 2 * PI * k / n
|
||||||
|
for (i in 0 until n) { re += w[i] * cos(a * i); im -= w[i] * sin(a * i) }
|
||||||
|
re * re + im * im
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun factoryTablesAreBuiltAndBandLimited() {
|
||||||
|
for (name in WaveTables.FACTORY_NAMES) {
|
||||||
|
val t = WaveTables.factory(name)!!
|
||||||
|
assertEquals(name, WaveTables.FRAMES, t.frames)
|
||||||
|
for (k in 0 until WaveTable.LEVELS) assertTrue(name, t.data[k].all { it.isFinite() && abs(it) < 2f })
|
||||||
|
// level 4 keeps 32 harmonics: nothing from harmonic 33 on, in any frame
|
||||||
|
val k = 4; val n = t.size(k)
|
||||||
|
for (f in 0 until t.frames) {
|
||||||
|
val x = FloatArray(n) { t.data[k][f * n + it] }
|
||||||
|
val p = DoubleArray(n / 2) { h ->
|
||||||
|
var re = 0.0; var im = 0.0
|
||||||
|
for (i in 0 until n) { re += x[i] * cos(2 * PI * h * i / n); im += x[i] * sin(2 * PI * h * i / n) }
|
||||||
|
re * re + im * im
|
||||||
|
}
|
||||||
|
val total = p.sum() + 1e-12
|
||||||
|
val above = p.drop(WaveTable.harmonics(k) + 1).sum()
|
||||||
|
assertTrue("$name frame $f above-band ${above / total}", above / total < 1e-6)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun aHighSawDoesNotAlias() {
|
||||||
|
// Classic at 0.5 is the saw; C7 (2093 Hz) has only 10 harmonics under Nyquist
|
||||||
|
val v = voice(slot(null, "o1table" to "Classic", "o1pos" to "0.5", "menvpos" to "0.0", "lfopos" to "0.0",
|
||||||
|
"cutoff" to "1.0", "reso" to "0.0", "keytrack" to "0.0", "fenv" to "0.0", "sustain" to "1.0"), 96)
|
||||||
|
repeat(fs / 10) { v.render() }
|
||||||
|
val n = 4096
|
||||||
|
val x = FloatArray(n) { v.render() }
|
||||||
|
val p = power(x)
|
||||||
|
val f0 = 440.0 * Math.pow(2.0, (96 - 69) / 12.0)
|
||||||
|
var harm = 0.0; var total = 0.0
|
||||||
|
for (k in p.indices) {
|
||||||
|
total += p[k]
|
||||||
|
val hz = k.toDouble() * fs / n
|
||||||
|
val h = round(hz / f0)
|
||||||
|
if (h >= 1 && abs(hz - h * f0) <= 4.0 * fs / n) harm += p[k]
|
||||||
|
}
|
||||||
|
val alias = 1 - harm / total
|
||||||
|
println("C7 saw: off-harmonic energy ${"%.2e".format(alias)}")
|
||||||
|
assertTrue("aliased energy $alias", alias < 1e-3)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun pitchFollowsTheNote() {
|
||||||
|
val v = voice(slot(null, "o1table" to "Classic", "o1pos" to "0.0", "menvpos" to "0.0", "lfopos" to "0.0", "cutoff" to "1.0", "sustain" to "1.0"), 69)
|
||||||
|
repeat(fs / 10) { v.render() }
|
||||||
|
var prev = v.render(); var crossings = 0
|
||||||
|
repeat(fs) { val x = v.render(); if (prev < 0f && x >= 0f) crossings++; prev = x }
|
||||||
|
assertEquals(440, crossings)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun serumAndWaveEditFrameLengthsAreDetected() {
|
||||||
|
val serum = FloatArray(4 * 2048) { sin(2 * PI * (it % 2048) / 2048.0).toFloat() * 0.5f }
|
||||||
|
val bytes = SampleStore.encodeWav(SampleStore.Sample(serum, 44100)) +
|
||||||
|
"clm ".toByteArray() + byteArrayOf(16, 0, 0, 0) + "<!>2048 01000000".toByteArray()
|
||||||
|
assertEquals(2048, WaveTables.detectFrameLength(bytes, serum.size))
|
||||||
|
assertEquals(256, WaveTables.guessFrameLength(64 * 256)) // WaveEdit
|
||||||
|
assertEquals(2048, WaveTables.guessFrameLength(16 * 2048))
|
||||||
|
val t = WaveTables.fromSamples("t", serum, 2048)
|
||||||
|
assertEquals(4, t.frames)
|
||||||
|
val n = t.size(0)
|
||||||
|
val peak = (0 until n).maxOf { abs(t.data[0][it]) }
|
||||||
|
assertEquals(1f, peak, 0.02f) // normalised
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun everyFactoryPresetPlaysAndFrees() {
|
||||||
|
assertEquals(12, WaveDefs.FACTORY.size)
|
||||||
|
for (p in WaveDefs.FACTORY) {
|
||||||
|
val v = voice(slot(p.name), 57)
|
||||||
|
var s = 0.0; var finite = true; var peak = 0f
|
||||||
|
repeat(fs * 2) { val x = v.render(); if (!x.isFinite()) finite = false; s += x * x; peak = maxOf(peak, abs(x)) }
|
||||||
|
val rms = sqrt(s / (fs * 2)).toFloat()
|
||||||
|
println("${p.name}: rms ${"%.3f".format(rms)} peak ${"%.3f".format(peak)}")
|
||||||
|
assertTrue(p.name, finite && rms > 0.01f && peak < 1.2f)
|
||||||
|
v.noteOff()
|
||||||
|
var frames = 0
|
||||||
|
while (v.isActive && frames < fs * 10) { v.render(); frames++ }
|
||||||
|
assertFalse("${p.name} frees", v.isActive)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun aWavetableNoteIsAboutAsLoudAsASynthNote() {
|
||||||
|
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 wt = SynthVoice(fs).apply { noteOn(60, 100, SynthPatch.forWave(WavePatch.from(slot("Morph Lead"), 120f))) }
|
||||||
|
val syn = SynthVoice(fs).apply { noteOn(60, 100, SynthPatch.DEFAULT) }
|
||||||
|
val ratio = rms(wt) / rms(syn)
|
||||||
|
println("wavetable/synth rms ratio $ratio")
|
||||||
|
assertTrue("ratio $ratio within -6..+6 dB", ratio in 0.5f..2f)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun cpuBudgetForFullPolyphony() {
|
||||||
|
val s = slot("Vowel Pad", "unison" to "4", "o2level" to "0.8")
|
||||||
|
val voices = Array(32) { voice(s, 40 + it) }
|
||||||
|
repeat(fs / 2) { for (v in voices) v.render() }
|
||||||
|
val t0 = System.nanoTime()
|
||||||
|
repeat(fs * 2) { for (v in voices) v.render() }
|
||||||
|
val load = (System.nanoTime() - t0) / 1e9 / 2
|
||||||
|
println("32 wavetable voices, 2 osc x 4 unison: ${"%.1f".format(load * 100)} % of real time on this host")
|
||||||
|
assertTrue(load < 1.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -212,7 +212,8 @@ cc.tiredsysadmin.android.sizzle
|
|||||||
│
|
│
|
||||||
├── audio/ The real-time sound engine (own thread)
|
├── audio/ The real-time sound engine (own thread)
|
||||||
│ ├── Transport.kt TransportState snapshot published to the UI
|
│ ├── Transport.kt TransportState snapshot published to the UI
|
||||||
│ ├── SynthVoice.kt One synth note (3-osc subtractive), or a Morph Pad note via FrasilVoice
|
│ ├── SynthVoice.kt One synth note (3-osc subtractive), or a Morph Pad / Wavetable note (FrasilVoice / WaveVoice)
|
||||||
|
│ ├── GrainSources.kt The Grain Cloud's ten built-in sources, synthesised in the background
|
||||||
│ ├── SampleVoice.kt Pitched + sliced playback of a decoded sample
|
│ ├── SampleVoice.kt Pitched + sliced playback of a decoded sample
|
||||||
│ ├── SampleStore.kt Process-wide decoded-PCM cache + WAV encode/decode
|
│ ├── SampleStore.kt Process-wide decoded-PCM cache + WAV encode/decode
|
||||||
│ ├── SampleRecorder.kt Ad-hoc mic/USB capture into a sample
|
│ ├── SampleRecorder.kt Ad-hoc mic/USB capture into a sample
|
||||||
@@ -228,6 +229,15 @@ cc.tiredsysadmin.android.sizzle
|
|||||||
│ ├── FrasilPatch.kt Parsed slot snapshot (+ morph target); FrasilClock (the shared TIDE time)
|
│ ├── FrasilPatch.kt Parsed slot snapshot (+ morph target); FrasilClock (the shared TIDE time)
|
||||||
│ └── FrasilVoice.kt One pad note: choir + partials + breath, drift, tide, warmth
|
│ └── FrasilVoice.kt One pad note: choir + partials + breath, drift, tide, warmth
|
||||||
│
|
│
|
||||||
|
├── wavetable/ The Wavetable synth (Sizzle's own, GPL; see §5.9)
|
||||||
|
│ ├── WaveTables.kt Band-limited tables: FFT, one mip level per octave, 12 generated tables, WAV import
|
||||||
|
│ ├── WaveDefs.kt Its settings, editor pages, 12 factory presets
|
||||||
|
│ └── WaveVoice.kt WavePatch + one note: 2 table oscillators, bend, unison, sub, SVF, 2 envelopes, LFO
|
||||||
|
│
|
||||||
|
├── echofield/ MIT: the Grain Cloud, ported from ECHOFIELD (see §5.8)
|
||||||
|
│ ├── EchofieldDefs.kt Its settings, editor pages, 14 factory presets, the source list
|
||||||
|
│ └── GrainCloud.kt GrainPatch + one channel's cloud: modes, scheduler, grains, gate, auto-level
|
||||||
|
│
|
||||||
├── cpp/native_audio.cpp Low-latency Oboe stream; RT callback pulls audio via JNI
|
├── cpp/native_audio.cpp Low-latency Oboe stream; RT callback pulls audio via JNI
|
||||||
│
|
│
|
||||||
├── io/ Human-readable text persistence
|
├── io/ Human-readable text persistence
|
||||||
@@ -467,6 +477,94 @@ are interpolated; the choir filter TYPE switches at the halfway point.
|
|||||||
real time (`FrasilVoiceTest.cpuBudgetForFullPolyphony`). The level of a held pad
|
real time (`FrasilVoiceTest.cpuBudgetForFullPolyphony`). The level of a held pad
|
||||||
is matched to a synth note (`aHeldPadIsAboutAsLoudAsASynthNote`).
|
is matched to a synth note (`aHeldPadIsAboutAsLoudAsASynthNote`).
|
||||||
|
|
||||||
|
### 5.8 The Grain Cloud (ECHOFIELD port, MIT)
|
||||||
|
|
||||||
|
The **Grain Cloud** instrument (`ToolboxType.GRAIN_CLOUD`) is the granular engine of
|
||||||
|
[ECHOFIELD FM-1](https://github.com/Philip-Bos/echofield-fm1) (commit `4734e97`) by
|
||||||
|
Philip Bos, translated from C to Kotlin. It was picked as the granular drone machine
|
||||||
|
from the FM-1 firmware hub because it is a real sample-to-cloud instrument with note
|
||||||
|
pitch, float maths, and the **MIT** licence: the two ported files keep the MIT notice
|
||||||
|
and Philip Bos's copyright (`LICENSES/MIT.txt`); nothing else is affected.
|
||||||
|
|
||||||
|
**Ported** (`app/dsp/engine.c`, `app/params.c`, `app/presets.c`): the six modes
|
||||||
|
(CLOUD, DUST, TAPE, BLOOM, PULSE, DRIFT) and their control laws (`compute_ctl`), the
|
||||||
|
asynchronous scheduler and PULSE's euclidean 16 steps, grain spawning (size,
|
||||||
|
pitch, harmony intervals, reverse, scatter, the colour filter, overlap-normalised
|
||||||
|
level), the five windows, the gate (ATTACK/RELEASE), the source swap fade, the
|
||||||
|
random walks and LFOs, FREEZE, and the auto-level that keeps the cloud near one
|
||||||
|
loudness. **Left out:** ECHOFIELD's effects (filter, drive, echo, reverb with
|
||||||
|
shimmer, tape), WIDTH/pan (Sizzle's channels are mono), the DRIFT ORACLE, LATCH and
|
||||||
|
the performance effects. Put Ambience / Tape Delay / Tape Engine on the channel.
|
||||||
|
|
||||||
|
**One cloud per mixer channel, not a voice per note.** ECHOFIELD has a single cloud
|
||||||
|
whose grains take their pitch from the held notes in turn (round robin, up to 8);
|
||||||
|
eight independent clouds would cost eight times as much and break the overlap
|
||||||
|
normalisation. So `AudioEngine` owns `clouds[4]` (one per channel) plus an
|
||||||
|
`auditionCloud` for the editor keyboard, outside the voice pools: `playNote`,
|
||||||
|
`busNoteOn/Off`, `releaseBus`, `releaseTrackVoices`, `allSeqVoicesOff` and `panic`
|
||||||
|
route notes to the cloud. Notes carry an owner (a tracker track, `OWNER_SEQ` for an
|
||||||
|
arpeggio's, `OWNER_LIVE` for keys/MIDI), so a track's next note and the transport
|
||||||
|
stop release only the sequencer's notes and never a note held on a MIDI keyboard.
|
||||||
|
A cloud renders while its channel's instrument is a Grain Cloud (`cloudOn`), every
|
||||||
|
sample into `channelSum` like a voice; its patch (`GrainPatch.from`) is rebuilt
|
||||||
|
only when the slot's version or the tempo changes.
|
||||||
|
|
||||||
|
**Sources.** ECHOFIELD's own factory sounds come from a generator outside its
|
||||||
|
public repository, and its published copies are 16–22 kHz ADPCM, so Sizzle makes
|
||||||
|
ten sources of its own (`audio/GrainSources.kt`, GPL): felt piano, bowed glass,
|
||||||
|
music box, warm pad, strings, low drone, rain field, kalimba, breath choir, glass
|
||||||
|
tines — six seconds each at 24 kHz, pitched material on C (note C4 plays a source
|
||||||
|
at its own pitch), rendered on a background thread at startup (`prewarm`).
|
||||||
|
`GrainSources.get` never blocks; the cloud asks every control block, so a source
|
||||||
|
that is still rendering simply starts when ready. SOURCE "Custom" plays the slot's
|
||||||
|
own sample, loaded (WAV, or an SF2/XI's sample) or recorded in the editor. It is
|
||||||
|
kept under the SF2/XI loader's keys (`sfSample` / `sfFile`), so preset saving,
|
||||||
|
project bundles and startup rehydration handle it with the same code, and
|
||||||
|
`AppViewModel.setGrainSample` writes the WAV into the preset folder at once, so a
|
||||||
|
custom source survives a restart without saving a preset.
|
||||||
|
|
||||||
|
**Level and cost.** The auto-level holds a sounding cloud near RMS 0.126, which is
|
||||||
|
about a synth note's level (`GrainCloudTest.aCloudIsAboutAsLoudAsASynthNote`).
|
||||||
|
Four dense clouds (32 grains each) took about 1.3 % of real time on a desktop JVM.
|
||||||
|
|
||||||
|
### 5.9 The Wavetable synth (Sizzle's own)
|
||||||
|
|
||||||
|
The **Wavetable** instrument (`ToolboxType.WAVETABLE`) was the third pick from the
|
||||||
|
FM-1 firmware hub, but the candidates there (Clipper's WAVE engine, TastyWaves) are
|
||||||
|
**GPL-3.0-only**: copying them would have made the whole app GPL-3.0-only. So it was
|
||||||
|
written from scratch with the standard techniques they also use; no code was taken.
|
||||||
|
|
||||||
|
**Tables** (`WaveTables`). A table is up to 256 single-cycle frames (16 in the
|
||||||
|
factory set). Each frame is kept as a spectrum (cosine/sine of harmonics 1..512) and
|
||||||
|
rendered by an inverse FFT into one **mip level per octave**: level k holds
|
||||||
|
`512 >> k` harmonics in `max(64, 4·harmonics)` samples, the top quarter of its
|
||||||
|
harmonics faded with a raised cosine so switching levels is inaudible. The voice
|
||||||
|
picks, every 16 samples, the level whose top harmonic (times BEND's steepening) stays
|
||||||
|
under 0.45·fs — `WavetableTest.aHighSawDoesNotAlias` measures the off-harmonic
|
||||||
|
energy of a C7 saw at about 3e-5. Reads are linear inside a cycle (four samples per
|
||||||
|
top harmonic make that clean) and linear between neighbouring frames.
|
||||||
|
|
||||||
|
**Factory tables** are formulas (no audio ships): Classic (sine → tri → saw → square
|
||||||
|
→ pulse), PWM, Vowels (moving formants), Harmonic Sweep, Sync, FM, Organ (drawbar
|
||||||
|
registrations), Fold, Digital (bit reduction), Glass (sparse harmonics), Odd Even,
|
||||||
|
Comb (moving notches). They are built on a background thread at startup
|
||||||
|
(`prewarm`); a table not ready yet is silent rather than blocking.
|
||||||
|
|
||||||
|
**Import.** LOAD TABLE takes a WAV: Serum's `clm ` chunk gives the frame length;
|
||||||
|
otherwise 16384 samples is read as WaveEdit (64 × 256), then 2048-, 256-, 1024- or
|
||||||
|
512-sample frames by divisibility (Frame Size overrides it). The table is built on
|
||||||
|
the UI thread at import; the WAV is kept like the Grain Cloud's custom source
|
||||||
|
(`sfSample`/`sfFile`, a copy in the preset folder), so after a restart only the WAV
|
||||||
|
comes back and `WaveTables.forSample` rebuilds the table once on its worker.
|
||||||
|
|
||||||
|
**Voice** (`WaveVoice`, played inside `SynthVoice` like the Morph Pad): two
|
||||||
|
oscillators (table, POSITION, octave/semi/fine, level, BEND), up to 4 unison copies
|
||||||
|
spread ±30 cents, a sub sine, noise, tanh drive, a TPT state-variable filter
|
||||||
|
(low/band/high), a linear amp envelope, a mod envelope (to position and cutoff) and a
|
||||||
|
tempo-synced LFO (to position, pitch, cutoff). BEND is a two-segment phase warp, as in
|
||||||
|
phase-distortion synthesis. 32 voices with 2 oscillators × 4 unison took about 6 %
|
||||||
|
of real time on a desktop JVM.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 6. How to extend
|
## 6. How to extend
|
||||||
|
|||||||
@@ -268,6 +268,37 @@ 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
|
Abyss, …). The pad is dry: put an **Ambience** reverb on its channel for the
|
||||||
spacious sound FRASIL is known for.
|
spacious sound FRASIL is known for.
|
||||||
|
|
||||||
|
**Grain Cloud** — a granular drone machine, ported from ECHOFIELD (a custom
|
||||||
|
firmware for the M‑VAVE FM‑1 by Philip Bos). It cuts a sound into many short
|
||||||
|
grains and scatters them into a cloud; the notes you hold set the grains' pitch, so
|
||||||
|
a chord becomes a slowly shifting texture. Pick a **Source**: one of ten built‑in
|
||||||
|
sounds (Felt Piano, Bowed Glass, Music Box, Warm Pad, Strings, Low Drone, Rain
|
||||||
|
Field, Kalimba, Breath Choir, Glass Tines), or **LOAD WAV** / **RECORD** your own
|
||||||
|
(the source then reads "Custom"). Your own sound is kept with the app, so it is
|
||||||
|
still there after a restart.
|
||||||
|
|
||||||
|
The **Mode** shapes the cloud: **Cloud** (long grains melting into a pad), **Dust**
|
||||||
|
(tiny specks and stutters), **Tape** (three loop heads at three speeds), **Bloom**
|
||||||
|
(slow swells with overtones), **Pulse** (soft notes on a 16‑step pattern at the
|
||||||
|
song's tempo) and **Drift** (everything wanders). **Position** is where in the
|
||||||
|
sound the grains come from (the lit part of the waveform is **Start**..**End**),
|
||||||
|
**Texture** their length and density, **Scatter** how widely they spread, **Drift**
|
||||||
|
and **Evolve** how much they wander, **Harmony** how often a grain jumps an octave
|
||||||
|
or a fifth. **Freeze** stops all movement. The Grain Cloud is dry: an **Ambience**
|
||||||
|
reverb or a **Tape Delay** on its channel gives it the space ECHOFIELD has.
|
||||||
|
|
||||||
|
**Wavetable** — a two‑oscillator wavetable synth. Each oscillator plays a
|
||||||
|
**Table** of single‑cycle waves and **Position** sweeps through it; the **Mod Env**
|
||||||
|
(**Env > Position**) and the **LFO** (**LFO > Position**) move the position while
|
||||||
|
a note plays, which is where the sound comes alive. Twelve tables are built in
|
||||||
|
(Classic, PWM, Vowels, Harmonic Sweep, Sync, FM, Organ, Fold, Digital, Glass, Odd
|
||||||
|
Even, Comb). **LOAD TABLE** imports your own: Serum and WaveEdit wavetables, or any
|
||||||
|
WAV made of frames of 256 to 2048 samples (set **Frame Size** if it guesses wrong);
|
||||||
|
oscillator 1 then plays it as **Custom**. **Bend** sharpens a wave without changing
|
||||||
|
its pitch, **Unison** stacks up to four detuned copies (**Spread**), and there is a
|
||||||
|
**Sub** sine, **Noise**, a **Filter** with its own envelope amount and **Drive**.
|
||||||
|
The table view shows oscillator 1's frames, the one at its position lit.
|
||||||
|
|
||||||
### Effects
|
### Effects
|
||||||
|
|
||||||
Insert effects (assign them to a channel's FX slots in the Mix tab):
|
Insert effects (assign them to a channel's FX slots in the Mix tab):
|
||||||
|
|||||||
+2
-2
@@ -8,8 +8,8 @@
|
|||||||
# or polish. android.versionCode is monotonic and bumps by 1 on every release,
|
# or polish. android.versionCode is monotonic and bumps by 1 on every release,
|
||||||
# because F-Droid and the Android package manager order installs by it alone.
|
# because F-Droid and the Android package manager order installs by it alone.
|
||||||
|
|
||||||
android.versionName = 0.30.0
|
android.versionName = 0.32.0
|
||||||
android.versionCode = 61
|
android.versionCode = 63
|
||||||
|
|
||||||
# No desktop builds exist yet. These lines are the agreed slots so a port starts
|
# No desktop builds exist yet. These lines are the agreed slots so a port starts
|
||||||
# with a version instead of inventing one; `-` means "not built on this
|
# with a version instead of inventing one; `-` means "not built on this
|
||||||
|
|||||||
Reference in New Issue
Block a user