Compare commits
3
Commits
e78b2c1418
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0e8032532f | ||
|
|
b3bae931b1 | ||
|
|
ba98ec56f4 |
@@ -5,6 +5,56 @@ version in `versions.properties`; versions before 0.28.0 are described in the gi
|
||||
log (one commit per version). Since 0.37.0 Android and iOS share one version and
|
||||
one feature set; the iOS side of each version is in `ios/CHANGELOG.md`.
|
||||
|
||||
## 0.42.0 (versionCode 79)
|
||||
|
||||
- **RANDOM:** the Synth, Morph Pad, Grain Cloud, Wavetable and Ambience Reverb
|
||||
editors have a RANDOM button in the preset bar. It throws a new patch into the
|
||||
editor and names it ("Hazy Drift"). It is a starting point rather than a slot
|
||||
machine: a roll is always something you can hear and never something that
|
||||
clips, because levels, filters and envelopes are drawn inside ranges that keep a
|
||||
patch in that territory instead of scattered over the whole knob. It replaces
|
||||
the editor's settings like loading a preset does, so SAVE first if you want to
|
||||
keep what is there — but it never touches a sample you loaded or a wavetable you
|
||||
imported. The other devices have none on purpose: a Sampler is only as
|
||||
interesting as the sound you put in it, and the MIDI effects have too few
|
||||
settings for a dice roll to say anything. (iOS has the same in 0.42.0.)
|
||||
- Fix: the shared engine did not compile outside Apple's toolchain — a missing
|
||||
`<cstdint>` in `core/include/sizzle/Model.hpp`. No change to the apps; it means
|
||||
the engine's tests and benchmark now build with GCC too.
|
||||
|
||||
## 0.41.2 (versionCode 78)
|
||||
|
||||
Housekeeping and speed; nothing you can see changes, except that the app is
|
||||
half the size and lighter on the battery.
|
||||
|
||||
- **The APK is half as big** — 21.5 MB → 10.1 MB. Release builds now go through
|
||||
R8 (shrink, optimise, obfuscate, and drop unused resources), which throws away
|
||||
the Compose and Material icon code the app never calls. Only the two JNI
|
||||
classes are pinned by name (`app/proguard-rules.pro`), because the native
|
||||
library looks them up at runtime; `make dist` keeps the de-obfuscation map next
|
||||
to the APK so a crash report from a published build can still be read.
|
||||
- **Less battery while a song is stopped.** The thread that feeds the transport
|
||||
display polled the engine 100 times a second whatever was happening; it now
|
||||
does that only while the song plays or a recording is armed, and waits 100 ms a
|
||||
turn otherwise. Pressing Play still moves the playhead in the same frame — a
|
||||
transport call wakes it. iOS does the same (30 Hz playing, 10 Hz stopped).
|
||||
- **Smoother editing.** Every edit hands the engine the whole song as text. That
|
||||
text is now built in one pre-sized pass instead of a string per line, and a
|
||||
burst of edits — dragging a note column, sweeping a knob — is collected into
|
||||
one sync instead of one per touch event.
|
||||
- **The mixer costs less per sample.** Channel volume, mute/solo and the effect
|
||||
chain are read once per audio block rather than once per frame, in the shared
|
||||
C++ engine (so iOS gets it too). Bit-for-bit the same audio: all 61 reference
|
||||
scenarios still match the Kotlin DSP.
|
||||
- **Dead code gone.** The Kotlin DSP that `core/` replaced in 0.37.0 was still
|
||||
compiled into every APK although nothing called it; it has moved to the test
|
||||
source set, where it belongs as the reference the C++ is checked against. The
|
||||
golden tests' `TestVoice` wrappers left the shared engine's sources for the
|
||||
same reason, and a handful of unused declarations are gone.
|
||||
- Fix: `make lint` failed on a manifest that asked for `ACCESS_FINE_LOCATION`
|
||||
without `ACCESS_COARSE_LOCATION` (the BLE MIDI scan on Android 8–11). Both are
|
||||
declared and both are requested now, so `make check` passes again.
|
||||
|
||||
## 0.41.1 (versionCode 77)
|
||||
|
||||
- No Android change: an iOS redraw fix (see `ios/CHANGELOG.md`).
|
||||
|
||||
@@ -35,6 +35,10 @@ FDROID_METADATA := /var/lib/fdroid/metadata
|
||||
# directory expects; app/build.gradle.kts stamps the same name onto the output.
|
||||
APK_NAME := $(APP_ID)_$(VERSION_CODE).apk
|
||||
RELEASE_APK := app/build/outputs/apk/release/$(APK_NAME)
|
||||
# R8 renames the release build, so a crash report from it is unreadable without
|
||||
# this. It is staged beside the APK and kept locally — never published.
|
||||
RELEASE_MAP := app/build/outputs/mapping/release/mapping.txt
|
||||
DIST_MAP := dist/$(APP_ID)_$(VERSION_CODE)-mapping.txt
|
||||
STAGING_APK := app/build/outputs/apk/staging/app-staging.apk
|
||||
METADATA_YML := dist/$(APP_ID).yml
|
||||
|
||||
@@ -110,12 +114,18 @@ launch:
|
||||
# ------------------------------------------------------------------ dist
|
||||
# Everything a publish needs, staged locally first so it can be inspected
|
||||
# before anything leaves the machine.
|
||||
dist: dist/$(APK_NAME) $(METADATA_YML)
|
||||
dist: dist/$(APK_NAME) $(DIST_MAP) $(METADATA_YML)
|
||||
|
||||
dist/$(APK_NAME): $(RELEASE_APK)
|
||||
@mkdir -p dist
|
||||
cp $(RELEASE_APK) $@
|
||||
|
||||
# The de-obfuscation map for this exact versionCode. `publish` does not upload it;
|
||||
# it stays here so a stack trace from the published APK can still be read.
|
||||
$(DIST_MAP): $(RELEASE_APK)
|
||||
@mkdir -p dist
|
||||
cp $(RELEASE_MAP) $@
|
||||
|
||||
# F-Droid metadata. Regenerated from versions.properties on every dist so the
|
||||
# CurrentVersion lines can never lag the APK next to them.
|
||||
$(METADATA_YML): $(VERSIONS) Makefile
|
||||
@@ -153,6 +163,7 @@ publish-metadata: $(METADATA_YML)
|
||||
|
||||
publish: publish-apk publish-metadata
|
||||
@echo "published $(APP_ID) $(VERSION_NAME) ($(VERSION_CODE)); sign it on the repo host"
|
||||
@echo "keep $(DIST_MAP) — it is the only way to read a crash from this build"
|
||||
|
||||
# ------------------------------------------------------------------ versioning
|
||||
# versionCode always moves by exactly 1: F-Droid and the package manager order
|
||||
|
||||
+10
-5
@@ -52,9 +52,13 @@ android {
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
// Shrinking is off by default so newcomers get readable stack traces.
|
||||
// Flip to true once the app stabilises.
|
||||
isMinifyEnabled = false
|
||||
// R8: shrink + optimise + obfuscate, and drop unreferenced resources.
|
||||
// Only the JNI entry points need keeping (see proguard-rules.pro); the
|
||||
// app reflects over nothing of its own. A release stack trace is now
|
||||
// obfuscated, so keep app/build/outputs/mapping/release/mapping.txt
|
||||
// beside any APK you publish — `make dist` copies it into dist/.
|
||||
isMinifyEnabled = true
|
||||
isShrinkResources = true
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro",
|
||||
@@ -66,8 +70,9 @@ android {
|
||||
// the app un-optimised and makes Compose several times slower — so measuring
|
||||
// UI "snappiness" on a debug build is misleading. This variant flips
|
||||
// debuggability off (the single biggest perf lever) while reusing the debug
|
||||
// signing key, so it still installs without a release keystore. R8/shrinking
|
||||
// stays off to avoid needing JNI/Compose keep-rules for now.
|
||||
// signing key, so it still installs without a release keystore. R8 stays off
|
||||
// here on purpose: staging exists to measure the UI, and un-obfuscated stack
|
||||
// traces are worth more than the last few hundred KB. `release` is minified.
|
||||
create("staging") {
|
||||
initWith(getByName("debug"))
|
||||
isDebuggable = false
|
||||
|
||||
Vendored
+19
-3
@@ -1,3 +1,19 @@
|
||||
# ProGuard/R8 rules for release builds. Minification is currently disabled in
|
||||
# build.gradle.kts (isMinifyEnabled = false), so this file is intentionally empty.
|
||||
# Add keep-rules here if/when you enable shrinking and hit reflection issues.
|
||||
# R8 rules for the release build (isMinifyEnabled = true in build.gradle.kts).
|
||||
#
|
||||
# Keep as little as possible: everything else — Compose, media3, DataStore,
|
||||
# coroutines — ships its own consumer rules inside its AAR, and the app itself
|
||||
# uses no reflection over its own classes (songs, presets, themes and bindings
|
||||
# are all read and written as text by hand-written parsers in io/).
|
||||
|
||||
# JNI. The native library resolves Java_<mangled package>_<class>_<method> by
|
||||
# name at *runtime*, so a renamed class or method is an UnsatisfiedLinkError on
|
||||
# first play — not a build error. Both halves of the bridge must keep their
|
||||
# names: audio/NativeEngine (the engine, src/main/cpp/jni_engine.cpp) and
|
||||
# audio/NativeAudioBridge (the Oboe stream, src/main/cpp/native_audio.cpp).
|
||||
-keepclasseswithmembernames,includedescriptorclasses class * {
|
||||
native <methods>;
|
||||
}
|
||||
|
||||
# Kotlin tells R8 what is nullable through these; dropping them makes R8's
|
||||
# warnings about the Kotlin stdlib noisy for no gain.
|
||||
-dontwarn kotlin.Unit
|
||||
|
||||
@@ -10,7 +10,11 @@
|
||||
BLUETOOTH_CONNECT : Bluetooth MIDI + gamepad on Android 12+.
|
||||
BLUETOOTH_SCAN : finding BLE MIDI controllers (Settings › MIDI inputs) on
|
||||
Android 12+; never used to derive location.
|
||||
BLUETOOTH / _ADMIN / ACCESS_FINE_LOCATION : the same scan on Android 8-11. -->
|
||||
BLUETOOTH / _ADMIN : the same scan on Android 8-11.
|
||||
ACCESS_FINE_LOCATION + ACCESS_COARSE_LOCATION : a BLE scan on Android 8-11
|
||||
was gated on location permission. Both are declared
|
||||
because the platform (and lint) treat FINE as an
|
||||
upgrade of COARSE, and we only ever scan with them. -->
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
|
||||
@@ -20,6 +24,7 @@
|
||||
android:usesPermissionFlags="neverForLocation" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="30" />
|
||||
|
||||
<!-- Hardware we can *use* but do not *require* (so the app still installs on
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#include <string>
|
||||
|
||||
#include "host/EngineHost.hpp"
|
||||
#include "sizzle/Randomizer.hpp"
|
||||
|
||||
using sizzle::host::EngineHost;
|
||||
|
||||
@@ -127,6 +128,25 @@ JNI_FN(void, nativeEndCapture)(JNIEnv *, jobject) { H->recorder().endCapture();
|
||||
JNI_FN(void, nativeExternalClockStart)(JNIEnv *, jobject) { H->externalClockStart(); }
|
||||
JNI_FN(void, nativeExternalClockStop)(JNIEnv *, jobject) { H->externalClockStop(); }
|
||||
|
||||
// The preset randomizer (core/src/model/Randomizer.cpp). Pure functions of type and
|
||||
// seed — no engine involved — so unlike everything above they work before
|
||||
// nativeCreate and cannot be affected by what the audio thread is doing.
|
||||
JNI_FN(jboolean, nativeCanRandomize)(JNIEnv *env, jobject, jstring type) {
|
||||
return sizzle::model::canRandomize(str(env, type).c_str()) ? JNI_TRUE : JNI_FALSE;
|
||||
}
|
||||
|
||||
/** A random patch as preset text (io/PresetIo's format), for PresetIo.import. */
|
||||
JNI_FN(jstring, nativeRandomPreset)(JNIEnv *env, jobject, jstring type, jint seed) {
|
||||
const std::string text = sizzle::model::randomPresetText(str(env, type).c_str(), (uint32_t)seed);
|
||||
return env->NewStringUTF(text.c_str());
|
||||
}
|
||||
|
||||
/** The name that goes with that seed (PresetIo.import does not carry NAME through). */
|
||||
JNI_FN(jstring, nativeRandomName)(JNIEnv *env, jobject, jstring type, jint seed) {
|
||||
const std::string name = sizzle::model::randomName(str(env, type).c_str(), (uint32_t)seed);
|
||||
return env->NewStringUTF(name.c_str());
|
||||
}
|
||||
|
||||
/** The AudioTrack fallback's render: [frames] interleaved stereo frames into [out]. */
|
||||
JNI_FN(void, nativeRender)(JNIEnv *env, jobject, jfloatArray out, jint frames) {
|
||||
EngineHost *h = host();
|
||||
|
||||
@@ -104,10 +104,12 @@ 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()
|
||||
cc.tiredsysadmin.android.sizzle.wavetable.WaveTables.prewarm()
|
||||
// The Grain Cloud's sources and the factory wavetables are synthesised, not
|
||||
// shipped — but the engine (core/, through EngineHost) renders its own set as
|
||||
// soon as it is created, and nothing outside the two editors' drawings reads
|
||||
// the Kotlin ones. They are built when those editors open (WavetablePreview /
|
||||
// GrainCloudEditor) instead of here, so launch no longer renders ~6 MB of PCM
|
||||
// twice and no longer holds the second copy for the life of the process.
|
||||
// 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)
|
||||
|
||||
@@ -49,13 +49,18 @@ class AudioEngine(
|
||||
rebuildFxChains()
|
||||
}
|
||||
|
||||
/** The Kotlin project changed: bring the engine's copy up to date soon (once per
|
||||
* main-loop turn however many edits arrive). Any thread. */
|
||||
/** The Kotlin project changed: bring the engine's copy up to date soon. Any thread.
|
||||
*
|
||||
* Coalesced to one sync per [SYNC_COALESCE_MS]. A drag over the pattern grid or a
|
||||
* knob fires an edit per pointer event — each one its own main-loop turn, so a
|
||||
* per-turn flag would still serialise the whole song 60 times a second. The
|
||||
* engine's copy being a frame or two stale is inaudible (nothing has sounded yet
|
||||
* that the edit changes), and every transport or routing call syncs first anyway. */
|
||||
fun requestSync() {
|
||||
main.post {
|
||||
if (syncPending) return@post
|
||||
syncPending = true
|
||||
main.post { syncPending = false; syncNow() }
|
||||
main.postDelayed({ syncPending = false; syncNow() }, SYNC_COALESCE_MS)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,13 +95,19 @@ class AudioEngine(
|
||||
private val _transport = MutableStateFlow(TransportState())
|
||||
val transport: StateFlow<TransportState> = _transport
|
||||
|
||||
/** Wakes the transport poller out of its idle wait (see [start]). At most one
|
||||
* permit is outstanding, so a flood of transport calls costs one extra turn. */
|
||||
private val pollWake = java.util.concurrent.Semaphore(0)
|
||||
|
||||
private fun wakePoller() { if (pollWake.availablePermits() == 0) pollWake.release() }
|
||||
|
||||
/** Start playback, optionally from [startBeat] (see Engine::play). */
|
||||
fun play(startBeat: Int = -1) { syncNow(); if (NativeEngine.created) NativeEngine.nativePlay(startBeat); publish() }
|
||||
fun pause() { if (NativeEngine.created) NativeEngine.nativePause(); publish() }
|
||||
fun play(startBeat: Int = -1) { syncNow(); if (NativeEngine.created) NativeEngine.nativePlay(startBeat); publish(); wakePoller() }
|
||||
fun pause() { if (NativeEngine.created) NativeEngine.nativePause(); publish(); wakePoller() }
|
||||
/** MIDI panic: hard-silence every voice and cancel the arpeggiators. */
|
||||
fun panic() { if (NativeEngine.created) NativeEngine.nativePanic(); publish() }
|
||||
fun panic() { if (NativeEngine.created) NativeEngine.nativePanic(); publish(); wakePoller() }
|
||||
/** Stop; if already stopped, rewind to the top. */
|
||||
fun stop() { if (NativeEngine.created) NativeEngine.nativeStop(); publish() }
|
||||
fun stop() { if (NativeEngine.created) NativeEngine.nativeStop(); publish(); wakePoller() }
|
||||
|
||||
private fun publish() {
|
||||
if (!NativeEngine.created) return
|
||||
@@ -160,6 +171,7 @@ class AudioEngine(
|
||||
fun setRecordingArm(armed: Boolean, tailBars: Int) {
|
||||
recordArmed = armed
|
||||
if (NativeEngine.created) NativeEngine.nativeSetRecordingArm(armed, tailBars.coerceIn(0, 8))
|
||||
wakePoller()
|
||||
}
|
||||
|
||||
fun setRecordTailBars(tailBars: Int) {
|
||||
@@ -167,10 +179,13 @@ class AudioEngine(
|
||||
}
|
||||
|
||||
/** An external MIDI clock's Start: an armed recording starts even with the song stopped. */
|
||||
fun externalClockStart() { if (NativeEngine.created) NativeEngine.nativeExternalClockStart() }
|
||||
fun externalClockStart() {
|
||||
if (NativeEngine.created) NativeEngine.nativeExternalClockStart()
|
||||
wakePoller()
|
||||
}
|
||||
fun externalClockStop() { if (NativeEngine.created) NativeEngine.nativeExternalClockStop() }
|
||||
|
||||
private var wasRecording = false
|
||||
@Volatile private var wasRecording = false
|
||||
|
||||
private fun pollRecording() {
|
||||
val active = NativeEngine.nativeRecordingActive()
|
||||
@@ -198,11 +213,15 @@ class AudioEngine(
|
||||
fun start() {
|
||||
if (running) return
|
||||
running = true
|
||||
// Transport and recording state for the UI, ~100 times a second.
|
||||
// Transport and recording state for the UI: ~100 times a second while there is
|
||||
// something to watch, 10 times a second when the song is stopped and nothing is
|
||||
// armed (then only an external MIDI clock could start a take). A transport call
|
||||
// wakes the thread through [pollWake], so the playhead still appears at once.
|
||||
poller = thread(name = "sizzle-transport", isDaemon = true) {
|
||||
while (running) {
|
||||
if (NativeEngine.created) { publish(); pollRecording() }
|
||||
Thread.sleep(10)
|
||||
val busy = _transport.value.isPlaying || recordArmed || wasRecording
|
||||
pollWake.tryAcquire(if (busy) 10L else 100L, java.util.concurrent.TimeUnit.MILLISECONDS)
|
||||
}
|
||||
}
|
||||
main.post(safetyNet)
|
||||
@@ -268,6 +287,7 @@ class AudioEngine(
|
||||
/** Stop the engine entirely (called when the last owner lets go). */
|
||||
fun release() {
|
||||
running = false
|
||||
wakePoller()
|
||||
main.removeCallbacks(safetyNet)
|
||||
if (NativeEngine.created) { NativeEngine.nativeSetRecordingArm(false, 0); NativeEngine.nativeEndCapture() }
|
||||
nativeBridge?.stop()
|
||||
@@ -276,11 +296,13 @@ class AudioEngine(
|
||||
renderThread = null
|
||||
track?.run { stop(); release() }
|
||||
track = null
|
||||
poller?.join(100)
|
||||
poller?.join(200)
|
||||
poller = null
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val BLOCK_FRAMES = 192 // the engine's block (~4 ms at 48 kHz)
|
||||
/** How long a burst of edits is collected before one sync (see [requestSync]). */
|
||||
const val SYNC_COALESCE_MS = 33L
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,18 @@ object NativeEngine {
|
||||
|
||||
fun removeSample(id: String) { if (created) nativeRemoveSample(id) }
|
||||
|
||||
// ---- the preset randomizer (core/src/model/Randomizer.cpp) ----
|
||||
// Gated on [loaded], not [created]: these need no engine, only the library.
|
||||
|
||||
/** Does this device type have a randomizer? */
|
||||
fun canRandomize(type: String): Boolean = loaded && nativeCanRandomize(type)
|
||||
|
||||
/** A random patch for [type] as preset text, or "" — feed it to PresetIo.import. */
|
||||
fun randomPreset(type: String, seed: Int): String = if (loaded) nativeRandomPreset(type, seed) else ""
|
||||
|
||||
/** The name belonging to that same [seed]. */
|
||||
fun randomName(type: String, seed: Int): String = if (loaded) nativeRandomName(type, seed) else ""
|
||||
|
||||
external fun nativeCreate(sampleRate: Int)
|
||||
external fun nativeLoad(text: String)
|
||||
external fun nativeSync(text: String)
|
||||
@@ -62,4 +74,7 @@ object NativeEngine {
|
||||
external fun nativeExternalClockStart()
|
||||
external fun nativeExternalClockStop()
|
||||
external fun nativeRender(out: FloatArray, frames: Int)
|
||||
external fun nativeCanRandomize(type: String): Boolean
|
||||
external fun nativeRandomPreset(type: String, seed: Int): String
|
||||
external fun nativeRandomName(type: String, seed: Int): String
|
||||
}
|
||||
|
||||
@@ -79,7 +79,9 @@ class BleMidi(private val context: Context) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT)
|
||||
} else {
|
||||
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
// Both, as the manifest declares them: a FINE request without COARSE is
|
||||
// rejected by the platform's permission model (and flagged by lint).
|
||||
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
|
||||
}
|
||||
|
||||
fun hasPermissions(): Boolean = requiredPermissions().all {
|
||||
|
||||
@@ -73,8 +73,8 @@ class MidiClock(context: Context) {
|
||||
override fun onDeviceAdded(device: MidiDeviceInfo) = openDevice(device)
|
||||
}
|
||||
callback = cb
|
||||
mm.devices.forEach(::openDevice)
|
||||
mm.registerDeviceCallback(cb, handler)
|
||||
allDevices(mm).forEach(::openDevice)
|
||||
registerCallback(mm, cb)
|
||||
running = true
|
||||
thread = Thread({ sendLoop() }, "sizzle-midi-clock").apply {
|
||||
priority = Thread.MAX_PRIORITY; isDaemon = true; start()
|
||||
@@ -90,6 +90,16 @@ class MidiClock(context: Context) {
|
||||
outPorts.clear()
|
||||
}
|
||||
|
||||
// Same two deprecations MidiInput suppresses the same way: getDevices and the
|
||||
// Handler overload of registerDeviceCallback are still the only ones that list
|
||||
// and watch every transport below API 33.
|
||||
@Suppress("DEPRECATION")
|
||||
private fun allDevices(mm: MidiManager): List<MidiDeviceInfo> = mm.devices.toList()
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun registerCallback(mm: MidiManager, cb: MidiManager.DeviceCallback) =
|
||||
mm.registerDeviceCallback(cb, handler)
|
||||
|
||||
private fun openDevice(info: MidiDeviceInfo) {
|
||||
if (info.inputPortCount == 0) return // need a port we can send TO
|
||||
midiManager?.openDevice(info, { device ->
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
package cc.tiredsysadmin.android.sizzle.io
|
||||
|
||||
import cc.tiredsysadmin.android.sizzle.model.Cell
|
||||
import cc.tiredsysadmin.android.sizzle.model.LoopRegion
|
||||
import cc.tiredsysadmin.android.sizzle.model.Mixer
|
||||
import cc.tiredsysadmin.android.sizzle.model.Pattern
|
||||
import cc.tiredsysadmin.android.sizzle.model.Project
|
||||
@@ -27,58 +28,100 @@ import cc.tiredsysadmin.android.sizzle.model.ToolboxType
|
||||
object ProjectIo {
|
||||
private const val HEADER = "SIZZLETRACKER-SNG 1"
|
||||
|
||||
/** Room for a typical song, so [save]'s buffer never has to grow and copy. */
|
||||
private const val INITIAL_CAPACITY = 32 * 1024
|
||||
|
||||
// ------------------------------------------------------------------- write
|
||||
fun save(project: Project): String = buildString {
|
||||
appendLine(HEADER)
|
||||
appendLine("NAME=${project.name}")
|
||||
appendLine("TEMPO=${project.tempoBpm}")
|
||||
appendLine("SIG=${project.timeSignature.name}")
|
||||
appendLine("SCALE=${project.scale.name}")
|
||||
appendLine("ROOT=${project.rootNote}")
|
||||
appendLine("ACTIVE=${project.activePatternId}")
|
||||
/**
|
||||
* The whole project as `.sng` text.
|
||||
*
|
||||
* This is the hot path of the UI → engine bridge, not just the file writer:
|
||||
* `AudioEngine.syncNow` calls it after every edit and the engine diffs the text
|
||||
* (see DEVELOPER_HANDOVER.md §5.4.2). So it builds into one pre-sized buffer and
|
||||
* appends numbers straight into it instead of formatting a String per line —
|
||||
* byte for byte the same output, a fraction of the garbage.
|
||||
*/
|
||||
fun save(project: Project): String {
|
||||
val sb = StringBuilder(INITIAL_CAPACITY)
|
||||
sb.append(HEADER).append('\n')
|
||||
sb.append("NAME=").append(project.name).append('\n')
|
||||
sb.append("TEMPO=").append(project.tempoBpm).append('\n')
|
||||
sb.append("SIG=").append(project.timeSignature.name).append('\n')
|
||||
sb.append("SCALE=").append(project.scale.name).append('\n')
|
||||
sb.append("ROOT=").append(project.rootNote).append('\n')
|
||||
sb.append("ACTIVE=").append(project.activePatternId).append('\n')
|
||||
|
||||
project.patterns.forEach { p ->
|
||||
appendLine("[PATTERN id=${p.id} name=${encodeName(p.name)} len=${p.length}]")
|
||||
sb.append("[PATTERN id=").append(p.id).append(" name=").append(encodeName(p.name))
|
||||
.append(" len=").append(p.length).append("]\n")
|
||||
for (t in 0 until Pattern.TRACK_COUNT) {
|
||||
val col = p.tracks[t]
|
||||
for (line in 0 until p.length) {
|
||||
val cell = p.cell(t, line)
|
||||
if (!cell.isEmpty) appendLine("$t,$line,${cell.note},${cell.velocity},${cell.channel}")
|
||||
val cell = col[line]
|
||||
if (cell.isEmpty) continue
|
||||
sb.append(t).append(',').append(line).append(',').append(cell.note)
|
||||
.append(',').append(cell.velocity).append(',').append(cell.channel).append('\n')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val arr = project.arrangement
|
||||
val mutes = arr.laneMuted.joinToString("") { if (it) "1" else "0" }
|
||||
appendLine("[ARRANGEMENT bars=${arr.lengthBars} loop=${arr.loopEnabled.b()} mutes=$mutes]")
|
||||
sb.append("[ARRANGEMENT bars=").append(arr.lengthBars)
|
||||
.append(" loop=").append(if (arr.loopEnabled) '1' else '0').append(" mutes=")
|
||||
for (muted in arr.laneMuted) sb.append(if (muted) '1' else '0')
|
||||
sb.append("]\n")
|
||||
val usedBeats = arr.lastFilledBeat() + 1
|
||||
for (lane in arr.slots.indices) {
|
||||
val row = arr.slots[lane]
|
||||
for (beat in 0 until usedBeats) {
|
||||
val pid = arr.slots[lane][beat]
|
||||
val pid = row[beat]
|
||||
// >= 0 is a block id; NOTE_OFF is a marker and must survive too.
|
||||
// Anything else is EMPTY and is simply omitted.
|
||||
if (pid >= 0 || pid == cc.tiredsysadmin.android.sizzle.model.Arrangement.NOTE_OFF) appendLine("$lane,$beat,$pid")
|
||||
if (pid < 0 && pid != cc.tiredsysadmin.android.sizzle.model.Arrangement.NOTE_OFF) continue
|
||||
sb.append(lane).append(',').append(beat).append(',').append(pid).append('\n')
|
||||
}
|
||||
}
|
||||
appendLine("[REGION A en=${arr.regionA.enabled.b()} s=${arr.regionA.start} e=${arr.regionA.end} r=${arr.regionA.repeats}]")
|
||||
appendLine("[REGION B en=${arr.regionB.enabled.b()} s=${arr.regionB.start} e=${arr.regionB.end} r=${arr.regionB.repeats}]")
|
||||
return sb.appendTail(project).toString()
|
||||
}
|
||||
|
||||
appendLine("[MIXER]")
|
||||
/** The rest of [save]: regions, mixer, toolbox. Split out only to keep each half
|
||||
* readable; the two together produce one buffer. */
|
||||
private fun StringBuilder.appendTail(project: Project): StringBuilder = apply {
|
||||
val arr = project.arrangement
|
||||
appendRegion('A', arr.regionA)
|
||||
appendRegion('B', arr.regionB)
|
||||
|
||||
append("[MIXER]\n")
|
||||
project.mixer.channels.forEach { ch ->
|
||||
appendLine(
|
||||
"${ch.index},${ch.instrumentSlot},${ch.fxSlots.joinToString(",")}," +
|
||||
"${ch.midiChannel},${ch.volume},${ch.mute.b()},${ch.solo.b()},${ch.limiter.b()}",
|
||||
)
|
||||
append(ch.index).append(',').append(ch.instrumentSlot)
|
||||
for (fx in ch.fxSlots) append(',').append(fx)
|
||||
append(',').append(ch.midiChannel).append(',').append(ch.volume)
|
||||
.append(',').append(if (ch.mute) '1' else '0')
|
||||
.append(',').append(if (ch.solo) '1' else '0')
|
||||
.append(',').append(if (ch.limiter) '1' else '0').append('\n')
|
||||
}
|
||||
|
||||
appendLine("[TOOLBOX]")
|
||||
append("[TOOLBOX]\n")
|
||||
project.toolbox.forEach { slot ->
|
||||
if (!slot.isEmpty) {
|
||||
val params = slot.values.entries.joinToString(",") { "${it.key}=${it.value}" }
|
||||
appendLine("${slot.index}=${slot.type!!.name};${slot.name};$params")
|
||||
if (slot.isEmpty) return@forEach
|
||||
append(slot.index).append('=').append(slot.type!!.name).append(';').append(slot.name).append(';')
|
||||
var first = true
|
||||
for ((k, v) in slot.values) {
|
||||
if (!first) append(',')
|
||||
first = false
|
||||
append(k).append('=').append(v)
|
||||
}
|
||||
append('\n')
|
||||
}
|
||||
}
|
||||
|
||||
private fun StringBuilder.appendRegion(id: Char, r: LoopRegion) {
|
||||
append("[REGION ").append(id)
|
||||
.append(" en=").append(if (r.enabled) '1' else '0')
|
||||
.append(" s=").append(r.start).append(" e=").append(r.end)
|
||||
.append(" r=").append(r.repeats).append("]\n")
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------- read
|
||||
/**
|
||||
* Parse [text] into the *existing* [project], replacing its contents. Used to
|
||||
@@ -153,8 +196,6 @@ object ProjectIo {
|
||||
}
|
||||
|
||||
// ----- small helpers -----
|
||||
private fun Boolean.b() = if (this) "1" else "0"
|
||||
|
||||
private fun parseAttrs(line: String): Map<String, String> =
|
||||
line.trim('[', ']').substringAfter(' ', "").split(' ')
|
||||
.mapNotNull { tok -> tok.split('=', limit = 2).takeIf { it.size == 2 }?.let { it[0] to it[1] } }
|
||||
@@ -195,7 +236,7 @@ object ProjectIo {
|
||||
p.arrangement.set(lane, beat, pid)
|
||||
}
|
||||
|
||||
private fun applyRegion(region: cc.tiredsysadmin.android.sizzle.model.LoopRegion, a: Map<String, String>) {
|
||||
private fun applyRegion(region: LoopRegion, a: Map<String, String>) {
|
||||
region.enabled = a["en"] == "1"
|
||||
region.start = a["s"]?.toIntOrNull() ?: 0
|
||||
region.end = a["e"]?.toIntOrNull() ?: 0
|
||||
|
||||
@@ -49,7 +49,7 @@ enum class ToolboxType(
|
||||
// ---------- Instruments ----------
|
||||
// A classic 3-oscillator subtractive synth (Minimoog-style): oscillators →
|
||||
// mixer → resonant filter (own contour) → amp (own envelope), with a tempo-synced
|
||||
// LFO and a small mod matrix. Rendered by [SynthVoice]; edited by NesSynthEditor.
|
||||
// LFO and a small mod matrix. Rendered by core/src/synth/SynthVoice; edited by NesSynthEditor.
|
||||
// NOTE: the enum name NES_SYNTH is the on-disk/serialized identifier (preset dirs,
|
||||
// .sng type) and must stay stable for backward compatibility; only the user-facing
|
||||
// displayName is generic.
|
||||
@@ -124,17 +124,17 @@ enum class ToolboxType(
|
||||
// FRASIL's drone voice (MPL-2.0, see the frasil package): three layers (a detuned
|
||||
// saw choir, drifting additive partials, noise through resonators) that evolve
|
||||
// while held, morphing toward one of FRASIL's 36 drone sounds. Rendered by
|
||||
// FrasilVoice inside SynthVoice; edited by the paged editor in ToolboxScreen.
|
||||
// core/src/frasil/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.
|
||||
// the grains. Rendered by core/src/echofield/GrainCloud; 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.
|
||||
// by core/src/wavetable/WaveVoice inside SynthVoice; edited by WavetableEditor + the paged list.
|
||||
WAVETABLE(ToolboxKind.INSTRUMENT, "Wavetable", WaveDefs.PARAMS),
|
||||
|
||||
// ---------- Effects ----------
|
||||
@@ -221,7 +221,7 @@ enum class ToolboxType(
|
||||
ToolboxKind.EFFECT, "Ambience Reverb",
|
||||
// A mono port of the Ambience 16-channel FDN reverb (OTODESK): 7 algorithms,
|
||||
// tempo-independent tunables and 21 factory spaces (seeded into the preset
|
||||
// library). Rendered by audio/AmbienceReverb.kt.
|
||||
// library). Rendered by core/src/fx/AmbienceReverb.cpp.
|
||||
listOf(
|
||||
ParamSpec("algo", "Algorithm", 0f, 0f, 6f, AmbiencePresets.ALGORITHMS),
|
||||
ParamSpec("predelay", "Pre-Delay", 10f, 0f, 500f),
|
||||
@@ -249,7 +249,7 @@ enum class ToolboxType(
|
||||
// morphs the whole chain from transparent (0) to the full preset (1). Every
|
||||
// per-band value is a hidden slot param set by the genre/instrument presets
|
||||
// (see MixTightenerPresets); only Strength is user-facing. Rendered by
|
||||
// MixTightener in Effects.kt, edited by ui/toolbox/MixTightenerEditor.
|
||||
// core/src/fx/MixTightener.cpp, edited by ui/toolbox/MixTightenerEditor.
|
||||
listOf(ParamSpec("strength", "Strength", 1f, 0f, 1f)),
|
||||
),
|
||||
TAPE_ENGINE(
|
||||
@@ -258,7 +258,7 @@ enum class ToolboxType(
|
||||
// the pitch dives like a slowing tape (the 'speed' param is driven by that reel
|
||||
// gesture, not a slider). wow/flutter add slow + fast pitch wobble, hiss adds
|
||||
// tape noise, and the wow wobble rate is tempo-synced via 'division'. Rendered
|
||||
// by TapeEngine in Effects.kt, edited by ui/toolbox/TapeEngineEditor.
|
||||
// by core/src/fx/TapeEngine.cpp, edited by ui/toolbox/TapeEngineEditor.
|
||||
listOf(
|
||||
ParamSpec("speed", "Speed", 1f, 0.25f, 1f),
|
||||
ParamSpec("wow", "Wow", 0.15f, 0f, 1f),
|
||||
@@ -272,7 +272,7 @@ enum class ToolboxType(
|
||||
// Stutters/repeats short grains read from a rolling buffer of the incoming
|
||||
// sound; the read head jumps around, and the editor draws it as a moving
|
||||
// playhead over a dotted scope of the signal. One control: Intensity (how often
|
||||
// it glitches + how mangled). Rendered by GranularGlitch in Effects.kt, edited
|
||||
// it glitches + how mangled). Rendered by core/src/fx/GranularGlitch.cpp, edited
|
||||
// by ui/toolbox/GranularEditor.
|
||||
listOf(ParamSpec("intensity", "Intensity", 0.3f, 0f, 1f)),
|
||||
);
|
||||
|
||||
@@ -156,9 +156,6 @@ class AppViewModel(
|
||||
* notification's Stop action changes it with no UI around. */
|
||||
val soundModuleMode: StateFlow<Boolean> get() = sizzleApp.soundModuleEnabled
|
||||
|
||||
/** MIDI sources currently open (USB, Bluetooth, other apps' virtual ports). */
|
||||
val midiSources: StateFlow<Int> get() = sizzleApp.soundModule.sources
|
||||
|
||||
fun updateSoundModuleMode(enabled: Boolean) = sizzleApp.setSoundModuleEnabled(enabled)
|
||||
|
||||
/** Every MIDI source that can send to Sizzle, with whether it is listened to. */
|
||||
@@ -1408,6 +1405,32 @@ class AppViewModel(
|
||||
return ok
|
||||
}
|
||||
|
||||
/** Does this device have a dice button? (The randomizer lives in core/.) */
|
||||
fun canRandomize(type: cc.tiredsysadmin.android.sizzle.model.ToolboxType): Boolean =
|
||||
cc.tiredsysadmin.android.sizzle.audio.NativeEngine.canRandomize(type.name)
|
||||
|
||||
/**
|
||||
* Roll a new patch into [slot]: a playable one, generated by core/'s randomizer
|
||||
* (the same rules and the same seeds as iOS). The slot's own files are kept —
|
||||
* a loaded sample or an imported wavetable is the user's, and a dice roll of the
|
||||
* *settings* must not throw it away — so the keys the device's parameter list
|
||||
* doesn't name (`sfSample`, `sfFile`, the Sampler's pads) are put back afterwards.
|
||||
*/
|
||||
fun randomizeSlot(slot: cc.tiredsysadmin.android.sizzle.model.ToolboxSlot): Boolean {
|
||||
val type = slot.type ?: return false
|
||||
val seed = java.util.concurrent.ThreadLocalRandom.current().nextInt()
|
||||
val text = cc.tiredsysadmin.android.sizzle.audio.NativeEngine.randomPreset(type.name, seed)
|
||||
if (text.isBlank()) return false
|
||||
val keep = slot.values.filterKeys { key -> type.params.none { it.key == key } }
|
||||
if (!cc.tiredsysadmin.android.sizzle.io.PresetIo.import(slot, text)) return false
|
||||
keep.forEach { (k, v) -> slot.set(k, v) }
|
||||
slot.name = cc.tiredsysadmin.android.sizzle.audio.NativeEngine.randomName(type.name, seed)
|
||||
.ifBlank { type.displayName }
|
||||
engine.rebuildFxChains()
|
||||
touched()
|
||||
return true
|
||||
}
|
||||
|
||||
/** Import a preset from picked bytes: a `.zip` bundle (Sampler) or plain text. */
|
||||
fun importPreset(slot: cc.tiredsysadmin.android.sizzle.model.ToolboxSlot, bytes: ByteArray): Boolean {
|
||||
val isZip = bytes.size >= 2 && bytes[0] == 'P'.code.toByte() && bytes[1] == 'K'.code.toByte()
|
||||
|
||||
@@ -23,7 +23,7 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.ChevronRight
|
||||
import androidx.compose.material.icons.filled.Piano
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
@@ -170,7 +170,7 @@ fun SettingsScreen(vm: AppViewModel) {
|
||||
@Composable
|
||||
private fun SubHeader(title: String, onBack: () -> Unit) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
IconButton(onClick = onBack) { Icon(Icons.Filled.ArrowBack, contentDescription = "Back") }
|
||||
IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") }
|
||||
Text(title, style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -58,6 +59,12 @@ fun GrainCloudEditor(vm: AppViewModel, slot: ToolboxSlot) {
|
||||
}
|
||||
}
|
||||
|
||||
// Same as the wavetables: the ten built-in sources are synthesised, the engine
|
||||
// renders its own set in core/, and this Kotlin copy exists only to draw the
|
||||
// waveform below. Built when the editor opens rather than at launch — that is
|
||||
// about 6 MB of PCM an app that never opens one no longer renders or holds.
|
||||
LaunchedEffect(Unit) { GrainSources.prewarm() }
|
||||
|
||||
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)
|
||||
|
||||
@@ -228,7 +228,7 @@ private fun roundedPoly(v: Array<Offset>, corner: Float): Path {
|
||||
val a = curr + toward(curr, prev, corner) // approach point on the incoming edge
|
||||
val b = curr + toward(curr, next, corner) // leave point on the outgoing edge
|
||||
if (i == 0) path.moveTo(a.x, a.y) else path.lineTo(a.x, a.y)
|
||||
path.quadraticBezierTo(curr.x, curr.y, b.x, b.y)
|
||||
path.quadraticTo(curr.x, curr.y, b.x, b.y)
|
||||
}
|
||||
path.close()
|
||||
return path
|
||||
|
||||
@@ -49,8 +49,10 @@ import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
@@ -532,6 +534,7 @@ private fun MidiLearnPopup(vm: AppViewModel, slot: ToolboxSlot, onClose: () -> U
|
||||
private fun PresetBar(vm: AppViewModel, slot: ToolboxSlot) {
|
||||
val c = LocalRetro.current
|
||||
val context = LocalContext.current
|
||||
val haptics = LocalHapticFeedback.current
|
||||
@Suppress("UNUSED_VARIABLE") val rev = vm.revision // refresh the list after save/import
|
||||
val type = slot.type ?: return
|
||||
|
||||
@@ -589,6 +592,16 @@ private fun PresetBar(vm: AppViewModel, slot: ToolboxSlot) {
|
||||
RetroButton("DELETE", danger = true) { confirmDelete = current }
|
||||
Spacer(Modifier.width(20.dp))
|
||||
}
|
||||
// RANDOM only for the devices core/'s randomizer covers (the Synth, Morph
|
||||
// Pad, Grain Cloud, Wavetable and Ambience). It replaces the settings in
|
||||
// place, like loading a preset; the slot's own sample or table is kept.
|
||||
if (vm.canRandomize(type)) {
|
||||
RetroButton("RANDOM") {
|
||||
haptics.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
vm.randomizeSlot(slot)
|
||||
selected = null
|
||||
}
|
||||
}
|
||||
RetroButton("SAVE") { showSave = true }
|
||||
RetroButton("IMPORT") {
|
||||
// Accept text presets and (for the Sampler) zip bundles.
|
||||
|
||||
@@ -17,6 +17,7 @@ import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -45,6 +46,12 @@ import cc.tiredsysadmin.android.sizzle.wavetable.WaveTables
|
||||
/** Every frame of oscillator [osc]'s table stacked back to front, the one at its POSITION lit. */
|
||||
@Composable
|
||||
fun WavetablePreview(slot: ToolboxSlot, osc: Int, tone: Color, rev: Int) {
|
||||
// The factory tables are formulas, built on a worker, and only this drawing needs
|
||||
// the Kotlin copy — the engine builds its own in core/. So they are built when a
|
||||
// Wavetable editor is first opened, not at launch: an app that never shows one
|
||||
// pays nothing. Idempotent and non-blocking; `factory` returns null until ready
|
||||
// and the caption says "preparing…".
|
||||
LaunchedEffect(Unit) { WaveTables.prewarm() }
|
||||
val c = LocalRetro.current
|
||||
val name = slot.string("o${osc}table", WaveDefs.TABLES[0])
|
||||
val frame = slot.string("wtframe", WaveDefs.FRAME_SIZES[0]).toIntOrNull() ?: 0
|
||||
|
||||
+6
@@ -1,6 +1,12 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// The Kotlin reference the C++ port in core/ is checked against (handover §5.4.2):
|
||||
// the IosGolden* tests render it, and `make -C ios core-test` compares the C++ with
|
||||
// that audio sample by sample. It lives in the TEST source set because both apps
|
||||
// play core/ — in src/main it would only be dead code in the APK. Keep it in step
|
||||
// with core/src/fx/AmbienceReverb.cpp.
|
||||
|
||||
package cc.tiredsysadmin.android.sizzle.audio
|
||||
|
||||
import cc.tiredsysadmin.android.sizzle.model.AmbiencePresets
|
||||
+6
@@ -1,6 +1,12 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// The Kotlin reference the C++ port in core/ is checked against (handover §5.4.2):
|
||||
// the IosGolden* tests render it, and `make -C ios core-test` compares the C++ with
|
||||
// that audio sample by sample. It lives in the TEST source set because both apps
|
||||
// play core/ — in src/main it would only be dead code in the APK. Keep it in step
|
||||
// with core/src/fx/.
|
||||
|
||||
package cc.tiredsysadmin.android.sizzle.audio
|
||||
|
||||
import cc.tiredsysadmin.android.sizzle.model.DelayDivisions
|
||||
+6
@@ -1,6 +1,12 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// The Kotlin reference the C++ port in core/ is checked against (handover §5.4.2):
|
||||
// the IosGolden* tests render it, and `make -C ios core-test` compares the C++ with
|
||||
// that audio sample by sample. It lives in the TEST source set because both apps
|
||||
// play core/ — in src/main it would only be dead code in the APK. Keep it in step
|
||||
// with core/src/host/MasterRecorder.cpp.
|
||||
|
||||
package cc.tiredsysadmin.android.sizzle.audio
|
||||
|
||||
import java.io.File
|
||||
+6
@@ -1,6 +1,12 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// The Kotlin reference the C++ port in core/ is checked against (handover §5.4.2):
|
||||
// the IosGolden* tests render it, and `make -C ios core-test` compares the C++ with
|
||||
// that audio sample by sample. It lives in the TEST source set because both apps
|
||||
// play core/ — in src/main it would only be dead code in the APK. Keep it in step
|
||||
// with core/src/sampler/SampleVoice.cpp.
|
||||
|
||||
package cc.tiredsysadmin.android.sizzle.audio
|
||||
|
||||
import kotlin.math.exp
|
||||
+6
@@ -1,6 +1,12 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// The Kotlin reference the C++ port in core/ is checked against (handover §5.4.2):
|
||||
// the IosGolden* tests render it, and `make -C ios core-test` compares the C++ with
|
||||
// that audio sample by sample. It lives in the TEST source set because both apps
|
||||
// play core/ — in src/main it would only be dead code in the APK. Keep it in step
|
||||
// with core/src/synth/SynthPatch.cpp.
|
||||
|
||||
package cc.tiredsysadmin.android.sizzle.audio
|
||||
|
||||
import cc.tiredsysadmin.android.sizzle.frasil.FrasilPatch
|
||||
+6
-1
@@ -1,6 +1,12 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// The Kotlin reference the C++ port in core/ is checked against (handover §5.4.2):
|
||||
// the IosGolden* tests render it, and `make -C ios core-test` compares the C++ with
|
||||
// that audio sample by sample. It lives in the TEST source set because both apps
|
||||
// play core/ — in src/main it would only be dead code in the APK. Keep it in step
|
||||
// with core/src/synth/SynthVoice.cpp.
|
||||
|
||||
package cc.tiredsysadmin.android.sizzle.audio
|
||||
|
||||
import cc.tiredsysadmin.android.sizzle.frasil.FrasilVoice
|
||||
@@ -80,7 +86,6 @@ class SynthVoice(private val sampleRate: Int) {
|
||||
private val pad = FrasilVoice(sampleRate)
|
||||
private val wave = WaveVoice(sampleRate)
|
||||
private var mode = MODE_SYNTH
|
||||
private val padMode get() = mode == MODE_PAD
|
||||
|
||||
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
|
||||
+6
@@ -7,6 +7,12 @@
|
||||
// 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.
|
||||
|
||||
// The Kotlin reference the C++ port in core/ is checked against (handover §5.4.2):
|
||||
// the IosGolden* tests render it, and `make -C ios core-test` compares the C++ with
|
||||
// that audio sample by sample. It lives in the TEST source set because both apps
|
||||
// play core/ — in src/main it would only be dead code in the APK. Keep it in step
|
||||
// with core/src/echofield/GrainCloud.cpp.
|
||||
|
||||
package cc.tiredsysadmin.android.sizzle.echofield
|
||||
|
||||
import cc.tiredsysadmin.android.sizzle.audio.GrainSources
|
||||
+6
@@ -6,6 +6,12 @@
|
||||
// If a copy of the MPL was not distributed with this file, You can obtain one at
|
||||
// https://mozilla.org/MPL/2.0/ (also in LICENSES/MPL-2.0.txt of this repository).
|
||||
|
||||
// The Kotlin reference the C++ port in core/ is checked against (handover §5.4.2):
|
||||
// the IosGolden* tests render it, and `make -C ios core-test` compares the C++ with
|
||||
// that audio sample by sample. It lives in the TEST source set because both apps
|
||||
// play core/ — in src/main it would only be dead code in the APK. Keep it in step
|
||||
// with core/src/frasil/FrasilVoice.cpp.
|
||||
|
||||
package cc.tiredsysadmin.android.sizzle.frasil
|
||||
|
||||
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
|
||||
+6
@@ -11,6 +11,12 @@
|
||||
// ch_svf, ch_lp, blepi, partial_ramp, partials_chunk, souffle_chunk, breath_noise,
|
||||
// render_part) and the mix's DC blocker, warmth and FULLNESS high-pass.
|
||||
|
||||
// The Kotlin reference the C++ port in core/ is checked against (handover §5.4.2):
|
||||
// the IosGolden* tests render it, and `make -C ios core-test` compares the C++ with
|
||||
// that audio sample by sample. It lives in the TEST source set because both apps
|
||||
// play core/ — in src/main it would only be dead code in the APK. Keep it in step
|
||||
// with core/src/frasil/FrasilVoice.cpp.
|
||||
|
||||
package cc.tiredsysadmin.android.sizzle.frasil
|
||||
|
||||
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs.AIR
|
||||
+6
@@ -1,6 +1,12 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// The Kotlin reference the C++ port in core/ is checked against (handover §5.4.2):
|
||||
// the IosGolden* tests render it, and `make -C ios core-test` compares the C++ with
|
||||
// that audio sample by sample. It lives in the TEST source set because both apps
|
||||
// play core/ — in src/main it would only be dead code in the APK. Keep it in step
|
||||
// with core/src/wavetable/WaveVoice.cpp.
|
||||
|
||||
package cc.tiredsysadmin.android.sizzle.wavetable
|
||||
|
||||
import cc.tiredsysadmin.android.sizzle.model.TimeDivision
|
||||
@@ -12,6 +12,7 @@
|
||||
// thread. Toolbox values are text (sizzle::Params), as ToolboxSlot's map is.
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "sizzle/Params.hpp"
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#pragma once
|
||||
|
||||
// The preset pseudorandomizer: a playable patch from a seed, for the five devices
|
||||
// where "surprise me" is a musical thing to ask for. Shared by both apps (handover
|
||||
// §5.4.2's parity rule), so a roll of the dice gives the same patch on Android and
|
||||
// on iOS for the same seed.
|
||||
//
|
||||
// "Playable" is the whole point, and it is what makes this more than scattering
|
||||
// values over the parameter ranges:
|
||||
//
|
||||
// - audible. Something always sounds: at least one oscillator or layer is up, an
|
||||
// amp envelope that decays to nothing gets a body, a filter is never shut, and
|
||||
// a reverb is never fully dry.
|
||||
// - inside the rails. Oscillator levels share a budget, resonance, drive and
|
||||
// saturation stay below the range where a patch screams, and the reverb's wet
|
||||
// and dry cannot both sit at 0 dB. `randomizer_test` renders every device over
|
||||
// many seeds and fails if a patch comes out silent or clipping.
|
||||
// - musical where it matters. Tunings come from consonant intervals rather than
|
||||
// a uniform draw over ±12 semitones, detune stays inside a chorus, and pitch
|
||||
// modulation is small enough to stay in tune.
|
||||
//
|
||||
// Nothing structural is rolled: a sample or an imported wavetable is the user's
|
||||
// choice, so "Custom" sources and tables are never picked, and the sample keys a
|
||||
// slot already holds are left alone.
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
#include "sizzle/Params.hpp"
|
||||
|
||||
namespace sizzle::model {
|
||||
|
||||
/** True when [type] (a ToolboxType name) has a randomizer: NES_SYNTH, MORPH_PAD,
|
||||
* GRAIN_CLOUD, WAVETABLE and AMBIENCE. The UI shows its dice button for these. */
|
||||
bool canRandomize(const char *type);
|
||||
|
||||
/** Fill [out] with a playable random patch for [type]. Every value is written
|
||||
* through the device's own ParamSpec, so nothing can land outside its range or
|
||||
* off an enum's choices. [seed] makes it reproducible: the same seed is the same
|
||||
* patch, here and on the other platform. Returns false, leaving [out] untouched,
|
||||
* for a type with no randomizer. */
|
||||
bool randomize(const char *type, uint32_t seed, Params &out);
|
||||
|
||||
/** A short two-word name for the patch [seed] produces ("Hazy Drift"), so a roll
|
||||
* arrives with something to call it and SAVE has a name to offer. Empty for a
|
||||
* type with no randomizer. */
|
||||
std::string randomName(const char *type, uint32_t seed);
|
||||
|
||||
/** The whole thing as preset text (io::PresetIo's format, NAME included) — what
|
||||
* the Android app receives over JNI and hands to PresetIo.import. Empty for a
|
||||
* type with no randomizer. */
|
||||
std::string randomPresetText(const char *type, uint32_t seed);
|
||||
|
||||
} // namespace sizzle::model
|
||||
@@ -19,7 +19,6 @@ public:
|
||||
bool resetOnBar = false;
|
||||
int genStamp = -1;
|
||||
|
||||
int noteCount() const { return noteCount_; }
|
||||
/** Active while it holds at least one note. */
|
||||
bool active() const { return noteCount_ > 0; }
|
||||
|
||||
|
||||
@@ -605,6 +605,24 @@ void Engine::Impl::fillBlock(float *out, int frames) {
|
||||
auditionCloudActive = auditionCloud->isActive();
|
||||
for (int i = 0; i < (int)auditionSampleVoices.size(); ++i) if (auditionSampleVoices[i]->isActive()) actASmp[actASmpN++] = i;
|
||||
|
||||
// Per-channel mixer state is read once per block, not once per sample: mute,
|
||||
// solo and volume cannot change inside a block (the UI's edits land through
|
||||
// syncProjectText between blocks), so this is the same audio with 4 loads and
|
||||
// 4 branches lifted out of a 48 000-iteration loop. The FX chain pointers come
|
||||
// out too, so the per-sample inner loop walks a plain pointer range.
|
||||
float chGain[TRACK_COUNT] = {0.f, 0.f, 0.f, 0.f};
|
||||
bool chLimit[TRACK_COUNT] = {false, false, false, false};
|
||||
FxUnit *chFxBegin[TRACK_COUNT] = {nullptr, nullptr, nullptr, nullptr};
|
||||
FxUnit *chFxEnd[TRACK_COUNT] = {nullptr, nullptr, nullptr, nullptr};
|
||||
if (proj) {
|
||||
for (int ch = 0; ch < TRACK_COUNT; ++ch) {
|
||||
const auto &mc = proj->mixer.channels[ch];
|
||||
chGain[ch] = mc.audible(anySolo) ? mc.volume : 0.f;
|
||||
chLimit[ch] = mc.limiter;
|
||||
chFxBegin[ch] = chains->ch[ch].data();
|
||||
chFxEnd[ch] = chFxBegin[ch] + chains->ch[ch].size();
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < frames; ++i) {
|
||||
if (playing.load(std::memory_order_relaxed) && proj) advanceSequencer(*proj);
|
||||
|
||||
@@ -618,11 +636,10 @@ void Engine::Impl::fillBlock(float *out, int frames) {
|
||||
for (int k = 0; k < actBSmpN; ++k) { const int vi = actBSmp[k]; channelSum[vi / BUS_POLYPHONY] += busSampleVoices[vi]->render(); }
|
||||
for (int ch = 0; ch < TRACK_COUNT; ++ch) if (cloudOn[ch]) channelSum[ch] += clouds[ch]->render();
|
||||
for (int ch = 0; ch < TRACK_COUNT; ++ch) {
|
||||
const auto &mc = proj->mixer.channels[ch];
|
||||
float s = mc.audible(anySolo) ? channelSum[ch] * mc.volume : 0.f;
|
||||
for (FxUnit &u : chains->ch[ch]) s = u.effect->process(s);
|
||||
float s = channelSum[ch] * chGain[ch];
|
||||
for (FxUnit *u = chFxBegin[ch]; u != chFxEnd[ch]; ++u) s = u->effect->process(s);
|
||||
if (!std::isfinite(s)) s = 0.f;
|
||||
if (mc.limiter) s = softClip(s);
|
||||
if (chLimit[ch]) s = softClip(s);
|
||||
const float a = s < 0.f ? -s : s;
|
||||
if (a > chBlockPeak[ch]) chBlockPeak[ch] = a;
|
||||
mixL += s; mixR += s;
|
||||
@@ -636,6 +653,8 @@ void Engine::Impl::fillBlock(float *out, int frames) {
|
||||
const float oR = limOutR;
|
||||
out[2 * i] = oL;
|
||||
out[2 * i + 1] = oR;
|
||||
// Checked per sample, not hoisted: recordSample itself clears recCapturing
|
||||
// when a take's FX tail runs out, and must not be called again after that.
|
||||
if (recCapturing.load(std::memory_order_relaxed) && sink) recordSample(proj, oL, oR);
|
||||
}
|
||||
|
||||
|
||||
@@ -93,8 +93,6 @@ public:
|
||||
void kill();
|
||||
/** Follow edits while sounding: the values glide there over ~25 ms. */
|
||||
void setPatch(const FrasilPatch &p) { patch = p; }
|
||||
/** A gliding engine value now (a defs index), for tests. */
|
||||
float valueForTest(int i) const { return cur[i]; }
|
||||
float render();
|
||||
|
||||
private:
|
||||
|
||||
@@ -0,0 +1,468 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// See sizzle/Randomizer.hpp for what a "playable" patch means here and why the
|
||||
// rules look the way they do. Choice lists are never repeated in this file: every
|
||||
// enum is picked by index out of the device's own ParamSpec, so a list that gains
|
||||
// or loses an entry in Kotlin carries through on its own.
|
||||
|
||||
#include "sizzle/Randomizer.hpp"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
#include "KotlinMath.hpp"
|
||||
#include "io/PresetIo.hpp"
|
||||
#include "sizzle/Model.hpp"
|
||||
#include "sizzle/Specs.hpp"
|
||||
|
||||
namespace sizzle::model {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr const char *kRandomizable[] = {"NES_SYNTH", "MORPH_PAD", "GRAIN_CLOUD", "WAVETABLE", "AMBIENCE"};
|
||||
|
||||
/** The engine's xorshift, so a seed means the same thing here as everywhere else. */
|
||||
struct Rng {
|
||||
uint32_t s;
|
||||
explicit Rng(uint32_t seed) : s(seed ? seed : 0x9E3779B9u) {}
|
||||
uint32_t next() { s ^= s << 13; s ^= s >> 17; s ^= s << 5; return s; }
|
||||
/** 0 .. 1 (never quite 1). */
|
||||
float unit() { return (float)next() * 2.3283064e-10f; }
|
||||
float range(float lo, float hi) { return lo + unit() * (hi - lo); }
|
||||
/** Like range, but bunched toward [lo]: `power` 2 spends most draws in the
|
||||
* lower third. Times, amounts and anything where "a little" is the common
|
||||
* musical answer and "a lot" is the exception. */
|
||||
float curve(float lo, float hi, float power) { return lo + std::pow(unit(), power) * (hi - lo); }
|
||||
int intIn(int lo, int hi) { return hi <= lo ? lo : lo + (int)(next() % (uint32_t)(hi - lo + 1)); }
|
||||
bool chance(float p) { return unit() < p; }
|
||||
template <int N> int pick(const int (&a)[N]) { return a[intIn(0, N - 1)]; }
|
||||
};
|
||||
|
||||
const ParamSpec *specFor(const DeviceSpec &dev, const char *key) {
|
||||
for (int i = 0; i < dev.paramCount; ++i)
|
||||
if (std::strcmp(dev.params[i].key, key) == 0) return &dev.params[i];
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/** Write a number, clamped to the parameter's own range and snapped if it is an
|
||||
* int. A rule with a bound slightly off therefore still produces a legal patch;
|
||||
* the bounds are musical intent, this is the rail. Unknown keys are dropped. */
|
||||
void put(Params &p, const DeviceSpec &dev, const char *key, float v) {
|
||||
const ParamSpec *ps = specFor(dev, key);
|
||||
if (!ps) return;
|
||||
float x = kt::coerceIn(v, ps->min, ps->max);
|
||||
if (ps->isInt) x = (float)kt::roundToInt(x);
|
||||
p.set(key, x);
|
||||
}
|
||||
|
||||
/** Write an enum by index into its own choice list (clamped). */
|
||||
void putChoice(Params &p, const DeviceSpec &dev, const char *key, int index) {
|
||||
const ParamSpec *ps = specFor(dev, key);
|
||||
if (!ps || !ps->isEnum()) return;
|
||||
const int n = ps->choiceCount();
|
||||
if (n <= 0) return;
|
||||
p.set(key, ps->choices[kt::coerceIn(index, 0, n - 1)]);
|
||||
}
|
||||
|
||||
int choiceCount(const DeviceSpec &dev, const char *key) {
|
||||
const ParamSpec *ps = specFor(dev, key);
|
||||
return ps && ps->isEnum() ? ps->choiceCount() : 0;
|
||||
}
|
||||
|
||||
/** A random choice index, with the last [skipTail] entries left out — the lists
|
||||
* that end in "Custom" mean "the user's own sample", which a dice roll must not
|
||||
* invent. */
|
||||
int pickChoice(Rng &r, const DeviceSpec &dev, const char *key, int skipTail = 0) {
|
||||
const int n = choiceCount(dev, key) - skipTail;
|
||||
return n <= 0 ? 0 : r.intIn(0, n - 1);
|
||||
}
|
||||
|
||||
/** A cutoff that suits the filter type. Both the Morph Pad and the Wavetable offer
|
||||
* the same Low / Band / High list, and only Low is open at the top: a band-pass has
|
||||
* to sit near the played pitch to pass it and a high-pass has to stay under it, so
|
||||
* rolling the whole 0..1 range for those two is how a patch comes out silent with
|
||||
* every oscillator up. (Measured: the quietest rolls of both devices were a band-pass
|
||||
* at 0.83 and 0.95, peaking at 0.010 and 0.025 against a median near 0.3.) */
|
||||
float cutoffFor(Rng &r, int filterType, float lowLo, float lowHi) {
|
||||
switch (filterType) {
|
||||
case 1: return r.range(0.20f, 0.60f); // Band: around the note, not above it
|
||||
case 2: return r.range(0.10f, 0.45f); // High: under it, or nothing is left
|
||||
default: return r.range(lowLo, lowHi); // Low: open at the top
|
||||
}
|
||||
}
|
||||
|
||||
/** Consonant intervals, in semitones: a dice roll over ±12 mostly lands on
|
||||
* something sour, and these are what a second oscillator is usually set to. */
|
||||
constexpr int kIntervals[] = {0, 0, 0, 3, 4, 5, 7, 12, -12};
|
||||
/** Octave offsets, weighted toward the root's own octave. */
|
||||
constexpr int kOctaves[] = {-1, 0, 0, 0, 1};
|
||||
|
||||
// ------------------------------------------------------------------ the synth
|
||||
|
||||
void randomizeSynth(Rng &r, const DeviceSpec &dev, Params &p) {
|
||||
// Oscillators. The voice sums them straight (SynthVoice: `mix += wave * level`)
|
||||
// before a filter that can add resonant gain of its own, so the levels share a
|
||||
// budget rather than each taking the full range.
|
||||
constexpr float kLevelBudget = 1.25f;
|
||||
const int active = r.chance(0.55f) ? 2 : (r.chance(0.5f) ? 1 : 3);
|
||||
float level[3] = {0.f, 0.f, 0.f};
|
||||
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
putChoice(p, dev, (std::string("osc") + std::to_string(i) + "wave").c_str(),
|
||||
pickChoice(r, dev, "osc0wave"));
|
||||
const std::string pre = "osc" + std::to_string(i);
|
||||
if (i >= active) { put(p, dev, (pre + "level").c_str(), 0.f); continue; }
|
||||
if (i == 0) {
|
||||
// Oscillator 1 is the pitch the player hears: it stays at the root.
|
||||
put(p, dev, (pre + "oct").c_str(), 0.f);
|
||||
put(p, dev, (pre + "semi").c_str(), 0.f);
|
||||
put(p, dev, (pre + "fine").c_str(), r.range(-4.f, 4.f));
|
||||
level[i] = r.range(0.55f, 0.90f);
|
||||
} else {
|
||||
put(p, dev, (pre + "oct").c_str(), (float)r.pick(kOctaves));
|
||||
put(p, dev, (pre + "semi").c_str(), (float)r.pick(kIntervals));
|
||||
put(p, dev, (pre + "fine").c_str(), r.range(-10.f, 10.f));
|
||||
level[i] = r.range(0.25f, 0.65f);
|
||||
}
|
||||
}
|
||||
const float noise = r.chance(0.3f) ? r.curve(0.f, 0.18f, 2.f) : 0.f;
|
||||
float sum = noise;
|
||||
for (float l : level) sum += l;
|
||||
const float scale = sum > kLevelBudget ? kLevelBudget / sum : 1.f;
|
||||
for (int i = 0; i < 3; ++i)
|
||||
put(p, dev, (std::string("osc") + std::to_string(i) + "level").c_str(), level[i] * scale);
|
||||
put(p, dev, "noise", noise * scale);
|
||||
|
||||
// Filter. Never shut (nothing would come out) and never near self-oscillation.
|
||||
// A negative contour sweeps the cutoff *down* as the note sounds, so it only
|
||||
// gets a patch that starts open — otherwise the two together close the filter
|
||||
// on a sound that has not been heard yet.
|
||||
const bool downwardSweep = !r.chance(0.75f);
|
||||
const float fenvamt = downwardSweep ? r.range(-0.50f, -0.10f) : r.range(0.10f, 0.80f);
|
||||
put(p, dev, "cutoff", downwardSweep ? r.range(0.65f, 0.95f) : r.range(0.40f, 0.95f));
|
||||
put(p, dev, "reso", r.curve(0.f, 0.45f, 1.6f));
|
||||
put(p, dev, "keytrack", r.range(0.15f, 0.80f));
|
||||
put(p, dev, "fenvamt", fenvamt);
|
||||
put(p, dev, "fatk", r.curve(0.001f, 0.60f, 2.2f));
|
||||
put(p, dev, "fdec", r.curve(0.05f, 1.50f, 1.6f));
|
||||
put(p, dev, "fsus", r.range(0.15f, 0.90f));
|
||||
put(p, dev, "frel", r.curve(0.05f, 1.50f, 1.6f));
|
||||
|
||||
// Amp envelope. A quiet sustain with a quick decay is a click, not a patch, so
|
||||
// a low sustain buys a longer decay to speak through.
|
||||
put(p, dev, "attack", r.curve(0.001f, 0.50f, 2.4f));
|
||||
const float sustain = r.range(0.30f, 0.95f);
|
||||
float decay = r.curve(0.05f, 1.20f, 1.6f);
|
||||
if (sustain < 0.40f) decay = kt::coerceAtLeast(decay, 0.40f);
|
||||
put(p, dev, "decay", decay);
|
||||
put(p, dev, "sustain", sustain);
|
||||
put(p, dev, "release", r.curve(0.06f, 1.40f, 1.6f));
|
||||
|
||||
putChoice(p, dev, "lfowave", pickChoice(r, dev, "lfowave"));
|
||||
put(p, dev, "lfodiv", (float)r.intIn(0, 6));
|
||||
putChoice(p, dev, "lfophase", pickChoice(r, dev, "lfophase"));
|
||||
|
||||
// Mod matrix: clear it, then light up a couple of slots.
|
||||
const int srcCount = choiceCount(dev, "m0src");
|
||||
const int dstCount = choiceCount(dev, "m0dst");
|
||||
for (int n = 0; n < 4; ++n) {
|
||||
const std::string pre = "m" + std::to_string(n);
|
||||
putChoice(p, dev, (pre + "src").c_str(), 0); // "Off"
|
||||
putChoice(p, dev, (pre + "dst").c_str(), 0);
|
||||
put(p, dev, (pre + "amt").c_str(), 0.f);
|
||||
}
|
||||
const int slots = r.intIn(0, 2);
|
||||
for (int n = 0; n < slots; ++n) {
|
||||
const std::string pre = "m" + std::to_string(n);
|
||||
const int dst = dstCount > 0 ? r.intIn(0, dstCount - 1) : 0;
|
||||
putChoice(p, dev, (pre + "src").c_str(), srcCount > 1 ? r.intIn(1, srcCount - 1) : 0);
|
||||
putChoice(p, dev, (pre + "dst").c_str(), dst);
|
||||
// MOD_DST is Pitch, Osc2, Osc3, Cutoff, PWM, Amp. Four of the six can take a
|
||||
// healthy patch down to nothing on their own, so they are bounded instead of
|
||||
// getting the full range — and Cutoff asymmetrically, because opening a
|
||||
// filter is free and closing it is not. (Measured: a Vel -> Cutoff slot at
|
||||
// -0.69 turned a patch with a square at 0.87 and the cutoff at 0.66 from
|
||||
// peak 0.41 into peak 0.02.)
|
||||
float lo = -0.70f, hi = 0.70f;
|
||||
switch (dst) {
|
||||
case 0: lo = -0.18f; hi = 0.18f; break; // Pitch: a patch should stay in tune
|
||||
case 3: lo = -0.30f; hi = 0.70f; break; // Cutoff: open freely, close a little
|
||||
case 4: lo = -0.45f; hi = 0.45f; break; // PWM: past this a pulse is a sliver
|
||||
case 5: lo = -0.30f; hi = 0.30f; break; // Amp: never enough to gate the voice off
|
||||
default: break; // Osc2 / Osc3 levels
|
||||
}
|
||||
put(p, dev, (pre + "amt").c_str(), r.range(lo, hi));
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- the morph pad
|
||||
|
||||
void randomizeMorphPad(Rng &r, const DeviceSpec &dev, Params &p) {
|
||||
// Three layers, summed into one voice: at least one has to carry the sound, and
|
||||
// all three near the top is where a pad stops being a pad and starts clipping,
|
||||
// so they share a budget the way the synth's oscillators do.
|
||||
constexpr float kLayerBudget = 1.45f;
|
||||
float choir = r.chance(0.80f) ? r.range(0.35f, 0.95f) : 0.f;
|
||||
float partials = r.chance(0.80f) ? r.range(0.30f, 0.95f) : 0.f;
|
||||
float breath = r.chance(0.60f) ? r.range(0.10f, 0.60f) : 0.f;
|
||||
if (choir + partials + breath < 0.50f) choir = r.range(0.60f, 0.95f);
|
||||
const float layers = choir + partials + breath;
|
||||
if (layers > kLayerBudget) {
|
||||
const float scale = kLayerBudget / layers;
|
||||
choir *= scale; partials *= scale; breath *= scale;
|
||||
}
|
||||
put(p, dev, "choir", choir);
|
||||
put(p, dev, "partials", partials);
|
||||
put(p, dev, "breath", breath);
|
||||
|
||||
put(p, dev, "timbre", r.range(0.20f, 0.85f));
|
||||
put(p, dev, "warmth", r.curve(0.f, 0.45f, 1.8f)); // drive: modest, or it buzzes
|
||||
put(p, dev, "body", r.range(0.55f, 1.0f)); // the high-pass: keep the fundamental
|
||||
put(p, dev, "attack", r.range(0.25f, 0.95f)); // a pad, so never a transient
|
||||
put(p, dev, "release", r.range(0.40f, 0.95f));
|
||||
put(p, dev, "velsens", r.range(0.10f, 0.70f));
|
||||
put(p, dev, "motion", r.range(0.10f, 0.80f));
|
||||
put(p, dev, "mrate", r.range(0.20f, 0.80f));
|
||||
put(p, dev, "tide", r.range(0.f, 0.60f));
|
||||
put(p, dev, "tperiod", r.range(0.20f, 0.80f));
|
||||
put(p, dev, "detune", r.range(0.20f, 0.75f));
|
||||
|
||||
// Choir filter, with a cutoff that suits the type (see cutoffFor). It filters the
|
||||
// choir alone — the partials and the breath go round it — so a patch whose choir
|
||||
// is the only thing sounding has nothing left if that filter is a narrow band.
|
||||
// It gets a plain low-pass instead, and an open one. (Measured: the quietest roll
|
||||
// of all was exactly this, choir 0.82 alone through a band-pass, peak 0.017.)
|
||||
const bool choirAlone = partials <= 0.f && breath <= 0.f;
|
||||
const int ctype = choirAlone ? 0 : (r.chance(0.60f) ? 0 : (r.chance(0.62f) ? 1 : 2));
|
||||
putChoice(p, dev, "ctype", ctype);
|
||||
put(p, dev, "cfilter", choirAlone ? r.range(0.45f, 0.90f) : cutoffFor(r, ctype, 0.25f, 0.85f));
|
||||
put(p, dev, "creso", r.curve(0.f, 0.50f, 1.8f));
|
||||
put(p, dev, "shape", r.range(0.f, 0.70f));
|
||||
put(p, dev, "soft", r.range(0.f, 0.70f));
|
||||
putChoice(p, dev, "interval", pickChoice(r, dev, "interval"));
|
||||
|
||||
put(p, dev, "tilt", r.range(0.20f, 0.85f));
|
||||
put(p, dev, "odd", r.range(0.f, 0.70f));
|
||||
put(p, dev, "stretch", r.curve(0.f, 0.50f, 2.f));
|
||||
put(p, dev, "evolve", r.range(0.f, 0.70f));
|
||||
put(p, dev, "beat", r.range(0.f, 0.50f));
|
||||
put(p, dev, "formant", r.range(0.20f, 0.90f));
|
||||
put(p, dev, "peak", r.curve(0.f, 0.50f, 1.8f));
|
||||
|
||||
put(p, dev, "bres", r.range(0.30f, 0.90f));
|
||||
put(p, dev, "color", r.range(0.f, 0.80f));
|
||||
put(p, dev, "grain", r.curve(0.f, 0.50f, 2.f));
|
||||
putChoice(p, dev, "bpitch", pickChoice(r, dev, "bpitch"));
|
||||
put(p, dev, "btone", r.range(0.20f, 0.85f));
|
||||
put(p, dev, "air", r.curve(0.f, 0.50f, 2.f));
|
||||
|
||||
// MORPH TO stays Off, and it is the one knob here a roll deliberately leaves
|
||||
// alone. Two reasons, and the first is measured: a target is one of FRASIL's
|
||||
// factory drones, MORPH TIME carries a held note all the way onto it, and from
|
||||
// then on the note *is* that preset at a level this randomizer never chose —
|
||||
// seeds that landed on "Static" peaked at 1.33 with every layer of their own
|
||||
// turned down to zero. Budgeting cannot reach past the morph. The second is
|
||||
// that "morph toward this named sound" is a musical decision between two
|
||||
// sounds, like picking a sample: the roll gives a fresh sound to start from and
|
||||
// leaves the destination to the player.
|
||||
putChoice(p, dev, "morphTo", 0);
|
||||
put(p, dev, "morph", 0.f);
|
||||
put(p, dev, "mtime", 0.f);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- the grain cloud
|
||||
|
||||
void randomizeGrainCloud(Rng &r, const DeviceSpec &dev, Params &p) {
|
||||
// SOURCES ends in "Custom" (the user's own sample): never rolled.
|
||||
putChoice(p, dev, "source", pickChoice(r, dev, "source", 1));
|
||||
putChoice(p, dev, "mode", pickChoice(r, dev, "mode"));
|
||||
putChoice(p, dev, "window", pickChoice(r, dev, "window"));
|
||||
putChoice(p, dev, "freeze", 0); // "Off": frozen is a performance move, not a patch
|
||||
|
||||
put(p, dev, "position", r.range(0.05f, 0.90f));
|
||||
put(p, dev, "texture", r.range(0.25f, 0.95f));
|
||||
put(p, dev, "scatter", r.range(0.05f, 0.80f));
|
||||
put(p, dev, "drift", r.range(0.f, 0.70f));
|
||||
put(p, dev, "motion", r.range(0.f, 0.70f));
|
||||
put(p, dev, "pitch", (float)r.pick(kIntervals));
|
||||
put(p, dev, "harmony", r.range(0.f, 0.60f));
|
||||
put(p, dev, "size_mul", r.range(-1.0f, 1.2f));
|
||||
put(p, dev, "dens_mul", r.range(-0.3f, 1.4f)); // low enough and the cloud thins to nothing
|
||||
put(p, dev, "scan", r.range(-0.6f, 0.6f));
|
||||
put(p, dev, "reverse", r.curve(0.f, 0.50f, 1.6f));
|
||||
put(p, dev, "pitch_rand", r.curve(0.f, 5.f, 1.8f));
|
||||
put(p, dev, "size_rand", r.range(0.f, 0.70f));
|
||||
put(p, dev, "grain_tone", r.range(-0.6f, 0.6f));
|
||||
put(p, dev, "attack", r.range(0.05f, 0.60f));
|
||||
put(p, dev, "release", r.range(0.20f, 0.80f));
|
||||
put(p, dev, "velo", r.range(0.20f, 0.80f));
|
||||
|
||||
// The window into the source has to be wide enough to hold grains.
|
||||
const float start = r.range(0.f, 0.50f);
|
||||
put(p, dev, "start", start);
|
||||
put(p, dev, "end", kt::coerceIn(start + r.range(0.30f, 1.0f), 0.f, 1.f));
|
||||
// The cloud auto-levels itself toward one loudness, so this is really how hard
|
||||
// the overlapping grains are allowed to stack on top of that.
|
||||
put(p, dev, "level", r.range(0.45f, 0.68f));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the wavetable
|
||||
|
||||
void randomizeWavetable(Rng &r, const DeviceSpec &dev, Params &p) {
|
||||
// TABLES ends in "Custom" (an imported WAV): never rolled.
|
||||
constexpr float kLevelBudget = 1.30f;
|
||||
const bool twoOsc = r.chance(0.60f);
|
||||
float l1 = r.range(0.55f, 0.90f);
|
||||
float l2 = twoOsc ? r.range(0.25f, 0.60f) : 0.f;
|
||||
|
||||
putChoice(p, dev, "o1table", pickChoice(r, dev, "o1table", 1));
|
||||
put(p, dev, "o1pos", r.range(0.f, 0.85f));
|
||||
put(p, dev, "o1oct", (float)r.pick(kOctaves));
|
||||
put(p, dev, "o1semi", 0.f);
|
||||
put(p, dev, "o1fine", r.range(-6.f, 6.f));
|
||||
put(p, dev, "o1bend", r.range(-0.50f, 0.50f));
|
||||
|
||||
putChoice(p, dev, "o2table", pickChoice(r, dev, "o2table", 1));
|
||||
put(p, dev, "o2pos", r.range(0.f, 0.85f));
|
||||
put(p, dev, "o2oct", twoOsc ? (float)r.pick(kOctaves) : 0.f);
|
||||
put(p, dev, "o2semi", twoOsc ? (float)r.pick(kIntervals) : 0.f);
|
||||
put(p, dev, "o2fine", twoOsc ? r.range(-14.f, 14.f) : 0.f);
|
||||
put(p, dev, "o2bend", r.range(-0.50f, 0.50f));
|
||||
|
||||
const float sub = r.curve(0.f, 0.40f, 1.5f);
|
||||
const float noise = r.curve(0.f, 0.12f, 2.f);
|
||||
const float sum = l1 + l2 + sub + noise;
|
||||
const float scale = sum > kLevelBudget ? kLevelBudget / sum : 1.f;
|
||||
put(p, dev, "o1level", l1 * scale);
|
||||
put(p, dev, "o2level", l2 * scale);
|
||||
put(p, dev, "sub", sub * scale);
|
||||
put(p, dev, "noise", noise * scale);
|
||||
|
||||
put(p, dev, "unison", (float)r.intIn(1, 4));
|
||||
put(p, dev, "spread", r.range(0.10f, 0.60f));
|
||||
put(p, dev, "velsens", r.range(0.20f, 0.80f));
|
||||
putChoice(p, dev, "wtframe", 0); // "Auto": frame size belongs to an imported table
|
||||
|
||||
// FILTER_TYPES is Low / Band / High, same shape as the Morph Pad's.
|
||||
const int ftype = r.chance(0.60f) ? 0 : (r.chance(0.62f) ? 1 : 2);
|
||||
putChoice(p, dev, "ftype", ftype);
|
||||
put(p, dev, "cutoff", cutoffFor(r, ftype, 0.45f, 1.0f));
|
||||
put(p, dev, "reso", r.curve(0.f, 0.40f, 1.7f));
|
||||
put(p, dev, "keytrack", r.range(0.20f, 0.80f));
|
||||
put(p, dev, "fenv", r.range(-0.40f, 0.70f));
|
||||
put(p, dev, "drive", r.curve(0.f, 0.35f, 1.8f)); // tanh: past this it is all fuzz
|
||||
|
||||
put(p, dev, "attack", r.curve(0.002f, 1.20f, 2.2f));
|
||||
const float sustain = r.range(0.35f, 0.95f);
|
||||
float decay = r.curve(0.10f, 2.0f, 1.6f);
|
||||
if (sustain < 0.45f) decay = kt::coerceAtLeast(decay, 0.50f);
|
||||
put(p, dev, "decay", decay);
|
||||
put(p, dev, "sustain", sustain);
|
||||
put(p, dev, "release", r.curve(0.15f, 3.0f, 1.6f));
|
||||
|
||||
put(p, dev, "mattack", r.curve(0.f, 3.0f, 1.8f));
|
||||
put(p, dev, "mdecay", r.curve(0.20f, 5.0f, 1.5f));
|
||||
put(p, dev, "msustain", r.range(0.20f, 0.90f));
|
||||
put(p, dev, "mrelease", r.curve(0.20f, 4.0f, 1.5f));
|
||||
put(p, dev, "menvpos", r.range(-0.60f, 0.60f));
|
||||
|
||||
putChoice(p, dev, "lfowave", pickChoice(r, dev, "lfowave"));
|
||||
const ParamSpec *div = specFor(dev, "lfodiv");
|
||||
put(p, dev, "lfodiv", div ? (float)r.intIn((int)div->min, (int)div->max) : 1.f);
|
||||
put(p, dev, "lfopos", r.range(0.f, 0.45f));
|
||||
put(p, dev, "lfopitch", r.curve(0.f, 0.08f, 2.f)); // small: a patch should stay in tune
|
||||
put(p, dev, "lfocut", r.range(0.f, 0.50f));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- ambience reverb
|
||||
|
||||
void randomizeAmbience(Rng &r, const DeviceSpec &dev, Params &p) {
|
||||
putChoice(p, dev, "algo", pickChoice(r, dev, "algo"));
|
||||
put(p, dev, "predelay", r.curve(0.f, 120.f, 1.5f));
|
||||
put(p, dev, "roomsize", r.range(0.50f, 1.80f));
|
||||
put(p, dev, "decay", r.curve(0.40f, 8.0f, 1.7f)); // the range runs to 20 s: a drone, not a space
|
||||
put(p, dev, "hfdamp", r.range(0.15f, 0.80f)); // always some: an undamped tail piles up
|
||||
put(p, dev, "lfabsorb", r.curve(0.f, 0.50f, 1.5f));
|
||||
put(p, dev, "diffusion", r.range(0.45f, 1.0f));
|
||||
put(p, dev, "modamt", r.curve(0.f, 0.50f, 1.4f));
|
||||
put(p, dev, "modrate", r.range(0.10f, 1.20f));
|
||||
put(p, dev, "erlevel", r.range(0.20f, 0.90f));
|
||||
put(p, dev, "saturation", r.curve(0.f, 0.30f, 1.8f));
|
||||
|
||||
// Wet and dry are the headroom. Both at 0 dB is the loudest thing this device
|
||||
// can be asked for, and a full-level reverb summed with a full-level dry signal
|
||||
// is where an insert chain starts clipping — so the wet sits below the dry.
|
||||
put(p, dev, "wet", r.range(-20.f, -8.f));
|
||||
put(p, dev, "dry", r.range(-3.f, 0.f));
|
||||
|
||||
if (r.chance(0.35f)) {
|
||||
put(p, dev, "duckamt", r.range(3.f, 10.f));
|
||||
put(p, dev, "duckthresh", r.range(-26.f, -12.f));
|
||||
put(p, dev, "duckattack", r.curve(1.f, 40.f, 1.5f));
|
||||
put(p, dev, "duckrelease", r.curve(40.f, 800.f, 1.4f));
|
||||
} else {
|
||||
put(p, dev, "duckamt", 0.f);
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------- the name
|
||||
|
||||
/** Two words from the seed. Deliberately atmospheric rather than descriptive —
|
||||
* the patch is a surprise, and a name like "Dim Drift" is easier to tell apart in
|
||||
* the preset list than "Random 7". */
|
||||
const char *const kAdjectives[] = {
|
||||
"Hazy", "Glass", "Dim", "Warm", "Wire", "Soft", "Iron", "Pale",
|
||||
"Deep", "Dry", "Slow", "Bright","Hollow","Velvet","Rust", "Frost",
|
||||
};
|
||||
const char *const kNouns[] = {
|
||||
"Drift", "Bloom", "Field", "Choir", "Signal","Tide", "Ember", "Static",
|
||||
"Garden","Column","Current","Veil", "Spark", "Hollow","Echo", "Grain",
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
bool canRandomize(const char *type) {
|
||||
if (!type) return false;
|
||||
for (const char *t : kRandomizable)
|
||||
if (std::strcmp(type, t) == 0) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool randomize(const char *type, uint32_t seed, Params &out) {
|
||||
if (!canRandomize(type)) return false;
|
||||
const DeviceSpec *dev = findDevice(type);
|
||||
if (!dev) return false;
|
||||
|
||||
Rng r(seed);
|
||||
Params p;
|
||||
p.fill(*dev); // defaults first, so nothing is left unset
|
||||
|
||||
if (std::strcmp(type, "NES_SYNTH") == 0) randomizeSynth(r, *dev, p);
|
||||
else if (std::strcmp(type, "MORPH_PAD") == 0) randomizeMorphPad(r, *dev, p);
|
||||
else if (std::strcmp(type, "GRAIN_CLOUD") == 0) randomizeGrainCloud(r, *dev, p);
|
||||
else if (std::strcmp(type, "WAVETABLE") == 0) randomizeWavetable(r, *dev, p);
|
||||
else if (std::strcmp(type, "AMBIENCE") == 0) randomizeAmbience(r, *dev, p);
|
||||
|
||||
out = p;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string randomName(const char *type, uint32_t seed) {
|
||||
if (!canRandomize(type)) return std::string();
|
||||
// A stream of its own, so the name does not depend on how many draws a device's
|
||||
// rules happen to make.
|
||||
Rng r(seed ^ 0x5BD1E995u);
|
||||
return std::string(kAdjectives[r.intIn(0, 15)]) + " " + kNouns[r.intIn(0, 15)];
|
||||
}
|
||||
|
||||
std::string randomPresetText(const char *type, uint32_t seed) {
|
||||
ToolboxSlot slot;
|
||||
if (!canRandomize(type)) return std::string();
|
||||
slot.fill(type);
|
||||
if (!randomize(type, seed, slot.values)) return std::string();
|
||||
slot.name = randomName(type, seed);
|
||||
return io::PresetIo::exportText(slot);
|
||||
}
|
||||
|
||||
} // namespace sizzle::model
|
||||
@@ -0,0 +1,277 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// What the insert-FX chain costs. Nothing here asserts; it prints numbers, so a
|
||||
// change to the DSP can be argued about with measurements instead of intuition.
|
||||
// Three parts:
|
||||
//
|
||||
// A a whole engine render (four channels of synth, a note on every line) with
|
||||
// 0, 1, 2 and 4 effects per channel: the share of fillBlock the chains take.
|
||||
// B each effect on its own: ns per sample, and what one instance costs as a
|
||||
// share of one channel's real-time budget.
|
||||
// C the block-rate question from DEVELOPER_HANDOVER.md §9, on a stand-in with
|
||||
// EQ10's shape (ten biquads in series), run three ways: per sample through a
|
||||
// virtual call (what the engine does today), per sample through the concrete
|
||||
// type (the same work with dispatch removed — the difference is what block
|
||||
// dispatch could save), and band-at-a-time over a block with the coefficients
|
||||
// hoisted. All three do the same arithmetic in the same order per band.
|
||||
//
|
||||
// bench [seconds] (default 4; part A renders that much audio per variant)
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "echofield/GrainSources.hpp"
|
||||
#include "sampler/SampleStore.hpp"
|
||||
#include "sizzle/Effect.hpp"
|
||||
#include "sizzle/Engine.hpp"
|
||||
#include "sizzle/Model.hpp"
|
||||
#include "wavetable/WaveTables.hpp"
|
||||
|
||||
using namespace sizzle;
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int SR = 48000;
|
||||
constexpr int BLOCK = engine::Engine::BLOCK_FRAMES;
|
||||
|
||||
double now() {
|
||||
using namespace std::chrono;
|
||||
return duration<double>(steady_clock::now().time_since_epoch()).count();
|
||||
}
|
||||
|
||||
/** White-ish noise, the same every run so two runs are comparable. */
|
||||
std::vector<float> noise(size_t n) {
|
||||
std::vector<float> v(n);
|
||||
uint32_t seed = 0x1234567u;
|
||||
for (float &x : v) {
|
||||
seed = seed * 1103515245u + 12345u;
|
||||
x = (float)((seed >> 8) & 0xFFFF) / 65535.f - 0.5f;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- part A
|
||||
|
||||
/** Four channels of NES_SYNTH, a note on every line of the active pattern, and
|
||||
* [nfx] shared effect slots on each channel. Slots 0..3 are the instruments and
|
||||
* 4..7 the effects, so four channels of four effects still fit in sixteen. */
|
||||
void buildProject(model::Project &p, int nfx) {
|
||||
static const char *kFx[4] = {"FILTER", "EQ10", "DELAY", "AMBIENCE"};
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
p.toolbox[i].fill("NES_SYNTH");
|
||||
p.toolbox[4 + i].fill(kFx[i]);
|
||||
}
|
||||
for (int ch = 0; ch < 4; ++ch) {
|
||||
auto &mc = p.mixer.channels[ch];
|
||||
mc.midiChannel = ch + 1;
|
||||
mc.instrumentSlot = ch;
|
||||
for (int i = 0; i < model::Mixer::FX_SLOTS; ++i) mc.fxSlots[i] = i < nfx ? 4 + i : -1;
|
||||
}
|
||||
model::Pattern &pat = p.activePattern();
|
||||
for (int t = 0; t < model::Pattern::TRACK_COUNT; ++t)
|
||||
for (int line = 0; line < pat.length; ++line) {
|
||||
model::Cell &c = pat.cell(t, line);
|
||||
c.note = 48 + t * 5 + line % 5;
|
||||
c.velocity = 100;
|
||||
c.channel = t + 1;
|
||||
}
|
||||
}
|
||||
|
||||
/** Seconds of wall time to render [seconds] of audio with [nfx] effects per channel. */
|
||||
double renderCost(int nfx, double seconds) {
|
||||
sampler::SampleStore store;
|
||||
model::Project project;
|
||||
buildProject(project, nfx);
|
||||
|
||||
engine::Engine eng(SR, &store, engine::EngineGlobals{});
|
||||
eng.setProject(&project);
|
||||
eng.play();
|
||||
|
||||
std::vector<float> buf((size_t)BLOCK * 2);
|
||||
const int warmup = (int)(0.5 * SR) / BLOCK;
|
||||
for (int b = 0; b < warmup; ++b) eng.fillBlock(buf.data(), BLOCK);
|
||||
|
||||
const int blocks = (int)(seconds * SR) / BLOCK;
|
||||
const double t0 = now();
|
||||
for (int b = 0; b < blocks; ++b) eng.fillBlock(buf.data(), BLOCK);
|
||||
return now() - t0;
|
||||
}
|
||||
|
||||
void partA(double seconds) {
|
||||
std::printf("\nA. engine render, 4 channels of synth, %.0f s of %d Hz audio per variant\n", seconds, SR);
|
||||
std::printf(" %-22s %9s %9s %12s\n", "effects per channel", "wall s", "x real", "vs 0 fx");
|
||||
double base = 0;
|
||||
for (int nfx : {0, 1, 2, 4}) {
|
||||
const double t = renderCost(nfx, seconds);
|
||||
if (nfx == 0) base = t;
|
||||
std::printf(" %-22d %9.3f %8.0fx %11s\n", nfx, t, seconds / t,
|
||||
nfx == 0 ? "-" : (std::to_string((long long)std::lround((t / base - 1) * 100)) + "%").c_str());
|
||||
}
|
||||
std::printf(" (the chain's share at 4 fx is 1 - base/total)\n");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- part B
|
||||
|
||||
void partB(double seconds) {
|
||||
static const char *kTypes[] = {"BITCRUSHER", "FILTER", "EQ10", "DELAY",
|
||||
"MIX_TIGHTENER", "TAPE_ENGINE", "GRANULAR", "AMBIENCE"};
|
||||
const size_t n = (size_t)(seconds * SR);
|
||||
const std::vector<float> in = noise(n);
|
||||
|
||||
double ns[8] = {0};
|
||||
double total = 0;
|
||||
for (size_t k = 0; k < sizeof(kTypes) / sizeof(*kTypes); ++k) {
|
||||
model::ToolboxSlot slot;
|
||||
slot.fill(kTypes[k]);
|
||||
std::unique_ptr<Effect> fx = Effect::create(kTypes[k], SR);
|
||||
if (!fx) continue;
|
||||
fx->update(slot.values, 120.f);
|
||||
|
||||
for (size_t i = 0; i < n / 8; ++i) fx->process(in[i]); // warm the delay lines
|
||||
double sink = 0;
|
||||
const double t0 = now();
|
||||
for (size_t i = 0; i < n; ++i) sink += fx->process(in[i]);
|
||||
ns[k] = (now() - t0) * 1e9 / (double)n;
|
||||
if (!std::isfinite(sink)) std::printf(" note: %s went non-finite\n", kTypes[k]);
|
||||
total += ns[k];
|
||||
}
|
||||
|
||||
std::printf("\nB. one effect instance, %.0f s of samples each\n", seconds);
|
||||
std::printf(" %-16s %12s %16s\n", "effect", "ns/sample", "share of all 8");
|
||||
for (size_t k = 0; k < sizeof(kTypes) / sizeof(*kTypes); ++k) {
|
||||
if (ns[k] == 0) { std::printf(" %-16s %12s\n", kTypes[k], "no processor"); continue; }
|
||||
std::printf(" %-16s %12.2f %15.0f%%\n", kTypes[k], ns[k], ns[k] / total * 100);
|
||||
}
|
||||
std::printf(" %-16s %12.2f\n", "all eight", total);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- part C
|
||||
|
||||
/** EQ10's PeakBiquad, copied so the bench can hold it by value and reach inside. */
|
||||
struct Biquad {
|
||||
double b0 = 1, b1 = 0, b2 = 0, a1 = 0, a2 = 0;
|
||||
double z1 = 0, z2 = 0;
|
||||
|
||||
void set(int sr, float centerHz, float gainDb) {
|
||||
const double a = std::pow(10.0, gainDb / 40.0);
|
||||
const double w0 = 2.0 * M_PI * centerHz / sr;
|
||||
const double cosW = std::cos(w0);
|
||||
const double alpha = std::sin(w0) / 2.0;
|
||||
const double a0 = 1 + alpha / a;
|
||||
b0 = (1 + alpha * a) / a0;
|
||||
b1 = (-2 * cosW) / a0;
|
||||
b2 = (1 - alpha * a) / a0;
|
||||
a1 = (-2 * cosW) / a0;
|
||||
a2 = (1 - alpha / a) / a0;
|
||||
}
|
||||
|
||||
float process(float x) {
|
||||
const double input = (double)x;
|
||||
const double out = b0 * input + z1;
|
||||
z1 = b1 * input - a1 * out + z2;
|
||||
z2 = b2 * input - a2 * out;
|
||||
return (float)out;
|
||||
}
|
||||
};
|
||||
|
||||
struct Cascade {
|
||||
Biquad bands[10];
|
||||
Cascade() {
|
||||
static const float centers[10] = {31.f, 63.f, 125.f, 250.f, 500.f, 1000.f, 2000.f, 4000.f, 8000.f, 16000.f};
|
||||
for (int i = 0; i < 10; ++i) bands[i].set(SR, centers[i], (i % 3) * 3.f - 3.f);
|
||||
}
|
||||
void reset() { for (Biquad &b : bands) { b.z1 = 0; b.z2 = 0; } }
|
||||
|
||||
/** Band-at-a-time over a whole block: each band is time-invariant, so this is
|
||||
* the same arithmetic in the same order per band — only the coefficient loads
|
||||
* are hoisted out of the sample loop. This is what an override would do. */
|
||||
void processBlockHoisted(const float *in, float *out, int n) {
|
||||
for (int i = 0; i < n; ++i) out[i] = in[i];
|
||||
for (Biquad &band : bands) {
|
||||
const double b0 = band.b0, b1 = band.b1, b2 = band.b2, a1 = band.a1, a2 = band.a2;
|
||||
double z1 = band.z1, z2 = band.z2;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
const double input = (double)out[i];
|
||||
const double y = b0 * input + z1;
|
||||
z1 = b1 * input - a1 * y + z2;
|
||||
z2 = b2 * input - a2 * y;
|
||||
out[i] = (float)y;
|
||||
}
|
||||
band.z1 = z1;
|
||||
band.z2 = z2;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/** The engine's shape today: a virtual call per sample through an Effect*. */
|
||||
struct VirtualCascade : Effect {
|
||||
Cascade c;
|
||||
void update(const Params &, float) override {}
|
||||
float process(float x) override {
|
||||
float y = x;
|
||||
for (Biquad &b : c.bands) y = b.process(y);
|
||||
return y;
|
||||
}
|
||||
};
|
||||
|
||||
void partC(double seconds) {
|
||||
const size_t n = (size_t)(seconds * SR) / BLOCK * BLOCK;
|
||||
const std::vector<float> in = noise(n);
|
||||
std::vector<float> outA(n), outB(n);
|
||||
|
||||
std::vector<float> outC(n);
|
||||
|
||||
VirtualCascade vc;
|
||||
Effect *fx = &vc; // through the base class, as the engine does
|
||||
double t0 = now();
|
||||
for (size_t i = 0; i < n; ++i) outA[i] = fx->process(in[i]);
|
||||
const double viaVirtual = now() - t0;
|
||||
|
||||
VirtualCascade dc; // same code, called on the concrete type
|
||||
dc.c.reset();
|
||||
t0 = now();
|
||||
for (size_t i = 0; i < n; ++i) outB[i] = dc.VirtualCascade::process(in[i]);
|
||||
const double viaDirect = now() - t0;
|
||||
|
||||
Cascade block;
|
||||
t0 = now();
|
||||
for (size_t i = 0; i < n; i += BLOCK) block.processBlockHoisted(in.data() + i, outC.data() + i, BLOCK);
|
||||
const double blocked = now() - t0;
|
||||
|
||||
double maxDiff = 0;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
maxDiff = std::fmax(maxDiff, std::fabs((double)outA[i] - (double)outB[i]));
|
||||
maxDiff = std::fmax(maxDiff, std::fabs((double)outA[i] - (double)outC[i]));
|
||||
}
|
||||
|
||||
const double perNs = viaVirtual * 1e9 / (double)n;
|
||||
std::printf("\nC. ten-biquad cascade (EQ10's shape), %.0f s of samples\n", seconds);
|
||||
std::printf(" %-32s %8.2f ns/sample\n", "per sample, virtual (today)", perNs);
|
||||
std::printf(" %-32s %8.2f ns/sample %+.0f%%\n", "per sample, direct call",
|
||||
viaDirect * 1e9 / (double)n, (viaDirect / viaVirtual - 1) * 100);
|
||||
std::printf(" %-32s %8.2f ns/sample %+.0f%%\n", "block, coefficients hoisted",
|
||||
blocked * 1e9 / (double)n, (blocked / viaVirtual - 1) * 100);
|
||||
std::printf(" dispatch is %.2f ns of the %.2f, max diff between the three %.3g\n",
|
||||
(viaVirtual - viaDirect) * 1e9 / (double)n, perNs, maxDiff);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
const double seconds = argc > 1 ? std::strtod(argv[1], nullptr) : 4.0;
|
||||
wavetable::WaveTables::prewarmBlocking();
|
||||
echofield::GrainSources::prewarmBlocking();
|
||||
|
||||
std::printf("sizzle bench: %d Hz, block %d, %.0f s per measurement\n", SR, BLOCK, seconds);
|
||||
partA(seconds);
|
||||
partB(seconds);
|
||||
partC(seconds);
|
||||
std::printf("\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -21,7 +21,7 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "sizzle/Effect.hpp"
|
||||
#include "sizzle/TestVoice.hpp"
|
||||
#include "voices/TestVoice.hpp"
|
||||
#include "wavetable/WaveTables.hpp"
|
||||
|
||||
using namespace sizzle;
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// The randomizer's promise, checked by playing what it produces: over many seeds,
|
||||
// every device must come out in range, audible, and with headroom left. A rule in
|
||||
// Randomizer.cpp that drifts into silence or into clipping fails here rather than
|
||||
// in someone's track.
|
||||
//
|
||||
// randomizer_test [seeds] (default 200 per device)
|
||||
//
|
||||
// Per seed it checks three things:
|
||||
// 1. every value is inside its own ParamSpec (and an enum is one of its choices)
|
||||
// 2. rendering a note (or, for the reverb, a test signal) is AUDIBLE
|
||||
// 3. ...and stays under the clipping ceiling, and finite throughout
|
||||
//
|
||||
// The thresholds are deliberately generous: this is a net under the rules, not a
|
||||
// taste test. It prints the measured spread per device so a tightening or a new
|
||||
// device can be judged against real numbers.
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "echofield/GrainSources.hpp"
|
||||
#include "sizzle/Effect.hpp"
|
||||
#include "sizzle/Model.hpp"
|
||||
#include "sizzle/Randomizer.hpp"
|
||||
#include "sizzle/Specs.hpp"
|
||||
#include "voices/TestVoice.hpp"
|
||||
#include "wavetable/WaveTables.hpp"
|
||||
|
||||
using namespace sizzle;
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int SR = 48000;
|
||||
|
||||
/** Peak and RMS of a render, and whether every sample was finite. */
|
||||
struct Level {
|
||||
float peak = 0.f;
|
||||
float rms = 0.f;
|
||||
size_t peakAt = 0; // sample index of the peak — a startup transient shows up here
|
||||
bool finite = true;
|
||||
};
|
||||
|
||||
Level measure(const std::vector<float> &v) {
|
||||
Level l;
|
||||
double sum = 0;
|
||||
for (size_t i = 0; i < v.size(); ++i) {
|
||||
const float x = v[i];
|
||||
if (!std::isfinite(x)) { l.finite = false; continue; }
|
||||
const float a = std::fabs(x);
|
||||
if (a > l.peak) { l.peak = a; l.peakAt = i; }
|
||||
sum += (double)x * x;
|
||||
}
|
||||
l.rms = v.empty() ? 0.f : (float)std::sqrt(sum / (double)v.size());
|
||||
return l;
|
||||
}
|
||||
|
||||
/** One held note through the instrument voice the engine would use, then its tail. */
|
||||
Level playInstrument(const char *type, const Params &p, double holdSec, double tailSec) {
|
||||
const char *kind = std::strcmp(type, "GRAIN_CLOUD") == 0 ? "GRAIN" : "SYNTH";
|
||||
TestVoiceSetup setup;
|
||||
setup.type = type;
|
||||
setup.params = &p;
|
||||
setup.sampleRate = SR;
|
||||
setup.tempoBpm = 120.f;
|
||||
setup.clock0 = 0.0;
|
||||
std::unique_ptr<TestVoice> voice = makeTestVoice(kind, setup);
|
||||
if (!voice) return Level{};
|
||||
|
||||
const int block = 192;
|
||||
const int hold = (int)(holdSec * SR) / block;
|
||||
const int tail = (int)(tailSec * SR) / block;
|
||||
std::vector<float> out;
|
||||
out.reserve((size_t)(hold + tail) * block);
|
||||
|
||||
voice->blockStart(block);
|
||||
voice->noteOn(60, 100);
|
||||
for (int b = 0; b < hold; ++b) {
|
||||
voice->blockStart(block);
|
||||
for (int i = 0; i < block; ++i) out.push_back(voice->render());
|
||||
}
|
||||
voice->noteOff(60);
|
||||
for (int b = 0; b < tail; ++b) {
|
||||
voice->blockStart(block);
|
||||
for (int i = 0; i < block; ++i) out.push_back(voice->render());
|
||||
}
|
||||
return measure(out);
|
||||
}
|
||||
|
||||
/** A test signal through the effect: a decaying saw burst, noise, then silence for
|
||||
* the tail — the same shape the golden scenarios use. */
|
||||
Level playEffect(const char *type, const Params &p) {
|
||||
std::unique_ptr<Effect> fx = Effect::create(type, SR);
|
||||
if (!fx) return Level{};
|
||||
fx->update(p, 120.f);
|
||||
|
||||
const int n = (int)(2.0 * SR);
|
||||
std::vector<float> out;
|
||||
out.reserve((size_t)n);
|
||||
uint32_t seed = 0x1234567u;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
const double t = (double)i / SR;
|
||||
float x = 0.f;
|
||||
if (t < 0.6) {
|
||||
x = (float)(0.6 * (2.0 * std::fmod(t * 110.0, 1.0) - 1.0) * std::exp(-t * 4.0));
|
||||
} else if (t < 1.0) {
|
||||
seed = seed * 1103515245u + 12345u;
|
||||
x = (float)((seed >> 8) & 0xFFFF) / 65535.f * 0.5f - 0.25f;
|
||||
}
|
||||
out.push_back(fx->process(x));
|
||||
}
|
||||
return measure(out);
|
||||
}
|
||||
|
||||
/** Every value the randomizer wrote must belong to the device and sit in range. */
|
||||
bool checkRanges(const DeviceSpec &dev, const Params &p, std::string &why) {
|
||||
for (int i = 0; i < p.size(); ++i) {
|
||||
const char *key = p.keyAt(i);
|
||||
const ParamSpec *ps = nullptr;
|
||||
for (int k = 0; k < dev.paramCount; ++k)
|
||||
if (std::strcmp(dev.params[k].key, key) == 0) { ps = &dev.params[k]; break; }
|
||||
if (!ps) { why = std::string("unknown key ") + key; return false; }
|
||||
if (ps->isEnum()) {
|
||||
bool found = false;
|
||||
for (int c = 0; c < ps->choiceCount(); ++c)
|
||||
if (std::strcmp(ps->choices[c], p.valueAt(i)) == 0) { found = true; break; }
|
||||
if (!found) { why = std::string(key) + " = '" + p.valueAt(i) + "' is not one of its choices"; return false; }
|
||||
} else {
|
||||
const float v = p.f(key, ps->def);
|
||||
if (!std::isfinite(v) || v < ps->min - 1e-4f || v > ps->max + 1e-4f) {
|
||||
why = std::string(key) + " = " + std::to_string(v) + " outside [" +
|
||||
std::to_string(ps->min) + ", " + std::to_string(ps->max) + "]";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
struct Device {
|
||||
const char *type;
|
||||
double hold, tail; // instruments only
|
||||
float minPeak; // below this, nobody would hear it
|
||||
float maxPeak; // above this, the patch is into the limiter
|
||||
};
|
||||
|
||||
// The floors and ceilings are per device because the voices do not share a gain
|
||||
// structure: SynthVoice ends in OUT_GAIN 0.5, the Grain Cloud auto-levels itself
|
||||
// near RMS 0.126, and the reverb is measured wet+dry at its own levels. Each floor
|
||||
// sits at roughly half the quietest roll measured over 400 seeds — loose enough not
|
||||
// to flake on a seed nobody has drawn yet, tight enough that a rule sliding toward
|
||||
// silence (a filter parked off the note, a layer budget scaled too hard) fails here.
|
||||
const Device kDevices[] = {
|
||||
{"NES_SYNTH", 1.5, 1.0, 0.060f, 1.0f},
|
||||
{"MORPH_PAD", 3.0, 1.5, 0.012f, 1.0f}, // a pad is genuinely the quietest of these
|
||||
{"GRAIN_CLOUD", 3.0, 1.0, 0.015f, 1.0f}, // the cloud's auto-level needs a moment to come up
|
||||
{"WAVETABLE", 1.5, 1.0, 0.030f, 1.0f},
|
||||
{"AMBIENCE", 0.0, 0.0, 0.200f, 1.0f},
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
/** `randomizer_test --dump <TYPE> <seed> [key=value ...]`: what that roll actually
|
||||
* set, and what it measured. The overrides make it a probe — re-render the same
|
||||
* patch with one value changed to find which one is responsible for a bad peak. */
|
||||
int dumpOne(const char *type, uint32_t seed, int nOverride, char **override) {
|
||||
const DeviceSpec *dev = findDevice(type);
|
||||
if (!dev) { std::printf("no such device: %s\n", type); return 2; }
|
||||
Params p;
|
||||
if (!model::randomize(type, seed, p)) { std::printf("%s is not randomizable\n", type); return 2; }
|
||||
for (int i = 0; i < nOverride; ++i) {
|
||||
const char *eq = std::strchr(override[i], '=');
|
||||
if (!eq) continue;
|
||||
const std::string key(override[i], eq - override[i]);
|
||||
p.set(key.c_str(), eq + 1);
|
||||
std::printf(" (override %s = %s)\n", key.c_str(), eq + 1);
|
||||
}
|
||||
std::printf("%s seed %u -- \"%s\"\n", type, seed, model::randomName(type, seed).c_str());
|
||||
for (int i = 0; i < p.size(); ++i) std::printf(" %-12s %s\n", p.keyAt(i), p.valueAt(i));
|
||||
for (const Device &d : kDevices) {
|
||||
if (std::strcmp(d.type, type) != 0) continue;
|
||||
const Level l = dev->kind == Kind::Instrument ? playInstrument(type, p, d.hold, d.tail)
|
||||
: playEffect(type, p);
|
||||
std::printf(" -> peak %.4f at %.3f s rms %.5f %s\n", l.peak, (double)l.peakAt / SR, l.rms,
|
||||
l.finite ? "finite" : "NON-FINITE");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc > 3 && std::strcmp(argv[1], "--dump") == 0) {
|
||||
wavetable::WaveTables::prewarmBlocking();
|
||||
echofield::GrainSources::prewarmBlocking();
|
||||
return dumpOne(argv[2], (uint32_t)std::strtoul(argv[3], nullptr, 10), argc - 4, argv + 4);
|
||||
}
|
||||
const int seeds = argc > 1 ? std::atoi(argv[1]) : 200;
|
||||
wavetable::WaveTables::prewarmBlocking();
|
||||
echofield::GrainSources::prewarmBlocking();
|
||||
|
||||
int pass = 0, fail = 0;
|
||||
std::printf("randomizer: %d seeds per device\n", seeds);
|
||||
std::printf(" %-13s %9s %9s %9s %9s %7s\n", "device", "peak min", "peak med", "peak max", "rms min", "result");
|
||||
|
||||
for (const Device &d : kDevices) {
|
||||
const DeviceSpec *dev = findDevice(d.type);
|
||||
if (!dev) { std::printf(" FAIL %s: no device spec\n", d.type); ++fail; continue; }
|
||||
if (!model::canRandomize(d.type)) { std::printf(" FAIL %s: not randomizable\n", d.type); ++fail; continue; }
|
||||
|
||||
std::vector<float> peaks;
|
||||
peaks.reserve((size_t)seeds);
|
||||
float worstRms = 1e9f;
|
||||
float worstPeak = 1e9f;
|
||||
uint32_t worstSeed = 0;
|
||||
int bad = 0;
|
||||
std::string firstProblem;
|
||||
|
||||
for (int s = 0; s < seeds; ++s) {
|
||||
const uint32_t seed = (uint32_t)(s * 2654435761u + 12345u);
|
||||
Params p;
|
||||
if (!model::randomize(d.type, seed, p)) {
|
||||
if (firstProblem.empty()) firstProblem = "randomize() returned false";
|
||||
++bad; continue;
|
||||
}
|
||||
std::string why;
|
||||
if (!checkRanges(*dev, p, why)) {
|
||||
if (firstProblem.empty()) firstProblem = "seed " + std::to_string(seed) + ": " + why;
|
||||
++bad; continue;
|
||||
}
|
||||
|
||||
const Level l = dev->kind == Kind::Instrument ? playInstrument(d.type, p, d.hold, d.tail)
|
||||
: playEffect(d.type, p);
|
||||
peaks.push_back(l.peak);
|
||||
if (l.rms < worstRms) worstRms = l.rms;
|
||||
if (l.peak < worstPeak) { worstPeak = l.peak; worstSeed = seed; }
|
||||
|
||||
const char *problem = nullptr;
|
||||
if (!l.finite) problem = "non-finite output";
|
||||
else if (l.peak < d.minPeak) problem = "inaudible";
|
||||
else if (l.peak > d.maxPeak) problem = "clipping";
|
||||
if (problem) {
|
||||
if (firstProblem.empty())
|
||||
firstProblem = "seed " + std::to_string(seed) + ": " + problem +
|
||||
" (peak " + std::to_string(l.peak) + ", rms " + std::to_string(l.rms) + ")";
|
||||
++bad;
|
||||
}
|
||||
}
|
||||
|
||||
std::sort(peaks.begin(), peaks.end());
|
||||
const float lo = peaks.empty() ? 0.f : peaks.front();
|
||||
const float mid = peaks.empty() ? 0.f : peaks[peaks.size() / 2];
|
||||
const float hi = peaks.empty() ? 0.f : peaks.back();
|
||||
std::printf(" %-13s %9.4f %9.4f %9.4f %9.5f %7s quietest seed %u\n", d.type, lo, mid, hi, worstRms,
|
||||
bad == 0 ? "PASS" : "FAIL", worstSeed);
|
||||
if (bad != 0) {
|
||||
std::printf(" %d/%d bad; first: %s\n", bad, seeds, firstProblem.c_str());
|
||||
++fail;
|
||||
} else {
|
||||
++pass;
|
||||
}
|
||||
}
|
||||
|
||||
std::printf("randomizer: %d passed, %d failed\n", pass, fail);
|
||||
return fail == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
#include <cmath>
|
||||
#include "frasil/FrasilVoice.hpp"
|
||||
#include "sizzle/TestVoice.hpp"
|
||||
#include "TestVoice.hpp"
|
||||
|
||||
namespace sizzle {
|
||||
namespace {
|
||||
@@ -6,9 +6,9 @@
|
||||
|
||||
#include <cmath>
|
||||
#include <memory>
|
||||
#include "GrainCloud.hpp"
|
||||
#include "GrainSources.hpp"
|
||||
#include "sizzle/TestVoice.hpp"
|
||||
#include "echofield/GrainCloud.hpp"
|
||||
#include "echofield/GrainSources.hpp"
|
||||
#include "TestVoice.hpp"
|
||||
|
||||
namespace sizzle {
|
||||
namespace {
|
||||
@@ -8,9 +8,9 @@
|
||||
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include "SampleStore.hpp"
|
||||
#include "SampleVoice.hpp"
|
||||
#include "sizzle/TestVoice.hpp"
|
||||
#include "sampler/SampleStore.hpp"
|
||||
#include "sampler/SampleVoice.hpp"
|
||||
#include "TestVoice.hpp"
|
||||
|
||||
namespace sizzle {
|
||||
namespace {
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include <cstring>
|
||||
#include "frasil/FrasilVoice.hpp"
|
||||
#include "sizzle/TestVoice.hpp"
|
||||
#include "TestVoice.hpp"
|
||||
#include "synth/SynthVoice.hpp"
|
||||
#include "wavetable/WaveTables.hpp"
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
// definition replaces its placeholder at link time.
|
||||
|
||||
#include <cstring>
|
||||
#include "sizzle/TestVoice.hpp"
|
||||
#include "TestVoice.hpp"
|
||||
|
||||
#define SIZZLE_TEST_MAKER(fn) \
|
||||
__attribute__((weak)) std::unique_ptr<TestVoice> fn(const TestVoiceSetup &) { return nullptr; }
|
||||
@@ -5,9 +5,9 @@
|
||||
// WaveVoice alone, patch from the slot, factory tables built up front.
|
||||
|
||||
#include <memory>
|
||||
#include "sizzle/TestVoice.hpp"
|
||||
#include "WaveTables.hpp"
|
||||
#include "WaveVoice.hpp"
|
||||
#include "TestVoice.hpp"
|
||||
#include "wavetable/WaveTables.hpp"
|
||||
#include "wavetable/WaveVoice.hpp"
|
||||
|
||||
namespace sizzle {
|
||||
namespace {
|
||||
+173
-53
@@ -38,10 +38,11 @@ in exactly what it needs and nothing else:
|
||||
| `make help` | lists every target and prints the current version |
|
||||
| `make deps` | fails loudly if the JDK or the Android SDK is missing |
|
||||
| `make check` | unit tests + lint — the gate before a commit |
|
||||
| `make -C ios bench` | prints what the FX chain and each effect cost; asserts nothing |
|
||||
| `make staging` | non-debuggable build, release-like performance, debug key |
|
||||
| `make install` | `adb install -r` of the staging APK (keeps projects/presets) |
|
||||
| `make release` | **unsigned** release APK, named for F-Droid |
|
||||
| `make dist` | stages the release APK + F-Droid metadata under `dist/` |
|
||||
| `make dist` | stages the release APK + its R8 mapping + F-Droid metadata under `dist/` |
|
||||
| `make publish` | uploads `dist/` to the private F-Droid repo — **manual only** |
|
||||
| `make bump-minor` | feature bump: `x.(y+1).0`, versionCode +1 |
|
||||
|
||||
@@ -98,11 +99,11 @@ the numbers by hand is how they drift apart.
|
||||
|
||||
### 2.3 Build types
|
||||
|
||||
| Type | Debuggable | Signing | Use |
|
||||
|------|-----------|---------|-----|
|
||||
| `debug` | yes | debug key | breakpoints, instant-run edits |
|
||||
| `staging` | **no** | debug key | anything on a real device |
|
||||
| `release` | no | **unsigned** | publishing only |
|
||||
| Type | Debuggable | R8 | Signing | Use |
|
||||
|------|-----------|----|---------|-----|
|
||||
| `debug` | yes | no | debug key | breakpoints, instant-run edits |
|
||||
| `staging` | **no** | no | debug key | anything on a real device |
|
||||
| `release` | no | **yes** | **unsigned** | publishing only |
|
||||
|
||||
`staging` exists because `debug` is misleading: a debuggable build makes ART run
|
||||
the app un-optimised and Compose several times slower, so UI "snappiness"
|
||||
@@ -114,6 +115,22 @@ installs without a release keystore. **Use `staging` for every on-device test.**
|
||||
the private F-Droid repo; `fdroid publish` signs what lands in the unsigned
|
||||
directory. No keystore should ever exist in this checkout.
|
||||
|
||||
`release` is also the only build R8 touches (shrink + optimise + obfuscate, plus
|
||||
unused-resource removal). The app reflects over nothing of its own — songs,
|
||||
presets, themes and bindings are all hand-written text parsers — so
|
||||
`app/proguard-rules.pro` keeps exactly one thing: **native method names**. JNI
|
||||
resolves `Java_cc_tiredsysadmin_android_sizzle_audio_NativeEngine_*` by name at
|
||||
runtime, so a renamed class or method is an `UnsatisfiedLinkError` on first play,
|
||||
not a build error. Everything else (Compose, media3, DataStore, coroutines) ships
|
||||
its own consumer rules inside its AAR.
|
||||
|
||||
A release stack trace is therefore obfuscated. `make dist` copies
|
||||
`app/build/outputs/mapping/release/mapping.txt` to
|
||||
`dist/<application_id>_<versionCode>-mapping.txt`; keep it for every published
|
||||
APK, because it is the only way to read a crash from that build. It is never
|
||||
uploaded. `staging` keeps R8 off on purpose: it exists to measure the UI, and a
|
||||
readable stack trace is worth more there than the last few hundred KB.
|
||||
|
||||
### 2.4 Publishing
|
||||
|
||||
Publishing is **always a manual action, never automatic** — it is not a side
|
||||
@@ -214,35 +231,28 @@ cc.tiredsysadmin.android.sizzle
|
||||
│ ├── MidiTrace.kt Optional receive/engine trace (setprop log.tag.SizzleMidiTrace VERBOSE)
|
||||
│ └── MidiInput.kt Lists/opens MIDI sources (USB, BLE, other apps' virtual ports), reconnects dead ones -> MidiSoundModule / CC bindings
|
||||
│
|
||||
├── audio/ The real-time sound engine (own thread)
|
||||
├── audio/ The engine's face (the DSP itself is core/, in C++)
|
||||
│ ├── AudioEngine.kt Drives core/ through NativeEngine: transport, sync, meters, recording
|
||||
│ ├── NativeEngine.kt JNI to core/src/host/EngineHost (src/main/cpp/jni_engine.cpp)
|
||||
│ ├── NativeAudioBridge.kt Starts/stops the Oboe stream (which renders in C++, no JVM call)
|
||||
│ ├── Transport.kt TransportState snapshot published to the UI
|
||||
│ ├── 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
|
||||
│ ├── SampleStore.kt Process-wide decoded-PCM cache + WAV encode/decode
|
||||
│ ├── SampleStore.kt Process-wide decoded-PCM cache + WAV encode/decode (mirrored into core/)
|
||||
│ ├── SampleRecorder.kt Ad-hoc mic/USB capture into a sample
|
||||
│ ├── SoundFontLoader.kt Extract PCM from an .sf2 / .xi into the SampleStore
|
||||
│ ├── Effects.kt Insert DSP: TapeDelay, Filter, Bitcrusher, GraphicEq (+ AudioEffect API)
|
||||
│ ├── AmbienceReverb.kt FDN reverb processor
|
||||
│ ├── MasterRecorder.kt Renders the master bus (with FX tail) to a WAV
|
||||
│ ├── NativeAudioBridge.kt JNI bridge to the Oboe callback (calls fillBlock)
|
||||
│ └── AudioEngine.kt Oboe/AudioTrack + sample-accurate sequencer + voice/FX mixing
|
||||
│ └── GrainSources.kt The Grain Cloud's ten built-in sources (the UI draws their peaks)
|
||||
│
|
||||
├── frasil/ MPL-2.0 (not GPL): the Morph Pad, ported from FRASIL (see §5.7)
|
||||
│ ├── FrasilDefs.kt Its settings, engine-unit mapping, the 36 drone presets
|
||||
│ ├── FrasilPatch.kt Parsed slot snapshot (+ morph target); FrasilClock (the shared TIDE time)
|
||||
│ └── FrasilVoice.kt One pad note: choir + partials + breath, drift, tide, warmth
|
||||
│ └── FrasilDefs.kt Its settings, engine-unit mapping, the 36 drone presets
|
||||
│
|
||||
├── 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, 12 factory presets
|
||||
│ └── WaveVoice.kt WavePatch + one note: 2 table oscillators, bend, unison, sub, SVF, 2 envelopes, LFO
|
||||
│ ├── WaveTables.kt Band-limited tables: FFT, one mip level per octave (the editor draws them)
|
||||
│ └── WaveDefs.kt Its settings, 12 factory presets
|
||||
│
|
||||
├── echofield/ MIT: the Grain Cloud, ported from ECHOFIELD (see §5.8)
|
||||
│ ├── EchofieldDefs.kt Its settings, 14 factory presets, the source list
|
||||
│ └── GrainCloud.kt GrainPatch + one channel's cloud: modes, scheduler, grains, gate, auto-level
|
||||
│ └── EchofieldDefs.kt Its settings, 14 factory presets, the source list
|
||||
│
|
||||
├── cpp/native_audio.cpp Low-latency Oboe stream; RT callback pulls audio via JNI
|
||||
├── cpp/native_audio.cpp Low-latency Oboe stream; its RT callback renders core/ directly
|
||||
├── cpp/jni_engine.cpp The JNI surface of core/src/host/EngineHost (+ the preset randomizer)
|
||||
│
|
||||
├── io/ Human-readable text persistence
|
||||
│ ├── PresetIo.kt Instrument/effect preset <-> KEY=VALUE text
|
||||
@@ -409,11 +419,17 @@ playback continues. Samples go across as they enter `SampleStore` (`put` /
|
||||
`remove` mirror into the native store). Transport, meters, scope and finished
|
||||
recordings are polled from a 10 ms thread.
|
||||
|
||||
The Kotlin engine (`ReferenceEngine` and the voices and effects under `audio/`,
|
||||
`frasil/`, `echofield/`, `wavetable/`) is now only a reference: the
|
||||
`IosGolden*` unit tests render it so the C++ can be checked bit for bit
|
||||
(`make -C ios golden core-test`). The UI still uses a few of those Kotlin classes
|
||||
to draw (wavetable frames, Grain Cloud source peaks, sample decoding).
|
||||
The Kotlin engine is now only a reference, and lives in the **test** source set:
|
||||
`app/src/test/java/.../audio` (`ReferenceEngine`, `SynthVoice`, `SynthPatch`,
|
||||
`Effects`, `AmbienceReverb`, `SampleVoice`, `MasterRecorder`), `.../frasil`
|
||||
(`FrasilVoice`, `FrasilPatch`), `.../echofield` (`GrainCloud`) and
|
||||
`.../wavetable` (`WaveVoice`). The `IosGolden*` unit tests render it so the C++
|
||||
can be checked bit for bit (`make -C ios golden core-test`). It is **not** in
|
||||
`src/main`, because nothing in the app calls it any more — there it would only be
|
||||
dead code in every APK. What the UI genuinely still needs to *draw* did stay in
|
||||
`src/main`: `wavetable/WaveTables` (table frames), `audio/GrainSources` (source
|
||||
peaks), `audio/SampleStore` + `SoundFontLoader` (sample decoding), and the three
|
||||
`*Defs` files (parameter and preset data, shared with the editors).
|
||||
|
||||
**Parity rule:** every feature or fix lands in both apps in the same change, with
|
||||
one shared version bump. Engine and DSP work goes into `core/` only.
|
||||
@@ -429,7 +445,9 @@ ordinary device callback, so it is listed and played like USB gear. Connected
|
||||
addresses are remembered (`SettingsStore.bleMidiDevices`) and reopened by
|
||||
address at start, without a scan. Permissions: `BLUETOOTH_SCAN`
|
||||
(`neverForLocation`) + `BLUETOOTH_CONNECT` on Android 12+, `ACCESS_FINE_LOCATION`
|
||||
(and the legacy `BLUETOOTH` / `BLUETOOTH_ADMIN`) on 8-11, asked for when SCAN is
|
||||
with `ACCESS_COARSE_LOCATION` (the platform treats FINE as an upgrade of COARSE
|
||||
and refuses a FINE-only request; `make lint` enforces it) and the legacy
|
||||
`BLUETOOTH` / `BLUETOOTH_ADMIN` on 8-11, asked for when SCAN is
|
||||
first tapped. The emulator has no usable Bluetooth radio (its Bluetooth service
|
||||
crashes on a scan); test on a phone.
|
||||
|
||||
@@ -439,6 +457,60 @@ connected BLE MIDI peripherals are remembered and reconnected at launch through
|
||||
CoreBluetooth (best effort: iOS decides whether that brings the CoreMIDI source
|
||||
back without the panel).
|
||||
|
||||
### 5.4.4 The preset randomizer (0.42.0)
|
||||
|
||||
`core/src/model/Randomizer.cpp` turns a seed into a playable patch for the five
|
||||
devices where "surprise me" is a musical thing to ask: **Synth**, **Morph Pad**,
|
||||
**Grain Cloud**, **Wavetable** and **Ambience Reverb**. Both apps show it as a
|
||||
**RANDOM** button in the shared preset bar, and the same seed gives the same patch
|
||||
on both (`model::randomize(type, seed, Params&)`).
|
||||
|
||||
**Why it is not just `random()` over each range.** Scattering values over the
|
||||
parameter ranges mostly produces silence and the occasional scream. The rules
|
||||
encode three things instead:
|
||||
|
||||
- *audible*: something always sounds. One oscillator or layer is always up, an
|
||||
envelope that decays to nothing is given a body, a filter is never shut, and a
|
||||
reverb is never fully dry.
|
||||
- *inside the rails*: oscillator levels share a budget, resonance, drive and
|
||||
saturation stay out of the range where a patch screams, and the reverb's wet sits
|
||||
under its dry.
|
||||
- *musical where it matters*: tunings come from consonant intervals, detune stays
|
||||
inside a chorus, and pitch modulation stays small enough to keep a patch in tune.
|
||||
|
||||
**Nothing structural is rolled.** "Custom" sources and tables are never picked and
|
||||
the slot's own keys (`sfSample`, `sfFile`, the Sampler's pads) survive a roll — a
|
||||
sample or an imported wavetable is the user's, and the dice are for the settings.
|
||||
`MORPH TO` is left Off for the same reason *and* for a measured one (below).
|
||||
|
||||
**The test is the specification.** `core/tests/randomizer_test.cpp` (part of
|
||||
`make -C ios core-test`) renders every device over hundreds of seeds through the
|
||||
real voice — the golden tests' `TestVoice` wrappers — and fails on a patch that
|
||||
is out of range, silent, clipping or non-finite. Every bound in Randomizer.cpp
|
||||
that looks arbitrary was put there by a seed this test caught; four worth knowing,
|
||||
because each is a trap the next device will have too:
|
||||
|
||||
| What it caught | Why |
|
||||
|---|---|
|
||||
| A band-pass parked above the note | Only a *low*-pass is open at the top. Band and high need a cutoff near or under the played pitch, or a patch with every oscillator up is silent (peak 0.010 against a median of 0.3). `cutoffFor` is the shared fix. |
|
||||
| `Vel → Cutoff` at −0.69 | A mod slot can close the filter. Pitch, Cutoff, PWM and Amp get bounded amounts; Cutoff asymmetrically, since opening is free and closing is not. |
|
||||
| A choir-only Morph Pad through a band-pass | That filter is on the choir layer alone — the partials and breath go round it — so a patch whose choir is its only layer gets a plain open low-pass. |
|
||||
| `MORPH TO` + `MORPH TIME` | A held note travels all the way onto a factory drone and *is* that preset from then on, at a level the randomizer never chose (peak 1.33 with every layer of its own at zero). Budgeting cannot reach past a morph, so a roll does not pick a target. |
|
||||
|
||||
`randomizer_test --dump <TYPE> <seed> [key=value …]` prints one roll and what it
|
||||
measured, with overrides, which is how each of those was found: re-render the same
|
||||
patch with one value changed until the peak moves.
|
||||
|
||||
**How it reaches the apps.** Android: `nativeCanRandomize` / `nativeRandomPreset` /
|
||||
`nativeRandomName` in `jni_engine.cpp` (pure functions — no engine, so they work
|
||||
before `nativeCreate`), the patch arriving as `PresetIo` text that
|
||||
`AppViewModel.randomizeSlot` imports. iOS: `SizzleSession.randomizeSlot` writes the
|
||||
`Params` into the slot directly. Both keep the slot's non-parameter keys.
|
||||
|
||||
**Adding a device to it** means writing its rules in Randomizer.cpp, adding its
|
||||
name to `kRandomizable`, and adding a row to `kDevices` in the test with a floor
|
||||
and a ceiling. The button then appears on both platforms with no UI change.
|
||||
|
||||
### 5.5 Sizzle as a background MIDI sound module
|
||||
|
||||
Goal: another app (Mikro Seq, a DAW, a controller app) plays Sizzle's mixer over
|
||||
@@ -710,14 +782,23 @@ of real time on a desktop JVM.
|
||||
### Add a new instrument or effect
|
||||
1. Add an entry to `ToolboxType` (`model/Toolbox.kt`) with its `ParamSpec` list.
|
||||
2. Teach the engine how to sound it:
|
||||
It all happens in `core/` (C++), which is what both apps play — never in the
|
||||
Kotlin reference, which only follows so the golden comparison still holds:
|
||||
- **Instrument**: handle its type where the engine picks a voice per channel
|
||||
(see how `NES_SYNTH`, `SAMPLER`, and `SOUNDFONT` are dispatched in
|
||||
`AudioEngine`).
|
||||
- **Signal effect**: add a processor in `audio/Effects.kt` implementing
|
||||
`AudioEffect` and register it in `AudioEffect.create(...)`; the per-channel
|
||||
insert chain picks it up automatically.
|
||||
(see how `NES_SYNTH`, `SAMPLER` and `SOUNDFONT` are dispatched in
|
||||
`core/src/engine/Engine.cpp`).
|
||||
- **Signal effect**: add a processor under `core/src/fx/` implementing
|
||||
`sizzle::Effect` (`core/include/sizzle/Effect.hpp`) and register its maker in
|
||||
`core/src/fx/Registry.cpp`; the per-channel insert chain picks it up
|
||||
automatically, and so does the AUv3 wrapper once it is in `ios/app/components.txt`.
|
||||
- **MIDI effect** (arp/transpose/LFO-style): hook into the sequencer instead
|
||||
of the signal path (see `advanceArps` / `applyLfos` in `AudioEngine`).
|
||||
of the signal path (see `advanceArps` / `applyLfos` in `Engine.cpp`).
|
||||
- **Keep the reference in step**: mirror the change in the Kotlin file under
|
||||
`app/src/test/.../audio` (or `frasil` / `echofield` / `wavetable`), then
|
||||
`make -C ios golden core-test` to check the two sample for sample.
|
||||
4. Optionally give it a **RANDOM** button: rules in `core/src/model/Randomizer.cpp`,
|
||||
its name in `kRandomizable`, a row in `randomizer_test`'s `kDevices`. See §5.4.4 —
|
||||
and read its table of traps before inventing bounds.
|
||||
The Toolbox picker, parameter editor, and preset save/load all work automatically
|
||||
from the `ParamSpec` list (the editor then shows one card with every parameter).
|
||||
3. Group its controls: add a case to `DeviceLayouts.pagesFor` (cards, tones,
|
||||
@@ -740,14 +821,25 @@ the Settings theme picker immediately.
|
||||
|
||||
## 7. Threading & performance notes
|
||||
|
||||
- The audio render loop is in `AudioEngine.renderLoop()` on a `MAX_PRIORITY`
|
||||
thread. It **must never allocate or block**. Keep it that way.
|
||||
- The audio render loop is `Engine::fillBlock` in `core/src/engine/Engine.cpp`,
|
||||
called from the Oboe real-time callback (`src/main/cpp/native_audio.cpp`) — all
|
||||
C++, with no JVM call on the audio thread, so no GC pause can glitch it. It
|
||||
**must never allocate, lock or block**. Keep it that way: the active-voice index
|
||||
lists are rebuilt once per block, per-channel mixer gains and FX-chain pointers
|
||||
are hoisted out of the per-sample loop, and `EngineHost` only ever *try*-locks.
|
||||
(`AudioEngine.startAudioTrack` keeps a Kotlin `MAX_PRIORITY` loop as the
|
||||
fallback when Oboe cannot start; it calls the same `nativeRender`.)
|
||||
- Timing is derived from *counting audio samples* (`samplesPerLine`), not from
|
||||
timers, so playback never drifts.
|
||||
- UI ⇄ audio sharing is lock-free by design (audio reads plain fields). This can
|
||||
produce a one-frame-stale read during a simultaneous edit — harmless for a
|
||||
tracker. If you ever add compound state that must be read atomically, publish it
|
||||
as an immutable snapshot (like `TransportState`) rather than adding locks.
|
||||
- UI ⇄ audio sharing crosses through text: `ProjectIo.save` plus
|
||||
`EngineHost::syncProjectText`, which diffs and copies only what changed (§5.4.2).
|
||||
`save` is therefore a hot path, not just the file writer — it builds into one
|
||||
pre-sized buffer, and `AudioEngine.requestSync` coalesces a burst of edits
|
||||
(a drag fires one per pointer event) into one sync per `SYNC_COALESCE_MS`.
|
||||
- The transport poller (`AudioEngine.start`) runs at 100 Hz only while the song
|
||||
plays or a take is armed; stopped and idle it waits 100 ms a turn, and any
|
||||
transport call wakes it through a semaphore so the playhead is never late.
|
||||
`AppModel.pollTransport` does the same on iOS (30 Hz playing, 10 Hz idle).
|
||||
- Block size is `BLOCK_FRAMES = 192` (~4 ms @ 48 kHz). Lower = tighter latency,
|
||||
higher = safer against underruns.
|
||||
- **UI rendering**: the pattern grid (`PatternGrid`) and arrangement roll
|
||||
@@ -856,11 +948,11 @@ polish and interchange niceties, not functional gaps.
|
||||
empty. Voices are a lane×track matrix so lanes layer polyphonically.
|
||||
- **Per-channel effect DSP** (milestone 3 ✓): each mixer channel runs an insert
|
||||
chain built from its FX slots — Tape Delay, Digital Reverb, Filter (LP/HP/BP),
|
||||
Bitcrusher, and 10-band EQ are real processors in `audio/Effects.kt`. Effect
|
||||
Bitcrusher, and 10-band EQ are real processors in `core/src/fx/`. Effect
|
||||
parameters update live per audio block; add/remove rebuilds the chain.
|
||||
- **Sampler instrument** ✓: WAV import (SAF file picker) + ad-hoc mic/USB
|
||||
recorder (`audio/SampleRecorder.kt`), decoded to a mono cache
|
||||
(`audio/SampleStore.kt`), played pitched + sliced by `audio/SampleVoice.kt`.
|
||||
(`audio/SampleStore.kt`), played pitched + sliced by `core/src/sampler/SampleVoice.cpp`.
|
||||
Its editor (`ui/toolbox/SamplerEditor.kt`) shows a waveform with two draggable
|
||||
slice markers, start-octave + volume, and a two-octave audition keyboard. Each
|
||||
(lane, track) has both a synth and a sample voice; the channel instrument type
|
||||
@@ -893,11 +985,16 @@ polish and interchange niceties, not functional gaps.
|
||||
(`version`/`bpm`/`sig`, `block`…`endblock` with `roll`/`track`/steps) — covered
|
||||
by passing JVM unit tests in `app/src/test`.
|
||||
- Background playback foreground service with Play/Pause/Stop notification.
|
||||
- **Full C++ audio port** ✓ (0.37.0): the whole DSP — sequencer, mixer, every
|
||||
instrument and effect, the master recorder — is `core/`, shared with the iOS app
|
||||
and driven over JNI. The Kotlin DSP it replaced lives on in the **test** source
|
||||
set (`app/src/test/.../audio`, `frasil`, `echofield`, `wavetable`) as the
|
||||
reference the C++ is checked against, so none of it ships in the APK.
|
||||
- **Oboe / AAudio native output** ✓ (default): `src/main/cpp/native_audio.cpp`
|
||||
opens a low-latency Oboe stream whose real-time callback pulls audio via JNI
|
||||
(`audio/NativeAudioBridge.kt`) from the SAME `AudioEngine.fillBlock` the
|
||||
AudioTrack loop uses — so both backends produce identical sound, only the
|
||||
delivery path differs. Oboe is the default engine; it falls back to the
|
||||
(`audio/NativeAudioBridge.kt`) from the SAME `Engine::fillBlock` the AudioTrack
|
||||
fallback loop reaches through `nativeRender` — so both backends produce
|
||||
identical sound, only the delivery path differs. Oboe is the default engine; it falls back to the
|
||||
AudioTrack loop only if it fails to initialise (or the native lib is absent),
|
||||
surfacing a popup with the reason (there is no user toggle).
|
||||
Built via **NDK r27** (`ndkVersion` in `app/build.gradle.kts`) + CMake + the
|
||||
@@ -909,9 +1006,9 @@ polish and interchange niceties, not functional gaps.
|
||||
`llvm-readelf -l <lib>.so` → LOAD `Align 0x4000`.)
|
||||
- **SF2 / XI loader instrument** ✓: `audio/SoundFontLoader.kt` extracts PCM from
|
||||
an `.sf2` / `.xi` into the `SampleStore`, played back through the same
|
||||
`SampleVoice` path as the Sampler; edited via `ui/toolbox/SoundFontEditor.kt`
|
||||
`SampleVoice` path in `core/` as the Sampler; edited via `ui/toolbox/SoundFontEditor.kt`
|
||||
(root note, volume, ADSR).
|
||||
- **Master recording** ✓: `audio/MasterRecorder.kt` renders the stereo master bus
|
||||
- **Master recording** ✓: `core/src/host/MasterRecorder.cpp` renders the stereo master bus
|
||||
(plus a configurable FX tail) to a WAV in a user-chosen folder (SAF).
|
||||
- **Stereo output & recording** ✓: `fillBlock` renders interleaved stereo and the
|
||||
recorder captures two channels (voices/inserts are mono, so both channels carry
|
||||
@@ -933,11 +1030,34 @@ polish and interchange niceties, not functional gaps.
|
||||
- **Byte-exact desktop `.sng` compatibility.** `io/SngFormat.kt` reads/writes the
|
||||
reference line format and round-trips musically; a field-for-field byte match
|
||||
with the CLI project layout is the remaining interchange nicety.
|
||||
- **Full C++ audio port.** The DSP currently runs in Kotlin behind the Oboe
|
||||
callback (via JNI). Porting the hot path to C++ would remove JVM/GC from the
|
||||
real-time thread — a performance hardening step, not a functional gap.
|
||||
- **Route the Oboe backend through the chosen output device** (Oboe
|
||||
`setDeviceId`), matching the AudioTrack path's device selection.
|
||||
- **Block-rate FX processing — measured, and not worth doing.** Insert effects are
|
||||
`process(float)` per sample, so a four-effect chain on four channels is 16
|
||||
virtual calls per frame. That looks like something to fix; `make -C ios bench`
|
||||
says it is not (M4, `-O2`, part C): on a ten-biquad cascade with EQ10's shape,
|
||||
dispatch costs **0.11 ns of 9.13 ns per sample, about 1 %** — the indirect
|
||||
branch is perfectly predicted and amortises over everything the effect does.
|
||||
The obvious block restructuring is a *large regression*: running band-at-a-time
|
||||
over a block, so each band's coefficients stay in registers, measured **+162 %**,
|
||||
because the running value then makes ten round trips through memory per sample
|
||||
instead of staying in one register across the cascade. Nor is there a SIMD win
|
||||
to chase — serial IIR filters are recurrences, so they do not vectorise across
|
||||
samples, and the chains differ per channel. Don't reopen this on intuition;
|
||||
re-run the bench first.
|
||||
|
||||
Where the cost actually is, if FX headroom is ever needed (part B): **Ambience
|
||||
is 52 % of all eight effects put together** (65.9 ns/sample, 3.5× the next, Tape
|
||||
Delay at 19.1) — an 8-line FDN with four diffusers, early reflections, a
|
||||
Walsh-Hadamard feedback mix and a modulated fractional-delay read per line,
|
||||
every sample. A full chain is about 77 % of render time (part A), and
|
||||
three-quarters of that is Ambience. Nothing is urgent: four channels with four
|
||||
effects each still render at **42× real time**.
|
||||
|
||||
One trap for whoever does touch `src/fx/`: only `AmbienceReverb.cpp` carries
|
||||
`#pragma clang fp contract(off)`. Make that explicit across the directory
|
||||
*first*, as its own commit, or a change in multiply-add contraction is
|
||||
indistinguishable from a real bug in the golden comparison.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -345,6 +345,8 @@ its number to switch it off/on:
|
||||
Every device editor has a preset bar at the top:
|
||||
|
||||
- **PRESET** dropdown — load a saved preset.
|
||||
- **RANDOM** — roll a new patch (Synth, Morph Pad, Grain Cloud, Wavetable and
|
||||
Ambience Reverb only; see below).
|
||||
- **SAVE** — save the current settings as a named preset.
|
||||
- **DELETE** — remove the selected preset (asks to confirm).
|
||||
- **IMPORT** — load a preset from a file (Sampler presets can be imported from a
|
||||
@@ -355,6 +357,26 @@ Presets are plain text (`.szp`), stored per device type in the app's storage.
|
||||
Factory presets are seeded automatically and reappear as new ones ship, but ones
|
||||
you delete stay deleted.
|
||||
|
||||
### RANDOM
|
||||
|
||||
The five devices with the most knobs — **Synth**, **Morph Pad**, **Grain Cloud**,
|
||||
**Wavetable** and **Ambience Reverb** — have a **RANDOM** button that throws a new
|
||||
patch into the editor and gives it a name ("Hazy Drift"). It is a starting point,
|
||||
not a slot machine: a roll is always something you can hear and never something
|
||||
that clips, because the levels, the filters and the envelopes are drawn inside
|
||||
ranges that keep a patch in that territory rather than scattered over the whole
|
||||
knob. Expect a usable sound most of the time and a keeper now and then.
|
||||
|
||||
RANDOM replaces the settings in the editor, exactly like loading a preset, so
|
||||
**SAVE** anything you want to keep first. It does *not* touch a sample you have
|
||||
loaded or a wavetable you have imported — the roll is of the settings, not of
|
||||
your sounds. Roll again as often as you like; when one is worth keeping, SAVE it.
|
||||
|
||||
The other devices have no RANDOM, and that is deliberate: a Sampler or an SF2/XI
|
||||
loader is only as interesting as the sound you put in it, and the MIDI effects
|
||||
(arpeggiator, transposer, LFO) have so few settings that a dice roll says nothing
|
||||
a glance at them would not.
|
||||
|
||||
---
|
||||
|
||||
## Setup tab
|
||||
|
||||
@@ -5,6 +5,39 @@ Sizzle for iOS/iPadOS (`cc.tiredsysadmin.ios.sizzle`). One entry per version in
|
||||
is shared with Android, continuing Android's numbering, and both apps ship the
|
||||
same features; the Android side of each version is in `../CHANGELOG.md`.
|
||||
|
||||
## 0.42.0 (build 79)
|
||||
|
||||
- RANDOM: the Synth, Morph Pad, Grain Cloud, Wavetable and Ambience Reverb
|
||||
editors have a RANDOM button in the preset bar, which rolls a new patch and
|
||||
names it. Always audible, never clipping — the ranges it draws from are picked
|
||||
to keep a patch there rather than scattered over the whole knob. It replaces the
|
||||
editor's settings like a preset does (SAVE first to keep what is there) and
|
||||
leaves a loaded sample or an imported wavetable alone. The same rules and the
|
||||
same seeds as Android, from `core/src/model/Randomizer.cpp`.
|
||||
(Android has the same in 0.42.0.)
|
||||
|
||||
## 0.41.2 (build 78)
|
||||
|
||||
Housekeeping and speed; nothing you can see changes.
|
||||
|
||||
- **The DSP core is built at `-O2`.** It was `-Os`, which traded the engine's
|
||||
speed for a little binary size in an app that has to hold a 4 ms deadline. The
|
||||
golden tests measure the core at `-O2`, so the build that ships is now the
|
||||
build that was checked.
|
||||
- **The mixer costs less per sample.** Channel volume, mute/solo and the effect
|
||||
chain are read once per audio block rather than once per frame
|
||||
(`core/src/engine/Engine.cpp`, shared with Android). Bit-for-bit the same
|
||||
audio: all 61 reference scenarios still match.
|
||||
- **Less battery while a song is stopped.** The transport display polled the
|
||||
engine 30 times a second whatever was happening; stopped it now ticks 10 times
|
||||
a second, and any transport call — the PLAY button, a gamepad, a MIDI binding —
|
||||
starts the display-rate ticks in the same turn. The tick also stopped hopping
|
||||
through a task per poll, 30 times a second, for a main-thread timer that was
|
||||
already on the main actor.
|
||||
- **Dead code gone.** The golden tests' `TestVoice` wrappers were compiled into
|
||||
the app and the plugin extension although only `golden_test` calls them; they
|
||||
have moved to `core/tests/voices/`. A couple of unused declarations went too.
|
||||
|
||||
## 0.41.1 (build 77)
|
||||
|
||||
- Fix: some controls only showed their new state after something else redrew
|
||||
|
||||
+26
-4
@@ -11,6 +11,8 @@
|
||||
# Android toolchain; runs IosGoldenExport in ../app)
|
||||
# make core-test build the C++ core and compare it with the reference audio
|
||||
# (TYPES="FILTER EQ10" limits it to some devices)
|
||||
# make bench print what the insert-FX chain and each effect cost (SECONDS=1
|
||||
# for a quick look); asserts nothing, so it is not part of check
|
||||
# make au-test macOS check of the AUv3 wrapper: every effect through AVAudioEngine
|
||||
# must match the core, plus parameters, presets and saved state
|
||||
# make project generate app/Sizzle.xcodeproj (components + XcodeGen)
|
||||
@@ -36,6 +38,10 @@ IPA := dist/$(APP_ID)_$(BUILD_NO).ipa
|
||||
# C++ DSP core: reference audio lives in ../core/golden/ (regenerated, not committed).
|
||||
CORE_SRC := $(wildcard ../core/src/*.cpp ../core/src/*/*.cpp)
|
||||
CORE_HDR := $(wildcard ../core/include/sizzle/*.hpp ../core/src/*/*.hpp)
|
||||
# The golden tests' TestVoice wrappers. They live under tests/, not src/, so neither
|
||||
# app compiles them: only golden_test calls makeTestVoice.
|
||||
VOICE_SRC := $(wildcard ../core/tests/voices/*.cpp)
|
||||
VOICE_HDR := ../core/tests/voices/TestVoice.hpp
|
||||
CXX ?= c++
|
||||
CXXFLAGS := -std=c++17 -O2 -Wall -Wextra -I../core/include -I../core/src -I../core/src/fx -lz
|
||||
GOLDEN := ../core/golden
|
||||
@@ -62,9 +68,9 @@ golden:
|
||||
./gradlew -q :app:testDebugUnitTest --tests '*IosGolden*' --rerun
|
||||
@ls $(GOLDEN)/*.scn | wc -l | xargs echo "reference scenarios:"
|
||||
|
||||
build/core/golden_test: $(CORE_SRC) $(CORE_HDR) ../core/tests/golden_test.cpp
|
||||
build/core/golden_test: $(CORE_SRC) $(CORE_HDR) $(VOICE_SRC) $(VOICE_HDR) ../core/tests/golden_test.cpp
|
||||
mkdir -p build/core
|
||||
$(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) ../core/tests/golden_test.cpp
|
||||
$(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) $(VOICE_SRC) ../core/tests/golden_test.cpp
|
||||
|
||||
build/core/sampler_test: $(CORE_SRC) $(CORE_HDR) ../core/tests/sampler_test.cpp
|
||||
mkdir -p build/core
|
||||
@@ -94,6 +100,21 @@ build/core/oneshot_test: $(CORE_SRC) $(CORE_HDR) ../core/tests/oneshot_test.cpp
|
||||
mkdir -p build/core
|
||||
$(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) ../core/tests/oneshot_test.cpp
|
||||
|
||||
# The randomizer plays what it generates, so it links the golden tests' TestVoice
|
||||
# wrappers too (see VOICE_SRC).
|
||||
build/core/randomizer_test: $(CORE_SRC) $(CORE_HDR) $(VOICE_SRC) $(VOICE_HDR) ../core/tests/randomizer_test.cpp
|
||||
mkdir -p build/core
|
||||
$(CXX) $(CXXFLAGS) -I../core/tests -o $@ $(CORE_SRC) $(VOICE_SRC) ../core/tests/randomizer_test.cpp
|
||||
|
||||
build/core/bench: $(CORE_SRC) $(CORE_HDR) ../core/tests/bench.cpp
|
||||
mkdir -p build/core
|
||||
$(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) ../core/tests/bench.cpp
|
||||
|
||||
# Not part of core-test: it asserts nothing, it just prints what the DSP costs, and
|
||||
# the numbers only mean something on a quiet machine. SECONDS=1 for a quick look.
|
||||
bench: build/core/bench
|
||||
build/core/bench $(SECONDS)
|
||||
|
||||
build/core/midi_test: ../core/include/sizzle/Midi.hpp ../core/tests/midi_test.cpp
|
||||
mkdir -p build/core
|
||||
$(CXX) $(CXXFLAGS) -o $@ ../core/tests/midi_test.cpp
|
||||
@@ -110,7 +131,7 @@ zip-test: build/core/zip_test
|
||||
build/core/zip_test build/core/java.zip build/core/ours.zip
|
||||
unzip -tq build/core/ours.zip
|
||||
|
||||
core-test: build/core/golden_test build/core/sampler_test build/core/engine_test build/core/io_test build/core/midi_test build/core/host_test build/core/midimap_test build/core/bundle_test build/core/oneshot_test zip-test
|
||||
core-test: build/core/golden_test build/core/sampler_test build/core/engine_test build/core/io_test build/core/midi_test build/core/host_test build/core/midimap_test build/core/bundle_test build/core/oneshot_test build/core/randomizer_test zip-test
|
||||
@test -f $(GOLDEN)/input.f32 || $(MAKE) --no-print-directory golden
|
||||
build/core/golden_test $(GOLDEN) $(TYPES)
|
||||
build/core/sampler_test
|
||||
@@ -121,6 +142,7 @@ core-test: build/core/golden_test build/core/sampler_test build/core/engine_test
|
||||
build/core/midimap_test ../app/src/test/resources/midimap/filter.szm
|
||||
build/core/oneshot_test
|
||||
build/core/bundle_test $(GOLDEN)/bundles/android_sampler.zip ../app/src/test/resources/presetbundle/ios_sampler.zip
|
||||
build/core/randomizer_test $(SEEDS)
|
||||
|
||||
# ------------------------------------------------------------------ app
|
||||
AU_SRC := app/FX/SizzleDeviceAU.mm app/FX/SizzleEffectAU.mm app/FX/SizzleInstrumentAU.mm app/FX/SizzleDeviceAU+Sources.mm
|
||||
@@ -220,4 +242,4 @@ $(SPIKE_IPA): $(SPIKE_PROJ)/project.pbxproj $(SPIKE_SRC)
|
||||
clean:
|
||||
rm -rf build dist
|
||||
|
||||
.PHONY: help golden core-test zip-test au-test project ipa bump-major bump-minor bump-patch bump spike-ipa clean
|
||||
.PHONY: help golden core-test bench zip-test au-test project ipa bump-major bump-minor bump-patch bump spike-ipa clean
|
||||
|
||||
+15
-4
@@ -10,6 +10,9 @@ Makefile (`make -C ios help`).
|
||||
| `../core/` | The shared C++ engine (Android plays through it too): a port of the Android app's Kotlin DSP |
|
||||
| `../core/include/sizzle/DeviceSpecs.gen.hpp` | Every device's parameters, generated from `ToolboxType` (Kotlin) |
|
||||
| `../core/tests/golden_test.cpp` | Compares the core with audio the Kotlin code renders |
|
||||
| `../core/tests/voices/` | The `TestVoice` wrappers `golden_test` drives the instruments through. Under `tests/`, not `src/`, so neither app compiles them |
|
||||
| `../core/tests/bench.cpp` | `make bench`: what the FX chain and each effect cost. Asserts nothing, so it is not part of `core-test` |
|
||||
| `../core/tests/randomizer_test.cpp` | Plays what the preset randomizer generates over many seeds: in range, audible, not clipping. `--dump <TYPE> <seed> [key=value …]` inspects one roll |
|
||||
| `app/components.txt` | The plugin list (AU type, subtype, device, name) |
|
||||
| `app/FX/` | The plugin extension: `SizzleDeviceAU` (shared: parameters, presets, state), `SizzleEffectAU` (aufx), `SizzleInstrumentAU` (aumu), `SizzleFXViewController` (factory + editor). The app compiles the same classes to host them itself |
|
||||
| `app/Host/SizzleSession*` | The bridge to the C++ song + engine (audio output, song lock, live-note queue); one category per screen |
|
||||
@@ -27,8 +30,11 @@ listed in `CHANGELOG.md` here.
|
||||
|
||||
## How the port is verified
|
||||
|
||||
The Kotlin DSP is the reference. `make golden` runs `IosGoldenExport` (a JVM unit
|
||||
test in the Android app, skipped by the normal `make check`), which:
|
||||
The Kotlin DSP is the reference. It lives in the Android app's **test** source set
|
||||
(`../app/src/test/java/.../audio`, `frasil`, `echofield`, `wavetable`) — both apps
|
||||
play `core/`, so it is no longer part of either one. `make golden` runs
|
||||
`IosGoldenExport` (a JVM unit test in the Android app, skipped by the normal
|
||||
`make check`), which:
|
||||
|
||||
- writes `DeviceSpecs.gen.hpp`, so iOS uses the same parameter definitions
|
||||
(keys, labels, ranges, defaults, choices) and the Mix Tightener presets;
|
||||
@@ -38,8 +44,13 @@ test in the Android app, skipped by the normal `make check`), which:
|
||||
`../core/golden/` (not committed; regenerate any time).
|
||||
|
||||
`make core-test` renders the same scenarios through the C++ core and requires a
|
||||
largest difference below 1e-4. Today all 25 pass; most are bit-exact, the rest
|
||||
differ by about one float ulp. Porting rules that make this possible:
|
||||
largest difference below 1e-4. Today all 61 pass; most are bit-exact, the rest
|
||||
differ by about one float ulp. It compiles the core at `-O2` — and so does Xcode
|
||||
(`GCC_OPTIMIZATION_LEVEL: 2` on the `SizzleCore` target in `app/project.yml`, in
|
||||
every configuration), so the build that ships is the build that was measured. An
|
||||
optimisation level is not a free choice here: it decides FP contraction, and the
|
||||
comparison only holds for the level the tests use. Porting rules that make this
|
||||
possible:
|
||||
|
||||
- translate line for line, keeping Kotlin's types: `Float` → `float`,
|
||||
`Double` → `double`, so every expression runs in the same precision;
|
||||
|
||||
@@ -20,7 +20,7 @@ final class AppModel: ObservableObject {
|
||||
@Published private(set) var revision = 0
|
||||
@Published var tab: Tab = .tracker
|
||||
|
||||
// Transport, polled ~30×/s.
|
||||
// Transport, polled 30×/s while playing (see pollTransport).
|
||||
@Published private(set) var isPlaying = false
|
||||
@Published private(set) var currentLine = 0
|
||||
@Published private(set) var currentBeat = 0
|
||||
@@ -45,13 +45,34 @@ final class AppModel: ObservableObject {
|
||||
|
||||
init() {
|
||||
observer = NotificationCenter.default.addObserver(forName: .SizzleSessionDidChange, object: nil, queue: .main) { [weak self] _ in
|
||||
Task { @MainActor in self?.revision += 1 }
|
||||
}
|
||||
timer = Timer.scheduledTimer(withTimeInterval: 1.0 / 30, repeats: true) { [weak self] _ in
|
||||
Task { @MainActor in self?.pollTransport() }
|
||||
// SizzleSession's -edit: announces transport calls too, so this is also
|
||||
// where the poll rate catches up: however playback was started — the
|
||||
// tracker's PLAY button, a gamepad, a MIDI binding — the display-rate
|
||||
// ticks begin in the same turn, not up to a tick later.
|
||||
Task { @MainActor in self?.revision += 1; self?.pollTransport() }
|
||||
}
|
||||
// The timer fires on the main run loop, so the body is already on the main
|
||||
// actor: assumeIsolated instead of `Task { @MainActor in … }`, which hopped
|
||||
// through an allocation and a scheduler turn 30 times a second forever.
|
||||
// Ticks while stopped only watch for isPlaying, so they run at 10×/s.
|
||||
startTimer(hz: Self.idleHz)
|
||||
}
|
||||
|
||||
private static let playingHz = 30.0
|
||||
private static let idleHz = 10.0
|
||||
|
||||
private func startTimer(hz: Double) {
|
||||
timer?.invalidate()
|
||||
timerHz = hz
|
||||
let t = Timer(timeInterval: 1.0 / hz, repeats: true) { [weak self] _ in
|
||||
MainActor.assumeIsolated { self?.pollTransport() }
|
||||
}
|
||||
RunLoop.main.add(t, forMode: .common)
|
||||
timer = t
|
||||
}
|
||||
|
||||
private var timerHz = 0.0
|
||||
|
||||
private func pollTransport() {
|
||||
let playing = session.isPlaying
|
||||
if playing != isPlaying { isPlaying = playing }
|
||||
@@ -60,8 +81,19 @@ final class AppModel: ObservableObject {
|
||||
if line != currentLine { currentLine = line }
|
||||
if beat != currentBeat { currentBeat = beat }
|
||||
}
|
||||
// Follow the playhead at display rate; idle at a third of that, which is what
|
||||
// a stopped song needs to notice someone else starting it.
|
||||
let want = playing ? Self.playingHz : Self.idleHz
|
||||
if want != timerHz { startTimer(hz: want) }
|
||||
}
|
||||
|
||||
func playPause() { session.isPlaying ? session.pause() : session.play() }
|
||||
func stop() { session.stop() }
|
||||
func playPause() {
|
||||
session.isPlaying ? session.pause() : session.play()
|
||||
pollTransport()
|
||||
}
|
||||
|
||||
func stop() {
|
||||
session.stop()
|
||||
pollTransport()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,11 +21,6 @@ final class PluginCheck: ObservableObject {
|
||||
.filter { [kAudioUnitType_Effect, kAudioUnitType_MusicDevice].contains($0.audioComponentDescription.componentType) }
|
||||
}
|
||||
|
||||
func listInstalled() {
|
||||
let comps = installed()
|
||||
lines = ["Registered plugins (extension): \(comps.count)"] + comps.map { " \($0.name)" }
|
||||
}
|
||||
|
||||
func run() async {
|
||||
running = true
|
||||
defer { running = false }
|
||||
|
||||
@@ -113,31 +113,6 @@ struct SetupRow: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// An Android settings section not ported yet: its place in the layout, greyed
|
||||
/// out and marked as coming later.
|
||||
struct ComingLaterRow: View {
|
||||
let title: String
|
||||
let subtitle: String
|
||||
let icon: String
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 12) {
|
||||
Image(systemName: icon).font(.system(size: 16)).foregroundColor(Theme.dim).frame(width: 24)
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(title).font(.system(size: 15, weight: .medium)).foregroundColor(Theme.dim)
|
||||
Text(subtitle).font(.system(size: 12)).foregroundColor(Theme.dim.opacity(0.75)).lineLimit(2)
|
||||
}
|
||||
Spacer(minLength: 8)
|
||||
Text("Later").font(.system(size: 11)).foregroundColor(Theme.dim)
|
||||
.padding(.horizontal, 8).padding(.vertical, 3)
|
||||
.overlay(Capsule().stroke(Theme.grid, lineWidth: 1))
|
||||
.fixedSize()
|
||||
}
|
||||
.padding(.vertical, 4)
|
||||
.accessibilityElement(children: .combine)
|
||||
.accessibilityHint("Coming in a later version")
|
||||
}
|
||||
}
|
||||
|
||||
/// The Setup tab's modal dialogs. iOS 15 alerts can't hold a text field, so the
|
||||
/// save prompt (and with it every dialog here, for one look) is drawn in SwiftUI.
|
||||
|
||||
@@ -246,6 +246,16 @@ private struct PresetBar: View {
|
||||
MixKit.Button(label: "DELETE", danger: true) { confirmDelete = current }
|
||||
Spacer().frame(width: 20)
|
||||
}
|
||||
// RANDOM, for the devices core/'s randomizer covers (the Synth,
|
||||
// Morph Pad, Grain Cloud, Wavetable and Ambience). It replaces the
|
||||
// settings in place, the way loading a preset does.
|
||||
if session.canRandomizeType(type) {
|
||||
MixKit.Button(label: "RANDOM") {
|
||||
guard session.randomizeSlot(slot) != nil else { return }
|
||||
selected = nil
|
||||
model.refresh()
|
||||
}
|
||||
}
|
||||
MixKit.Button(label: "SAVE") {
|
||||
saveName = slotName.trimmingCharacters(in: .whitespaces).isEmpty ? displayName : slotName
|
||||
saving = true
|
||||
|
||||
@@ -136,6 +136,12 @@ NS_SWIFT_UI_ACTOR
|
||||
/// Factory preset names for a device type (Android's PresetLibrary set).
|
||||
- (NSArray<NSString *> *)factoryPresetsForType:(NSString *)type;
|
||||
- (void)applyFactoryPreset:(NSString *)name toSlot:(NSInteger)slot;
|
||||
/// Does this device type have a preset randomizer (core/src/model/Randomizer.cpp)?
|
||||
- (BOOL)canRandomizeType:(NSString *)type;
|
||||
/// Roll a playable patch into [slot] and return the name it came with, or nil when
|
||||
/// the slot's device has no randomizer. The slot's own files — a loaded sample, an
|
||||
/// imported wavetable — are kept: the roll is of the settings, not of the sounds.
|
||||
- (nullable NSString *)randomizeSlot:(NSInteger)slot;
|
||||
|
||||
#pragma mark - Live notes (keyboard, MIDI): queued to the audio thread
|
||||
- (void)noteOn:(NSInteger)note velocity:(NSInteger)velocity midiChannel:(NSInteger)channel;
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
#include "sizzle/DeviceSpecs.gen.hpp"
|
||||
#include "sizzle/Engine.hpp"
|
||||
#include "sizzle/Model.hpp"
|
||||
#include "sizzle/Randomizer.hpp"
|
||||
|
||||
using namespace sizzle;
|
||||
|
||||
@@ -498,6 +499,34 @@ bool isSampleKey(const char *key) {
|
||||
}];
|
||||
}
|
||||
|
||||
- (BOOL)canRandomizeType:(NSString *)type {
|
||||
return type.length && model::canRandomize(type.UTF8String) ? YES : NO;
|
||||
}
|
||||
|
||||
- (nullable NSString *)randomizeSlot:(NSInteger)slot {
|
||||
if (slot < 0 || slot >= 16) return nil;
|
||||
const std::string type = [self typeOfSlot:slot].UTF8String;
|
||||
if (!model::canRandomize(type.c_str())) return nil;
|
||||
|
||||
const uint32_t seed = arc4random();
|
||||
Params rolled;
|
||||
if (!model::randomize(type.c_str(), seed, rolled)) return nil;
|
||||
const std::string name = model::randomName(type.c_str(), seed);
|
||||
|
||||
[self edit:^(model::Project &p, engine::Engine &e) {
|
||||
model::ToolboxSlot &s = p.toolbox[(size_t)slot];
|
||||
// Only the keys the roll produced are written, and those are exactly the
|
||||
// device's own parameters. Anything else the slot holds — the sample a Grain
|
||||
// Cloud reads, the WAV behind a custom wavetable — is therefore left in
|
||||
// place: the roll is of the settings, not of the sounds. Writing through
|
||||
// set() also bumps the slot version, so the engine re-reads it.
|
||||
for (int i = 0; i < rolled.size(); ++i) s.set(rolled.keyAt(i), rolled.valueAt(i));
|
||||
s.name = name;
|
||||
e.rebuildFxChains();
|
||||
}];
|
||||
return @(name.c_str());
|
||||
}
|
||||
|
||||
#pragma mark - live notes
|
||||
|
||||
- (void)noteOn:(NSInteger)note velocity:(NSInteger)velocity midiChannel:(NSInteger)ch {
|
||||
|
||||
+6
-1
@@ -25,7 +25,12 @@ targets:
|
||||
settings:
|
||||
base:
|
||||
PRODUCT_NAME: SizzleCore
|
||||
GCC_OPTIMIZATION_LEVEL: s
|
||||
# -O2 in every configuration, matching ios/Makefile's CXXFLAGS — the one
|
||||
# build of this code the golden tests actually measure. It was -Os, which
|
||||
# trades the DSP's speed for a few hundred KB in an app that has to hold a
|
||||
# 4 ms deadline; and optimising Debug too is deliberate (the Android
|
||||
# CMakeLists does the same), because an -O0 core cannot render in real time.
|
||||
GCC_OPTIMIZATION_LEVEL: 2
|
||||
SizzleFX:
|
||||
type: app-extension
|
||||
platform: iOS
|
||||
|
||||
+2
-2
@@ -12,8 +12,8 @@
|
||||
# or polish. versionCode is monotonic and bumps by 1 on every release,
|
||||
# because F-Droid and the Android package manager order installs by it alone.
|
||||
|
||||
versionName = 0.41.1
|
||||
versionCode = 77
|
||||
versionName = 0.42.0
|
||||
versionCode = 79
|
||||
|
||||
# Namespace for every platform: cc.tiredsysadmin.<os>.sizzle. Android:
|
||||
# cc.tiredsysadmin.android.sizzle (app/), iOS/iPadOS: cc.tiredsysadmin.ios.sizzle
|
||||
|
||||
Reference in New Issue
Block a user