Files
feedBack-desktop/tests/sandbox/e2e/signalchain_fault_test.cpp
T
7671385ba8 Audio: song loudness normalization, in-process VSTs (perf), and stereo routing (#24)
* audio: flush denormals in the RT path + normalize the backing track

Two realtime-audio fixes (engine only — no change to amp/effect DSP):

1. Denormal flush (FTZ/DAZ). The signal path is full of IIR state (NAM, cab
   IRs, VST amp/EQ/comp chains); after each note that state decays toward zero
   and lands in the denormal range, where each float op is 10-100x slower. That
   produced sporadic CPU spikes -> buffer underruns heard as random "scratches"
   plus frame stutter (worse with larger buffers, independent of song/tone).
   Add a scoped juce::ScopedNoDenormals at the three RT entry points:
     - AudioEngine::audioDeviceIOCallbackWithContext (whole callback)
     - SignalChain::process (the plugin chain)
     - the sandbox worker's plugin processBlock in src/vst-host/main.cpp
       (VST3s run OUT-OF-PROCESS, so the host-side FTZ doesn't reach them)
   Denormals are sub -300 dBFS, so this is inaudible — CPU only, no tone change.

2. Backing-track loudness normalizer (BackingLeveler.h). Brings each song's
   backing to a consistent -12 LUFS so songs don't jump in level, applied in
   renderBackingBlockLocked BEFORE the mixer's backing-volume fader (so the
   fader still attenuates). Short-term BS.1770 K-weighted AGC (slow, no pumping)
   + a -1 dBFS brickwall limiter. RT-safe (no allocation in process()).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* audio: extend denormal flush to the split-output path + reuse chain MidiBuffer

Opt-1 low-risk RT tidy-ups (no DSP/tone change):
- ScopedNoDenormals in audioOutputCallback (the split-mode output clock that
  renders the backing track + phase-vocoder + leveler) — the primary callback's
  scope doesn't reach this separate output thread, leaving an IIR/decay path
  unprotected (a remaining source of the periodic "scratches").
- SignalChain::process reuses one juce::MidiBuffer across slots instead of
  copy-constructing it per slot per block (avoids RT-thread allocation).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* audio: per-slot pan + parallel branch routing (St-1 stereo, engine side)

Adds pan-only stereo to the signal chain so the node editor can place one amp
left and another right, pan effects, and let stereo plugins pass true L/R.

ProcessorSlot gains two fields:
  - pan    : -1..+1 constant-power, applied to that slot's output (0 = no-op)
  - branch : 0 = trunk (serial), >=1 = a parallel branch id

SignalChain::process keeps a bit-identical serial fast path when no slot has a
branch. When branches exist it runs the trunk-pre slots in place, snapshots that
as the split source, processes each branch on its own pre-allocated scratch
buffer, pans it, sums the branches into a merge bus, then runs any trunk-post
slots on the merged signal. Scratch is sized in prepare() (never on the RT
thread); falls back to serial for a non-stereo / oversized block.

The dual-mono amp output + post-amp pan is what yields "amp A left, amp B right"
without touching NAM or amp DSP. Preset schema emits pan/branch only when
non-default (mono presets unchanged); N-API gains setPan/setBranch and
getChainState/loadPreset round-trip them.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* audio: per-branch source channel (St-2) — feed a split L/R into separate branches

Extends the parallel-branch model so a stereo-out gear (e.g. a stereo delay) can
send its L output to one branch and its R to another. ProcessorSlot gains
branchSrc (0 = both, 1 = L, 2 = R); when seeding a branch from the split source,
L-only / R-only mono-izes that channel into the branch. Read from any slot in the
branch. N-API setBranchSrc + getChainState/preset round-trip it. Default 0 keeps
existing routing identical.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* audio-bridge: expose setPan/setBranch/setBranchSrc to the renderer

The engine N-API gained the stereo routing setters (setPan/setBranch/
setBranchSrc) but the main-process IPC handlers + the preload bridge didn't
forward them, so window.slopsmithDesktop.audio.setPan was undefined and the
node editor's stereo controls no-op'd. Wire all three through audio:setPan /
setBranch / setBranchSrc.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* audio: run scanned VSTs in-process + forward params + cut RT stalls

Big CPU/latency win for chains with VST plugins, plus the missing parameter
path. The out-of-process sandbox exists to crash-isolate the SCAN of unknown
plugins; a plugin only reaches a chain after it scanned cleanly, so paying the
per-block IPC cost (N serial round-trips, memcpy, poll waits) for every block
of playback was pure overhead.

- shouldSandbox(): default VST3 playback to IN-PROCESS. The runtime crash
  blocklist + launch sentinel still route a faulting plugin back through the
  sandbox on its next load, so it self-heals; only genuinely crash-prone gear
  keeps paying for isolation. Eliminates the IPC round-trips + the per-load
  subprocess spawn that caused the load-time "scratches".
- SignalChain::clear(): detach slots under a brief lock, destroy them OFF the
  lock. Sandbox teardown is slow; doing it under `lock` starved the RT
  ScopedTryLock and dropped audio blocks on every chain reload.
- AudioChannel::popBlock(): bounded busy-spin on the write index before the
  blocking poll() — a fast plugin's output lands within microseconds, so we
  skip the syscall + doorbell wakeup latency; a slow plugin falls through to the
  efficient wait (correctness + heavy-chain cost unchanged).
- SandboxedProcessor::setSandboxedParameter() + SignalChain::setParameter()
  route param changes to a sandboxed plugin over the control pipe (kSetParameter)
  — the JUCE getParameters() proxy layer isn't wired, so without this a
  sandboxed plugin's knobs/preset never reached it and it played at defaults.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* audio: PR #24 review follow-ups — POSIX fault guard + routing/spin/leveler fixes

Follow-up fixes from review of PR #24.

== POSIX in-process plugin fault guard (the main one) ==
PR #24 makes scanned VSTs run in-process by default. invokePlugin()'s catch(...)
only catches a plugin fault on Windows (where /EHa maps the SEH access violation
to a C++ exception); on macOS/Linux a plugin SIGSEGV during playback took down
the whole app, breaking the fail-soft-audio + cross-platform guarantees.

Add a POSIX fault guard in SignalChain.cpp: install chained SIGSEGV/SIGBUS/
SIGFPE/SIGILL handlers; while a guarded plugin call is live on the current
thread (thread-local, initial-exec TLS so the handler stays async-signal-safe),
siglongjmp() back into invokePlugin() and take the SAME blocklist+leak+survive
path as Windows. Faults outside a guarded call chain to the previously-installed
handler (V8/ASan/default), so real crashes and sanitizers are never masked. The
guard's armed flag is restored on EVERY exit from the guarded region — normal
return, signal-fault longjmp, and a normal C++ exception from the plugin — so a
thread is never left armed with a stale landing pad. Known limit: stack-overflow
faults aren't reliably caught (no sigaltstack on JUCE audio threads).

Comments in SandboxFactory_shared.cpp updated to match the kept in-process
default (the stale 'every VST3 sandboxes' / 'diagnostic tagging only' notes).

== Smaller correctness/quality fixes ==
- SignalChain parallel path: a branch==0 (trunk) slot interleaved inside the
  branch region was run by none of the loops -> silently dropped. Detect the
  region first and fall back to a serial chain (jassertfalse in debug) so no
  slot is lost if the node-editor contiguity invariant breaks.
- AudioChannel pop busy-spin: add a cpuRelax() (_mm_pause / arm yield) hint.
- BackingLeveler: reset AGC/limiter state on loadBackingTrack so a new song
  doesn't inherit the previous track's gain follower and briefly mis-level.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test: integration test for the in-process plugin fault guard

Drives deliberately-faulting in-process AudioProcessors through a real
SignalChain::process() and asserts the host survives, the processor is released,
and it's added to the crash blocklist (shouldSandbox() then routes it
out-of-process). Covers BOTH fault kinds: a hardware SIGSEGV (POSIX guard /
Windows SEH) and a normal C++ exception (the path that must leave the guard
disarmed). End-to-end counterpart to the standalone mechanism check — exercises
the actual invokePlugin() guard.

