// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown // SPDX-License-Identifier: GPL-3.0-or-later // Mac-side check of the AUv3 wrapper (SizzleEffectAU), run by `make -C ios au-test`. // AUAudioUnit exists on macOS too, so every effect in components.txt is registered // in-process and driven through AVAudioEngine (offline), like a host would: // 1. audio: the reference input through the AU must equal the C++ core run // directly (both channels), so the wrapper adds nothing and drops nothing; // 2. parameters: moving every parameter through the AU's tree must change the // output to exactly what the core gives for those values; // 3. presets (Mix Tightener) and saved state (fullState round trip); // 5. instruments: MIDI notes at given sample offsets through the AU's render // block must give exactly what the C++ Instrument gives for the same notes; // the Sampler / SF2 get a test sample through fullState; // 4. zero-copy input: calling the render block directly with an upstream that // points the input buffers at its own memory instead of filling ours. Real // hosts do that out of process; AVAudioEngine in-process copies, which is why // 0.1.0 passed here and was silent on the iPad. #import #include #include #include #include #import "Components.gen.h" #import "SizzleDeviceAU.h" #import "SizzleInstrumentAU.h" #include "sizzle/Instrument.hpp" #include "sampler/SampleStore.hpp" #include "echofield/GrainSources.hpp" #include "wavetable/WaveTables.hpp" #include "sizzle/DeviceSpecs.gen.hpp" #include "sizzle/Effect.hpp" using namespace sizzle; static int failures = 0; static void check(bool ok, const char *what, const char *name) { std::printf("%s %-18s %s\n", ok ? "PASS" : "FAIL", name, what); if (!ok) ++failures; } static std::vector readF32(const char *path) { std::ifstream f(path, std::ios::binary); std::vector b((std::istreambuf_iterator(f)), {}); std::vector v(b.size() / 4); memcpy(v.data(), b.data(), v.size() * 4); return v; } static AVAudioUnit *instantiate(AudioComponentDescription d) { __block AVAudioUnit *unit = nil; dispatch_semaphore_t sem = dispatch_semaphore_create(0); [AVAudioUnit instantiateWithComponentDescription:d options:0 completionHandler:^(AVAudioUnit *u, NSError *e) { unit = u; if (e) std::printf("instantiate error: %s\n", e.localizedDescription.UTF8String); dispatch_semaphore_signal(sem); }]; dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); return unit; } /// Render [in] (mono, both channels) through [unit]; returns the left and right outputs. static void renderAU(AVAudioUnit *unit, const std::vector &in, std::vector &L, std::vector &R) { AVAudioEngine *engine = [AVAudioEngine new]; AVAudioFormat *fmt = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:48000 channels:2]; NSError *err = nil; [engine enableManualRenderingMode:AVAudioEngineManualRenderingModeOffline format:fmt maximumFrameCount:1024 error:&err]; AVAudioPlayerNode *player = [AVAudioPlayerNode new]; [engine attachNode:player]; [engine attachNode:unit]; [engine connect:player to:unit format:fmt]; [engine connect:unit to:engine.mainMixerNode format:fmt]; [engine startAndReturnError:&err]; AVAudioPCMBuffer *src = [[AVAudioPCMBuffer alloc] initWithPCMFormat:fmt frameCapacity:(AVAudioFrameCount)in.size()]; src.frameLength = (AVAudioFrameCount)in.size(); memcpy(src.floatChannelData[0], in.data(), in.size() * 4); memcpy(src.floatChannelData[1], in.data(), in.size() * 4); [player scheduleBuffer:src completionHandler:nil]; [player play]; AVAudioPCMBuffer *out = [[AVAudioPCMBuffer alloc] initWithPCMFormat:engine.manualRenderingFormat frameCapacity:1024]; L.clear(); R.clear(); while (L.size() < in.size()) { [engine renderOffline:1024 toBuffer:out error:&err]; L.insert(L.end(), out.floatChannelData[0], out.floatChannelData[0] + out.frameLength); R.insert(R.end(), out.floatChannelData[1], out.floatChannelData[1] + out.frameLength); } L.resize(in.size()); R.resize(in.size()); [engine stop]; } static std::vector renderCore(const char *type, const Params &p, const std::vector &in, int sr = 48000) { auto fx = Effect::create(type, sr); fx->update(p, 120.f); std::vector y(in.size()); for (size_t i = 0; i < in.size(); ++i) { float v = fx->process(in[i]); y[i] = std::isfinite(v) ? v : 0.f; } return y; } /// Render [in] through the AU's render block at 44.1 kHz in 512-frame blocks. The /// upstream hands over its own buffers (mData replaced, ours untouched); with /// [inPlace] the output buffers are null too, as hosts may pass them. static void renderZeroCopy(AUAudioUnit *au, const std::vector &in, bool inPlace, std::vector &L, std::vector &R) { au.maximumFramesToRender = 4096; NSError *err = nil; if (![au allocateRenderResourcesAndReturnError:&err]) { std::printf("allocate: %s\n", err.localizedDescription.UTF8String); return; } AURenderBlock render = au.renderBlock; const AVAudioFrameCount n = 512; std::vector upL(n), upR(n), outL(n), outR(n); L.clear(); R.clear(); for (size_t pos = 0; pos + n <= in.size(); pos += n) { memcpy(upL.data(), &in[pos], n * 4); memcpy(upR.data(), &in[pos], n * 4); float *upL0 = upL.data(), *upR0 = upR.data(); AURenderPullInputBlock pull = ^AUAudioUnitStatus(AudioUnitRenderActionFlags *f, const AudioTimeStamp *t, AUAudioFrameCount frames, NSInteger bus, AudioBufferList *data) { for (UInt32 c = 0; c < data->mNumberBuffers; ++c) { data->mBuffers[c].mData = c ? upR0 : upL0; data->mBuffers[c].mDataByteSize = frames * 4; } return noErr; }; struct { AudioBufferList list; AudioBuffer extra; } out; out.list.mNumberBuffers = 2; for (int c = 0; c < 2; ++c) { out.list.mBuffers[c].mNumberChannels = 1; out.list.mBuffers[c].mDataByteSize = n * 4; out.list.mBuffers[c].mData = inPlace ? nullptr : (c ? outR.data() : outL.data()); } AudioTimeStamp ts = {}; ts.mSampleTime = (Float64)pos; ts.mFlags = kAudioTimeStampSampleTimeValid; AudioUnitRenderActionFlags flags = 0; AUAudioUnitStatus st = render(&flags, &ts, n, 0, &out.list, pull); if (st != noErr) { std::printf("render status %d\n", (int)st); break; } const float *l = (const float *)out.list.mBuffers[0].mData, *r = (const float *)out.list.mBuffers[1].mData; L.insert(L.end(), l, l + n); R.insert(R.end(), r, r + n); } [au deallocateRenderResources]; } static double maxDiff(const std::vector &a, const std::vector &b) { double m = 0; for (size_t i = 0; i < a.size() && i < b.size(); ++i) m = std::max(m, std::fabs((double)a[i] - b[i])); return m; } static sampler::SampleStore gStore; /// Instruments: render the AU's render block directly with MIDI events at sample /// offsets inside 512-frame blocks, against the C++ Instrument with the same notes. static void checkInstrument(AudioComponentDescription d, const SizzleComponent &sc) { const int sr = 44100, n = 512, blocks = 120; // ~1.4 s struct Note { int frame, status, midi, vel; }; const Note notes[] = {{100, 0x90, 60, 100}, {9000, 0x90, 64, 90}, {9000, 0x90, 67, 70}, {26000, 0x80, 60, 0}, {30001, 0x80, 64, 0}, {30001, 0x80, 67, 0}, {40000, 0x90, 48, 127}, {52000, 0x80, 48, 0}}; const bool sampled = !strcmp(sc.toolboxType, "SAMPLER") || !strcmp(sc.toolboxType, "SOUNDFONT"); char msg[200]; AVAudioUnit *unit = instantiate(d); if (!unit) { check(false, "instantiate", sc.name); return; } SizzleInstrumentAU *au = (SizzleInstrumentAU *)unit.AUAudioUnit; au.sampleStore = &gStore; const DeviceSpec *spec = findDevice(sc.toolboxType); Params p; p.fill(*spec); if (sampled) { // point it at the test sample through saved state NSMutableDictionary *values = [NSMutableDictionary dictionary]; for (int i = 0; i < p.size(); ++i) values[@(p.keyAt(i))] = @(p.valueAt(i)); if (!strcmp(sc.toolboxType, "SAMPLER")) { values[@"pad12"] = @"t"; values[@"pad24"] = @"t"; p.set("pad12", "t"); p.set("pad24", "t"); } else { values[@"sfSample"] = @"t"; p.set("sfSample", "t"); } au.fullState = @{@"sizzleValues": values}; } au.maximumFramesToRender = 4096; NSError *err = nil; if (![au allocateRenderResourcesAndReturnError:&err]) { check(false, "allocate", sc.name); return; } auto inst = Instrument::create(sc.toolboxType, sr, &gStore); inst->update(p, 120.f); std::vector want, got; AURenderBlock render = au.renderBlock; AUScheduleMIDIEventBlock midi = au.scheduleMIDIEventBlock; size_t next = 0; for (int b = 0; b < blocks; ++b) { const int base = b * n; // reference: same notes on the same frames inst->blockStart(n); size_t k = next; for (int i = 0; i < n; ++i) { while (k < sizeof notes / sizeof notes[0] && notes[k].frame == base + i) { if (notes[k].status == 0x90) inst->noteOn(notes[k].midi, notes[k].vel); else inst->noteOff(notes[k].midi); ++k; } want.push_back(inst->render()); } // AU: schedule this block's notes at their sample times, then render for (; next < k; ++next) { uint8_t bytes[3] = {(uint8_t)notes[next].status, (uint8_t)notes[next].midi, (uint8_t)notes[next].vel}; midi((AUEventSampleTime)notes[next].frame, 0, 3, bytes); } float bufL[512], bufR[512]; struct { AudioBufferList list; AudioBuffer extra; } out; out.list.mNumberBuffers = 2; out.list.mBuffers[0] = {1, (UInt32)(n * 4), bufL}; out.list.mBuffers[1] = {1, (UInt32)(n * 4), bufR}; AudioTimeStamp ts = {}; ts.mSampleTime = base; ts.mFlags = kAudioTimeStampSampleTimeValid; AudioUnitRenderActionFlags flags = 0; if (render(&flags, &ts, n, 0, &out.list, nil) != noErr) { check(false, "render", sc.name); return; } for (int i = 0; i < n; ++i) { if (bufL[i] != bufR[i]) { check(false, "left != right", sc.name); return; } got.push_back(bufL[i]); } } [au deallocateRenderResources]; double peak = 0; for (float v : want) peak = std::max(peak, (double)std::fabs(v)); double dl = maxDiff(got, want); snprintf(msg, sizeof msg, "MIDI at sample offsets: AU == Instrument (%.2g, peak %.3f)", dl, peak); check(dl < 1e-6 && peak > 0.01, msg, sc.name); } int main(int argc, char **argv) { @autoreleasepool { if (argc < 2) { std::fprintf(stderr, "usage: au_test \n"); return 2; } std::vector in = readF32(argv[1]); wavetable::WaveTables::prewarmBlocking(); echofield::GrainSources::prewarmBlocking(); { // the Sampler / SF2 test sample: 0.5 s decaying saw at 44.1 kHz, looped Sample s; s.sampleRate = 44100; for (int i = 0; i < 22050; ++i) s.data.push_back(0.6f * (2.f * fmodf(i * 220.f / 44100.f, 1.f) - 1.f) * expf(-i / 20000.f)); s.loopStart = 4000; s.loopEnd = 16000; gStore.put("t", std::move(s)); } in.resize(48000); // 1 s is plenty for (int c = 0; c < kSizzleComponentCount; ++c) { const SizzleComponent &sc = kSizzleComponents[c]; AudioComponentDescription d = {sc.type, sc.subtype, 'Tsys', 0, 0}; [AUAudioUnit registerSubclass:[SizzleDeviceAU classForComponentType:sc.type] asComponentDescription:d name:@(sc.name) version:1]; if (sc.type == kAudioUnitType_MusicDevice) { checkInstrument(d, sc); continue; } AVAudioUnit *unit = instantiate(d); if (!unit) { check(false, "instantiate", sc.name); continue; } const DeviceSpec *spec = findDevice(sc.toolboxType); // 1. defaults Params p; p.fill(*spec); std::vector L, R, want = renderCore(sc.toolboxType, p, in); renderAU(unit, in, L, R); char msg[160]; double dl = maxDiff(L, want), dr = maxDiff(R, want); snprintf(msg, sizeof msg, "defaults: AU == core (L %.2g, R %.2g)", dl, dr); check(dl < 1e-6 && dr < 1e-6, msg, sc.name); // 2. move every parameter to 70% (enums: last choice) through the AU tree AUAudioUnit *au = unit.AUAudioUnit; for (int i = 0; i < spec->paramCount; ++i) { const ParamSpec &s = spec->params[i]; AUParameter *param = [au.parameterTree parameterWithAddress:(AUParameterAddress)i]; AUValue v = s.isEnum() ? (AUValue)(s.choiceCount() - 1) : s.min + 0.7f * (s.max - s.min); if (s.isInt) v = std::round(v); param.value = v; if (s.isEnum()) p.set(s.key, s.choices[s.choiceCount() - 1]); else p.set(s.key, v); } want = renderCore(sc.toolboxType, p, in); renderAU(unit, in, L, R); dl = maxDiff(L, want); snprintf(msg, sizeof msg, "parameters at 70%%: AU == core (%.2g)", dl); check(dl < 1e-6, msg, sc.name); // 3a. factory presets if (au.factoryPresets.count > 0) { au.currentPreset = au.factoryPresets[1]; Params pp; pp.fill(*spec); const FactoryPreset *fp = nullptr; for (int i = 0, n = 0; i < gen::factoryPresetCount; ++i) if (!strcmp(gen::factoryPresets[i].type, sc.toolboxType) && n++ == 1) fp = &gen::factoryPresets[i]; const char *const *kv = fp->values; for (int i = 0; kv[i] && kv[i + 1]; i += 2) pp.set(kv[i], kv[i + 1]); want = renderCore(sc.toolboxType, pp, in); renderAU(unit, in, L, R); dl = maxDiff(L, want); snprintf(msg, sizeof msg, "factory preset \"%s\": AU == core (%.2g)", fp->name, dl); check(dl < 1e-6, msg, sc.name); } // 3b. fullState round trip into a fresh instance NSDictionary *state = au.fullState; AVAudioUnit *other = instantiate(d); other.AUAudioUnit.fullState = state; std::vector L2, R2; renderAU(unit, in, L, R); renderAU(other, in, L2, R2); dl = maxDiff(L, L2); snprintf(msg, sizeof msg, "fullState round trip renders the same (%.2g)", dl); check(dl < 1e-6, msg, sc.name); // 4. zero-copy input, with and without host output buffers for (int inPlace = 0; inPlace < 2; ++inPlace) { AVAudioUnit *fresh = instantiate(d); Params dp; dp.fill(*spec); std::vector zin(in.begin(), in.begin() + 44032); // 86 blocks of 512 std::vector zw = renderCore(sc.toolboxType, dp, zin, 44100), zL, zR; renderZeroCopy(fresh.AUAudioUnit, zin, inPlace, zL, zR); double zl = zL.size() == zin.size() ? maxDiff(zL, zw) : 1e9; double zr = zR.size() == zin.size() ? maxDiff(zR, zw) : 1e9; snprintf(msg, sizeof msg, "zero-copy input%s: AU == core (L %.2g, R %.2g)", inPlace ? ", in-place output" : "", zl, zr); check(zl < 1e-6 && zr < 1e-6, msg, sc.name); } } std::printf("\n%s (%d failures)\n", failures ? "FAILED" : "all passed", failures); } return failures ? 1 : 0; }