Compare commits

...
9 Commits
Author SHA1 Message Date
ReactorcoremeltdownandClaude Opus 5 0e8032532f 0.42.0 (79): preset randomizer for five devices (Android and iOS)
A RANDOM button in the preset bar of the Synth, Morph Pad, Grain Cloud,
Wavetable and Ambience Reverb editors: it rolls a playable patch and names it.
The rules live in core/src/model/Randomizer.cpp and are shared, so a seed gives
the same patch on both platforms. Android reaches it over JNI as preset text and
imports it; iOS writes the Params into the slot. Neither touches the slot's own
files — a loaded sample or an imported wavetable survives a roll, because the
dice are for the settings, not for the sounds.

Scattering values over the parameter ranges produces silence and the occasional
scream, so the rules encode three things instead: something always sounds (a
layer is always up, an envelope that decays to nothing gets a body, a filter is
never shut, a reverb is never fully dry); levels share a budget and resonance,
drive and saturation stay out of the range where a patch screams; and tunings
come from consonant intervals rather than a uniform draw.

core/tests/randomizer_test.cpp is the specification: it renders every device over
hundreds of seeds through the real voice and fails on anything out of range,
silent, clipping or non-finite. Every bound that looks arbitrary was put there by
a seed it caught — a band-pass parked above the note (peak 0.010 against a 0.3
median), a Vel -> Cutoff mod slot closing the filter (0.41 -> 0.02), a choir-only
Morph Pad through its own band-pass, and MORPH TO, which a roll now leaves alone
because MORPH TIME carries a held note all the way onto a factory drone at a
level the randomizer never chose (1.33 with every layer of its own at zero).
--dump <TYPE> <seed> [key=value ...] re-renders one roll with overrides, which is
how each of those was found.

Also fixes the shared engine not compiling outside Apple's toolchain: a missing
<cstdint> in core/include/sizzle/Model.hpp. No change to the apps, but the
engine's tests and benchmark now build with GCC too — which is how the rules
above were iterated while the Mac was unreachable.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-11-18 21:02:24 +01:00
ReactorcoremeltdownandClaude Opus 5 b3bae931b1 bench: measure what the insert-FX chain costs, and drop the block-rate idea
`make -C ios bench` renders four channels of synth with 0/1/2/4 effects each,
times every effect on its own, and compares a ten-biquad cascade three ways. It
asserts nothing, so it stays out of core-test; no shipped code changes (the file
is under core/tests, which neither app compiles).

What it says, on an M4 at -O2. Per-sample virtual dispatch — listed in the
handover as a thing to fix — costs 0.11 ns of 9.13 ns per sample, about 1%: the
indirect branch is predicted and amortises over the effect's own work. The
obvious block restructuring is a 162% regression, because running band-at-a-time
over a block sends the running value through memory ten times per sample instead
of keeping it in a register across the cascade. So that idea is recorded as
measured and closed, rather than left as an invitation.

Where the cost actually is: Ambience, 52% of all eight effects together
(65.9 ns/sample, 3.5x Tape Delay). A full chain is ~77% of render time, and
three-quarters of that is Ambience. Not urgent — four channels of four effects
still render at 42x real time.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-11-18 21:01:29 +01:00
ReactorcoremeltdownandClaude Opus 5 ba98ec56f4 0.41.2 (78): cleanup and optimisation round (Android and iOS)
Nothing user-visible changes, except that the Android app is half the size and
both are lighter on the battery.

R8 is on for release builds (21.5 MB -> 10.1 MB); only the two JNI classes are
pinned by name, since the app reflects over nothing of its own, and `make dist`
keeps the mapping beside the APK. The Kotlin DSP that core/ replaced in 0.37.0
was still compiled into every APK with nothing calling it — it moves to the test
source set, where it belongs as the reference the C++ is checked against — and
the golden tests' TestVoice wrappers leave core/src for core/tests/voices, so
neither app compiles them either.

Speed: channel gain, mute/solo and the FX chain are read once per audio block
instead of once per frame in Engine::fillBlock (both platforms, bit-identical —
all 61 reference scenarios still match); the transport pollers idle at 100 ms
(Android) and 10 Hz (iOS) instead of polling flat out while a song is stopped,
woken by any transport call; ProjectIo.save builds into one pre-sized buffer and
a burst of edits is coalesced into one engine sync; the Kotlin grain sources and
factory wavetables are built when their editor opens rather than at launch, where
they duplicated ~6 MB the engine already renders in core/; and Xcode builds the
DSP core at -O2, the level the golden tests measure, not -Os.

Fix: `make lint` failed on a manifest asking for ACCESS_FINE_LOCATION without
ACCESS_COARSE_LOCATION (the BLE MIDI scan on Android 8-11), so `make check`
passes again.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-11-18 21:01:29 +01:00
ReactorcoremeltdownandClaude Opus 5.5 634dd05486 0.41.1 (77): iOS controls redraw when the song changes
The Mix record bar, the Sampler waveform page, the LFO target picker and the
audition keyboards read the session but had no changing inputs, so SwiftUI
skipped redrawing them until something else (rotation) forced it. They now
observe MixSongWatch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:30:06 +01:00
ReactorcoremeltdownandClaude Opus 5.5 cdabf3018b 0.41.0 (76): Keep screen on toggle (Android and iOS)
Settings › Interface: Android sets FLAG_KEEP_SCREEN_ON on the window, iOS turns
the idle timer off; persisted (and in iOS backups).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:15:46 +01:00
ReactorcoremeltdownandClaude Opus 5.5 6939dccbf0 samplepack-builder: slice one WAV (e.g. a GarageBand export) across pads by beats
Tempo (default 120 BPM) and beats per pad (default 4); the file is cut from 0:00
into equal slices filling pads 1..16, silent slices at the end are dropped and
slices past 16 reported. Boundaries are rounded per slice, so odd tempos don't drift.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 11:43:23 +01:00
ReactorcoremeltdownandClaude Opus 5.5 7041f762e5 0.40.0 (75): Sampler One-shot (Android and iOS)
- Sampler parameter oneShot (Off/On): note-offs don't release its pads; they
  play their whole slice. Transport stop/pause still releases (SampleVoice::
  release), panic kills
- Engine in core/ and the Kotlin reference both implement it; the golden
  Sampler "high" scenario covers it; oneshot_test checks MIDI, song, stop, panic
- ONE-SHOT toggle in both apps' Sampler editors; specs and layouts regenerated

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 16:53:13 +01:00
ReactorcoremeltdownandClaude Opus 5.5 5240019b47 0.39.1 (74): preset bundles between Android and iOS, both ways
iOS couldn't import Android's Sampler preset bundle (a ZIP with the .szp and
its WAVs) and shared sample presets as bare text naming iOS sample ids.

- core/src/io/PresetBundle: import/export in Android's bundle layout
  (padNFile / sfFile), used by iOS IMPORT and SHARE
- bundle_test imports a bundle written by Android's PresetLibrary
  (IosGoldenPresetBundle); PresetBundleInteropTest imports the iOS-written
  fixture with Android's importZip

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 16:39:33 +01:00
ReactorcoremeltdownandClaude Opus 5.5 6688718bed 0.39.0 (73): export and import MIDI mappings as .szm text (Android and iOS)
- SIZZLE-MIDIMAP 1 format: TYPE, NAME, one parameter=CC line each
- core/src/io/MidiMapIo (iOS) and io/MidiMapIo.kt (Android), tested on one
  shared fixture (midimap_test, MidiMapIoTest)