Lives in the POSIX-only sandbox e2e harness (already links juce_audio_processors
+ the full sandbox set). Leak detection is disabled for the target because the
guard leaks the faulting processor by design.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Jafz2001 <ignacio.fritis@mundotelecomunicaciones.cl>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Byron Gamatos <xasiklas@gmail.com>
2026-06-19 23:08:05 +02:00

148 lines
5.7 KiB
C++

// Integration test for the in-process plugin fault guard in SignalChain.cpp.
//
// Drives a deliberately-segfaulting in-process AudioProcessor through a REAL
// SignalChain::process() and asserts that:
// 1. the host process SURVIVES the plugin's SIGSEGV (POSIX guard / SEH),
// 2. the faulting processor is released from its slot,
// 3. the plugin is added to the runtime crash blocklist, so shouldSandbox()
// now routes it out-of-process on its next load (self-healing), and
// 4. a subsequent process() call is safe (the dead slot is skipped).
//
// This is the end-to-end counterpart to the standalone mechanism check: it
// exercises the actual invokePlugin() guard, not a copy. POSIX-only harness
// (matches the sandbox e2e job); on Windows the same path is covered by the
// /EHa SEH catch.
#include "SignalChain.h"
#include "Sandbox/SandboxedProcessor.h" // slopsmith::sandbox::{shouldSandbox,addCrashedPlugin}
#include <juce_audio_processors/juce_audio_processors.h>
#include <cstdio>
#include <stdexcept>
namespace {
// Base fixture: a minimal in-process AudioProcessor. Subclasses decide how
// processBlock() fails.
class FaultFixture : public juce::AudioProcessor
{
public:
FaultFixture()
: juce::AudioProcessor(BusesProperties()
.withInput("In", juce::AudioChannelSet::stereo(), true)
.withOutput("Out", juce::AudioChannelSet::stereo(), true)) {}
const juce::String getName() const override { return "FaultGuardFixture"; }
void prepareToPlay(double, int) override {}
void releaseResources() override {}
double getTailLengthSeconds() const override { return 0.0; }
bool acceptsMidi() const override { return false; }
bool producesMidi() const override { return false; }
bool isMidiEffect() const override { return false; }
juce::AudioProcessorEditor* createEditor() override { return nullptr; }
bool hasEditor() const override { return false; }
int getNumPrograms() override { return 1; }
int getCurrentProgram() override { return 0; }
void setCurrentProgram(int) override {}
const juce::String getProgramName(int) override { return {}; }
void changeProgramName(int, const juce::String&) override {}
void getStateInformation(juce::MemoryBlock&) override {}
void setStateInformation(const void*, int) override {}
};
// Faults with a hardware signal (SIGSEGV) — the POSIX guard / Windows SEH path.
class SignalFaultingProcessor : public FaultFixture
{
public:
void processBlock(juce::AudioBuffer<float>&, juce::MidiBuffer&) override
{
// Deliberate null dereference → SIGSEGV. volatile so the compiler can't
// elide it; the asm barrier keeps it from being hoisted/removed under -O2.
volatile int* p = nullptr;
*p = 0xC0FFEE;
asm volatile("" ::: "memory");
}
};
// Faults with a normal C++ exception — the path that left the POSIX guard armed
// with a stale landing pad before the fix (catch must restore the guard).
class ThrowingProcessor : public FaultFixture
{
public:
void processBlock(juce::AudioBuffer<float>&, juce::MidiBuffer&) override
{
throw std::runtime_error("deliberate plugin exception");
}
};
bool fail(const char* msg) { std::printf("FAIL: %s\n", msg); return false; }
// Drive one faulting processor through a fresh chain; assert the host survives,
// the processor is released, and the plugin is blocklisted.
template <typename ProcT>
bool runFaultScenario(const char* label, const char* fileName)
{
// A unique on-disk path ending in .vst3 so shouldSandbox() treats it as a
// VST3 (non-VST3 paths always stay in-process and skip the blocklist).
const juce::String fakePath = juce::File::getCurrentWorkingDirectory()
.getChildFile(fileName).getFullPathName();
juce::PluginDescription desc;
desc.fileOrIdentifier = fakePath;
if (slopsmith::sandbox::shouldSandbox(desc))
return fail("fixture was already blocklisted before the fault");
SignalChain chain;
chain.prepare(48000.0, 256);
const int slotId = chain.addProcessor(std::make_unique<ProcT>(),
ProcessorSlot::Type::VST, label, fakePath);
if (chain.getNumSlots() != 1)
return fail("processor was not added to the chain");
juce::AudioBuffer<float> buffer(2, 256);
buffer.clear();
juce::MidiBuffer midi;
// The crux: this drives the faulting plugin and MUST return rather than die.
chain.process(buffer, midi);
std::printf(" [%s] survived\n", label);
const ProcessorSlot* slot = chain.getSlot(slotId);
if (slot == nullptr) return fail("slot vanished after the fault");
if (slot->processor != nullptr) return fail("faulting processor was not released");
if (! slopsmith::sandbox::shouldSandbox(desc))
return fail("plugin was not blocklisted after faulting");
// A second block must be safe: the dead slot is simply skipped.
chain.process(buffer, midi);
return true;
}
bool runTest()
{
// Signal fault (SIGSEGV) and C++-exception fault, each through its own chain.
// Running both in one process also exercises that the C++-exception path
// leaves the per-thread POSIX guard in a clean (disarmed) state — a stale
// armed flag from the first scenario would corrupt the second.
if (! runFaultScenario<SignalFaultingProcessor>("signal-fault", "FaultGuardSignal.vst3"))
return false;
if (! runFaultScenario<ThrowingProcessor>("cxx-exception", "FaultGuardThrow.vst3"))
return false;
std::printf("OK: SignalChain survived both fault kinds; processors released + blocklisted\n");
return true;
}
} // namespace
int main()
{
const bool ok = runTest();
return ok ? 0 : 1;
}