diff --git a/core/tests/bench.cpp b/core/tests/bench.cpp new file mode 100644 index 0000000..f2a8f20 --- /dev/null +++ b/core/tests/bench.cpp @@ -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 +#include +#include +#include +#include +#include +#include + +#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(steady_clock::now().time_since_epoch()).count(); +} + +/** White-ish noise, the same every run so two runs are comparable. */ +std::vector noise(size_t n) { + std::vector 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 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 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 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 in = noise(n); + std::vector outA(n), outB(n); + + std::vector 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; +} diff --git a/docs/DEVELOPER_HANDOVER.md b/docs/DEVELOPER_HANDOVER.md index a7456a5..e1f2e3c 100644 --- a/docs/DEVELOPER_HANDOVER.md +++ b/docs/DEVELOPER_HANDOVER.md @@ -38,6 +38,7 @@ 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 | @@ -974,11 +975,32 @@ polish and interchange niceties, not functional gaps. with the CLI project layout is the remaining interchange nicety. - **Route the Oboe backend through the chosen output device** (Oboe `setDeviceId`), matching the AudioTrack path's device selection. -- **Block-rate FX processing.** Insert effects are `process(float)` per sample, so - a four-effect chain on four channels is 16 virtual calls per frame. Giving - `Effect` a block entry point (defaulting to a loop over `process`) would let the - heavier ports vectorise. Sample-for-sample identical if done carefully, but it - touches every effect and the golden comparison, so it is its own change. +- **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. --- diff --git a/ios/Makefile b/ios/Makefile index f9c1883..47b5917 100644 --- a/ios/Makefile +++ b/ios/Makefile @@ -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) @@ -98,6 +100,15 @@ 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/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 @@ -224,4 +235,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 diff --git a/ios/README.md b/ios/README.md index 3beb958..ab96d89 100644 --- a/ios/README.md +++ b/ios/README.md @@ -11,6 +11,7 @@ Makefile (`make -C ios help`). | `../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` | | `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 |