FM1SoundDocs.kt
src/jvmMain/kotlin/afield/audio/synth/FM1SoundDocs.kt · 274 lines
@file:afield.runtime.completion.CompletionCategory("Audio")
package afield.audio.synth
import afield.audio.engine.WavFloatArrayWriter
import java.io.File
import java.nio.file.Files
FIELD_TEST id: synth.fm1.sound runner: jvm-main entrypoint: afield.audio.synth.FM1SoundDocs tags: [smoke, synth, audio, wav, docs, wasm, cpu] timeoutSec: 300 expect: exitCode: 0 stdoutContains: - "fm1 sound docs rendered"
object FM1SoundDocs
The clips on fm1.md, each rendered offline from a fresh FM1Sim.create through FM1SimNode in
128-frame blocks at 48 kHz with no audio device: the same render path a launched box plays.
project-0 and project-1 are factory projects with PLAY tapped. The others put Field in front
of the simulator: pattern lays a Field pattern on ACID ALLEY's DX7 track, cutoff-lfo lets a
slow sine turn the 303's filter, and voice-morph plays one phrase eight times while the voice
moves from the factory piano to a bell built in Field.
firmware-swap plays ACID ALLEY and, four seconds in, swaps in a build of the firmware whose 303 is
cut down to eighths (crushedFirmware); it needs the WASI SDK, so the synth.fm1.firmware smoke
test checks it rather than this object's main.
object FM1SoundDocs {
const val SR = 48_000
Sample rate of every clip.
const val BLOCK = 128
Frames per block, the audio engine's.
const val SETTLE_SECONDS = 0.5
Seconds the project is left to load before anything starts.
const val PLAY_SECONDS = 6.0
Seconds of each clip.
A clip: the factory project it starts from, how long it runs, and what it does once loaded.
private class Figure(
val slot: Int,
val seconds: Double = PLAY_SECONDS,
/** Seconds into the clip, and what happens then. */
val events: List<Pair<Double, (FM1Sim) -> Unit>> = emptyList(),
/** Whether the clip builds firmware, which needs the WASI SDK and the source (the network, once). */
val buildsFirmware: Boolean = false,
val begin: (FM1Sim) -> Unit,
)
val crushedFirmware: ByteArray by lazy
The firmware firmwareSwap changes to: the shipped source with the 303's output quantized to
eighths before it is scaled to the mix, a three-bit 303. Built once per JVM from a copy of the
source, so the shared checkout stays as it was cloned.
val crushedFirmware: ByteArray by lazy {
val copy = Files.createTempDirectory("fm1-crushed").toFile()
try {
FM1Firmware.checkout().copyRecursively(copy, overwrite = true)
FM1Firmware.patch(copy, CRUSH_FILE, CRUSH_FIND, CRUSH_REPLACE)
FM1Firmware.build(copy, File(copy, "crushed.wasm")).readBytes()
} finally {
copy.deleteRecursively()
}
}
const val CRUSH_FILE = "third_party/synth/bass303.c"
The line of bass303.c the crushed firmware changes, and what it becomes.
const val CRUSH_FIND = "out[i]=(int32_t)(sample*16777216);"
const val CRUSH_REPLACE = "out[i]=(int32_t)((int)(sample*8)*2097152);"
const val HOOK_FOLD = "in 30 * sin 0.12 *"
The first hook in hooks: the 303 folded through a sine, 0.12 sin(30x). The 303's samples
run to about a tenth of full scale, so it takes a drive of 30 to fold; 0.12 brings it back to
about the 303's own level (measured in synth.fm1.hooks).
const val HOOK_BRIGHT = "in 80 * sin 0.12 *"
The second: folded harder still, 0.12 sin(80x), at about the same level.
const val NOTE_FIFTHS = "in in .x in .z 2 mod 7 * + >x"
The first note hook in note-hooks: odd steps of the sequence a fifth up.
const val NOTE_OCTAVE = "in in .x 12 + >x"
The second: every note an octave up, velocities as written.
val noteFifths: FM1Hook by lazy { FM1Hooks.compileNotes(NOTE_FIFTHS) }
NOTE_FIFTHS compiled once per JVM.
val noteOctave: FM1Hook by lazy { FM1Hooks.compileNotes(NOTE_OCTAVE) }
NOTE_OCTAVE compiled once per JVM.
val hookFold: FM1Hook by lazy { FM1Hooks.compile(HOOK_FOLD) }
HOOK_FOLD compiled once per JVM.
val hookBright: FM1Hook by lazy { FM1Hooks.compile(HOOK_BRIGHT) }
HOOK_BRIGHT compiled once per JVM.
const val SWAP_SECONDS = 4.0
Seconds into firmware-swap that the crushed firmware is swapped in.
fun bell(piano: Dx7Voice): Dx7Voice
The bell voiceMorph ends on: the factory piano with a brighter algorithm and inharmonic ratios.
body — 59 lines, from line 111
fun bell(piano: Dx7Voice): Dx7Voice = piano.copy().apply {
algorithm = 5
feedback = 6
op(2).coarse = 7
op(4).coarse = 3
op(4).fine = 41
op(6).coarse = 11
name = "BELLPIANO"
}
private val figures: Map<String, Figure> = linkedMapOf(
"project-0" to Figure(0) { it.play() },
"project-1" to Figure(1) { it.play() },
"pattern" to Figure(1) { sim ->
sim.start()
sim.schedule(pat("<c5 ef5> ~ [g5 bf5] ~ c6 ~ g5 ~"), track = 2, cycles = 3, cps = sim.cps)
},
"cutoff-lfo" to Figure(1) { sim ->
sim.modulate(0, FM1Sim.CC.CUTOFF, SineOsc(0.25.p) * 0.5 + 0.5)
sim.start()
},
"field-kit" to Figure(1) { sim ->
fieldKit(sim)
sim.source(1, FM1Sim.SourceType.SAMPLER)
sim.start()
},
"firmware-swap" to Figure(1, seconds = 8.0, events = listOf(SWAP_SECONDS to { it.loadFirmware(crushedFirmware) }),
buildsFirmware = true) { it.start() },
"hooks" to Figure(
1, seconds = 8.0, buildsFirmware = true,
events = listOf(
2.0 to { it.hook(0, hookFold) },
4.0 to { it.hook(0, hookBright) },
6.0 to { it.clearHook(0) },
),
) { sim ->
sim.loadFirmware(FM1Hooks.firmware())
sim.start()
},
"note-hooks" to Figure(
1, seconds = 8.0, buildsFirmware = true,
events = listOf(
2.0 to { it.hook(0, noteFifths) },
5.0 to { it.hook(0, noteOctave) },
),
) { sim ->
sim.loadFirmware(FM1Hooks.firmware())
sim.start()
},
"voice-morph" to Figure(0, seconds = 8.0) { sim ->
val piano = sim.voices(0)[0]
val bell = bell(piano)
for (k in 0 until 8) {
val at = k * 1.0
sim.morphStep(piano.lerp(bell, k / 7.0), at)
sim.chord(0, listOf(60, 64, 67), seconds = 0.7, afterSeconds = at + 0.05)
}
},
)
fun fieldKit(sim: FM1Sim)
Put a drum kit made of Field signals on the FM-1's sampler pads: a kick that falls from 150 to 45 Hz, a snare of tone and high-passed noise, closed and open hats of noise above 7 kHz.
fun fieldKit(sim: FM1Sim) {
val kick = SineOsc(Param(0f).modulate(Line(150f, 45f, 0.09f))) * perc(0.45) * 0.9
val snare = (SineOsc(185.p) * perc(0.08) * 0.5 + WhiteNoise(seed = 1).highpass(1800f) * perc(0.18) * 0.6)
val hat = WhiteNoise(seed = 2).highpass(7000f) * perc(0.05) * 0.7
val open = WhiteNoise(seed = 3).highpass(7000f) * perc(0.35) * 0.6
sim.sample(0, 0.5, kick, "FIELD KICK")
sim.sample(1, 0.3, snare, "FIELD SNARE")
sim.sample(6, 0.1, hat, "FIELD HAT")
sim.sample(7, 0.45, open, "FIELD OPEN")
}
Queue voice for track 0 at atSeconds, on the simulator's clock.
private fun FM1Sim.morphStep(voice: Dx7Voice, atSeconds: Double) {
val block = blocksRendered + FM1Sim.blocks(atSeconds)
val sysex = voice.toSysex(0)
midiAt(block, *IntArray(sysex.size) { sysex[it].toInt() and 0xff })
}
val FIGURES: Set<String> get() = figures.keys
The clips, by the name their fences ask for.
fun render(name: String): Pair<FloatArray, FloatArray>
Renders clip name as left and right channels, without the settle.
fun render(name: String): Pair<FloatArray, FloatArray> {
val fig = figures[name] ?: error("unknown FM1SoundDocs figure '$name'; known: ${figures.keys}")
FM1Sim.create().use { sim ->
sim.preset(fig.slot)
val node = FM1SimNode(sim)
val ctx = SynthContext(SR.toFloat(), BLOCK)
val l = FloatArray(BLOCK)
val r = FloatArray(BLOCK)
var block = 0L
fun pull() {
ctx.cycleId = ++block
ctx.time = (block - 1).toFloat() * BLOCK / SR
node.render(l, r, BLOCK, ctx)
}
repeat((SETTLE_SECONDS * SR / BLOCK).toInt()) { pull() }
fig.begin(sim)
val frames = (fig.seconds * SR).toInt()
val events = fig.events.map { (seconds, f) -> (seconds * SR).toInt() / BLOCK * BLOCK to f }
if (fig.buildsFirmware) { crushedFirmware; hookFold; hookBright; noteFifths; noteOctave } // build before the clock starts
val left = FloatArray(frames)
val right = FloatArray(frames)
var at = 0
while (at < frames) {
for ((frame, f) in events) if (frame == at) f(sim)
pull()
val n = minOf(BLOCK, frames - at)
System.arraycopy(l, 0, left, at, n)
System.arraycopy(r, 0, right, at, n)
at += BLOCK
}
return left to right
}
}
fun renderWav(name: String, outPath: String)
Offline-renders clip name to a stereo 16-bit WAV at outPath: the docs fence's entry point.
fun renderWav(name: String, outPath: String) {
val (left, right) = render(name)
require(left.any { it != 0f } || right.any { it != 0f }) { "figure '$name' rendered silence" }
WavFloatArrayWriter.writeStereo16(outPath, left, right, SR, normalizePeak = 0.9f)
}
fun main(args: Array<String>)
Renders each clip twice and checks it is sound and that the two renders are identical.
@JvmStatic
fun main(args: Array<String>) {
for (name in FIGURES) {
if (figures.getValue(name).buildsFirmware) {
println("$name: builds firmware, so it is checked by synth.fm1.firmware (FM1FirmwareCheck)")
continue
}
val (a, _) = render(name)
val (b, _) = render(name)
val peak = a.maxOf { kotlin.math.abs(it) }
check(peak > 0.02f) { "$name: effectively silent (peak $peak)" }
check(a.contentEquals(b)) { "$name: two renders differ, so a published clip could not be reproduced" }
println("$name: ${a.size} frames, peak ${"%.3f".format(peak)}, deterministic")
}
println("fm1 renders ${"%.1f".format(realtimeFactor())}x faster than real time")
println("fm1 sound docs rendered")
}
fun realtimeFactor(seconds: Double = 10.0, slot: Int = 1): Double
How many seconds of a playing factory project one second of this thread renders at 48 kHz, after two warm-up seconds for GraalWasm's compiler: above 1 keeps up with the audio engine.
fun realtimeFactor(seconds: Double = 10.0, slot: Int = 1): Double = FM1Sim.create().use { sim ->
sim.preset(slot)
val l = FloatArray(4800)
val r = FloatArray(4800)
repeat(5) { sim.render(l, r, 4800, SR.toFloat()) }
sim.start()
repeat(20) { sim.render(l, r, 4800, SR.toFloat()) }
val n = (seconds * 10).toInt()
val t0 = System.nanoTime()
repeat(n) { sim.render(l, r, 4800, SR.toFloat()) }
seconds / ((System.nanoTime() - t0) / 1e9)
}
}