diff --git a/core/branchrunner.cpp b/core/branchrunner.cpp new file mode 100644 index 0000000..f68044c --- /dev/null +++ b/core/branchrunner.cpp @@ -0,0 +1,283 @@ +// BranchRunner implementation. See branchrunner.h for the protocol and why it is safe. + +#include "branchrunner.h" + +#include "platform/rtdenormal.h" + +#include +#include +#include +#include + +#if defined(__x86_64__) || defined(__i386__) +#include +#endif + +#if defined(_WIN32) +#include +#endif + +namespace Rations +{ + +namespace +{ + +// One spin-wait step. PAUSE on x86 and YIELD on AArch64 tell the core this is a spin loop, which +// saves power and frees the sibling hyper-thread; neither is a syscall or a scheduler yield. +inline void cpuRelax() +{ +#if defined(__x86_64__) || defined(__i386__) + _mm_pause(); +#elif defined(__aarch64__) + __asm__ __volatile__("yield"); +#endif +} + +#if defined(_WIN32) +// avrt.dll's two MMCSS entry points, resolved at run time so the plug-in gains no import. The +// signatures are avrt.h's (MinGW-w64): AvSetMmThreadCharacteristicsW(LPCWSTR, LPDWORD) returning a +// HANDLE, and AvRevertMmThreadCharacteristics(HANDLE) returning a BOOL. +using AvSetFn = HANDLE(WINAPI *)(LPCWSTR, LPDWORD); +using AvRevertFn = BOOL(WINAPI *)(HANDLE); + +// GetProcAddress returns a FARPROC; going through a generic function pointer is the conversion +// GCC's -Wcast-function-type accepts without complaint. +template Fn resolve(HMODULE module, const char *name) +{ + return reinterpret_cast(reinterpret_cast(GetProcAddress(module, name))); +} +#endif + +} // namespace + +//------------------------------------------------------------------------ +BranchRunner::BranchRunner() +{ +#if defined(__linux__) + mWakeValid = sem_init(&mWake, 0, 0) == 0; + if (!mWakeValid) + std::fprintf(stderr, "rations: branch runner unavailable (sem_init: %s)\n", + std::strerror(errno)); +#elif defined(_WIN32) + mWake = CreateSemaphoreW(nullptr, 0, LONG_MAX, nullptr); + if (!mWake) + std::fprintf(stderr, "rations: branch runner unavailable (CreateSemaphoreW: %lu)\n", + static_cast(GetLastError())); +#endif +} + +BranchRunner::~BranchRunner() +{ + stop(); +#if defined(__linux__) + if (mWakeValid) + sem_destroy(&mWake); +#elif defined(_WIN32) + if (mWake) + CloseHandle(static_cast(mWake)); +#endif +} + +//------------------------------------------------------------------------ +void BranchRunner::start() +{ +#if defined(__linux__) || defined(_WIN32) +#if defined(__linux__) + if (!mWakeValid) + return; + mMatched = false; +#else + if (!mWake) + return; +#endif + if (mThread.joinable()) + return; + mState.store(kIdle, std::memory_order_relaxed); + mClaimAllowed = false; + mThread = std::thread([this] { loop(); }); + mRunning.store(true, std::memory_order_release); +#endif +} + +void BranchRunner::stop() +{ + if (!mThread.joinable()) + return; + mRunning.store(false, std::memory_order_release); +#if defined(__linux__) + sem_post(&mWake); +#elif defined(_WIN32) + ReleaseSemaphore(static_cast(mWake), 1, nullptr); +#endif + mThread.join(); +} + +//------------------------------------------------------------------------ +void BranchRunner::noteAudioThread() +{ +#if defined(__linux__) + const pthread_t self = pthread_self(); + if (!mAudioThreadKnown.load(std::memory_order_relaxed) || + !pthread_equal(mAudioThread.load(std::memory_order_relaxed), self)) { + mAudioThread.store(self, std::memory_order_relaxed); + mAudioThreadKnown.store(true, std::memory_order_release); + } +#endif +} + +//------------------------------------------------------------------------ +void BranchRunner::post(nam::DSP *model, NAM_SAMPLE *in, NAM_SAMPLE *out, int numFrames) +{ + mModel = model; + mIn = in; + mOut = out; + mFrames = numFrames; + mState.store(kPosted, std::memory_order_release); + // Not checked, deliberately: a failed post means the helper is not woken, and RT then takes + // the job back and runs it itself. See the header. +#if defined(__linux__) + sem_post(&mWake); +#elif defined(_WIN32) + ReleaseSemaphore(static_cast(mWake), 1, nullptr); +#endif +} + +bool BranchRunner::takeBack() +{ + int expected = kPosted; + // Acquire on failure too: if the helper got there first, everything after this point reads + // state the helper published. + if (!mState.compare_exchange_strong(expected, kIdle, std::memory_order_acq_rel, + std::memory_order_acquire)) + return false; + mJobsTakenBack.store(mJobsTakenBack.load(std::memory_order_relaxed) + 1, + std::memory_order_relaxed); + return true; +} + +void BranchRunner::waitDone() +{ + while (mState.load(std::memory_order_acquire) != kDone) + cpuRelax(); + mState.store(kIdle, std::memory_order_relaxed); +} + +//------------------------------------------------------------------------ +bool BranchRunner::mayClaim() +{ +#if defined(__linux__) + if (!mAudioThreadKnown.load(std::memory_order_acquire)) + return false; + const pthread_t audio = mAudioThread.load(std::memory_order_relaxed); + if (mMatched && pthread_equal(audio, mMatchedThread)) + return mClaimAllowed; + mMatched = true; + mMatchedThread = audio; + mClaimAllowed = false; + + int policy = 0; + sched_param param = {}; + int err = pthread_getschedparam(audio, &policy, ¶m); + if (err != 0) { + std::fprintf(stderr, + "rations: branch runner cannot read the audio thread's priority (%s); it " + "stays idle and the audio thread runs both branches\n", + std::strerror(err)); + return false; + } + if (policy != SCHED_FIFO && policy != SCHED_RR) { + // The audio thread is not real-time, so a helper at the default policy is on the same + // footing as it and may share its work. + mClaimAllowed = true; + return true; + } + err = pthread_setschedparam(pthread_self(), policy, ¶m); + if (err != 0) { + std::fprintf(stderr, + "rations: branch runner cannot match the audio thread's real-time priority " + "(%s); it stays idle and the audio thread runs both branches\n", + std::strerror(err)); + return false; + } + mClaimAllowed = true; + return true; +#elif defined(_WIN32) + return mClaimAllowed; +#else + return false; +#endif +} + +void BranchRunner::loop() +{ + // The same floating-point mode as the audio thread, so a branch computed here is bit-identical + // to the same branch computed there. + rtSetDenormalMode(); + +#if defined(_WIN32) + HANDLE mmcss = nullptr; + AvRevertFn avRevert = nullptr; + HMODULE avrt = LoadLibraryW(L"avrt.dll"); + if (avrt) { + const AvSetFn avSet = resolve(avrt, "AvSetMmThreadCharacteristicsW"); + avRevert = resolve(avrt, "AvRevertMmThreadCharacteristics"); + DWORD taskIndex = 0; + if (avSet && avRevert) + mmcss = avSet(L"Pro Audio", &taskIndex); + } + mClaimAllowed = mmcss != nullptr; + if (!mClaimAllowed) + std::fprintf(stderr, "rations: branch runner could not join MMCSS \"Pro Audio\"; it stays " + "idle and the audio thread runs both branches\n"); +#endif + + for (;;) { +#if defined(__linux__) + if (sem_wait(&mWake) != 0) { + if (errno == EINTR) + continue; + std::fprintf(stderr, "rations: branch runner stopped (sem_wait: %s)\n", + std::strerror(errno)); + break; + } +#elif defined(_WIN32) + if (WaitForSingleObject(static_cast(mWake), INFINITE) != WAIT_OBJECT_0) { + std::fprintf(stderr, "rations: branch runner stopped (WaitForSingleObject: %lu)\n", + static_cast(GetLastError())); + break; + } +#else + break; +#endif + if (!mRunning.load(std::memory_order_acquire)) + break; + // A helper that may not claim simply never does: every job it is woken for is taken back + // by RT, which is the serial path. + if (!mayClaim()) + continue; + + // A wake can be stale: RT may have taken the job back already, and every post counts one + // wake whether or not the helper was the one that ran it. The claim settles it. + int expected = kPosted; + if (!mState.compare_exchange_strong(expected, kRunning, std::memory_order_acq_rel, + std::memory_order_relaxed)) + continue; + NAM_SAMPLE *in = mIn; + NAM_SAMPLE *out = mOut; + mModel->process(&in, &out, mFrames); + mJobsRun.store(mJobsRun.load(std::memory_order_relaxed) + 1, std::memory_order_relaxed); + mState.store(kDone, std::memory_order_release); + } + +#if defined(_WIN32) + if (mmcss && !avRevert(mmcss)) + std::fprintf(stderr, "rations: branch runner could not leave MMCSS (%lu)\n", + static_cast(GetLastError())); + // LoadLibraryW counts references, so this releases only the one taken above. + if (avrt) + FreeLibrary(avrt); +#endif +} + +} // namespace Rations diff --git a/core/branchrunner.h b/core/branchrunner.h new file mode 100644 index 0000000..889cefb --- /dev/null +++ b/core/branchrunner.h @@ -0,0 +1,162 @@ +// BranchRunner — a second thread that may run ONE model call for the audio thread. +// +// While a dial on the sounding channel moves, its CrossfadeEngine runs two models per chunk, +// branch A and branch B, and on one thread that doubles the amp's cost for the length of the +// sweep. The two calls are independent — two different nam::DSP instances, read-only shared +// input, separate outputs — so they can run at the same time on two cores. This class is the +// other core. +// +// The protocol is one job slot and one atomic state, and its shape is the safety argument: +// +// Idle --post (RT)--> Posted --claim (helper)--> Running --finish (helper)--> Done +// | +// +--takeBack (RT)--> Idle (RT runs the job itself) +// +// * RT never waits for work that has not STARTED. After running branch A it tries to take the +// job back with one compare-exchange; if the helper has not claimed it yet, RT runs branch B +// itself and the block costs what it cost before this class existed. A helper that is late, +// starved, or not running at all therefore costs nothing but a wasted post. +// * RT waits only for a job the helper has already claimed, and that wait is bounded by one +// model call on at most engine::kChunk samples. It spins on an acquire load with a pause +// instruction; there is no syscall and no lock in it. +// * Ownership is exclusive. From the post until RT has observed Done (or taken the job back), +// the model, its input and its output buffer belong to the job, and RT touches none of them. +// The slot's plain fields are written by RT before the release store of Posted and read by +// the helper only after its acquire-release claim, so the atomic carries them. +// * The helper is a real-time thread under every rule the audio thread is under: it allocates +// nothing after start(), takes no lock, arms flush-to-zero exactly as RT does (so a branch +// computed here is bit-identical to the same branch computed there), and is joined in stop(). +// +// Waking the helper is a semaphore post per job: sem_post on Linux and ReleaseSemaphore on Windows. +// Neither blocks (sem_post is also async-signal-safe, signal-safety(7)), so both are fit for the +// audio thread. The helper sleeps on the semaphore between jobs and burns no core while the dial is +// still. A post that fails — a count at its ceiling — only means the helper is not woken, and RT +// then takes the job back, so the result is not checked on RT, where there is nothing to do with +// it. +// +// Priority is the helper's own business and never RT's, and it decides whether the helper may +// claim at all. The rule is that the helper is NEVER LESS REAL-TIME THAN THE AUDIO THREAD: a job +// claimed by a thread the scheduler can preempt in favour of ordinary work is a job RT could be +// left waiting on for a whole time slice. So: +// +// * Linux: RT publishes its thread handle (a plain value, no syscall) and the helper copies that +// thread's scheduling policy and priority onto itself. That works under JACK, inside a DAW and +// inside a bridge alike, because it asks the thread actually running the audio rather than +// guessing what the host gave it. If the audio thread is real-time and the copy is refused, +// the helper claims nothing and every job is taken back. If the audio thread is NOT real-time +// (an offline render, a test tool), the helper is on the same footing as it and may claim. +// * Windows: the helper asks MMCSS for "Pro Audio", as the standalone's WASAPI thread does, and +// claims nothing if that is refused. avrt.dll is loaded at run time rather than linked, so the +// plug-in carries no new import. UNVERIFIED on a real Windows machine under ASIO — flagged. +// * Everywhere else (macOS): not implemented. start() leaves the runner stopped and every job is +// run serially, exactly as before this class existed. The macOS mechanism is an audio +// workgroup, and nothing about it can be checked on the machine this was written on. + +#pragma once + +#include "NAM/dsp.h" + +#include +#include + +#if defined(__linux__) +#include +#include +#endif + +namespace Rations +{ + +//------------------------------------------------------------------------ +class BranchRunner +{ +public: + BranchRunner(); + ~BranchRunner(); + BranchRunner(const BranchRunner &) = delete; + BranchRunner &operator=(const BranchRunner &) = delete; + + // Non-RT. Starts the helper thread. A no-op where the platform has no implementation, which + // leaves the runner stopped: running() stays false and the engine runs both branches itself. + void start(); + // Non-RT. Joins the helper. Must not race a process() call, which the plug-in lifecycle + // already guarantees: terminate() never overlaps the audio thread. + void stop(); + + // RT. True when a helper exists to take a job. Checked before posting, so a stopped runner + // costs one load and no syscall. + bool running() const + { + return mRunning.load(std::memory_order_acquire); + } + + // RT. Tell the helper which thread is the audio thread, so it can match that thread's + // scheduling. Cheap enough to call every block; it only stores when the thread changes. + void noteAudioThread(); + + // RT. Hand one model call to the helper. The caller must later call either takeBack() or + // waitDone() before touching model, in or out again. + void post(nam::DSP *model, NAM_SAMPLE *in, NAM_SAMPLE *out, int numFrames); + // RT. Returns true if the job had not been claimed and is now RT's again, to run itself. + // Returns false if the helper is running it, in which case waitDone() must follow. + bool takeBack(); + // RT. Waits for a job the helper has already claimed. Bounded by one model call. + void waitDone(); + + // Diagnostics, any thread: how many jobs the helper ran, and how many RT took back and ran + // itself. The tools read them to prove the parallel path was actually taken, because a runner + // that never wins a single claim is indistinguishable from serial by output alone. + unsigned long long jobsRun() const + { + return mJobsRun.load(std::memory_order_relaxed); + } + unsigned long long jobsTakenBack() const + { + return mJobsTakenBack.load(std::memory_order_relaxed); + } + +private: + enum State : int { + kIdle = 0, + kPosted = 1, + kRunning = 2, + kDone = 3, + }; + + void loop(); + // Called by the helper on itself, between jobs. Returns whether it may claim: true only when + // it is at least as real-time as the audio thread. See the top of this file. + bool mayClaim(); + + // The job slot. Plain fields, published by the release store of kPosted and consumed after + // the helper's acquire-release claim; see the protocol at the top of this file. + nam::DSP *mModel = nullptr; + NAM_SAMPLE *mIn = nullptr; + NAM_SAMPLE *mOut = nullptr; + int mFrames = 0; + + std::atomic mState{kIdle}; + // Each written by one thread only: the helper counts what it ran, RT counts what it took back. + std::atomic mJobsRun{0}; + std::atomic mJobsTakenBack{0}; + std::atomic mRunning{false}; + std::thread mThread; + +#if defined(__linux__) + sem_t mWake; + bool mWakeValid = false; + // The audio thread's handle as RT last published it. Atomic because RT writes it and the + // helper reads it; pthread_t is an integer on glibc. + std::atomic mAudioThread{}; + std::atomic mAudioThreadKnown{false}; + // Helper-only: which audio thread the helper last matched, and the verdict it reached. + pthread_t mMatchedThread{}; + bool mMatched = false; + bool mClaimAllowed = false; +#elif defined(_WIN32) + void *mWake = nullptr; // HANDLE of a semaphore; void* keeps out of this header + bool mClaimAllowed = false; // helper-only: whether MMCSS took it +#endif +}; + +} // namespace Rations diff --git a/core/channelrack.cpp b/core/channelrack.cpp index d0f568b..d1c5d36 100644 --- a/core/channelrack.cpp +++ b/core/channelrack.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include namespace Rations @@ -107,6 +108,11 @@ void ChannelRack::start() mPrimeRunning.store(true, std::memory_order_release); mPrimeThread = std::thread([this] { primeLoop(); }); } + + // The branch runner. Left stopped, the engine runs both branches itself, exactly as it did + // before the runner existed. + if (mParallelBranches && !std::getenv("RATIONS_SERIAL_BRANCHES")) + mRunner.start(); } void ChannelRack::stop() @@ -116,6 +122,7 @@ void ChannelRack::stop() mPrimeRunning.store(false, std::memory_order_release); if (mPrimeThread.joinable()) mPrimeThread.join(); + mRunner.stop(); for (int c = 0; c < kChannelCount; ++c) mLoader[c].stop(); @@ -847,7 +854,10 @@ void ChannelRack::processNative(NAM_SAMPLE **in, NAM_SAMPLE **out, int numFrames // which is what keeps the audio thread's steady-state cost at one model however many banks // are resident. The prime worker does feed the idle three, on its own thread, so that they // are already exact when the footswitch is stomped. + mRunner.noteAudioThread(); + mEngine[mFrom].setRunner(&mRunner); mEngine[mFrom].processNative(in, out, numFrames); + mEngine[mFrom].setRunner(nullptr); applyLevel(mFrom, dst, numFrames); if (mFading) { diff --git a/core/channelrack.h b/core/channelrack.h index e150496..618de6a 100644 --- a/core/channelrack.h +++ b/core/channelrack.h @@ -40,6 +40,7 @@ #pragma once +#include "branchrunner.h" #include "crossfadeengine.h" #include "modelbank.h" #include "nativeresampler.h" @@ -155,6 +156,21 @@ class ChannelRack : public NativeBlockProcessor // only thing under test is whether the concurrency is correct. bool warm(Channel ch) const; + // Non-RT, before start(). Whether the sounding channel's dial crossfade may run its second + // branch on the branch runner's thread. On by default; the tools turn it off to have a serial + // reference to compare against, and RATIONS_SERIAL_BRANCHES in the environment turns it off + // for the whole process so the same binary can be measured both ways. + void setParallelBranches(bool on) + { + mParallelBranches = on; + } + + // The branch runner's counters, for the tools. See BranchRunner::jobsRun(). + const BranchRunner &branchRunner() const + { + return mRunner; + } + private: // Which thread owns a channel's engine. Exactly one at any instant, with no object either may // "just read": the handover is the whole safety property, so it is one atomic per channel and @@ -292,6 +308,11 @@ class ChannelRack : public NativeBlockProcessor std::thread mPrimeThread; std::atomic mPrimeRunning{false}; + // The second thread the sounding channel's dial crossfade may lend branch B to. Lent only to + // mFrom, and only for the duration of its processNative() call, so no other engine ever sees + // it and the prime worker's engines stay serial. + BranchRunner mRunner; + bool mParallelBranches = true; std::atomic mWorstPrimeLag{0}; // The worker's own staging. Sized in prepare() and never resized afterwards, because the // worker allocates nothing once it is running. diff --git a/core/crossfadeengine.cpp b/core/crossfadeengine.cpp index 7fbb184..34916ff 100644 --- a/core/crossfadeengine.cpp +++ b/core/crossfadeengine.cpp @@ -1,6 +1,7 @@ // CrossfadeEngine implementation. See crossfadeengine.h for why position is continuous. #include "crossfadeengine.h" +#include "branchrunner.h" #include "modelbank.h" #include @@ -32,7 +33,8 @@ void CrossfadeEngine::prepare(int maxNativeFrames, double nativeSampleRate) const size_t n = static_cast(std::max(maxNativeFrames, engine::kChunk)); mScratchA.assign(n, 0.0); mScratchB.assign(n, 0.0); - mScratchIn.assign(n, 0.0); + mScratchInA.assign(n, 0.0); + mScratchInB.assign(n, 0.0); mNativeSampleRate = nativeSampleRate > 0.0 ? nativeSampleRate : kNativeSampleRate; // The gate that opens when the first entry becomes playable. Reuses the bypass ramp length — @@ -478,26 +480,36 @@ void CrossfadeEngine::processNative(NAM_SAMPLE **in, NAM_SAMPLE **out, int numFr // calibration off, where every inputGain is exactly 1.0 and this costs one comparison per // branch per sub-chunk and touches no memory — which is what keeps the default path, and // every measurement taken on it, exactly what it was. - auto branchInput = [&](const Branch &branch) -> NAM_SAMPLE * { + auto branchInput = [&](const Branch &branch, std::vector &scratch) { if (branch.inputGain == 1.0) return inPtr; - NAM_SAMPLE *scaled = mScratchIn.data(); + NAM_SAMPLE *scaled = scratch.data(); for (int i = 0; i < n; ++i) scaled[i] = chunkIn[i] * branch.inputGain; return scaled; }; + // With both branches bound and a runner lent, branch B goes to the runner's thread while + // branch A runs here, and the two meet again before the mix. RT never waits for B unless + // the runner has already STARTED it: if B is still unclaimed when A is done, it is taken + // back and run here, so a late or absent runner costs exactly what serial always cost. + // Both paths hand B's model the same input pointer and the same output buffer, so the + // samples it produces cannot depend on which thread ran it. + NAM_SAMPLE *inB = mB.bound() ? branchInput(mB, mScratchInB) : nullptr; + NAM_SAMPLE *outB = mScratchB.data(); + const bool parallel = mA.bound() && mB.bound() && mRunner && mRunner->running(); + if (parallel) + mRunner->post(mB.model, inB, outB, n); if (mA.bound()) { - NAM_SAMPLE *inA = branchInput(mA); + NAM_SAMPLE *inA = branchInput(mA, mScratchInA); NAM_SAMPLE *outA = mScratchA.data(); mA.model->process(&inA, &outA, n); mA.samplesLive += n; } if (mB.bound()) { - // Recomputed rather than reused: A and B are different captures and may state - // different input levels, and the buffer above holds A's scaling by now. - NAM_SAMPLE *inB = branchInput(mB); - NAM_SAMPLE *outB = mScratchB.data(); - mB.model->process(&inB, &outB, n); + if (!parallel || mRunner->takeBack()) + mB.model->process(&inB, &outB, n); + else + mRunner->waitDone(); mB.samplesLive += n; } diff --git a/core/crossfadeengine.h b/core/crossfadeengine.h index e4dc4cc..fa1f203 100644 --- a/core/crossfadeengine.h +++ b/core/crossfadeengine.h @@ -32,6 +32,7 @@ namespace Rations { +class BranchRunner; class ModelBank; //------------------------------------------------------------------------ @@ -71,6 +72,14 @@ class CrossfadeEngine : public NativeBlockProcessor // stepping at the crossing. void setOutputMode(int mode, double calLevelDbu, bool calibrateInput); + // RT. Lend this engine a second thread for branch B, or take it away with nullptr. Only the + // thread that owns the engine calls this, and only the audio thread ever lends one: the prime + // worker's engines run serially, because nothing is waiting on them. + void setRunner(BranchRunner *runner) + { + mRunner = runner; + } + // NativeBlockProcessor. void processNative(NAM_SAMPLE **in, NAM_SAMPLE **out, int numFrames) override; @@ -170,6 +179,7 @@ class CrossfadeEngine : public NativeBlockProcessor static double primedFraction(const Branch &branch); ModelBank *mLoader = nullptr; + BranchRunner *mRunner = nullptr; Bank *mBank = nullptr; // Held when the retirement queue was momentarily full. Retried on the next block; the audio // thread never deletes it itself. @@ -206,9 +216,11 @@ class CrossfadeEngine : public NativeBlockProcessor std::vector mScratchA; std::vector mScratchB; - // Where a branch's input is scaled when its inputGain is not 1.0. Written and consumed inside - // one sub-chunk, so one buffer serves both branches even when they want different gains. - std::vector mScratchIn; + // Where a branch's input is scaled when its inputGain is not 1.0. One per branch, because + // branch B may be running on the runner's thread while branch A is being scaled on this one; + // a single buffer shared between them was a data race the moment they could overlap. + std::vector mScratchInA; + std::vector mScratchInB; }; } // namespace Rations diff --git a/core/tools/rations_racecheck.cpp b/core/tools/rations_racecheck.cpp index c31966a..c5ef7ea 100644 --- a/core/tools/rations_racecheck.cpp +++ b/core/tools/rations_racecheck.cpp @@ -250,6 +250,16 @@ int main(int argc, char **argv) printf("worst lag %lld samples (%.1f ms) of %lld before the worker is lapped (%.0f%%)\n", worst, 1000.0 * static_cast(worst) / kNativeRate, budget, 100.0 * static_cast(worst) / static_cast(budget)); + // The branch runner is only under test if it actually ran branches. A run in which every job + // was taken back would be clean under ThreadSanitizer and would have tested nothing of it. + const unsigned long long runnerJobs = rack.branchRunner().jobsRun(); + printf("branch runner %llu branch calls run on it, %llu taken back by the audio thread\n", + runnerJobs, rack.branchRunner().jobsTakenBack()); + if (runnerJobs == 0) { + fprintf(stderr, "rations_racecheck: the branch runner never ran a branch, so this run did " + "not exercise it\n"); + return 1; + } printf("\nrations_racecheck: completed - a clean run under ThreadSanitizer is the gate\n"); return 0; } diff --git a/core/tools/rations_switchcheck.cpp b/core/tools/rations_switchcheck.cpp index 0bda4c9..a2f0897 100644 --- a/core/tools/rations_switchcheck.cpp +++ b/core/tools/rations_switchcheck.cpp @@ -604,6 +604,32 @@ int main(int argc, char **argv) rack.releaseBanks(); } + // --- the rack: the dial sweeping for the whole run, serial and parallel ---------------------- + // The branch runner may run branch B on a second thread. Whichever thread runs it, it is the + // same model fed the same samples into the same buffer, so the two renders must agree to the + // BIT, not to a tolerance: any difference at all means the threads touched each other's data + // or ran in different floating-point modes. + std::vector outSerial(n, 0.0), outParallel(n, 0.0); + unsigned long long helperJobs = 0, takenBack = 0; + for (int parallel = 0; parallel < 2; ++parallel) { + Rations::ChannelRack rack; + rack.setParallelBranches(parallel != 0); + rack.prepare(opt.block, kNativeRate); + rack.setOutputMode(kOutputModeNormalized, kCalLevelDbu, opt.calibrate); + rack.start(); + rack.loadChannel(kSlotA, opt.dirA, /*isDirectory=*/true, 1.0, Rations::engine::kChunk); + rack.loadChannel(kSlotB, opt.dirB, /*isDirectory=*/true, 1.0, Rations::engine::kChunk); + for (int i = 0; i < 1200 && rack.progress() < 1.0f; ++i) + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + renderRack(rack, opt, input, parallel ? outParallel : outSerial, total, total, -1, total); + if (parallel) { + helperJobs = rack.branchRunner().jobsRun(); + takenBack = rack.branchRunner().jobsTakenBack(); + } + rack.stop(); + rack.releaseBanks(); + } + refA.close(); refB.close(); @@ -737,6 +763,27 @@ int main(int argc, char **argv) } } + // --- 6. PARALLEL BRANCHES ------------------------------------------------------------------- + const bool bitIdentical = + std::memcmp(outSerial.data(), outParallel.data(), n * sizeof(double)) == 0; + printf("\nparallel dial swept for the whole run; %llu branch calls on the runner, %llu " + "taken back; serial and parallel %s\n", + helperJobs, takenBack, bitIdentical ? "bit-identical" : "DIFFER"); + if (!bitIdentical) { + fprintf(stderr, + "FAIL: running branch B on the branch runner changed the output (max " + "difference %.3e). The two threads shared data they must not, or ran in " + "different floating-point modes.\n", + maxDiff(outSerial, outParallel, 0, n)); + ++failures; + } + if (helperJobs == 0) { + fprintf(stderr, + "FAIL: the branch runner never ran a single branch, so the comparison above " + "compared serial with serial and proves nothing.\n"); + ++failures; + } + if (failures > 0) { printf("\nFAILED - %d assertion(s)\n", failures); return 1; diff --git a/products/rack/CMakeLists.txt b/products/rack/CMakeLists.txt index a5b91b3..8985850 100644 --- a/products/rack/CMakeLists.txt +++ b/products/rack/CMakeLists.txt @@ -568,6 +568,7 @@ set(NAMP_PLUGIN_SOURCES ${NAMP_CORE_DIR}/modelbank.cpp ${NAMP_CORE_DIR}/crossfadeengine.h ${NAMP_CORE_DIR}/crossfadeengine.cpp + ${NAMP_CORE_DIR}/branchrunner.cpp ${NAMP_CORE_DIR}/channelrack.h ${NAMP_CORE_DIR}/channelrack.cpp ${NAMP_CORE_DIR}/irblend.h @@ -1058,6 +1059,7 @@ if(NAMPRACK_BUILD_TOOLS) ${NAMP_CORE_DIR}/capturesource.cpp ${NAMP_CORE_DIR}/modelbank.cpp ${NAMP_CORE_DIR}/crossfadeengine.cpp + ${NAMP_CORE_DIR}/branchrunner.cpp ${NAMP_CORE_DIR}/channelrack.cpp # For utf8ToPath, which modelbank.cpp uses to keep an unrepresentable path from # throwing out of the worker thread. @@ -1089,6 +1091,7 @@ if(NAMPRACK_BUILD_TOOLS) ${NAMP_CORE_DIR}/capturesource.cpp ${NAMP_CORE_DIR}/modelbank.cpp ${NAMP_CORE_DIR}/crossfadeengine.cpp + ${NAMP_CORE_DIR}/branchrunner.cpp ${NAMP_CORE_DIR}/channelrack.cpp ${NAMP_CORE_DIR}/platform/respath.cpp ${NAMP_CORE_DIR}/gfx/resourcestore.cpp diff --git a/products/rack/tools/rations_rtcheck.cpp b/products/rack/tools/rations_rtcheck.cpp index a3f420e..c3d1d8f 100644 --- a/products/rack/tools/rations_rtcheck.cpp +++ b/products/rack/tools/rations_rtcheck.cpp @@ -234,6 +234,54 @@ int main(int argc, char **argv) rack.releaseBanks(); } + // --- the channel rack, the sounding dial sweeping ------------------------------------------- + // Two branches bound on the sounding channel for the whole count, so branch B is handed to the + // branch runner every chunk. The allocation counters are process-wide, so this counts the + // runner's thread as well as the audio thread's — and it only counts anything if the runner + // actually ran branches, which is checked rather than assumed. + { + Rations::ChannelRack rack; + rack.prepare(kBlock, Rations::kNativeSampleRate); + rack.start(); + rack.loadChannel(Rations::kChannelClean, dir, /*isDirectory=*/true, 1.0, + Rations::engine::kChunk); + for (int i = 0; i < 1200 && rack.progress() < 1.0f; ++i) + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + if (rack.progress() < 1.0f) { + fprintf(stderr, "rations_rtcheck: the rack's bank never finished building\n"); + return 1; + } + + long long block = 0; + auto drive = [&](int blocks) { + NAM_SAMPLE *ip = in.data(); + NAM_SAMPLE *op = out.data(); + for (int b = 0; b < blocks; ++b, ++block) { + rack.pollBanks(); + rack.setPositionNorm(Rations::kChannelClean, + static_cast(block % 400) / 400.0); + rack.requestChannel(Rations::kChannelClean); + rack.processNative(&ip, &op, kBlock); + } + }; + drive(8); + const unsigned long long before = rack.branchRunner().jobsRun(); + + printf("counting channel rack, sounding dial sweeping, branch B on the runner\n"); + allocation_tracking::run_allocation_test_no_allocations( + nullptr, [&] { drive(200); }, nullptr, + "channel rack, sounding dial sweeping, branch B on the runner"); + + const unsigned long long ran = rack.branchRunner().jobsRun() - before; + rack.stop(); + rack.releaseBanks(); + if (ran == 0) { + fprintf(stderr, "rations_rtcheck: the branch runner ran no branches during the count, " + "so it was not tested\n"); + return 1; + } + } + // --- the cabinet, both slots filled --------------------------------------------------------- // The IRs are built from raw audio rather than read from files: ImpulseResponse takes an IRData // directly, so the test needs no WAV on disk and no assumption about what is installed. Two diff --git a/products/rations/CMakeLists.txt b/products/rations/CMakeLists.txt index f5aee8b..707beb7 100644 --- a/products/rations/CMakeLists.txt +++ b/products/rations/CMakeLists.txt @@ -604,6 +604,7 @@ set(NAMP_PLUGIN_SOURCES ${NAMP_CORE_DIR}/modelbank.cpp ${NAMP_CORE_DIR}/crossfadeengine.h ${NAMP_CORE_DIR}/crossfadeengine.cpp + ${NAMP_CORE_DIR}/branchrunner.cpp ${NAMP_CORE_DIR}/channelrack.h ${NAMP_CORE_DIR}/channelrack.cpp ${NAMP_CORE_DIR}/irblend.h @@ -1074,6 +1075,7 @@ add_executable(rations_switchcheck ${NAMP_CORE_DIR}/capturesource.cpp ${NAMP_CORE_DIR}/modelbank.cpp ${NAMP_CORE_DIR}/crossfadeengine.cpp + ${NAMP_CORE_DIR}/branchrunner.cpp ${NAMP_CORE_DIR}/channelrack.cpp # For utf8ToPath, which modelbank.cpp uses to keep an unrepresentable path # from throwing out of the worker thread. @@ -1105,6 +1107,7 @@ add_executable(rations_racecheck ${NAMP_CORE_DIR}/capturesource.cpp ${NAMP_CORE_DIR}/modelbank.cpp ${NAMP_CORE_DIR}/crossfadeengine.cpp + ${NAMP_CORE_DIR}/branchrunner.cpp ${NAMP_CORE_DIR}/channelrack.cpp ${NAMP_CORE_DIR}/platform/respath.cpp ${NAMP_CORE_DIR}/gfx/resourcestore.cpp @@ -1155,6 +1158,7 @@ add_executable(rations_rtcheck ${NAMP_CORE_DIR}/capturesource.cpp ${NAMP_CORE_DIR}/modelbank.cpp ${NAMP_CORE_DIR}/crossfadeengine.cpp + ${NAMP_CORE_DIR}/branchrunner.cpp ${NAMP_CORE_DIR}/channelrack.cpp ${NAMP_PRODUCT_DIR}/src/pedals/pedalchain.cpp # For utf8ToPath, which modelbank.cpp uses to keep an unrepresentable path @@ -1273,6 +1277,7 @@ if(NAMP_LINUX AND RATIONS_LV2_FOUND) ${NAMP_CORE_DIR}/capturesource.cpp ${NAMP_CORE_DIR}/modelbank.cpp ${NAMP_CORE_DIR}/crossfadeengine.cpp + ${NAMP_CORE_DIR}/branchrunner.cpp ${NAMP_CORE_DIR}/channelrack.cpp ${NAMP_CORE_DIR}/irblend.cpp ${NAMP_CORE_DIR}/midilearn.cpp diff --git a/products/rations/tools/rations_rtcheck.cpp b/products/rations/tools/rations_rtcheck.cpp index 1f506d5..6da3390 100644 --- a/products/rations/tools/rations_rtcheck.cpp +++ b/products/rations/tools/rations_rtcheck.cpp @@ -235,6 +235,54 @@ int main(int argc, char **argv) rack.releaseBanks(); } + // --- the channel rack, the sounding dial sweeping ------------------------------------------- + // Two branches bound on the sounding channel for the whole count, so branch B is handed to the + // branch runner every chunk. The allocation counters are process-wide, so this counts the + // runner's thread as well as the audio thread's — and it only counts anything if the runner + // actually ran branches, which is checked rather than assumed. + { + Rations::ChannelRack rack; + rack.prepare(kBlock, Rations::kNativeSampleRate); + rack.start(); + rack.loadChannel(Rations::kChannelClean, dir, /*isDirectory=*/true, 1.0, + Rations::engine::kChunk); + for (int i = 0; i < 1200 && rack.progress() < 1.0f; ++i) + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + if (rack.progress() < 1.0f) { + fprintf(stderr, "rations_rtcheck: the rack's bank never finished building\n"); + return 1; + } + + long long block = 0; + auto drive = [&](int blocks) { + NAM_SAMPLE *ip = in.data(); + NAM_SAMPLE *op = out.data(); + for (int b = 0; b < blocks; ++b, ++block) { + rack.pollBanks(); + rack.setPositionNorm(Rations::kChannelClean, + static_cast(block % 400) / 400.0); + rack.requestChannel(Rations::kChannelClean); + rack.processNative(&ip, &op, kBlock); + } + }; + drive(8); + const unsigned long long before = rack.branchRunner().jobsRun(); + + printf("counting channel rack, sounding dial sweeping, branch B on the runner\n"); + allocation_tracking::run_allocation_test_no_allocations( + nullptr, [&] { drive(200); }, nullptr, + "channel rack, sounding dial sweeping, branch B on the runner"); + + const unsigned long long ran = rack.branchRunner().jobsRun() - before; + rack.stop(); + rack.releaseBanks(); + if (ran == 0) { + fprintf(stderr, "rations_rtcheck: the branch runner ran no branches during the count, " + "so it was not tested\n"); + return 1; + } + } + // --- the cabinet, both slots filled --------------------------------------------------------- // The IRs are built from raw audio rather than read from files: ImpulseResponse takes an IRData // directly, so the test needs no WAV on disk and no assumption about what is installed. Two