- EXPORT / IMPORT in each device's MIDI learn panel on both platforms
- Params::remove; iOS clears a mapping by removing it
- ios/Makefile regenerates the Xcode project when source folders change

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 16:31:46 +01:00
95 changed files with 3206 additions and 218 deletions
+83
View File
@@ -5,6 +5,89 @@ 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`).
## 0.41.0 (versionCode 76)
- **Keep screen on:** a Settings › Interface toggle that stops the screen from
dimming or locking while Sizzle is open (remembered). (iOS has the same in 0.41.0.)
## 0.40.0 (versionCode 75)
- **Sampler One-shot:** a ONE-SHOT toggle at the top of the Sampler editor. On,
note-offs are ignored: releasing a MIDI key or pad, the tracker's `===` and a
new note on the same track no longer cut a pad, which plays its whole slice
(the bus's eight voices overlap). Stopping or pausing the song still fades the
pads it played, and MIDI PANIC silences everything. It's a Sampler setting, so
it's saved with the song and in presets, and the Sampler plugin offers it as a
parameter. (iOS has the same in 0.40.0.)
## 0.39.1 (versionCode 74)
- Sampler, SF2/XI, Grain Cloud and Wavetable preset bundles now travel between
Android and iOS in both directions (the fix is on the iOS side; Android's
bundle format is unchanged and is now checked against the iOS code by tests).
## 0.39.0 (versionCode 73)
- **MIDI mappings as files:** the ⇄ MIDI panel of every toolbox device has
EXPORT and IMPORT. EXPORT shares the device's mapping (which MIDI CC drives
which parameter) as a plain-text `.szm` file; IMPORT replaces the device's
mapping with one from a file for the same kind of device, moving any CC another
parameter used. The same files work on iOS. (iOS has the same in 0.39.0.)
## 0.38.0 (versionCode 72)
- **Bluetooth LE MIDI controllers:** Settings › MIDI Sync › MIDI inputs has a
+12 -1
View File
@@ -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
View File
@@ -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
+19 -3
View File
@@ -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
+6 -1
View File
@@ -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
+20
View File
@@ -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();
@@ -83,6 +83,12 @@ class MainActivity : ComponentActivity() {
SizzleTheme(palette = viewModel.palette) {
SizzleAppUi(viewModel)
}
// "Keep screen on" (Settings › Interface): the window's flag follows the setting.
val keepOn = viewModel.keepScreenOn
androidx.compose.runtime.LaunchedEffect(keepOn) {
if (keepOn) window.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
else window.clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
}
// Hold the MIDI ports (USB, Bluetooth, other apps' virtual devices) for the
@@ -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 ->
@@ -0,0 +1,99 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.io
import cc.tiredsysadmin.android.sizzle.model.Project
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
/**
* A device's MIDI mapping as plain text (.szm), shared between Sizzle installs
* (Android and iOS read and write the same format; the C++ core's io/MidiMapIo):
*
* SIZZLE-MIDIMAP 1
* # comments start with '#'
* TYPE=WAVETABLE
* NAME=Lead
* cutoff=74
* resonance=71
*
* One `parameter=CC` line per mapped parameter (CC 0..127), in the device's
* parameter order. In the song a mapping is the slot value `midicc@<parameter>`.
*/
object MidiMapIo {
const val HEADER = "SIZZLE-MIDIMAP 1"
const val EXT = ".szm"
const val CC_PREFIX = "midicc@"
data class MidiMap(val type: String, val name: String, val bindings: List<Pair<String, Int>>)
/** [slot]'s mappings, in its device's parameter order. */
fun fromSlot(slot: ToolboxSlot): MidiMap = MidiMap(
type = slot.type?.name.orEmpty(),
name = slot.name,
bindings = slot.type?.params.orEmpty().mapNotNull { spec ->
slot.string(CC_PREFIX + spec.key).toIntOrNull()?.takeIf { it in 0..127 }?.let { spec.key to it }
},
)
fun save(map: MidiMap): String = buildString {
appendLine(HEADER)
appendLine("# Sizzle MIDI mapping: parameter=CC number (0-127), one per line.")
appendLine("TYPE=${map.type}")
appendLine("NAME=${map.name}")
for ((key, cc) in map.bindings) appendLine("$key=$cc")
}
/** The mapping in [text], or null if it has no header or TYPE. Lines that aren't
* `key=CC` with CC 0..127 are skipped; a repeated key or CC keeps its first line
* (one control drives one parameter). */
fun parse(text: String): MidiMap? {
var header = false
var type = ""
var name = ""
val bindings = ArrayList<Pair<String, Int>>()
val keys = HashSet<String>()
val ccs = HashSet<Int>()
for (raw in text.lineSequence()) {
val line = raw.trim()
if (line.isEmpty() || line.startsWith("#")) continue
if (line == HEADER) { header = true; continue }
val eq = line.indexOf('=')
if (eq <= 0) continue
val key = line.substring(0, eq).trim()
val value = line.substring(eq + 1).trim()
when (key) {
"TYPE" -> type = value
"NAME" -> name = value
else -> {
val cc = value.toIntOrNull() ?: continue
if (cc !in 0..127 || key in keys || cc in ccs) continue
keys += key; ccs += cc
bindings += key to cc
}
}
}
return if (header && type.isNotEmpty()) MidiMap(type, name, bindings) else null
}
/** Replace toolbox [slotIndex]'s mappings with [map]'s: only parameters its device
* has; a CC another parameter (of any slot) used moves to this one. Returns how
* many were applied, or -1 when [map] is for another device type. */
fun apply(project: Project, slotIndex: Int, map: MidiMap): Int {
val target = project.toolbox.getOrNull(slotIndex) ?: return -1
val type = target.type ?: return -1
if (type.name != map.type) return -1
type.params.forEach { target.values.remove(CC_PREFIX + it.key) }
var applied = 0
for ((key, cc) in map.bindings) {
if (type.params.none { it.key == key }) continue
for (s in project.toolbox) {
s.values.entries.removeAll { it.key.startsWith(CC_PREFIX) && it.value.toIntOrNull() == cc }
}
target.set(CC_PREFIX + key, cc.toString())
applied++
}
return applied
}
}
@@ -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,56 +28,98 @@ 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
@@ -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
@@ -30,6 +30,8 @@ data class AppSettings(
val kbdOctave: Int = 3,
/** Show the live VU meters inside the mixer volume faders. */
val vuMeters: Boolean = true,
/** Keep the screen on while Sizzle is in front. */
val keepScreenOn: Boolean = false,
/** Send MIDI clock + start/stop to attached MIDI devices (drive external gear). */
val sendMidiClock: Boolean = false,
/** Follow an external MIDI clock's tempo + start/stop. */
@@ -63,6 +65,7 @@ class SettingsStore(private val context: Context) {
kbdChannel = prefs[KBD_CHANNEL] ?: 0,
kbdOctave = prefs[KBD_OCTAVE] ?: 3,
vuMeters = prefs[VU_METERS] ?: true,
keepScreenOn = prefs[KEEP_SCREEN_ON] ?: false,
sendMidiClock = prefs[MIDI_CLOCK_SEND] ?: false,
receiveMidiClock = prefs[MIDI_CLOCK_RECV] ?: false,
soundModule = prefs[SOUND_MODULE] ?: false,
@@ -102,6 +105,11 @@ class SettingsStore(private val context: Context) {
context.settingsDataStore.edit { prefs -> prefs[VU_METERS] = enabled }
}
/** Persist "Keep screen on". */
suspend fun saveKeepScreenOn(enabled: Boolean) {
context.settingsDataStore.edit { prefs -> prefs[KEEP_SCREEN_ON] = enabled }
}
/** Persist the MIDI-clock send / receive toggles. */
suspend fun saveMidiClock(send: Boolean, receive: Boolean) {
context.settingsDataStore.edit { prefs ->
@@ -132,6 +140,7 @@ class SettingsStore(private val context: Context) {
val KBD_CHANNEL = intPreferencesKey("kbdChannel")
val KBD_OCTAVE = intPreferencesKey("kbdOctave")
val VU_METERS = booleanPreferencesKey("vuMeters")
val KEEP_SCREEN_ON = booleanPreferencesKey("keepScreenOn")
val MIDI_CLOCK_SEND = booleanPreferencesKey("midiClockSend")
val MIDI_CLOCK_RECV = booleanPreferencesKey("midiClockRecv")
val SOUND_MODULE = booleanPreferencesKey("soundModule")
@@ -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.
@@ -94,6 +94,10 @@ enum class ToolboxType(
ToolboxKind.INSTRUMENT, "Sampler",
listOf(
ParamSpec("volume", "Volume", 0.8f, 0f, 1f),
// On: note-offs (MIDI, the tracker's ===, a new note on the track) are
// ignored and every pad plays its whole slice. Stop / pause / panic still
// silence it. Played by the C++ engine (core/), not the Kotlin reference.
ParamSpec("oneShot", "One-shot", choices = listOf("Off", "On")),
// A 16-pad bank: each pad maps to a consecutive note from C2 (see
// [SamplerPads]) and stores its own sample id + slice as string params
// ("pad0", "pad0S", "pad0E", …). Edited by ui/toolbox/SamplerEditor.
@@ -120,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 ----------
@@ -217,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),
@@ -245,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(
@@ -254,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),
@@ -268,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)),
);
@@ -21,6 +21,7 @@ import cc.tiredsysadmin.android.sizzle.model.Pitch
import cc.tiredsysadmin.android.sizzle.model.Project
import cc.tiredsysadmin.android.sizzle.model.TimeSignature
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
import cc.tiredsysadmin.android.sizzle.model.ToolboxType
import kotlin.math.roundToInt
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.SharingStarted
@@ -116,6 +117,15 @@ class AppViewModel(
/** Whether the mixer's fader VU meters are shown (Settings toggle). */
var vuMeters by mutableStateOf(true); private set
/** Keep the screen on while Sizzle is in front (Settings toggle). */
var keepScreenOn by mutableStateOf(false); private set
fun updateKeepScreenOn(enabled: Boolean) {
keepScreenOn = enabled
viewModelScope.launch { settingsStore.saveKeepScreenOn(enabled) }
touched()
}
/** Enable/disable the mixer fader VU meters and persist the choice. */
fun updateVuMeters(enabled: Boolean) {
vuMeters = enabled
@@ -146,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. */
@@ -711,6 +718,34 @@ class AppViewModel(
touched()
}
/** [slotIndex]'s MIDI mapping as a shareable `.szm` file (in presets/.export,
* which the FileProvider serves), or null for an empty slot. */
fun midiMapExportFile(slotIndex: Int): java.io.File? {
val slot = project.toolbox.getOrNull(slotIndex)?.takeIf { !it.isEmpty } ?: return null
val map = cc.tiredsysadmin.android.sizzle.io.MidiMapIo.fromSlot(slot)
val dir = java.io.File(appContext.filesDir, "presets/.export").apply { mkdirs() }
val base = slot.name.ifBlank { slot.type?.name ?: "device" }
.replace(Regex("[^A-Za-z0-9._ -]"), "_").trim().ifBlank { "device" }
return java.io.File(dir, "$base MIDI${cc.tiredsysadmin.android.sizzle.io.MidiMapIo.EXT}").apply {
writeText(cc.tiredsysadmin.android.sizzle.io.MidiMapIo.save(map))
}
}
/** Replace [slotIndex]'s MIDI mapping with the `.szm` [text]; null when done,
* else why not (for a dialog). */
fun importMidiMap(slotIndex: Int, text: String): String? {
val io = cc.tiredsysadmin.android.sizzle.io.MidiMapIo
val map = io.parse(text) ?: return "This doesn't look like a Sizzle MIDI mapping (.szm)."
val slot = project.toolbox.getOrNull(slotIndex) ?: return "No device here."
if (slot.type?.name != map.type) {
val want = runCatching { ToolboxType.valueOf(map.type).displayName }.getOrDefault(map.type)
return "This mapping is for a $want, not a ${slot.type?.displayName ?: "empty slot"}."
}
io.apply(project, slotIndex, map)
touched()
return null
}
/** Remove the MIDI-CC binding for [slotIndex]'s [paramKey]. */
fun clearParamCc(slotIndex: Int, paramKey: String) {
project.toolbox.getOrNull(slotIndex)?.values?.remove(ccKey(paramKey))
@@ -1069,6 +1104,7 @@ class AppViewModel(
kbdChannel = s.kbdChannel.coerceIn(0, Cell.MAX_CHANNEL)
kbdOctave = s.kbdOctave.coerceIn(0, 8)
vuMeters = s.vuMeters
keepScreenOn = s.keepScreenOn
// MIDI clock sync: the transport/tempo follow and the send thread's
// providers are wired in SizzleApp (they must work with no UI); here we
@@ -1369,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)
}
}
@@ -685,6 +685,12 @@ private fun InterfaceCard(vm: AppViewModel) {
"Show live level meters inside the mixer volume faders.",
vm.vuMeters,
) { vm.updateVuMeters(it) }
HorizontalDivider()
ToggleRow(
"Keep screen on",
"Don't let the screen dim or lock while Sizzle is open.",
vm.keepScreenOn,
) { vm.updateKeepScreenOn(it) }
}
}
@@ -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)
@@ -102,6 +102,24 @@ fun SamplerEditor(vm: AppViewModel, slot: ToolboxSlot, pad: Int, onSelectPad: (I
}
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
// ----- One-shot (the whole Sampler): note-offs don't cut the pads -----
val oneShot = slot.string("oneShot", "Off") == "On"
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
RetroButton("ONE-SHOT", active = oneShot) {
slot.set("oneShot", if (oneShot) "Off" else "On")
vm.bumpForToolbar()
}
Text(
if (oneShot) "Pads play their whole slice; note-offs are ignored."
else "Pads stop on note-off (key release, ===).",
color = c.textDim, fontFamily = FontFamily.Monospace, fontSize = 11.sp,
)
}
// ----- Selected pad + source buttons (act on the selected pad) -----
Text(
"Pad ${pad + 1} · ${Pitch.name(SamplerPads.noteFor(pad))}",
@@ -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
@@ -422,6 +424,16 @@ private fun MidiLearnPopup(vm: AppViewModel, slot: ToolboxSlot, onClose: () -> U
val type = slot.type ?: return
// Always disarm learn when the popup leaves the composition (closed / editor exited).
DisposableEffect(slot.index) { onDispose { vm.cancelParamLearn() } }
val context = LocalContext.current
var importMessage by remember { mutableStateOf<String?>(null) }
// IMPORT: a .szm mapping for this device type replaces this slot's mappings.
val mapImporter = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri == null) return@rememberLauncherForActivityResult
val text = runCatching {
context.contentResolver.openInputStream(uri)?.use { it.readBytes().takeIf { b -> b.size <= 1 shl 20 } }
}.getOrNull()?.toString(Charsets.UTF_8)
importMessage = if (text == null) "Couldn't read the selected file." else vm.importMidiMap(slot.index, text)
}
Box(
Modifier.fillMaxSize().background(c.background.copy(alpha = 0.92f))
@@ -440,10 +452,29 @@ private fun MidiLearnPopup(vm: AppViewModel, slot: ToolboxSlot, onClose: () -> U
) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
Text("MIDI LEARN — ${slot.name}", color = c.accent,
fontFamily = FontFamily.Monospace, fontSize = 14.sp)
fontFamily = FontFamily.Monospace, fontSize = 14.sp, modifier = Modifier.weight(1f))
Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
// Share this device's mapping as a .szm text file / take one in.
Text("EXPORT", color = c.accent, fontFamily = FontFamily.Monospace, fontSize = 13.sp,
modifier = Modifier.pointerInput(Unit) {
detectTapGestures {
vm.midiMapExportFile(slot.index)?.let { f ->
val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", f)
val send = Intent(Intent.ACTION_SEND).apply {
this.type = "text/plain"
putExtra(Intent.EXTRA_STREAM, uri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
context.startActivity(Intent.createChooser(send, "Share MIDI mapping"))
}
}
})
Text("IMPORT", color = c.accent, fontFamily = FontFamily.Monospace, fontSize = 13.sp,
modifier = Modifier.pointerInput(Unit) { detectTapGestures { mapImporter.launch(arrayOf("*/*")) } })
Text("DONE", color = c.textDim, fontFamily = FontFamily.Monospace, fontSize = 13.sp,
modifier = Modifier.pointerInput(Unit) { detectTapGestures { onClose() } })
}
}
Text(
"Tap LEARN, then move a knob/fader on your MIDI controller.",
color = c.textDim, fontFamily = FontFamily.Monospace, fontSize = 10.sp,
@@ -481,6 +512,14 @@ private fun MidiLearnPopup(vm: AppViewModel, slot: ToolboxSlot, onClose: () -> U
}
}
}
importMessage?.let { msg ->
AlertDialog(
onDismissRequest = { importMessage = null },
title = { Text("Import failed") },
text = { Text(msg) },
confirmButton = { TextButton(onClick = { importMessage = null }) { Text("OK") } },
)
}
}
/**
@@ -495,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
@@ -552,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
@@ -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
@@ -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
@@ -166,6 +166,7 @@ class IosGoldenInstruments {
val s = SampleStore.get(slot.string(SamplerPads.key(pad))) ?: return
v.noteOn(s, note, velocity, note, slot.float(SamplerPads.sliceStartKey(pad), 0f),
slot.float(SamplerPads.sliceEndKey(pad), 1f), slot.float(SamplerPads.volumeKey(pad), SamplerPads.DEFAULT_VOLUME))
v.oneShot = slot.string("oneShot", "Off") == "On"
} else {
val s = SampleStore.get(slot.string("sfSample")) ?: return
v.noteOn(s, note, velocity, slot.float("sfRoot", 60f).toInt(), 0f, 1f, slot.float("volume", 0.8f),
@@ -0,0 +1,41 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.audio
import cc.tiredsysadmin.android.sizzle.io.PresetLibrary
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
import cc.tiredsysadmin.android.sizzle.model.ToolboxType
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.io.File
import java.nio.file.Files
/**
* Writes a Sampler preset bundle with Android's own PresetLibrary (save, then
* bundleForShare: what SHARE sends) to SIZZLE_GOLDEN_DIR/bundles/android_sampler.zip,
* for core/tests/bundle_test.cpp to import as the iOS app does. The kit: pad 0 =
* 100 frames at 44.1 kHz (start 0.25), pad 3 = 200 frames at 22.05 kHz.
* Runs only when SIZZLE_GOLDEN_DIR is set (`make -C ios golden`).
*/
class IosGoldenPresetBundle {
@Test
fun writeAndroidBundle() {
val out = System.getenv("SIZZLE_GOLDEN_DIR")
assumeTrue(out != null)
fun ramp(frames: Int, rate: Int) = SampleStore.Sample(FloatArray(frames) { it.toFloat() / frames - 0.5f }, rate)
SampleStore.put("golden-kick", ramp(100, 44_100))
SampleStore.put("golden-snare", ramp(200, 22_050))
val slot = ToolboxSlot(0).apply {
fill(ToolboxType.SAMPLER)
set("pad0", "golden-kick")
set("pad0S", 0.25f)
set("pad3", "golden-snare")
}
val lib = PresetLibrary(Files.createTempDirectory("presets").toFile())
lib.save(slot, "Kit")
val zip = lib.bundleForShare(ToolboxType.SAMPLER, "Kit")!!
val dir = File(out, "bundles").apply { mkdirs() }
zip.copyTo(File(dir, "android_sampler.zip"), overwrite = true)
}
}
@@ -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
@@ -1056,9 +1056,11 @@ class ReferenceEngine(
val vs = voiceSample(slot, note)
when {
vs != null ->
allocSampleVoice(bus).also { it.ownerTrack = ownerTrack }.noteOn(
vs.sample, note, velocity, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume,
allocSampleVoice(bus).also { it.ownerTrack = ownerTrack }.apply {
noteOn(vs.sample, note, velocity, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume,
vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs)
oneShot = vs.oneShot
}
// Empty bus (no instrument — e.g. the default channel 0) or a Sampler
// with an empty pad → silent, matching the live audition path.
slot?.type == null || slot.type == ToolboxType.SAMPLER -> {}
@@ -1079,6 +1081,7 @@ class ReferenceEngine(
val attack: Float = 0.002f, val decay: Float = 0f,
val sustain: Float = 1f, val release: Float = 0.02f,
val loop: Boolean = false, val crossfadeMs: Float = 0f,
val oneShot: Boolean = false,
)
/**
@@ -1101,6 +1104,7 @@ class ReferenceEngine(
slot.float(SamplerPads.sliceStartKey(pad), 0f),
slot.float(SamplerPads.sliceEndKey(pad), 1f),
slot.float(SamplerPads.volumeKey(pad), SamplerPads.DEFAULT_VOLUME),
oneShot = slot.string("oneShot", "Off") == "On",
)
}
}
@@ -1282,6 +1286,7 @@ class ReferenceEngine(
val v = auditionSampleVoices.firstOrNull { !it.isActive } ?: auditionSampleVoices[0].also { it.kill() }
v.noteOn(vs.sample, midi, 110, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume,
vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs)
v.oneShot = vs.oneShot
return
}
// A Sampler with an empty pad stays silent (audition is a one-shot with no
@@ -1337,6 +1342,7 @@ class ReferenceEngine(
val v = freeBusVoice(busSampleVoices, base)
v.noteOn(vs.sample, midi, velocity, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume,
vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs)
v.oneShot = vs.oneShot
}
// Sampler with an empty pad → silent (no synth fallback).
type == ToolboxType.SAMPLER -> {}
@@ -1559,7 +1565,7 @@ class ReferenceEngine(
private fun allSeqVoicesOff() {
clouds.forEach { it.releaseSequenced() }
seqVoices.forEach { it.noteOff() }
sampleVoices.forEach { it.noteOff() }
sampleVoices.forEach { it.release() } // a stopped song stops One-shot pads too
arps.forEach { it.stop() }
allMidiNotesOff() // release any notes we sent to external gear
}
@@ -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
@@ -86,6 +92,7 @@ class SampleVoice(private val engineSampleRate: Int) {
attack: Float = 0.002f, decay: Float = 0f, sustain: Float = 1f, release: Float = 0.02f,
loop: Boolean = false, crossfadeMs: Float = 0f,
) {
oneShot = false // the caller sets it again for a One-shot Sampler
// Carry the level we're interrupting so the new note starts continuously
// (the new note fades in from ~0; without this the sum would jump from the
// old voice's level straight to ~0 → a click when stealing a loud voice).
@@ -139,8 +146,15 @@ class SampleVoice(private val engineSampleRate: Int) {
endGain = 1f
}
/** Playing a One-shot Sampler pad: [noteOff] leaves it be (it plays to its slice
* end); [release] still fades it. Reset by [noteOn]. */
var oneShot = false
/** A note-off: the release stage, unless the voice is one-shot. */
fun noteOff() { if (!oneShot) release() }
/** Enter the release stage: fade from the current level to 0 over the release time. */
fun noteOff() {
fun release() {
val sr = engineSampleRate.toFloat()
releaseInc = if (releaseSeconds <= 0f) 1f else env / (releaseSeconds * sr)
if (releaseInc <= 0f) releaseInc = 1f
@@ -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
@@ -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
@@ -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,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
@@ -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
@@ -0,0 +1,46 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.io
import cc.tiredsysadmin.android.sizzle.model.Project
import cc.tiredsysadmin.android.sizzle.model.ToolboxType
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Test
/** The same expectations as core/tests/midimap_test.cpp, on the same fixture. */
class MidiMapIoTest {
private val fixture = javaClass.getResource("/midimap/filter.szm")!!.readText()
@Test
fun parsesTheSharedFixture() {
val map = MidiMapIo.parse(fixture)
assertNotNull(map)
assertEquals("FILTER", map!!.type)
assertEquals("Sweep", map.name)
assertEquals(listOf("cutoff" to 74, "resonance" to 71, "nosuchparam" to 20, "release" to 7), map.bindings)
assertNull(MidiMapIo.parse("TYPE=FILTER\ncutoff=1\n"))
assertNull(MidiMapIo.parse("SIZZLE-MIDIMAP 1\ncutoff=1\n"))
}
@Test
fun appliesExportsAndRoundTrips() {
val map = MidiMapIo.parse(fixture)!!
val p = Project()
p.toolbox[2].fill(ToolboxType.FILTER)
p.toolbox[5].fill(ToolboxType.BITCRUSHER)
p.toolbox[5].set("midicc@bits", "71")
p.toolbox[2].set("midicc@warmth", "30")
assertEquals(-1, MidiMapIo.apply(p, 5, map))
assertEquals(3, MidiMapIo.apply(p, 2, map))
assertFalse("midicc@bits" in p.toolbox[5].values)
assertFalse("midicc@warmth" in p.toolbox[2].values)
val applied = listOf("cutoff" to 74, "resonance" to 71, "release" to 7)
val back = MidiMapIo.fromSlot(p.toolbox[2])
assertEquals(applied, back.bindings)
assertEquals(applied, MidiMapIo.parse(MidiMapIo.save(back))!!.bindings)
}
}
@@ -0,0 +1,37 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.io
import cc.tiredsysadmin.android.sizzle.audio.SampleStore
import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot
import cc.tiredsysadmin.android.sizzle.model.ToolboxType
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import java.nio.file.Files
/**
* A Sampler bundle written by the iOS app (core/src/io/PresetBundle, the fixture
* core/tests/bundle_test.cpp checks byte for byte) imports here like Android's own:
* pad 0 = 100 frames at 44.1 kHz starting at 0.25, pad 3 = 200 frames at 22.05 kHz.
*/
class PresetBundleInteropTest {
@Test
fun importsTheIosBundle() {
val bytes = javaClass.getResource("/presetbundle/ios_sampler.zip")!!.readBytes()
val lib = PresetLibrary(Files.createTempDirectory("presets").toFile())
val slot = ToolboxSlot(0).apply { fill(ToolboxType.FILTER) }
assertTrue(lib.importZip(slot, bytes.inputStream()))
assertEquals(ToolboxType.SAMPLER, slot.type)
// (No name check: Android's PresetIo.import replaces the name with the device's, for its own bundles too.)
val pad0 = SampleStore.get(slot.string("pad0"))!!
val pad3 = SampleStore.get(slot.string("pad3"))!!
assertEquals(100, pad0.data.size)
assertEquals(44_100, pad0.sampleRate)
assertEquals(200, pad3.data.size)
assertEquals(22_050, pad3.sampleRate)
assertEquals(0.25f, slot.float("pad0S"))
assertEquals("", slot.string("pad1"))
}
}
@@ -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
+13
View File
@@ -0,0 +1,13 @@
SIZZLE-MIDIMAP 1
# A shared fixture: core/tests/midimap_test.cpp and MidiMapIoTest.kt read it.
TYPE=FILTER
NAME=Sweep
cutoff = 74
resonance=71
cutoff=12
warmth=74
envamt=300
nosuchparam=20
garbage line
decay=x
release=7
Binary file not shown.
+3 -1
View File
@@ -64,8 +64,10 @@ inline const ParamSpec NES_SYNTH_params[] = {
{"m3amt", "Mod4 Amt", 0.0f, -1.0f, 1.0f, false, nullptr},
};
inline const char *const SAMPLER_c1[] = {"Off", "On", nullptr};
inline const ParamSpec SAMPLER_params[] = {
{"volume", "Volume", 0.8f, 0.0f, 1.0f, false, nullptr},
{"oneShot", "One-shot", 0.0f, 0.0f, 1.0f, false, SAMPLER_c1},
};
inline const char *const SOUNDFONT_c6[] = {"Off", "On", nullptr};
@@ -309,7 +311,7 @@ inline const ParamSpec GRANULAR_params[] = {
inline const DeviceSpec devices[] = {
{"NES_SYNTH", "Synth", Kind::Instrument, NES_SYNTH_params, 43},
{"SAMPLER", "Sampler", Kind::Instrument, SAMPLER_params, 1},
{"SAMPLER", "Sampler", Kind::Instrument, SAMPLER_params, 2},
{"SOUNDFONT", "SF2 / XI Loader", Kind::Instrument, SOUNDFONT_params, 8},
{"MORPH_PAD", "Morph Pad", Kind::Instrument, MORPH_PAD_params, 36},
{"GRAIN_CLOUD", "Grain Cloud", Kind::Instrument, GRAIN_CLOUD_params, 24},
+1
View File
@@ -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"
+2
View File
@@ -25,6 +25,8 @@ public:
void fill(const DeviceSpec &spec);
void set(const char *key, const char *value);
void set(const char *key, float value);
/** Drop [key] (Kotlin's values.remove); the others keep their order. */
void remove(const char *key);
/** Number as Kotlin's String.toFloat would parse it, else [fallback]. */
float f(const char *key, float fallback = 0.f) const;
/** The stored text (enum choice name), else [fallback]. */
+56
View File
@@ -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
+12
View File
@@ -4,6 +4,7 @@
#include "sizzle/Params.hpp"
#include <cctype>
#include <cstdio>
#include <cstring>
namespace sizzle {
@@ -38,6 +39,17 @@ void Params::set(const char *key, const char *value) {
std::snprintf(vals_[i], kValLen, "%s", value);
}
void Params::remove(const char *key) {
const int i = find(key);
if (i < 0) return;
for (int k = i; k + 1 < n_; ++k) { // keep the insertion order of the rest
std::memcpy(keys_[k], keys_[k + 1], kKeyLen);
std::memcpy(vals_[k], vals_[k + 1], kValLen);
}
--n_;
keys_[n_][0] = vals_[n_][0] = '\0';
}
void Params::set(const char *key, float value) {
// Shortest text that reads back as the same float (Kotlin stores toString()).
char buf[kValLen];
-1
View File
@@ -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; }
+27 -5
View File
@@ -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);
}
@@ -855,6 +874,7 @@ void Engine::Impl::playNote(Project &proj, int bus, int note, int velocity, int
v.ownerTrack = ownerTrack;
v.noteOn(*vs.sample, note, velocity, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume,
vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs);
v.oneShot = vs.oneShot;
} else if (!hasType(slot) || is(slot, "SAMPLER")) {
// Empty bus or a Sampler with an empty pad: silent.
} else if (is(slot, "GRAIN_CLOUD")) {
@@ -926,6 +946,7 @@ void Engine::Impl::auditionSlotOn(int slotIndex, int midi) {
if (!v) { v = auditionSampleVoices[0].get(); v->kill(); }
v->noteOn(*vs.sample, midi, 110, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume,
vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs);
v->oneShot = vs.oneShot;
return;
}
if (is(slot, "SAMPLER")) return;
@@ -972,6 +993,7 @@ void Engine::Impl::busNoteOn(int midiChannel, int midi, int velocity) {
if (!v) { v = busSampleVoices[base].get(); v->kill(); }
v->noteOn(*vs.sample, midi, velocity, vs.root, vs.sliceStart, vs.sliceEnd, vs.volume,
vs.attack, vs.decay, vs.sustain, vs.release, vs.loop, vs.crossfadeMs);
v->oneShot = vs.oneShot;
} else if (is(slot, "SAMPLER")) {
} else if (is(slot, "GRAIN_CLOUD")) {
clouds[ch]->noteOn(midi, velocity, GrainCloud::OWNER_LIVE);
@@ -1146,7 +1168,7 @@ void Engine::Impl::refreshSynthPatches(Project &proj) {
void Engine::Impl::allSeqVoicesOff() {
for (auto &c : clouds) c->releaseSequenced();
for (auto &v : seqVoices) v->noteOff();
for (auto &v : sampleVoices) v->noteOff();
for (auto &v : sampleVoices) v->release(); // a stopped song stops One-shot pads too
for (auto &a : arps) a.stop();
allMidiNotesOff();
}
-2
View File
@@ -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:
+97
View File
@@ -0,0 +1,97 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#include "io/MidiMapIo.hpp"
#include <set>
#include "io/KotlinText.hpp"
#include "sizzle/Specs.hpp"
namespace sizzle::io {
namespace {
std::string ccKey(const std::string &param) { return std::string(MidiMapIo::CC_PREFIX) + param; }
/// The CC [slot] maps [param] to, or -1 (Kotlin: string(key).toIntOrNull()).
int ccOf(const model::ToolboxSlot &slot, const std::string &param) {
int v = -1;
return kt::toIntOrNull(slot.s(ccKey(param).c_str(), ""), v) ? v : -1;
}
} // namespace
MidiMap MidiMapIo::fromSlot(const model::ToolboxSlot &slot) {
MidiMap m;
m.type = slot.type;
m.name = slot.name;
if (const DeviceSpec *spec = findDevice(slot.type.c_str())) {
for (int i = 0; i < spec->paramCount; ++i) {
const int cc = ccOf(slot, spec->params[i].key);
if (cc >= 0 && cc <= 127) m.bindings.emplace_back(spec->params[i].key, cc);
}
}
return m;
}
std::string MidiMapIo::save(const MidiMap &map) {
std::string out = std::string(HEADER) + "\n";
out += "# Sizzle MIDI mapping: parameter=CC number (0-127), one per line.\n";
out += "TYPE=" + map.type + "\n";
out += "NAME=" + map.name + "\n";
for (const auto &[key, cc] : map.bindings) out += key + "=" + std::to_string(cc) + "\n";
return out;
}
std::optional<MidiMap> MidiMapIo::parse(const std::string &text) {
MidiMap m;
bool header = false, typed = false;
std::set<std::string> keys;
std::set<int> ccs;
for (const std::string &raw : kt::lines(text)) {
const std::string line = kt::trim(raw);
if (line.empty() || line[0] == '#') continue;
if (line == HEADER) { header = true; continue; }
const size_t eq = line.find('=');
if (eq == std::string::npos || eq == 0) continue;
const std::string key = kt::trim(line.substr(0, eq)), value = kt::trim(line.substr(eq + 1));
if (key == "TYPE") { m.type = value; typed = !value.empty(); continue; }
if (key == "NAME") { m.name = value; continue; }
int cc = -1;
if (!kt::toIntOrNull(value, cc) || cc < 0 || cc > 127 || keys.count(key) || ccs.count(cc)) continue;
keys.insert(key);
ccs.insert(cc);
m.bindings.emplace_back(key, cc);
}
if (!header || !typed) return std::nullopt;
return m;
}
int MidiMapIo::apply(model::Project &project, int slot, const MidiMap &map) {
if (slot < 0 || slot >= model::Project::TOOLBOX_SLOTS) return -1;
model::ToolboxSlot &target = project.toolbox[(size_t)slot];
if (target.type != map.type) return -1;
const DeviceSpec *spec = findDevice(target.type.c_str());
if (!spec) return -1;
for (int i = 0; i < spec->paramCount; ++i) target.values.remove(ccKey(spec->params[i].key).c_str());
int applied = 0;
for (const auto &[key, cc] : map.bindings) {
bool known = false;
for (int i = 0; i < spec->paramCount && !known; ++i) known = key == spec->params[i].key;
if (!known) continue;
// One physical control drives one parameter: take the CC from wherever it was.
for (auto &s : project.toolbox) {
if (s.isEmpty()) continue;
const DeviceSpec *other = findDevice(s.type.c_str());
for (int i = 0; other && i < other->paramCount; ++i)
if (ccOf(s, other->params[i].key) == cc) s.values.remove(ccKey(other->params[i].key).c_str());
}
target.set(ccKey(key).c_str(), std::to_string(cc).c_str());
++applied;
}
++target.version;
return applied;
}
} // namespace sizzle::io
+52
View File
@@ -0,0 +1,52 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// A device's MIDI mapping as plain text (.szm), the same format the Android app
// reads and writes (io/MidiMapIo.kt):
//
// SIZZLE-MIDIMAP 1
// # comments start with '#'
// TYPE=WAVETABLE
// NAME=Lead
// cutoff=74
// resonance=71
//
// One `parameter=CC` line per mapped parameter (CC 0..127), in the device's
// parameter order. In the song a mapping is the slot value `midicc@<parameter>`.
#pragma once
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "sizzle/Model.hpp"
namespace sizzle::io {
struct MidiMap {
std::string type; // ToolboxType name
std::string name; // the slot's name when exported (informational)
std::vector<std::pair<std::string, int>> bindings; // parameter key, CC
};
class MidiMapIo {
public:
static constexpr const char *HEADER = "SIZZLE-MIDIMAP 1";
static constexpr const char *CC_PREFIX = "midicc@";
/** [slot]'s mappings, in its device's parameter order. */
static MidiMap fromSlot(const model::ToolboxSlot &slot);
static std::string save(const MidiMap &map);
/** The mapping in [text], or nothing if it has no header or TYPE. Lines that
* aren't `key=CC` with CC 0..127 are skipped; a repeated key or CC keeps its
* first line (one control drives one parameter). */
static std::optional<MidiMap> parse(const std::string &text);
/** Replace toolbox [slot]'s mappings with [map]'s: only parameters its device
* has; a CC another parameter (of any slot) used moves to this one. Returns
* how many were applied, or -1 when [map] is for another device type. */
static int apply(model::Project &project, int slot, const MidiMap &map);
};
} // namespace sizzle::io
+100
View File
@@ -0,0 +1,100 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#include "io/PresetBundle.hpp"
#include <map>
#include "io/PresetIo.hpp"
#include "io/Zip.hpp"
#include "sampler/SampleStore.hpp"
namespace sizzle::io {
namespace {
constexpr int PADS = 16;
std::string baseNameOf(const std::string &path) {
const size_t slash = path.find_last_of("/\\");
return slash == std::string::npos ? path : path.substr(slash + 1);
}
bool endsWith(const std::string &s, const char *suffix) {
const size_t n = std::char_traits<char>::length(suffix);
return s.size() >= n && s.compare(s.size() - n, n, suffix) == 0;
}
} // namespace
bool PresetBundle::carriesSamples(const std::string &type) {
return type == "SAMPLER" || type == "SOUNDFONT" || type == "GRAIN_CLOUD" || type == "WAVETABLE";
}
bool PresetBundle::importInto(model::ToolboxSlot &slot, const uint8_t *zipBytes, size_t size,
const std::function<std::string(const std::string &, Sample)> &keep) {
std::vector<zip::Entry> entries;
if (!zip::read(zipBytes, size, entries, 64ull << 20)) return false; // ZipLimits.forBundle
std::string preset;
bool havePreset = false;
std::map<std::string, const std::vector<uint8_t> *> files;
for (const auto &e : entries) {
const std::string name = baseNameOf(e.name);
if (name.empty() || e.name.rfind("__MACOSX", 0) == 0 || name.rfind("._", 0) == 0) continue;
if (!havePreset && endsWith(name, ".szp")) { preset.assign(e.data.begin(), e.data.end()); havePreset = true; }
else files.emplace(name, &e.data);
}
if (!havePreset) return false;
model::ToolboxSlot fresh = slot;
if (!PresetIo::importText(fresh, preset)) return false;
auto resolve = [&](const char *fileKey, const char *idKey) {
const std::string ref = fresh.s(fileKey, "");
if (ref.empty()) return;
auto it = files.find(baseNameOf(ref));
if (it == files.end()) return;
auto sample = sampler::SampleStore::decodeWav(it->second->data(), it->second->size());
if (!sample) return;
const std::string id = keep(it->first, std::move(*sample));
if (!id.empty()) fresh.set(idKey, id.c_str());
};
if (fresh.type == "SAMPLER") {
for (int p = 0; p < PADS; ++p) {
const std::string pad = "pad" + std::to_string(p);
resolve((pad + "File").c_str(), pad.c_str());
}
} else if (carriesSamples(fresh.type)) {
resolve("sfFile", "sfSample");
}
slot = fresh;
return true;
}
std::vector<uint8_t> PresetBundle::exportFrom(const model::ToolboxSlot &slot, const std::string &baseName,
const std::function<std::vector<uint8_t>(const std::string &)> &wavOf) {
model::ToolboxSlot copy = slot;
std::vector<zip::Entry> entries;
auto carry = [&](const char *idKey, const char *fileKey, const std::string &fileName) {
const std::string id = copy.s(idKey, "");
copy.values.remove(fileKey);
if (id.empty()) return;
std::vector<uint8_t> wav = wavOf(id);
copy.values.remove(idKey); // a sample id means nothing on another device
if (wav.empty()) return;
copy.set(fileKey, fileName.c_str());
entries.push_back({fileName, std::move(wav)});
};
if (copy.type == "SAMPLER") {
for (int p = 0; p < PADS; ++p) {
const std::string pad = "pad" + std::to_string(p);
carry(pad.c_str(), (pad + "File").c_str(), baseName + "_" + pad + ".wav");
}
} else if (carriesSamples(copy.type)) {
carry("sfSample", "sfFile", baseName + "_sf.wav");
}
const std::string text = PresetIo::exportText(copy);
entries.insert(entries.begin(), zip::Entry{baseName + ".szp", std::vector<uint8_t>(text.begin(), text.end())});
return zip::write(entries);
}
} // namespace sizzle::io
+52
View File
@@ -0,0 +1,52 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// Preset bundles: a device preset with its own sounds, as the Android app shares
// Sampler, SF2/XI, Grain Cloud and Wavetable presets (PresetLibrary.bundleForShare
// / importZip). A ZIP holding `<name>.szp` (PresetIo text) and the WAVs it names:
//
// Kick.szp ... pad0File=Kick_pad0.wav, pad0S=..., pad0E=...
// Kick_pad0.wav
// Pad_sf.wav (sfFile=Pad_sf.wav for SF2/XI, Grain Cloud, Wavetable)
//
// In a song a slot names its sounds by sample id (`padN`, `sfSample`); in a bundle
// by file (`padNFile`, `sfFile`). These functions translate between the two.
#pragma once
#include <functional>
#include <optional>
#include <string>
#include <vector>
#include "sizzle/Model.hpp"
#include "sizzle/Sample.hpp"
namespace sizzle::io {
class PresetBundle {
public:
/** Device types whose presets travel as bundles. */
static bool carriesSamples(const std::string &type);
/**
* Import bundle [zip] into [slot] (which takes the preset's device type, as
* PresetIo::importText). Every WAV the preset names is decoded and handed to
* [keep] (its file name, the sample), which stores it and returns its sample id;
* the slot then plays it (`padN` / `sfSample`). False if [zip] isn't a ZIP or
* holds no valid preset (the slot is then unchanged). The first `.szp` wins;
* macOS `__MACOSX/` and `._` entries are skipped, and only base names count.
*/
static bool importInto(model::ToolboxSlot &slot, const uint8_t *zip, size_t size,
const std::function<std::string(const std::string &file, Sample sample)> &keep);
/**
* [slot] as a bundle named [baseName] (`<baseName>.szp` and its WAVs). [wavOf]
* gives the WAV file bytes of a sample id (empty if unknown: that sound is left
* out). The preset names files instead of sample ids, as Android writes them.
*/
static std::vector<uint8_t> exportFrom(const model::ToolboxSlot &slot, const std::string &baseName,
const std::function<std::vector<uint8_t>(const std::string &id)> &wavOf);
};
} // namespace sizzle::io
+468
View File
@@ -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
+3 -1
View File
@@ -50,6 +50,7 @@ bool voiceSample(const char *type, const Params &slot, const SampleStore &store,
out.sliceStart = slot.f(SamplerPads::sliceStartKey(pad).s, 0.f);
out.sliceEnd = slot.f(SamplerPads::sliceEndKey(pad).s, 1.f);
out.volume = slot.f(SamplerPads::volumeKey(pad).s, SamplerPads::DEFAULT_VOLUME);
out.oneShot = std::strcmp(slot.s("oneShot", "Off"), "On") == 0;
return true;
}
if (std::strcmp(type, "SOUNDFONT") == 0) {
@@ -93,6 +94,7 @@ void SampleVoice::noteOn(const Sample &s, int midi, int velocity, int root,
const int len = (int)s.data.size();
// An empty sample would make Kotlin's coerceIn(startIndex + 1, 0) throw; play nothing.
if (len <= 0) return;
oneShot = false; // the caller sets it again for a One-shot Sampler
// Carry the level we're interrupting so the new note starts continuously.
declick += lastY;
setSample(&s);
@@ -142,7 +144,7 @@ void SampleVoice::noteOn(const Sample &s, int midi, int velocity, int root,
endGain = 1.f;
}
void SampleVoice::noteOff() {
void SampleVoice::release() {
const float sr = (float)engineSampleRate;
releaseInc = releaseSeconds <= 0.f ? 1.f : env / (releaseSeconds * sr);
if (releaseInc <= 0.f) releaseInc = 1.f;
+13 -3
View File
@@ -54,6 +54,8 @@ struct VoiceSample {
float sustain = 1.f, release = 0.02f;
bool loop = false;
float crossfadeMs = 0.f;
/** A Sampler with One-shot on: note-offs don't release the voice. */
bool oneShot = false;
};
/**
@@ -83,6 +85,9 @@ public:
int pitch = -1;
/** Which tracker (lane,track) started this voice, or -1 if unowned. */
int ownerTrack = -1;
/** Playing a One-shot Sampler pad: noteOff() leaves it be, it plays to its slice
* end; release() (transport stop / pause) still fades it. Reset by noteOn. */
bool oneShot = false;
bool isActive() const { return sample != nullptr; }
/** Note is still held (not in its release stage). */
@@ -98,11 +103,16 @@ public:
float attack = 0.002f, float decay = 0.f, float sustain = 1.f, float release = 0.02f,
bool loop = false, float crossfadeMs = 0.f);
void noteOn(const VoiceSample &v, int midi, int velocity) {
if (v.sample) noteOn(*v.sample, midi, velocity, v.root, v.sliceStart, v.sliceEnd, v.volume,
if (!v.sample) return;
noteOn(*v.sample, midi, velocity, v.root, v.sliceStart, v.sliceEnd, v.volume,
v.attack, v.decay, v.sustain, v.release, v.loop, v.crossfadeMs);
oneShot = v.oneShot;
}
/** Enter the release stage: fade from the current level to 0 over the release time. */
void noteOff();
/** A note-off: enter the release stage (fade from the current level to 0 over
* the release time), unless the voice is one-shot. */
void noteOff() { if (!oneShot) release(); }
/** Enter the release stage whatever the note (transport stop / pause). */
void release();
void kill();
float render();
+277
View File
@@ -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;
}
+91
View File
@@ -0,0 +1,91 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// io::PresetBundle both ways with the Android app:
// argv[1]: a Sampler bundle Android's PresetLibrary wrote (IosGoldenPresetBundle;
// core/golden/bundles/android_sampler.zip), imported here;
// argv[2]: app/src/test/resources/presetbundle/ios_sampler.zip, the bundle this
// code writes, which Android's PresetBundleInteropTest imports. Checked
// byte for byte here (`--write` regenerates it).
// Both hold the same kit: pad 0 = 100 frames at 44.1 kHz (start 0.25), pad 3 = 200
// frames at 22.05 kHz.
#include "io/PresetBundle.hpp"
#include "io/PresetIo.hpp"
#include "sampler/SampleStore.hpp"
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iterator>
#include <map>
using namespace sizzle;
static int failures = 0;
#define CHECK(c) do { if (!(c)) { std::printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #c); ++failures; } } while (0)
static std::vector<uint8_t> readFile(const char *path) {
std::ifstream f(path, std::ios::binary);
return std::vector<uint8_t>((std::istreambuf_iterator<char>(f)), {});
}
static Sample ramp(int frames, int rate) {
std::vector<float> d((size_t)frames);
for (int i = 0; i < frames; ++i) d[(size_t)i] = (float)i / (float)frames - 0.5f;
return Sample(std::move(d), rate);
}
/// Imports [zip] and checks it is the kit; samples kept by file name.
static void checkKit(const std::vector<uint8_t> &zip, const char *what) {
std::map<std::string, Sample> kept;
model::ToolboxSlot slot;
slot.fill("FILTER"); // the bundle's type replaces it
const bool ok = io::PresetBundle::importInto(slot, zip.data(), zip.size(), [&](const std::string &file, Sample s) {
kept[file] = std::move(s);
return "id:" + file;
});
std::printf(" %s: %s\n", what, ok ? "imported" : "NOT imported");
CHECK(ok && slot.type == "SAMPLER");
const std::string p0 = slot.s("pad0", ""), p3 = slot.s("pad3", "");
CHECK(p0.rfind("id:", 0) == 0 && p3.rfind("id:", 0) == 0 && !*slot.s("pad1", ""));
CHECK(kept.count(p0.substr(3)) && kept[p0.substr(3)].data.size() == 100 && kept[p0.substr(3)].sampleRate == 44100);
CHECK(kept.count(p3.substr(3)) && kept[p3.substr(3)].data.size() == 200 && kept[p3.substr(3)].sampleRate == 22050);
CHECK(slot.f("pad0S", -1) == 0.25f);
}
int main(int argc, char **argv) {
if (argc < 3) { std::printf("usage: bundle_test <android_sampler.zip|-> <ios_sampler.zip> [--write]\n"); return 2; }
// The kit as an iOS slot: pads name sample ids.
std::map<std::string, Sample> store;
store["kick#1"] = ramp(100, 44100);
store["snare#2"] = ramp(200, 22050);
model::ToolboxSlot slot;
slot.fill("SAMPLER");
slot.name = "Kit";
slot.set("pad0", "kick#1");
slot.set("pad0S", 0.25f);
slot.set("pad3", "snare#2");
const auto zip = io::PresetBundle::exportFrom(slot, "Kit", [&](const std::string &id) {
auto it = store.find(id);
return it == store.end() ? std::vector<uint8_t>() : sampler::SampleStore::encodeWav(it->second);
});
checkKit(zip, "own bundle");
if (argc > 3 && !std::strcmp(argv[3], "--write")) {
std::ofstream(argv[2], std::ios::binary).write((const char *)zip.data(), (std::streamsize)zip.size());
std::printf(" wrote %s\n", argv[2]);
} else {
CHECK(readFile(argv[2]) == zip); // the fixture Android imports is what this code writes
}
if (std::strcmp(argv[1], "-")) {
const auto android = readFile(argv[1]);
if (android.empty()) std::printf(" (no Android bundle at %s: run `make golden`)\n", argv[1]);
else checkKit(android, "Android bundle");
}
std::printf(failures ? "bundle_test: %d failure(s)\n" : "bundle_test: ok\n", failures);
return failures ? 1 : 0;
}
+1 -1
View File
@@ -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;
+52
View File
@@ -0,0 +1,52 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// io::MidiMapIo against the fixture the Android test reads too
// (argv[1]: app/src/test/resources/midimap/filter.szm).
#include "io/MidiMapIo.hpp"
#include "io/ProjectIo.hpp"
#include <cstdio>
#include <fstream>
#include <sstream>
using namespace sizzle;
static int failures = 0;
#define CHECK(c) do { if (!(c)) { std::printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #c); ++failures; } } while (0)
int main(int argc, char **argv) {
if (argc < 2) { std::printf("usage: midimap_test <filter.szm>\n"); return 2; }
std::ifstream f(argv[1]);
std::stringstream ss;
ss << f.rdbuf();
const auto map = io::MidiMapIo::parse(ss.str());
CHECK(map && map->type == "FILTER" && map->name == "Sweep");
// Repeated key, repeated CC, CC out of range and junk lines are skipped.
const std::vector<std::pair<std::string, int>> want = {{"cutoff", 74}, {"resonance", 71}, {"nosuchparam", 20}, {"release", 7}};
CHECK(map && map->bindings == want);
CHECK(!io::MidiMapIo::parse("TYPE=FILTER\ncutoff=1\n")); // no header
CHECK(!io::MidiMapIo::parse("SIZZLE-MIDIMAP 1\ncutoff=1\n")); // no type
model::Project p;
p.toolbox[2].fill("FILTER");
p.toolbox[5].fill("BITCRUSHER");
p.toolbox[5].set("midicc@bits", "71"); // CC 71 moves to the filter
p.toolbox[2].set("midicc@warmth", "30"); // replaced by the import
CHECK(io::MidiMapIo::apply(p, 5, *map) == -1); // another device
CHECK(io::MidiMapIo::apply(p, 2, *map) == 3); // nosuchparam skipped
CHECK(!p.toolbox[5].values.has("midicc@bits"));
CHECK(!p.toolbox[2].values.has("midicc@warmth"));
const io::MidiMap back = io::MidiMapIo::fromSlot(p.toolbox[2]);
const std::vector<std::pair<std::string, int>> applied = {{"cutoff", 74}, {"resonance", 71}, {"release", 7}};
CHECK(back.bindings == applied && back.type == "FILTER");
// Round trip, and the mapping survives the song file.
CHECK(io::MidiMapIo::parse(io::MidiMapIo::save(back))->bindings == applied);
model::Project q;
io::ProjectIo::loadInto(q, io::ProjectIo::save(p));
CHECK(io::MidiMapIo::fromSlot(q.toolbox[2]).bindings == applied);
std::printf(failures ? "midimap_test: %d failure(s)\n" : "midimap_test: ok\n", failures);
return failures ? 1 : 0;
}
+79
View File
@@ -0,0 +1,79 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
// The Sampler's One-shot: a note-off (MIDI or the tracker) doesn't stop the pad,
// it plays its whole slice; with One-shot off it fades out; stopping the song
// stops it either way.
#include "sampler/SampleStore.hpp"
#include "sizzle/Engine.hpp"
#include "sizzle/Model.hpp"
#include <cmath>
#include <cstdio>
#include <vector>
using namespace sizzle;
static int failures = 0;
#define CHECK(c) do { if (!(c)) { std::printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #c); ++failures; } } while (0)
constexpr int SR = 48000;
/// Peak of [frames] rendered frames.
static float peak(engine::Engine &e, int frames) {
std::vector<float> buf(192 * 2);
float p = 0;
for (int done = 0; done < frames; done += 192) {
e.fillBlock(buf.data(), 192);
for (float v : buf) p = std::max(p, std::fabs(v));
}
return p;
}
enum class Way { Midi, MidiThenPanic, Song, SongThenStop };
/// Pad 0 (C2, MIDI 36) holds a one-second tone; channel 1 plays the Sampler. The
/// pad starts and gets its note-off 125 ms later, from MIDI or from the song (a
/// note on line 0, "===" on line 1 at 120 BPM); returns the peak at 300..400 ms.
static float afterNoteOff(const char *oneShot, Way way) {
sampler::SampleStore store;
std::vector<float> tone(SR);
for (int i = 0; i < SR; ++i) tone[(size_t)i] = 0.5f * std::sin(i * 0.05f);
store.put("tone", Sample(std::move(tone), SR));
model::Project p;
p.toolbox[0].fill("SAMPLER");
p.toolbox[0].set("pad0", "tone");
p.toolbox[0].set("oneShot", oneShot);
p.mixer.channels[0].instrumentSlot = 0;
p.mixer.channels[0].midiChannel = 1;
p.patterns[0].tracks[0][0] = model::Cell{36, 127, 1};
p.patterns[0].tracks[0][1] = model::Cell{model::Cell::OFF, 127, 1};
engine::Engine e(SR, &store);
e.setProject(&p);
e.rebuildArrangement();
e.rebuildFxChains();
const bool song = way == Way::Song || way == Way::SongThenStop;
if (song) e.play(); else e.busNoteOn(1, 36, 127);
peak(e, SR / 8);
if (!song) e.busNoteOff(1, 36);
peak(e, SR / 16); // the song's "===" lands meanwhile
if (way == Way::SongThenStop) e.stop();
if (way == Way::MidiThenPanic) e.panic();
peak(e, SR / 8); // past any release
return peak(e, SR / 10); // ~300..400 ms: still inside the one-second tone
}
int main() {
const float midiOn = afterNoteOff("On", Way::Midi), midiOff = afterNoteOff("Off", Way::Midi);
const float songOn = afterNoteOff("On", Way::Song), songOff = afterNoteOff("Off", Way::Song);
const float stopped = afterNoteOff("On", Way::SongThenStop), panicked = afterNoteOff("On", Way::MidiThenPanic);
std::printf(" after a MIDI note-off: one-shot %.3f, normal %.3f\n", midiOn, midiOff);
std::printf(" after the song's ===: one-shot %.3f, normal %.3f\n", songOn, songOff);
std::printf(" one-shot after Stop %.3f, after panic %.3f\n", stopped, panicked);
CHECK(midiOn > 0.05f && songOn > 0.05f);
CHECK(midiOff < 1e-4f && songOff < 1e-4f);
CHECK(stopped < 1e-4f && panicked < 1e-4f);
std::printf(failures ? "oneshot_test: %d failure(s)\n" : "oneshot_test: ok\n", failures);
return failures ? 1 : 0;
}
+270
View File
@@ -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 {
+208 -53
View File
@@ -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
@@ -776,6 +868,41 @@ attack=0.01
```
Copy/paste from the Toolbox parameter editor uses this exact text.
### Preset bundle (`.zip`)
What SHARE sends for a Sampler, SF2/XI, Grain Cloud or Wavetable preset: a ZIP
holding `<name>.szp` and the WAVs it names. In a song, pads name sample ids
(`padN`, `sfSample`); in a bundle they name files (`padNFile=<name>_padN.wav`,
`sfFile=<name>_sf.wav`). Android: `PresetLibrary.bundleForShare` / `importZip`.
iOS: `core/src/io/PresetBundle`. The two are checked against each other.
`IosGoldenPresetBundle` (part of `make -C ios golden`) writes a bundle with
Android's code for `core/tests/bundle_test.cpp` to import. `bundle_test` also
writes `app/src/test/resources/presetbundle/ios_sampler.zip` (checked byte for
byte), which `PresetBundleInteropTest` imports with Android's code.
### MIDI mapping (`MidiMapIo`, `.szm`, 0.39.0)
One device's parameter → MIDI CC mapping, exported and imported from the ⇄ MIDI
panel. Written and read by `io/MidiMapIo.kt` (Android) and
`core/src/io/MidiMapIo` (iOS); both tests read the same fixture,
`app/src/test/resources/midimap/filter.szm`.
```
SIZZLE-MIDIMAP 1
# comments start with '#'
TYPE=FILTER
NAME=Sweep
cutoff=74
resonance=71
```
The header and `TYPE` (a `ToolboxType` name) are required; `NAME` is the slot's
name, for information. Then one `parameter=CC` line per mapping (CC 0..127), in
the device's parameter order. Reading skips anything else, and a repeated
parameter or CC keeps its first line. Importing needs the same `TYPE` and
replaces the slot's mappings. Parameters the device doesn't have are skipped,
and a CC that another parameter (in any slot) used moves to the imported one,
because one control drives one parameter. In the song, a mapping is the slot
value `midicc@<parameter>`.
### Interchange `.sng` (`SngFormat`)
The desktop sizzletracker format, read the way the desktop reader does it:
`block <name...> <length> <numTracks>` (names may contain spaces; the trailing
@@ -821,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
@@ -858,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
@@ -874,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
@@ -898,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.
---
+22
View File
@@ -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
+69
View File
@@ -5,6 +5,75 @@ 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
the screen (rotating the iPad): the Mix tab's ● ARM / TAIL / SHARE bar, the
Sampler's slice markers, the LFO's target and the audition keyboards. They now
redraw as soon as the song changes. (SwiftUI skipped them because none of their
own inputs changed.)
## 0.41.0 (build 76)
- Keep screen on: a Setup › Interface toggle that turns the idle timer off while
Sizzle is open (remembered, and in backups). (Android has the same in 0.41.0.)
## 0.40.0 (build 75)
- Sampler One-shot: a ONE-SHOT toggle above the pad tools (also in the Sampler's
card and as the plugin's "One-shot" parameter). On, note-offs (key release,
`===`, the next note on the track) don't cut a pad; it plays its whole slice.
Stop / pause still fade the song's pads; MIDI PANIC silences everything.
(Android has the same in 0.40.0.)
## 0.39.1 (build 74)
- Fix: a Sampler preset shared from Android (a .zip with the preset and its
WAVs) failed with "Couldn't import this preset". Preset IMPORT now takes these
bundles, for the Sampler, SF2/XI loader, Grain Cloud and Wavetable, and their
sounds come along. SHARE sends the same kind of bundle, so presets with samples
also go from iOS to Android (before, they named iOS-only sample ids).
## 0.39.0 (build 73)
- MIDI mappings as files: EXPORT / IMPORT in each device's ⇄ MIDI sheet share a
device's CC mapping as a plain-text `.szm` file (the same files as Android).
Clearing a mapping now removes it from the song instead of leaving it empty.
(Android has the same in 0.39.0.)
## 0.38.0 (build 72)
- Bluetooth LE MIDI controllers: Setup › MIDI Sync › Bluetooth MIDI › Find
+46 -5
View File
@@ -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
@@ -82,6 +88,33 @@ build/core/host_test: $(CORE_SRC) $(CORE_HDR) ../core/tests/host_test.cpp
mkdir -p build/core
$(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) ../core/tests/host_test.cpp
build/core/midimap_test: $(CORE_SRC) $(CORE_HDR) ../core/tests/midimap_test.cpp
mkdir -p build/core
$(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) ../core/tests/midimap_test.cpp
build/core/bundle_test: $(CORE_SRC) $(CORE_HDR) ../core/tests/bundle_test.cpp
mkdir -p build/core
$(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) ../core/tests/bundle_test.cpp
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
@@ -98,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 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
@@ -106,6 +139,10 @@ core-test: build/core/golden_test build/core/sampler_test build/core/engine_test
build/core/io_test $(GOLDEN)/songs ../app/src/test/resources/mikroseq
build/core/midi_test
build/core/host_test $(GOLDEN)/songs
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
@@ -158,8 +195,12 @@ app/FX/Info.plist app/FX/Components.gen.h: app/components.txt tools/gen_componen
python3 tools/gen_components.py app/components.txt app/FX/Info.plist app/FX/Components.gen.h
project: $(PROJECT)/project.pbxproj
$(PROJECT)/project.pbxproj: app/project.yml app/FX/Info.plist
# The folders too: a directory's time changes when a file is added or removed, and
# the generated project lists every source file.
SRC_DIRS := $(shell find app ../core/src ../core/include -type d -not -path '*.xcodeproj*')
$(PROJECT)/project.pbxproj: app/project.yml app/FX/Info.plist $(SRC_DIRS)
cd app && xcodegen generate --spec project.yml --quiet
touch $@
# Device: build without signing, then ad-hoc sign inside-out (extension first) with
# each target's entitlements. TrollStore re-signs at install and keeps them.
@@ -201,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
View File
@@ -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;
+1 -1
View File
@@ -6,7 +6,7 @@
],
"SAMPLER": [
{"title": "Sampler", "panels": [
{"title": "Sampler", "tone": "SOURCE", "keys": ["volume"]}]}
{"title": "Sampler", "tone": "SOURCE", "keys": ["volume", "oneShot"]}]}
],
"SOUNDFONT": [
{"title": "SF2 / XI Loader", "panels": [
+1
View File
@@ -12,6 +12,7 @@ enum AppBoot {
let session = SizzleSession.shared
session.recordTailBars = settings.recordTailBars
ThemeLibrary.shared.select(settings.paletteName)
settings.applyKeepScreenOn()
let input = InputController.shared
input.app = AppModel.main
+38 -6
View File
@@ -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,12 +45,33 @@ final class AppModel: ObservableObject {
init() {
observer = NotificationCenter.default.addObserver(forName: .SizzleSessionDidChange, object: nil, queue: .main) { [weak self] _ in
Task { @MainActor in self?.revision += 1 }
// 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() }
}
timer = Timer.scheduledTimer(withTimeInterval: 1.0 / 30, repeats: true) { [weak self] _ in
Task { @MainActor in 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
@@ -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()
}
}
+17 -2
View File
@@ -2,6 +2,9 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import Foundation
#if canImport(UIKit)
import UIKit
#endif
/// App-level settings that persist across launches (Android's SettingsStore and
/// BindingStore). Song, mixer and toolbox settings live in the project instead.
@@ -21,6 +24,16 @@ final class AppSettings: ObservableObject {
@Published var kbdOctave: Int { didSet { d.set(kbdOctave, forKey: "kbdOctave") } }
/// The live meters inside the mixer's volume faders.
@Published var vuMeters: Bool { didSet { d.set(vuMeters, forKey: "vuMeters") } }
/// Keep the screen on while Sizzle is in front (the idle timer off).
@Published var keepScreenOn: Bool {
didSet { d.set(keepScreenOn, forKey: "keepScreenOn"); applyKeepScreenOn() }
}
func applyKeepScreenOn() {
#if canImport(UIKit)
UIApplication.shared.isIdleTimerDisabled = keepScreenOn
#endif
}
/// Send MIDI clock, Start/Stop and the sequenced notes to MIDI destinations.
@Published var sendMidiClock: Bool { didSet { d.set(sendMidiClock, forKey: "midiClockSend") } }
/// Follow an external MIDI clock's tempo and Start/Stop.
@@ -45,6 +58,7 @@ final class AppSettings: ObservableObject {
kbdChannel = d.object(forKey: "kbdChannel") as? Int ?? 1
kbdOctave = d.object(forKey: "kbdOctave") as? Int ?? 3
vuMeters = d.object(forKey: "vuMeters") as? Bool ?? true
keepScreenOn = d.bool(forKey: "keepScreenOn")
sendMidiClock = d.bool(forKey: "midiClockSend")
receiveMidiClock = d.bool(forKey: "midiClockRecv")
soundModule = d.bool(forKey: "soundModule")
@@ -61,7 +75,7 @@ final class AppSettings: ObservableObject {
// MARK: Backup text
private static let keys = ["palette", "recordTailBars", "kbdChannel", "kbdOctave", "vuMeters", "midiClockSend",
"midiClockRecv", "soundModule", "midiSourcesOff", "bleMidiDevices", "bindKeyboard",
"midiClockRecv", "soundModule", "keepScreenOn", "midiSourcesOff", "bleMidiDevices", "bindKeyboard",
"bindGamepad", "bindMidi"]
/// Every setting as `key=value` lines; multi-line values (bindings, the source
@@ -73,7 +87,7 @@ final class AppSettings: ObservableObject {
let text: String
switch v {
case let a as [String]: text = a.joined(separator: "\n")
case let n as NSNumber where k == "vuMeters" || k.hasPrefix("midiClock") || k == "soundModule": text = n.boolValue ? "true" : "false"
case let n as NSNumber where k == "vuMeters" || k.hasPrefix("midiClock") || k == "soundModule" || k == "keepScreenOn": text = n.boolValue ? "true" : "false"
default: text = "\(v)"
}
lines.append(k + "=" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\n", with: "\\n"))
@@ -100,6 +114,7 @@ final class AppSettings: ObservableObject {
if let v = map["midiClockSend"] { sendMidiClock = v == "true" }
if let v = map["midiClockRecv"] { receiveMidiClock = v == "true" }
if let v = map["soundModule"] { soundModule = v == "true" }
if let v = map["keepScreenOn"] { keepScreenOn = v == "true" }
if let v = map["midiSourcesOff"] { midiSourcesOff = Set(v.split(separator: "\n").map(String.init)) }
if let v = map["bleMidiDevices"] {
bleMidiDevices = Dictionary(v.split(separator: "\n").map { e -> (String, String) in
+2 -1
View File
@@ -158,7 +158,7 @@ final class InputController: ObservableObject {
func paramCc(slot: Int, key: String) -> Int? { Int(session.value(ofSlot: slot, key: Self.ccPrefix + key)) }
func clearParamCc(slot: Int, key: String) { session.setValue("", ofSlot: slot, key: Self.ccPrefix + key) }
func clearParamCc(slot: Int, key: String) { session.removeValue(ofSlot: slot, key: Self.ccPrefix + key) }
private func onRaw(_ source: InputSource, _ code: Int, _ value: Float, _ modifier: Int) {
if let key = paramLearnKey {
@@ -187,6 +187,7 @@ final class InputController: ObservableObject {
clearParamCc(slot: s, key: spec.key)
}
}
// (Same rule as MidiMapIo.apply: one control drives one parameter.)
session.setValue(String(cc), ofSlot: slot, key: Self.ccPrefix + key)
}
-5
View File
@@ -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 }
+3
View File
@@ -50,6 +50,9 @@ private struct MixBody: View {
/// external MIDI clock Start), the FX tail after the stop, and the last take. Takes
/// are saved in Sizzle's Recordings folder (Files app); SHARE sends the last one.
private struct RecordToolbar: View {
/// Redraw when the song changes: these inputs alone never change, so SwiftUI
/// would otherwise keep showing the old state.
@ObservedObject private var watch = MixSongWatch.shared
let session: SizzleSession
var body: some View {
@@ -62,6 +62,9 @@ struct InterfaceCard: View {
SetupCard(title: "Interface", subtitle: "On-screen display options") {
SetupToggle(title: "Mixer VU meters", detail: "Show live level meters inside the mixer volume faders.",
isOn: settings.vuMeters) { settings.vuMeters = $0 }
SetupDivider()
SetupToggle(title: "Keep screen on", detail: "Don't let the screen dim or lock while Sizzle is open.",
isOn: settings.keepScreenOn) { settings.keepScreenOn = $0 }
}
}
}
@@ -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.
@@ -11,6 +11,9 @@ import UIKit
/// mix bus on the keyboard's MIDI channel; out-of-scale keys are dimmed, unless the
/// channel reaches a Sampler (every pad must stay playable).
struct ToolboxKeyboard: View {
/// Redraw when the song changes: these inputs alone never change, so SwiftUI
/// would otherwise keep showing the old state.
@ObservedObject private var watch = MixSongWatch.shared
let app: AppModel
let channel: Int
let octave: Int
@@ -66,6 +69,9 @@ struct ToolboxKeyboard: View {
/// SlotAuditionKeyboard: an OCT stepper over two octaves that play one toolbox slot
/// directly (the instrument editors pin it under their controls).
struct SlotAuditionKeyboard: View {
/// Redraw when the song changes: these inputs alone never change, so SwiftUI
/// would otherwise keep showing the old state.
@ObservedObject private var watch = MixSongWatch.shared
let slot: Int
@State private var octave = 3
@@ -6,12 +6,15 @@ import SwiftUI
/// Android's MidiLearnPopup: every parameter of the slot with its MIDI CC. LEARN,
/// then move a knob or fader on a MIDI controller; ✕ removes the binding. The
/// bindings are saved in the song (`midicc@<key>` slot values), as on Android.
/// EXPORT shares them as a .szm text file; IMPORT takes one for this device type.
struct MidiLearnSheet: View {
let slot: Int
let type: String
@ObservedObject private var input = InputController.shared
@ObservedObject private var watch = MixSongWatch.shared
@Environment(\.dismiss) private var dismiss
@State private var importing = false
@State private var importError: String?
var body: some View {
let session = SizzleSession.shared
@@ -19,6 +22,12 @@ struct MidiLearnSheet: View {
HStack {
Text("MIDI LEARN — \(session.name(ofSlot: slot))").font(Theme.mono(14)).foregroundColor(Theme.accent)
Spacer()
Text("EXPORT").font(Theme.mono(13)).foregroundColor(Theme.accent)
.contentShape(Rectangle()).onTapGesture(perform: export)
.padding(.trailing, 14)
Text("IMPORT").font(Theme.mono(13)).foregroundColor(Theme.accent)
.contentShape(Rectangle()).onTapGesture { importing = true }
.padding(.trailing, 14)
Text("DONE").font(Theme.mono(13)).foregroundColor(Theme.dim)
.contentShape(Rectangle()).onTapGesture { dismiss() }
}
@@ -46,5 +55,32 @@ struct MidiLearnSheet: View {
.background(Theme.surface.ignoresSafeArea())
.preferredColorScheme(.dark)
.onDisappear { input.cancelParamLearn() }
// The completion needs nothing but the URL (iOS 15 resets the binding first).
.fileImporter(isPresented: $importing, allowedContentTypes: [.item]) { result in
guard case .success(let url) = result else { return }
do {
let data = try SetupFiles.readData(url, limit: 1 << 20)
guard let text = String(data: data, encoding: .utf8) else { throw SetupFileError.notText }
try SizzleSession.shared.importMidiMapText(text, intoSlot: slot)
} catch {
importError = error.localizedDescription
}
}
.alert("Import failed", isPresented: Binding(get: { importError != nil }, set: { if !$0 { importError = nil } }),
actions: { Button("OK") { importError = nil } }, message: { Text(importError ?? "") })
}
/// The mapping as "<slot name> MIDI.szm", through the share sheet.
private func export() {
let session = SizzleSession.shared
guard let text = session.midiMapText(ofSlot: slot) else { return }
let name = session.name(ofSlot: slot).trimmingCharacters(in: .whitespaces)
let base = SetupFiles.fileStem(name.isEmpty ? type : name) + " MIDI"
do {
let url = try SetupFiles.export(Data(text.utf8), name: base, ext: "szm")
ShareSheet.present(url) { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }
} catch {
importError = error.localizedDescription
}
}
}
@@ -24,7 +24,17 @@ struct SamplerDetail: View {
var body: some View {
let session = SizzleSession.shared
let assigned = !session.value(ofSlot: slot, key: "pad\(pad)").isEmpty
let oneShot = session.value(ofSlot: slot, key: "oneShot") == "On"
VStack(alignment: .leading, spacing: 8) {
// One-shot (the whole Sampler): note-offs don't cut the pads.
HStack(spacing: 8) {
MixKit.Button(label: "ONE-SHOT", active: oneShot) {
session.setValue(oneShot ? "Off" : "On", ofSlot: slot, key: "oneShot")
}
Text(oneShot ? "Pads play their whole slice; note-offs are ignored."
: "Pads stop on note-off (key release, ===).")
.font(Theme.mono(11)).foregroundColor(Theme.dim).lineLimit(2)
}
Text("Pad \(pad + 1) · \(MixKit.pitchName(SamplerPads.note(pad)))").font(Theme.mono(13)).foregroundColor(Theme.accent)
MixKit.HScroll {
HStack(spacing: 8) {
@@ -78,6 +88,9 @@ struct SamplerDetail: View {
/// The selected pad's waveform; drag near a marker to move the slice start / end.
private struct WaveformPage: View {
/// Redraw when the song changes: these inputs alone never change, so SwiftUI
/// would otherwise keep showing the old state.
@ObservedObject private var watch = MixSongWatch.shared
let slot: Int
let pad: Int
@State private var dragging = -1
+16 -2
View File
@@ -147,7 +147,8 @@ struct SlotEditor: View {
let name = url.deletingPathExtension().lastPathComponent
switch kind {
case .preset:
guard let text = String(data: data, encoding: .utf8), session.importPresetText(text, intoSlot: slot) else {
// Preset text, or a bundle with its sounds (how Android shares Sampler presets).
guard session.importPresetData(data, intoSlot: slot) else {
let display = SizzleSession.deviceTypes.first { $0.type == type }?.displayName ?? type
importError = "Couldn't import this preset. The file may be corrupt, or not a valid \(display) preset or bundle."
return
@@ -245,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
@@ -295,7 +306,7 @@ private struct PresetBar: View {
let name = slotName.trimmingCharacters(in: .whitespaces).isEmpty ? displayName : slotName
_ = session.savePreset(ofSlot: slot, name: name)
names = session.libraryPresets(forType: type)
guard let url = session.presetFile(forType: type, name: name) else { return }
guard let url = session.presetShareURL(forType: type, name: name) else { return }
#if canImport(UIKit)
let vc = UIActivityViewController(activityItems: [url], applicationActivities: nil)
let root = UIApplication.shared.connectedScenes.compactMap { ($0 as? UIWindowScene)?.keyWindow }.first?.rootViewController
@@ -314,6 +325,9 @@ private struct PresetBar: View {
/// LfoTargetPicker: every numeric parameter of every other filled slot; choosing
/// one makes the LFO drive it (the parameter's value now is the centre).
private struct LfoTargetPicker: View {
/// Redraw when the song changes: these inputs alone never change, so SwiftUI
/// would otherwise keep showing the old state.
@ObservedObject private var watch = MixSongWatch.shared
let lfo: Int
private struct Target: Hashable {
+9
View File
@@ -19,6 +19,15 @@ NS_ASSUME_NONNULL_BEGIN
/// True for a ZIP archive (bundle or backup) rather than text.
+ (BOOL)isZipData:(NSData *)data;
/// Toolbox [slot]'s MIDI mapping as .szm text (io/MidiMapIo: TYPE, NAME, one
/// `parameter=CC` line each), or nil for an empty slot.
- (nullable NSString *)midiMapTextOfSlot:(NSInteger)slot;
/// Replace [slot]'s MIDI mapping with the .szm [text] (a CC another parameter used
/// moves here). NO with [error] set when it isn't a mapping or is for another device.
- (BOOL)importMidiMapText:(NSString *)text intoSlot:(NSInteger)slot error:(NSError **)error;
/// Remove setting [key] from [slot] (a cleared MIDI mapping).
- (void)removeValueOfSlot:(NSInteger)slot key:(NSString *)key;
/// Everything Sizzle keeps: Documents/songs, themes, presets and samples, the
/// autosaved song, and [settings] as settings.txt. The open song is autosaved first.
- (nullable NSData *)backupDataWithSettings:(NSString *)settings;
+40
View File
@@ -9,7 +9,9 @@
#include <string>
#include <vector>
#include "io/MidiMapIo.hpp"
#include "io/Zip.hpp"
#include "sizzle/Specs.hpp"
using namespace sizzle;
namespace zip = sizzle::io::zip;
@@ -138,6 +140,44 @@ NSString *const kSettings = @"settings.txt";
return [self importProjectText:text error:error];
}
#pragma mark - MIDI mappings
- (nullable NSString *)midiMapTextOfSlot:(NSInteger)slot {
if (slot < 0 || slot >= 16) return nil;
__block std::string text;
[self read:^(const model::Project &p, const engine::Engine &) {
const auto &s = p.toolbox[(size_t)slot];
if (!s.isEmpty()) text = io::MidiMapIo::save(io::MidiMapIo::fromSlot(s));
}];
return text.empty() ? nil : @(text.c_str());
}
- (BOOL)importMidiMapText:(NSString *)text intoSlot:(NSInteger)slot error:(NSError **)error {
const auto map = io::MidiMapIo::parse(text.UTF8String ?: "");
if (!map) {
if (error) *error = filesError(@"This doesn't look like a Sizzle MIDI mapping (.szm).");
return NO;
}
__block int applied = -1;
[self edit:^(model::Project &p, engine::Engine &) { applied = io::MidiMapIo::apply(p, (int)slot, *map); }];
if (applied < 0 && error) {
const DeviceSpec *want = findDevice(map->type.c_str());
const DeviceSpec *have = findDevice([self typeOfSlot:slot].UTF8String);
*error = filesError([NSString stringWithFormat:@"This mapping is for a %s, not a %s.",
want ? want->displayName : map->type.c_str(), have ? have->displayName : "empty slot"]);
}
return applied >= 0;
}
- (void)removeValueOfSlot:(NSInteger)slot key:(NSString *)key {
if (slot < 0 || slot >= 16) return;
std::string k = key.UTF8String ?: "";
[self edit:^(model::Project &p, engine::Engine &) {
p.toolbox[(size_t)slot].values.remove(k.c_str());
++p.toolbox[(size_t)slot].version;
}];
}
#pragma mark - backups
- (nullable NSData *)backupDataWithSettings:(NSString *)settings {
+7
View File
@@ -41,6 +41,13 @@ NS_ASSUME_NONNULL_BEGIN
- (BOOL)importPresetText:(NSString *)text intoSlot:(NSInteger)slot;
/// The preset's file, for sharing (nil when missing).
- (nullable NSURL *)presetFileForType:(NSString *)type name:(NSString *)name;
/// Import a picked preset file into [slot]: preset text, or a bundle (a ZIP with
/// the preset and its WAVs, as Android shares Sampler, SF2/XI, Grain Cloud and
/// Wavetable presets). Saved to the library like importPresetText.
- (BOOL)importPresetData:(NSData *)data intoSlot:(NSInteger)slot;
/// What SHARE sends for a saved preset: a bundle with its sounds (Android's
/// layout) for the device types that carry samples, else the .szp itself.
- (nullable NSURL *)presetShareURLForType:(NSString *)type name:(NSString *)name;
@end
+52
View File
@@ -9,6 +9,7 @@
#include <set>
#include <string>
#include <vector>
#include "io/PresetBundle.hpp"
#include "io/PresetIo.hpp"
#include "sizzle/DeviceSpecs.gen.hpp"
@@ -17,6 +18,7 @@ using namespace sizzle;
/// SizzleSession.mm's own: put back into the store the samples the song refers to.
@interface SizzleSession (MixPrivate)
- (void)rehydrateSamples;
- (NSURL *)sampleURL:(const std::string &)id;
@end
namespace {
@@ -268,6 +270,56 @@ NSString *sanitize(NSString *name) {
return [self savePresetOfSlot:slot name:name.length ? name : [self typeOfSlot:slot]];
}
- (BOOL)importPresetData:(NSData *)data intoSlot:(NSInteger)slot {
if (slot < 0 || slot >= model::Project::TOOLBOX_SLOTS) return NO;
if (data.length < 4 || memcmp(data.bytes, "PK\x03\x04", 4)) {
NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return text && [self importPresetText:text intoSlot:slot];
}
// A bundle: each sound becomes one of the song's samples (store + Documents/samples).
__block model::ToolboxSlot fresh;
[self read:^(const model::Project &p, const engine::Engine &) { fresh = p.toolbox[(size_t)slot]; }];
sampler::SampleStore &store = [self sampleStore];
const bool ok = io::PresetBundle::importInto(fresh, (const uint8_t *)data.bytes, data.length,
[self, &store](const std::string &file, Sample sample) {
std::string stem = file.substr(0, file.rfind('.'));
std::string id = stem + "#" + NSUUID.UUID.UUIDString.UTF8String;
const auto wav = sampler::SampleStore::encodeWav(sample);
[[NSData dataWithBytes:wav.data() length:wav.size()] writeToURL:[self sampleURL:id] atomically:YES];
store.put(id, std::move(sample));
return id;
});
if (!ok) return NO;
[self edit:^(model::Project &p, engine::Engine &e) {
p.toolbox[(size_t)slot] = fresh;
++p.toolbox[(size_t)slot].version;
e.rebuildFxChains();
}];
NSString *name = [self nameOfSlot:slot];
return [self savePresetOfSlot:slot name:name.length ? name : [self typeOfSlot:slot]];
}
- (nullable NSURL *)presetShareURLForType:(NSString *)type name:(NSString *)name {
NSURL *file = [self presetFileForType:type name:name];
if (!file || !io::PresetBundle::carriesSamples(type.UTF8String)) return file;
NSString *text = [NSString stringWithContentsOfURL:file encoding:NSUTF8StringEncoding error:nil];
model::ToolboxSlot slot;
if (!text || !io::PresetIo::importText(slot, text.UTF8String)) return file;
sampler::SampleStore &store = [self sampleStore];
NSString *base = sanitize(name);
const auto zip = io::PresetBundle::exportFrom(slot, base.UTF8String, [self, &store](const std::string &id) {
if (NSData *d = [NSData dataWithContentsOfURL:[self sampleURL:id]])
return std::vector<uint8_t>((const uint8_t *)d.bytes, (const uint8_t *)d.bytes + d.length);
const Sample *s = store.get(id.c_str());
return s ? sampler::SampleStore::encodeWav(*s) : std::vector<uint8_t>();
});
NSURL *dir = [NSFileManager.defaultManager.temporaryDirectory URLByAppendingPathComponent:@"PresetShare" isDirectory:YES];
[NSFileManager.defaultManager removeItemAtURL:dir error:nil];
[NSFileManager.defaultManager createDirectoryAtURL:dir withIntermediateDirectories:YES attributes:nil error:nil];
NSURL *out = [dir URLByAppendingPathComponent:[base stringByAppendingPathExtension:@"zip"]];
return [[NSData dataWithBytes:zip.data() length:zip.size()] writeToURL:out atomically:YES] ? out : nil;
}
- (NSURL *)presetFileForType:(NSString *)type name:(NSString *)name {
NSURL *u = [self mixPresetURL:type name:name];
return [NSFileManager.defaultManager fileExistsAtPath:u.path] ? u : nil;
+6
View File
@@ -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;
+29
View File
@@ -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
View File
@@ -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
+97 -2
View File
@@ -20,9 +20,12 @@
.bar{display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end;
background:var(--surface);border:1px solid var(--grid);padding:12px;margin-bottom:16px}
label{display:block;font-size:10px;color:var(--dim);margin-bottom:4px;text-transform:uppercase;letter-spacing:.5px}
input[type=text]{background:var(--bg);border:1px solid var(--grid);color:var(--text);
input[type=text],input[type=number]{background:var(--bg);border:1px solid var(--grid);color:var(--text);
font-family:inherit;font-size:14px;padding:8px 10px;width:220px;outline:none}
input[type=text]:focus{border-color:var(--accent)}
input[type=number]{width:96px}
input[type=text]:focus,input[type=number]:focus{border-color:var(--accent)}
.bar .note{font-size:11px;color:var(--dim);align-self:center;max-width:300px;line-height:1.4}
button.over{border-color:var(--play);color:var(--play)}
button{font-family:inherit;font-size:12px;background:var(--surface);color:var(--text);
border:1px solid var(--grid);padding:9px 14px;cursor:pointer;letter-spacing:.5px}
button:hover{border-color:var(--accent);color:var(--accent)}
@@ -78,6 +81,21 @@
<button id="download" class="primary" disabled>⤓ Download .zip</button>
</div>
<!-- One long file (e.g. a GarageBand export) cut into equal slices, one per pad. -->
<div class="bar">
<div>
<label for="bpm">Tempo (BPM)</label>
<input id="bpm" type="number" value="120" min="20" max="400" step="any">
</div>
<div>
<label for="beats">Beats per pad</label>
<input id="beats" type="number" value="4" min="0.25" max="64" step="any">
</div>
<span class="note" id="sliceInfo"></span>
<div class="spacer"></div>
<button id="sliceBtn" title="Or drop the file on this button">✂ Slice one WAV across pads…</button>
</div>
<div class="grid" id="grid"></div>
<div class="status" id="status"></div>
@@ -88,8 +106,16 @@
Pads holding the <strong>same sample</strong> as another pad are tinted <span style="color:var(--danger)">red</span> (matched by audio content, not file name).
Import the downloaded zip via the Sampler's preset toolbar (<code>Import</code>).
</p>
<p class="hint">
<strong>Slicing one file:</strong> export the song from GarageBand as one WAV (Share › Export Song to Disk, WAV),
set its tempo and how many beats each pad gets, then drop the file on <code>✂ Slice one WAV</code> (or click it).
The file is cut at those beat boundaries from its very start (bar 1 must be at 0:00) and the slices fill pads
1, 2, 3… replacing what's there. Silent slices at the end (the export's tail) are left out; a file longer than
16 slices keeps the first 16. Turn on <code>ONE-SHOT</code> in the Sampler so each pad plays its whole slice.
</p>
<input id="filepick" type="file" accept="audio/*,.wav" multiple style="display:none">
<input id="slicepick" type="file" accept="audio/*,.wav" style="display:none">
<script>
"use strict";
@@ -258,6 +284,62 @@ async function loadFiles(pad, fileList){
}
}
// ---- slicing one file into beat-length pads ----
const bpmInput = document.getElementById("bpm");
const beatsInput = document.getElementById("beats");
const sliceInfo = document.getElementById("sliceInfo");
const SILENT = 0.001; // peak below this (-60 dBFS) counts as silence
function sliceSeconds(){
const bpm = parseFloat(bpmInput.value), beats = parseFloat(beatsInput.value);
if (!(bpm >= 20 && bpm <= 400) || !(beats > 0 && beats <= 64)) return 0;
return beats * 60 / bpm;
}
function updateSliceInfo(){
const s = sliceSeconds();
sliceInfo.textContent = s ? ("= " + s.toFixed(3).replace(/\.?0+$/, "") + " s per pad") : "tempo 20-400, beats above 0";
}
// Cut [ab] (decoded) into slices of sliceSeconds(), dropping silent ones at the end,
// and put them on pads 1.. (at most 16). Boundaries are rounded per slice from the
// exact length, so odd tempos don't drift.
function sliceIntoPads(fileName, ab){
const secs = sliceSeconds();
if (!secs){ setStatus("Set a tempo (20-400 BPM) and beats per pad first.", "err"); return 0; }
const mono = toMono(ab), sr = ab.sampleRate, exact = secs * sr;
const total = Math.ceil(mono.length / exact - 1e-9);
const slices = [];
for (let i = 0; i < total; i++){
const a = Math.round(i * exact), b = Math.min(mono.length, Math.round((i + 1) * exact));
if (b > a) slices.push(mono.subarray(a, b));
}
const loud = sl => { for (let i = 0; i < sl.length; i++) if (Math.abs(sl[i]) >= SILENT) return true; return false; };
while (slices.length && !loud(slices[slices.length - 1])) slices.pop();
if (!slices.length){ setStatus("“" + fileName + "” is silent.", "err"); return 0; }
const used = Math.min(PADS, slices.length);
const base = fileName.replace(/\.[^.]+$/, "");
for (let p = 0; p < used; p++){
const data = new Float32Array(slices[p]); // own copy: the WAV writer and the signature read it
const buffer = ctx().createBuffer(1, data.length, sr);
buffer.copyToChannel(data, 0);
pads[p] = { fileName: base + " · " + (p + 1) + "/" + slices.length, mono: data, sampleRate: sr, buffer, sig: sigOf(data, sr) };
}
refresh();
const more = slices.length > PADS ? " (it holds " + slices.length + "; the first 16 were used)" : "";
setStatus("Sliced “" + fileName + "” into " + used + " pad" + (used === 1 ? "" : "s") +
" of " + beatsInput.value + " beats at " + bpmInput.value + " BPM" + more + ".", more ? "err" : "ok");
return used;
}
async function sliceFile(file){
try{
const ab = await ctx().decodeAudioData(await file.arrayBuffer());
sliceIntoPads(file.name, ab);
}catch(e){
setStatus("Could not decode “" + file.name + "” — not a supported audio file.", "err");
}
}
function play(pad){
const s = pads[pad];
if (!s) return;
@@ -309,6 +391,19 @@ for (let p=0;p<PADS;p++){
filepick.addEventListener("change", () => { if (filepick.files.length) loadFiles(pickTarget, filepick.files); });
const sliceBtn = document.getElementById("sliceBtn");
const slicepick = document.getElementById("slicepick");
sliceBtn.addEventListener("click", () => { slicepick.value = ""; slicepick.click(); });
slicepick.addEventListener("change", () => { if (slicepick.files.length) sliceFile(slicepick.files[0]); });
["dragenter","dragover"].forEach(ev => sliceBtn.addEventListener(ev, (e) => { e.preventDefault(); sliceBtn.classList.add("over"); }));
["dragleave","dragend"].forEach(ev => sliceBtn.addEventListener(ev, () => sliceBtn.classList.remove("over")));
sliceBtn.addEventListener("drop", (e) => {
e.preventDefault(); sliceBtn.classList.remove("over");
if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length) sliceFile(e.dataTransfer.files[0]);
});
[bpmInput, beatsInput].forEach(i => i.addEventListener("input", updateSliceInfo));
updateSliceInfo();
// Prevent the browser from navigating when a file is dropped outside a pad.
["dragover","drop"].forEach(ev => window.addEventListener(ev, (e) => e.preventDefault()));
+2 -2
View File
@@ -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.38.0
versionCode = 72
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