From aa023d1f01cbcda76da4fe25b92fc2526d64b73b Mon Sep 17 00:00:00 2001 From: Reactorcoremeltdown Date: Fri, 13 Nov 2026 09:18:04 +0100 Subject: [PATCH] Grain Cloud instrument: ECHOFIELD's granular engine ported to Kotlin (0.31.0) A granular drone machine from ECHOFIELD FM-1 (Philip Bos, MIT): six modes (Cloud, Dust, Tape, Bloom, Pulse, Drift), up to 32 grains, held notes pitch the grains, freeze, auto-level. One shared cloud per mixer channel (plus one for editor audition) with note ownership, so sequencer releases never cut a held MIDI note. Ten built-in sources synthesised at startup (GrainSources, GPL), or a loaded/recorded sample kept across restarts. 14 factory presets. The echofield/ package stays MIT, LICENSES/MIT.txt. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 + LICENSES/MIT.txt | 21 + README.md | 5 + .../tiredsysadmin/android/sizzle/SizzleApp.kt | 3 + .../android/sizzle/audio/AudioEngine.kt | 53 ++ .../android/sizzle/audio/GrainSources.kt | 296 ++++++++ .../android/sizzle/echofield/EchofieldDefs.kt | 107 +++ .../android/sizzle/echofield/GrainCloud.kt | 702 ++++++++++++++++++ .../android/sizzle/io/PresetLibrary.kt | 28 +- .../android/sizzle/io/ProjectBundleIo.kt | 5 +- .../android/sizzle/model/Toolbox.kt | 6 + .../android/sizzle/ui/AppViewModel.kt | 38 + .../sizzle/ui/toolbox/GrainCloudEditor.kt | 110 +++ .../sizzle/ui/toolbox/ToolboxScreen.kt | 9 +- .../sizzle/echofield/GrainCloudTest.kt | 134 ++++ docs/DEVELOPER_HANDOVER.md | 55 ++ docs/USER_GUIDE.md | 19 + versions.properties | 4 +- 18 files changed, 1594 insertions(+), 12 deletions(-) create mode 100644 LICENSES/MIT.txt create mode 100644 app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/GrainSources.kt create mode 100644 app/src/main/java/cc/tiredsysadmin/android/sizzle/echofield/EchofieldDefs.kt create mode 100644 app/src/main/java/cc/tiredsysadmin/android/sizzle/echofield/GrainCloud.kt create mode 100644 app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/GrainCloudEditor.kt create mode 100644 app/src/test/java/cc/tiredsysadmin/android/sizzle/echofield/GrainCloudTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 7322a8f..f4bab30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,17 @@ Sizzletracker for Android (`cc.tiredsysadmin.android.sizzle`). One entry per version in `versions.properties`; versions before 0.28.0 are described in the git log (one commit per version). +## 0.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) - **Morph Pad**, a new instrument for evolving pads and drones: the drone voice of diff --git a/LICENSES/MIT.txt b/LICENSES/MIT.txt new file mode 100644 index 0000000..00cbce5 --- /dev/null +++ b/LICENSES/MIT.txt @@ -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. diff --git a/README.md b/README.md index c4e822a..59c70b4 100644 --- a/README.md +++ b/README.md @@ -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 Styves Goupil, and those files remain under the **Mozilla Public License 2.0** ([`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)). diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/SizzleApp.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/SizzleApp.kt index 8a60c97..39ead0a 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/SizzleApp.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/SizzleApp.kt @@ -102,6 +102,9 @@ class SizzleApp : Application() { override fun 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() // 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. projectStore.restore(project) diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/AudioEngine.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/AudioEngine.kt index 897f573..17b94fd 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/AudioEngine.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/AudioEngine.kt @@ -6,6 +6,8 @@ package cc.tiredsysadmin.android.sizzle.audio import android.media.AudioAttributes import android.media.AudioFormat import android.media.AudioTrack +import cc.tiredsysadmin.android.sizzle.echofield.GrainCloud +import cc.tiredsysadmin.android.sizzle.echofield.GrainPatch import cc.tiredsysadmin.android.sizzle.frasil.FrasilClock import cc.tiredsysadmin.android.sizzle.frasil.FrasilPatch import cc.tiredsysadmin.android.sizzle.model.Arrangement @@ -103,6 +105,18 @@ class AudioEngine( private val moutNote = IntArray(Arrangement.LANE_COUNT * Pattern.TRACK_COUNT) { -1 } 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 // (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. @@ -147,6 +161,7 @@ class AudioEngine( /** Release (fade out) every active voice on [bus] — a note-off cell on its channel. */ private fun releaseBus(bus: Int) { + clouds[bus].releaseSequenced() val base = bus * POLYPHONY for (i in 0 until POLYPHONY) { seqVoices[base + i].noteOff() @@ -552,6 +567,8 @@ class AudioEngine( * tick. */ fun panic() { + clouds.forEach { it.kill() } + auditionCloud.kill() seqVoices.forEach { it.kill() } sampleVoices.forEach { it.kill() } liveVoices.forEach { it.kill() } @@ -641,6 +658,7 @@ class AudioEngine( 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 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 0 until frames) { @@ -658,6 +676,7 @@ class AudioEngine( 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 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) { val mc = proj.mixer.channels[ch] var s = if (mc.audible(anySolo)) channelSum[ch] * mc.volume else 0f @@ -677,6 +696,7 @@ class AudioEngine( } } 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 } // Makeup gain (lifts instruments to media loudness) into a look-ahead // brickwall limiter that guarantees the output stays under the ceiling. @@ -1012,6 +1032,7 @@ class AudioEngine( } 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 sampleVoices) if (v.ownerTrack == trackKey && v.isGated) v.noteOff() } @@ -1041,6 +1062,8 @@ class AudioEngine( // Empty bus (no instrument — e.g. the default channel 0) or a Sampler // with an empty pad → silent, matching the live audition path. 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. else -> { allocSynthVoice(bus).also { it.ownerTrack = ownerTrack } @@ -1265,6 +1288,15 @@ class AudioEngine( // note-off, so a sustaining synth voice would ring forever). A SoundFont // with nothing loaded still falls through to the synth preview below. 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 // knob turns into the held preview note. if (hasSynthPatch(slot?.type)) auditionSlotIdx = slotIndex @@ -1277,6 +1309,7 @@ class AudioEngine( * 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. */ fun auditionSlotOff(midi: Int) { + auditionCloud.noteOff(midi) (liveVoices.firstOrNull { it.pitch == midi && it.isGated } ?: liveVoices.firstOrNull { it.isActive && it.pitch == midi })?.noteOff() (auditionSampleVoices.firstOrNull { it.pitch == midi && it.isGated } @@ -1307,6 +1340,7 @@ class AudioEngine( } // Sampler with an empty pad → silent (no synth fallback). type == ToolboxType.SAMPLER -> {} + type == ToolboxType.GRAIN_CLOUD -> clouds[ch].noteOn(midi, velocity, GrainCloud.OWNER_LIVE) else -> { val v = freeBusVoice(busVoices, base) v.noteOn(midi, velocity, synthPatch[ch] ?: patchForSlot(slot, proj.tempoBpm)) @@ -1356,6 +1390,7 @@ class AudioEngine( val proj = project ?: return for (ch in 0 until Pattern.TRACK_COUNT) { if (proj.mixer.channels[ch].midiChannel != midiChannel) continue + clouds[ch].noteOff(midi) val base = ch * BUS_POLYPHONY for (i in 0 until BUS_POLYPHONY) { busVoices[base + i].takeIf { it.isActive && it.pitch == midi }?.noteOff() @@ -1475,6 +1510,17 @@ class AudioEngine( val tempo = proj.tempoBpm for (ch in 0 until Pattern.TRACK_COUNT) { val slot = proj.toolbox.getOrNull(proj.mixer.channels[ch].instrumentSlot) + if (slot?.type == ToolboxType.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 (synthPatch[ch] == null || slot.version != synthPatchVer[ch] || tempo != synthPatchTempo[ch]) { synthPatch[ch] = patchForSlot(slot, tempo) @@ -1489,6 +1535,12 @@ class AudioEngine( } // Editor audition voices follow the slot currently being previewed. 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 (auditionPatch == null || aslot.version != auditionPatchVer || tempo != auditionPatchTempo) { auditionPatch = patchForSlot(aslot, tempo) @@ -1503,6 +1555,7 @@ class AudioEngine( sampleRate * (60.0 / proj.tempoBpm) / proj.timeSignature.linesPerBeat private fun allSeqVoicesOff() { + clouds.forEach { it.releaseSequenced() } seqVoices.forEach { it.noteOff() } sampleVoices.forEach { it.noteOff() } arps.forEach { it.stop() } diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/GrainSources.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/GrainSources.kt new file mode 100644 index 0000000..ad22486 --- /dev/null +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/audio/GrainSources.kt @@ -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() + @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 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, 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 + } + +} diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/echofield/EchofieldDefs.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/echofield/EchofieldDefs.kt new file mode 100644 index 0000000..ef89c4f --- /dev/null +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/echofield/EchofieldDefs.kt @@ -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 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>> = 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) + + /** 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 by lazy { + fun p(name: String, source: String, mode: Int, vararg v: Pair): Preset { + val m = LinkedHashMap() + 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), + ) + } +} diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/echofield/GrainCloud.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/echofield/GrainCloud.kt new file mode 100644 index 0000000..f13140b --- /dev/null +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/echofield/GrainCloud.kt @@ -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 = 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 + } + + } +} diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/PresetLibrary.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/PresetLibrary.kt index fe06d01..b9ba6d5 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/PresetLibrary.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/PresetLibrary.kt @@ -4,6 +4,7 @@ package cc.tiredsysadmin.android.sizzle.io 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.model.AmbiencePresets import cc.tiredsysadmin.android.sizzle.model.MixTightenerPresets @@ -56,6 +57,9 @@ class PresetLibrary(private val baseDir: File) { seedType(ToolboxType.MORPH_PAD, FrasilDefs.FACTORY.map { it.name }) { slot, name -> FrasilDefs.FACTORY.first { it.name == name }.values.forEach { (k, v) -> slot.set(k, v) } } + seedType(ToolboxType.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.MIX_TIGHTENER, MixTightenerPresets.FACTORY.map { it.name }) { slot, name -> MixTightenerPresets.apply(slot, MixTightenerPresets.FACTORY.first { it.name == name }) } @@ -143,6 +147,18 @@ class PresetLibrary(private val baseDir: File) { } preset.writeText(exportSoundFont(slot, rel)) } + ToolboxType.GRAIN_CLOUD -> { + // A custom grain source 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)) } return preset @@ -165,7 +181,7 @@ class PresetLibrary(private val baseDir: File) { } if (type == ToolboxType.SAMPLER) { 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) { File(dir, "${base}_sf.wav").delete() } return preset.delete() @@ -182,7 +198,7 @@ class PresetLibrary(private val baseDir: File) { project.toolbox.forEach { slot -> when (slot.type) { ToolboxType.SAMPLER -> resolvePads(slot, typeDir(ToolboxType.SAMPLER)) - ToolboxType.SOUNDFONT -> resolveSoundFont(slot, typeDir(ToolboxType.SOUNDFONT)) + ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD -> resolveSoundFont(slot, typeDir(ToolboxType.SOUNDFONT)) else -> {} } } @@ -197,7 +213,7 @@ class PresetLibrary(private val baseDir: File) { val dir = file.parentFile ?: typeDir(type) when (slot.type) { ToolboxType.SAMPLER -> resolvePads(slot, dir) - ToolboxType.SOUNDFONT -> resolveSoundFont(slot, dir) + ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD -> resolveSoundFont(slot, dir) else -> {} } true @@ -214,7 +230,7 @@ class PresetLibrary(private val baseDir: File) { val type = slot.type ?: return false when (type) { ToolboxType.SAMPLER -> resolvePads(slot, typeDir(type)) - ToolboxType.SOUNDFONT -> resolveSoundFont(slot, typeDir(type)) + ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD -> resolveSoundFont(slot, typeDir(type)) else -> {} } save(slot, slot.name.ifBlank { type.displayName }) @@ -255,7 +271,7 @@ class PresetLibrary(private val baseDir: File) { if (!PresetIo.import(slot, text)) return false when (slot.type) { ToolboxType.SAMPLER -> resolvePads(slot, scratch) - ToolboxType.SOUNDFONT -> resolveSoundFont(slot, scratch) + ToolboxType.SOUNDFONT, ToolboxType.GRAIN_CLOUD -> resolveSoundFont(slot, scratch) else -> {} } // Persist a self-contained copy into the real library folder. @@ -272,7 +288,7 @@ class PresetLibrary(private val baseDir: File) { fun bundleForShare(type: ToolboxType, name: String): File? { val preset = File(typeDir(type), sanitize(name) + PRESET_EXT) 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) return preset val bundles = File(baseDir, BUNDLE_DIR).apply { mkdirs() } val zip = File(bundles, sanitize(name) + ".zip") diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/ProjectBundleIo.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/ProjectBundleIo.kt index 67d5b81..efc5478 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/ProjectBundleIo.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/ProjectBundleIo.kt @@ -112,7 +112,7 @@ object ProjectBundleIo { ToolboxType.SAMPLER -> for (p in 0 until SamplerPads.COUNT) { 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 -> idToPath[slot.string("sfSample")]?.let { slot.set("sfFile", it) } else -> {} } } @@ -127,7 +127,8 @@ object ProjectBundleIo { ToolboxType.SAMPLER -> for (p in 0 until SamplerPads.COUNT) { 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 -> + slot.string("sfSample").takeIf { it.isNotBlank() }?.let { ids.add(it) } else -> {} } } diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/model/Toolbox.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/model/Toolbox.kt index 5ae5569..594214e 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/model/Toolbox.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/model/Toolbox.kt @@ -3,6 +3,7 @@ package cc.tiredsysadmin.android.sizzle.model +import cc.tiredsysadmin.android.sizzle.echofield.EchofieldDefs import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs /** @@ -120,6 +121,11 @@ enum class ToolboxType( // while held, morphing toward one of FRASIL's 36 drone sounds. Rendered by // FrasilVoice inside SynthVoice; edited by the paged editor in ToolboxScreen. MORPH_PAD(ToolboxKind.INSTRUMENT, "Morph Pad", FrasilDefs.PARAMS), + // 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), // ---------- Effects ---------- ARPEGGIATOR( diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt index 26ea56d..f4ddfe5 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt @@ -1068,6 +1068,44 @@ 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, + ) { + val store = cc.tiredsysadmin.android.sizzle.audio.SampleStore + val dir = java.io.File(presetLibrary.typeDir(cc.tiredsysadmin.android.sizzle.model.ToolboxType.GRAIN_CLOUD), "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(cc.tiredsysadmin.android.sizzle.echofield.EchofieldDefs.SAMPLE_KEY, id) + if (file.exists()) slot.set("sfFile", file.absolutePath) + slot.set("source", cc.tiredsysadmin.android.sizzle.echofield.EchofieldDefs.CUSTOM) + touched() + } + /** Point an LFO slot at another device's parameter, capturing that param's * current value as the modulation centre. Pass targetSlotIndex < 0 to clear. */ fun setLfoTarget( diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/GrainCloudEditor.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/GrainCloudEditor.kt new file mode 100644 index 0000000..c189717 --- /dev/null +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/GrainCloudEditor.kt @@ -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(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") } }, + ) + } +} diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/ToolboxScreen.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/ToolboxScreen.kt index 10b4295..86f0001 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/ToolboxScreen.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/ToolboxScreen.kt @@ -57,6 +57,7 @@ import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.content.FileProvider +import cc.tiredsysadmin.android.sizzle.echofield.EchofieldDefs import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs import cc.tiredsysadmin.android.sizzle.model.ParamSpec import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot @@ -297,7 +298,7 @@ private fun ParamEditor(vm: AppViewModel, slot: ToolboxSlot, onClose: () -> Unit // the toolbox / tracker keyboards), so their controls scroll in a weighted region // above the keyboard rather than the whole editor scrolling as one. val pinnedKeyboard = type == ToolboxType.SOUNDFONT || type == ToolboxType.NES_SYNTH || - type == ToolboxType.MORPH_PAD + type == ToolboxType.MORPH_PAD || type == ToolboxType.GRAIN_CLOUD // The Sampler pins its 16-pad grid at the bottom in that same region, so the // playable pads are the same height as the keyboards across every instrument editor. val pinnedBottom = pinnedKeyboard || type == ToolboxType.SAMPLER @@ -344,6 +345,10 @@ private fun ParamEditor(vm: AppViewModel, slot: ToolboxSlot, onClose: () -> Unit ToolboxType.DELAY -> DelayEditor(vm, slot) ToolboxType.AMBIENCE -> AmbiencePager(vm, slot) ToolboxType.MORPH_PAD -> SectionPager(vm, slot, FrasilDefs.SECTIONS, 300.dp) + ToolboxType.GRAIN_CLOUD -> { + GrainCloudEditor(vm, slot) + SectionPager(vm, slot, EchofieldDefs.SECTIONS, 300.dp) + } ToolboxType.LFO -> { ParamGrid(vm, slot, type.params) LfoTargetPicker(vm, slot) @@ -474,7 +479,7 @@ private fun AmbiencePager(vm: AppViewModel, slot: ToolboxSlot) = /** A device's parameters as swipeable pages of (title, keys), with dot pagination. */ @Composable -private fun SectionPager(vm: AppViewModel, slot: ToolboxSlot, sections: List>>, height: Dp) { +internal fun SectionPager(vm: AppViewModel, slot: ToolboxSlot, sections: List>>, height: Dp) { val c = LocalRetro.current val byKey = (slot.type ?: return).params.associateBy { it.key } val pagerState = rememberPagerState(pageCount = { sections.size }) diff --git a/app/src/test/java/cc/tiredsysadmin/android/sizzle/echofield/GrainCloudTest.kt b/app/src/test/java/cc/tiredsysadmin/android/sizzle/echofield/GrainCloudTest.kt new file mode 100644 index 0000000..d315560 --- /dev/null +++ b/app/src/test/java/cc/tiredsysadmin/android/sizzle/echofield/GrainCloudTest.kt @@ -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): 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) + } +} diff --git a/docs/DEVELOPER_HANDOVER.md b/docs/DEVELOPER_HANDOVER.md index 8ec0159..4c7e019 100644 --- a/docs/DEVELOPER_HANDOVER.md +++ b/docs/DEVELOPER_HANDOVER.md @@ -213,6 +213,7 @@ cc.tiredsysadmin.android.sizzle ├── audio/ The real-time sound engine (own thread) │ ├── Transport.kt TransportState snapshot published to the UI │ ├── SynthVoice.kt One synth note (3-osc subtractive), or a Morph Pad note via FrasilVoice +│ ├── GrainSources.kt The Grain Cloud's ten built-in sources, synthesised in the background │ ├── SampleVoice.kt Pitched + sliced playback of a decoded sample │ ├── SampleStore.kt Process-wide decoded-PCM cache + WAV encode/decode │ ├── SampleRecorder.kt Ad-hoc mic/USB capture into a sample @@ -228,6 +229,10 @@ cc.tiredsysadmin.android.sizzle │ ├── FrasilPatch.kt Parsed slot snapshot (+ morph target); FrasilClock (the shared TIDE time) │ └── FrasilVoice.kt One pad note: choir + partials + breath, drift, tide, warmth │ +├── 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 │ ├── io/ Human-readable text persistence @@ -467,6 +472,56 @@ are interpolated; the choir filter TYPE switches at the halfway point. real time (`FrasilVoiceTest.cpuBudgetForFullPolyphony`). The level of a held pad 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. + --- ## 6. How to extend diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md index 9d963c4..f78273e 100644 --- a/docs/USER_GUIDE.md +++ b/docs/USER_GUIDE.md @@ -268,6 +268,25 @@ The 36 factory presets are FRASIL's drone sounds (Mist, Cathedral, Glacier, Abyss, …). The pad is dry: put an **Ambience** reverb on its channel for the spacious sound FRASIL is known for. +**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. + ### Effects Insert effects (assign them to a channel's FX slots in the Mix tab): diff --git a/versions.properties b/versions.properties index aa94b2a..5f12403 100644 --- a/versions.properties +++ b/versions.properties @@ -8,8 +8,8 @@ # or polish. android.versionCode is monotonic and bumps by 1 on every release, # because F-Droid and the Android package manager order installs by it alone. -android.versionName = 0.30.0 -android.versionCode = 61 +android.versionName = 0.31.0 +android.versionCode = 62 # 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