Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7041f762e5 | ||
|
|
5240019b47 | ||
|
|
6688718bed |
@@ -5,6 +5,30 @@ 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.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
|
||||
|
||||
@@ -86,6 +86,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 +140,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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
@@ -711,6 +712,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))
|
||||
|
||||
@@ -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))}",
|
||||
|
||||
@@ -422,6 +422,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 +450,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 +510,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") } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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"))
|
||||
}
|
||||
}
|
||||
@@ -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.
@@ -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},
|
||||
|
||||
@@ -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]. */
|
||||
|
||||
@@ -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];
|
||||
|
||||
@@ -855,6 +855,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 +927,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 +974,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 +1149,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();
|
||||
}
|
||||
|
||||
@@ -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 ¶m) { 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 ¶m) {
|
||||
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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -776,6 +776,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
|
||||
|
||||
@@ -5,6 +5,29 @@ 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.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
|
||||
|
||||
+21
-2
@@ -82,6 +82,18 @@ 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
|
||||
|
||||
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 +110,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 zip-test
|
||||
@test -f $(GOLDEN)/input.f32 || $(MAKE) --no-print-directory golden
|
||||
build/core/golden_test $(GOLDEN) $(TYPES)
|
||||
build/core/sampler_test
|
||||
@@ -106,6 +118,9 @@ 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
|
||||
|
||||
# ------------------------------------------------------------------ app
|
||||
AU_SRC := app/FX/SizzleDeviceAU.mm app/FX/SizzleEffectAU.mm app/FX/SizzleInstrumentAU.mm app/FX/SizzleDeviceAU+Sources.mm
|
||||
@@ -158,8 +173,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.
|
||||
|
||||
@@ -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": [
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
@@ -295,7 +296,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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
+2
-2
@@ -12,8 +12,8 @@
|
||||
# or polish. versionCode is monotonic and bumps by 1 on every release,
|
||||
# because F-Droid and the Android package manager order installs by it alone.
|
||||
|
||||
versionName = 0.38.0
|
||||
versionCode = 72
|
||||
versionName = 0.40.0
|
||||
versionCode = 75
|
||||
|
||||
# Namespace for every platform: cc.tiredsysadmin.<os>.sizzle. Android:
|
||||
# cc.tiredsysadmin.android.sizzle (app/), iOS/iPadOS: cc.tiredsysadmin.ios.sizzle
|
||||
|
||||
Reference in New Issue
Block a user