From 4a3d424aeaa52ab0096e007a9230a6653271a7c7 Mon Sep 17 00:00:00 2001 From: Stephan Terning Date: Sun, 18 Oct 2026 10:42:25 +0200 Subject: [PATCH 1/2] Fix correctness findings from the technical review --- AGENTS.md | 1 + CHANGELOG.md | 10 ++ app/src/AudioEngine.cpp | 52 ++++---- app/src/AudioEngine.h | 8 +- app/src/MainComponent.cpp | 26 ++-- app/src/MainComponent.h | 2 +- app/src/Settings.cpp | 7 +- app/src/Settings.h | 4 +- core/CMakeLists.txt | 3 + core/include/visona/AudioDeviceWatchdog.h | 50 ++++++++ core/include/visona/AudioRingSizing.h | 24 ++++ core/include/visona/BarImpulseScheduler.h | 16 ++- core/include/visona/BarPeaks.h | 3 +- core/include/visona/HostPlayheadReader.h | 38 ++++++ core/include/visona/HostTransport.h | 2 + core/include/visona/TimeSignature.h | 7 ++ core/src/AutoGain.cpp | 10 ++ core/src/BarImpulseScheduler.cpp | 61 +++++----- core/src/HostAnalysisPipeline.cpp | 17 +++ core/src/HostTransport.cpp | 2 +- core/src/SidechainSyncDetector.cpp | 4 +- docs/plugins.md | 2 + docs/technical-review.md | 5 + plugin/CMakeLists.txt | 23 ++++ plugin/src/HostPlayheadReader.h | 29 +++++ plugin/src/PluginProcessor.cpp | 66 ++-------- plugin/src/PluginProcessor.h | 9 +- plugin/src/PluginState.cpp | 14 ++- plugin/src/ScopeEditor.cpp | 41 +++---- plugin/src/ScopeEditor.h | 4 +- plugin/src/SyncProcessor.cpp | 76 ++++-------- plugin/src/SyncProcessor.h | 21 ++-- site/static/manual/index.html | 6 +- tests/AnalysisSelectorUiChecks.cpp | 5 +- tests/AutoGainTests.cpp | 46 ++++++- tests/BarImpulseSchedulerTests.cpp | 141 +++++++++++++++++----- tests/CMakeLists.txt | 1 + tests/HostAnalysisPipelineTests.cpp | 65 +++++++++- tests/HostPlayheadReaderTests.cpp | 86 +++++++++++++ tests/PluginChecks.cpp | 126 +++++++++++++++++++ tests/SpectrumAnalyzerTests.cpp | 8 +- tests/StereoUiChecks.cpp | 14 +++ ui/AnalysisSelector.cpp | 2 + ui/CMakeLists.txt | 1 + ui/DiagnosticsOverlay.cpp | 23 ++-- ui/DiagnosticsOverlay.h | 3 +- ui/RenderStats.h | 19 +++ ui/ScopeView.h | 16 +-- ui/SpectrumView.h | 9 +- ui/StereoView.cpp | 17 +-- ui/StereoView.h | 1 + 51 files changed, 899 insertions(+), 327 deletions(-) create mode 100644 core/include/visona/AudioDeviceWatchdog.h create mode 100644 core/include/visona/AudioRingSizing.h create mode 100644 core/include/visona/HostPlayheadReader.h create mode 100644 plugin/src/HostPlayheadReader.h create mode 100644 tests/HostPlayheadReaderTests.cpp create mode 100644 tests/PluginChecks.cpp create mode 100644 ui/RenderStats.h diff --git a/AGENTS.md b/AGENTS.md index 49c3cac..dc0dfaa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,6 +25,7 @@ Requires CMake 3.22+ and Ninja; on macOS also Xcode. macOS builds target Apple S - `ui/`: JUCE components, compiled into the app and plugin targets. - `third_party/`: vendored KISS FFT, the build glue for the LSP meters, and provenance and licence notes. Its READMEs say what to check when a pin changes. - `tests/`: Catch2 tests for `core/`, plus the optional offline UI checks (`*UiChecks.cpp`), a JUCE program that `ui/CMakeLists.txt` builds as `visona_ui_checks` only with `-DVISONA_BUILD_UI_CHECKS=ON`. Keep JUCE out of `core/` and the Catch2 tests. Multi-threaded stress tests are tagged `[stress]`. +- Optional `VISONA_BUILD_PLUGIN_CHECKS=ON` adds `visona_effect_checks` and `visona_sync_checks` when plugins are built. CTest runs these offline processor checks when tests are enabled; they cover lifecycle, saved state and callback allocation without a DAW. - `site/`: the static website, visona.org, with the download page and the user manual. `python3 site/build.py --serve` previews it; `.github/workflows/site.yml` deploys it to GitHub Pages. See `docs/website.md`. When a change alters what the user sees or does, update the manual in `site/static/manual/index.html` too. ## Website and manual on every pull request diff --git a/CHANGELOG.md b/CHANGELOG.md index f5b53fa..96aac0b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,16 @@ All notable changes to this project are documented here. The format is based on - The diagnostics overlay refreshes at 4 Hz in the app, so it costs less while measuring. +### Fixed + +- Plugin preparation detaches the old audio stream before replacing it, including repeated host preparation and destruction without an explicit release. +- Visona Sync schedules bar impulses without heap allocation and retains impulses that round across a block boundary. Missing PPQ positions no longer produce repeated bar impulses; invalid host tempo and time signatures retain valid defaults. +- Plugin state clamps saved colour and window indices. Small host blocks retain enough timing slots, and time-signature changes update the scope's window length. +- Auto gain retains more than ten seconds of input peaks. If the UI misses the entire retained history, gain returns to unity and waits for a new ten-second history before rising. App settings writes are coalesced and flushed on shutdown. +- The app retries an input device that fails to start, stops or reports an error. Selecting the active view preserves its history, and plugin diagnostics no longer share timing counters between instances or consume modified D shortcuts. +- Visona Sync's editor reads atomic transport display values. Stereo diagnostics report the physical display scale and recent timing maxima; scope-only counters are hidden in other views. The spectrum stress test consumes the final snapshot even when its producer finishes first. + + ## [1.0.0-beta.1] - 2026-10-16 ### Added diff --git a/app/src/AudioEngine.cpp b/app/src/AudioEngine.cpp index 731a4c0..9b323d0 100644 --- a/app/src/AudioEngine.cpp +++ b/app/src/AudioEngine.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include @@ -22,17 +23,8 @@ namespace // so every input channel is opened. constexpr int allInputChannels = 1024; -constexpr double ringSeconds = 1.0; - -// The frames fill up before the timings unless blocks average fewer frames than this. -constexpr std::size_t framesPerTimingSlot = 16; - constexpr int devicePollMs = 500; -// A running device that delivers nothing for this long is lost. JUCE's ALSA thread ends without -// telling anyone when its device is unplugged or fails, and the device still reports that it plays. -constexpr int stallTicks = 4; - // How often opening the chosen device is tried while it is listed but does not open. constexpr juce::uint32 openRetryMs = 2'000; @@ -46,13 +38,6 @@ juce::String soundCards() #endif } -std::size_t ringCapacityFrames(double sampleRate, int bufferSize) -{ - const auto oneSecond = - static_cast(std::ceil(std::max(sampleRate, 1.0) * ringSeconds)); - return std::max(oneSecond, static_cast(std::max(bufferSize, 1)) * 4); -} - /** The index of a device input channel among the channels the callback delivers, or noInput. The callback delivers the active channels in ascending order, without gaps. */ int callbackInputIndex(const juce::BigInteger& activeInputs, int deviceChannel) @@ -68,8 +53,7 @@ struct AudioEngine::Stream { Stream(std::size_t numChannels, std::size_t capacityFrames, juce::BigInteger activeInputsIn, int numDeviceInputsIn) - : ring(numChannels, capacityFrames, - std::max(capacityFrames / framesPerTimingSlot, 1)) + : ring(numChannels, capacityFrames, ringTimingSlots(capacityFrames)) , writer(ring) , activeInputs(std::move(activeInputsIn)) , numDeviceInputs(numDeviceInputsIn) @@ -138,7 +122,8 @@ void AudioEngine::openSavedDevice() bool AudioEngine::isInputRunning() const { auto* const device = deviceManager_.getCurrentAudioDevice(); - return device != nullptr && device->isPlaying() && !device->getActiveInputChannels().isZero(); + return !deviceFailed_.load(std::memory_order_relaxed) && device != nullptr && + device->isPlaying() && !device->getActiveInputChannels().isZero(); } juce::String AudioEngine::noInputReason() const @@ -158,6 +143,8 @@ juce::String AudioEngine::noInputReason() const return "The audio device \"" + savedDevice + "\" is not connected." + (waitingForChosen_ ? " Visona opens it when it is plugged in." : ""); } + if (deviceManager_.getCurrentAudioDevice() != nullptr) + return "The audio device stopped. Visona will try to reopen it."; if (lastError_.isNotEmpty()) return lastError_; if (availableDevices.isEmpty()) @@ -324,6 +311,7 @@ void AudioEngine::setSyncInputChannel(int deviceInputChannel) void AudioEngine::audioDeviceAboutToStart(juce::AudioIODevice* device) { + deviceFailed_.store(false, std::memory_order_relaxed); const auto sampleRate = device->getCurrentSampleRate(); // The source channels, and the sync input after them. auto stream = std::make_unique( @@ -460,24 +448,28 @@ bool AudioEngine::followChosenDevice() bool AudioEngine::closeStalledDevice() { const auto status = streamStatus(); - if (!status.has_value() || !isInputRunning() || status->framesDelivered != lastFramesDelivered_) - { - lastFramesDelivered_ = status.has_value() ? status->framesDelivered : 0; - stalledTicks_ = 0; - return false; - } - if (++stalledTicks_ < stallTicks) + auto* const device = deviceManager_.getCurrentAudioDevice(); + const bool selected = + device != nullptr && deviceManager_.getAudioDeviceSetup().inputDeviceName.isNotEmpty(); + const auto frames = + status ? std::optional(status->framesDelivered) : std::nullopt; + if (!watchdog_.shouldRestart(selected, device != nullptr && device->isPlaying(), frames, + deviceFailed_.exchange(false, std::memory_order_relaxed))) return false; - stalledTicks_ = 0; deviceManager_.closeAudioDevice(); waitingForChosen_ = true; - lastError_ = "The audio device stopped delivering audio."; - // It may be back already, so it is opened again at once if it is listed. - nextOpenAttemptMs_ = juce::Time::getMillisecondCounter(); + lastError_ = "The audio device stopped. Visona will try to reopen it."; + nextOpenAttemptMs_ = juce::Time::getMillisecondCounter() + openRetryMs; return true; } +void AudioEngine::audioDeviceError(const juce::String& /*errorMessage*/) +{ + // JUCE may call this from a device thread. Recovery and UI updates stay on the timer. + deviceFailed_.store(true, std::memory_order_relaxed); +} + void AudioEngine::rescanDevices() { // An open device does not depend on its type, so it keeps running if it is still there. The diff --git a/app/src/AudioEngine.h b/app/src/AudioEngine.h index e44f72a..bc5982a 100644 --- a/app/src/AudioEngine.h +++ b/app/src/AudioEngine.h @@ -4,6 +4,7 @@ #include "MidiClockInput.h" #include "ui/AudioSettings.h" +#include #include #include #include @@ -158,6 +159,7 @@ class AudioEngine final : public AudioSettings, int numSamples, const juce::AudioIODeviceCallbackContext& context) override; void audioDeviceStopped() override; + void audioDeviceError(const juce::String& errorMessage) override; void changeListenerCallback(juce::ChangeBroadcaster* source) override; void timerCallback() override; @@ -167,7 +169,7 @@ class AudioEngine final : public AudioSettings, /** Closes a device that is not the chosen one or has gone, and opens the chosen device while it is missing and listed again. */ bool followChosenDevice(); - /** Closes a running device that has delivered nothing for stallTicks timer ticks. */ + /** Closes an input that failed to start, stopped or stalled. */ bool closeStalledDevice(); /** Replaces the device types with fresh ones, which list the devices there are now. */ void rescanDevices(); @@ -199,8 +201,8 @@ class AudioEngine final : public AudioSettings, // error it shows. bool waitingForChosen_ = false; juce::uint32 nextOpenAttemptMs_ = 0; - std::uint64_t lastFramesDelivered_ = 0; - int stalledTicks_ = 0; + AudioDeviceWatchdog watchdog_; + std::atomic deviceFailed_{false}; juce::String soundCards_; juce::MidiDeviceListConnection midiDevicesChanged_; diff --git a/app/src/MainComponent.cpp b/app/src/MainComponent.cpp index 62c6540..dddd96f 100644 --- a/app/src/MainComponent.cpp +++ b/app/src/MainComponent.cpp @@ -363,7 +363,10 @@ void MainComponent::timerCallback() void MainComponent::setAnalysisView(int view) { - analysisView_ = std::clamp(view, 0, 3); + view = std::clamp(view, 0, 3); + if (analysisView_ == view) + return; + analysisView_ = view; scope_.setVisible(analysisView_ == 0); spectrum_.setActive(analysisView_ == 1); bandSpectrum_.setActive(analysisView_ == 2); @@ -746,22 +749,11 @@ void MainComponent::updateDiagnostics() values.callbackAllocations = callbackAllocations; values.allocationCheckWorks = allocationCheckWorks_; values.analysisLoad = analysisLoad; - values.rendering = scope_.stats(); - if (analysisView_ != 0) - { - const auto stats = analysisView_ == 3 ? stereo_.stats() - : analysisView_ == 2 ? bandSpectrum_.stats() - : spectrum_.stats(); - values.rendering = {}; - values.rendering.framesPerSecond = stats.framesPerSecond; - values.rendering.renderMsAverage = stats.renderMsAverage; - values.rendering.renderMsMax = stats.renderMsMax; - values.rendering.paintMsAverage = stats.paintMsAverage; - values.rendering.paintMsMax = stats.paintMsMax; - values.rendering.imageWidth = stats.imageWidth; - values.rendering.imageHeight = stats.imageHeight; - values.rendering.scale = stats.scale; - } + values.scopeRendering = analysisView_ == 0; + values.rendering = analysisView_ == 3 ? stereo_.stats() + : analysisView_ == 2 ? bandSpectrum_.stats() + : analysisView_ == 1 ? spectrum_.stats() + : scope_.stats(); values.processCpu = processCpu; const auto& snapshot = scope_.snapshot(); diff --git a/app/src/MainComponent.h b/app/src/MainComponent.h index b9352d7..d87a5a9 100644 --- a/app/src/MainComponent.h +++ b/app/src/MainComponent.h @@ -59,7 +59,7 @@ class MainComponent final : public juce::Component, /** Sets the gain by hand, which turns auto gain off. */ void setAnalysisView(int view); - int analysisView_ = 0; + int analysisView_ = -1; void setGainDb(int gainDb); void showGainDb(int gainDb); void setAutoGain(bool isOn); diff --git a/app/src/Settings.cpp b/app/src/Settings.cpp index 47d515a..51d3176 100644 --- a/app/src/Settings.cpp +++ b/app/src/Settings.cpp @@ -32,7 +32,7 @@ juce::PropertiesFile::Options fileOptions() options.folderName = "Visona"; #endif options.storageFormat = juce::PropertiesFile::storeAsXML; - options.millisecondsBeforeSaving = 0; + options.millisecondsBeforeSaving = 1000; return options; } @@ -49,6 +49,11 @@ Settings::Settings() { } +Settings::~Settings() +{ + applicationProperties_.saveIfNeeded(); +} + std::unique_ptr Settings::audioDeviceState() const { return properties_.getXmlValue(audioDeviceStateKey); diff --git a/app/src/Settings.h b/app/src/Settings.h index e66b62c..56aa4cf 100644 --- a/app/src/Settings.h +++ b/app/src/Settings.h @@ -14,12 +14,14 @@ namespace visona /** Visona's saved user configuration, kept with juce::ApplicationProperties. On macOS the file is - ~/Library/Application Support/Visona/Visona.settings. Every change is written to disk at once. + ~/Library/Application Support/Visona/Visona.settings. Changes are coalesced for one second and + flushed on orderly shutdown. */ class Settings { public: Settings(); + ~Settings(); int analysisView() const { const auto view = properties_.getIntValue("analysisView", 0); diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index 394cf73..42f1cd3 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -19,6 +19,9 @@ add_library(visona_core STATIC include/visona/AnalysisPipeline.h include/visona/AudioInputWriter.h include/visona/AudioRingBuffer.h + include/visona/AudioRingSizing.h + include/visona/AudioDeviceWatchdog.h + include/visona/HostPlayheadReader.h include/visona/AutoGain.h include/visona/Band.h include/visona/BarPeaks.h diff --git a/core/include/visona/AudioDeviceWatchdog.h b/core/include/visona/AudioDeviceWatchdog.h new file mode 100644 index 0000000..f43335c --- /dev/null +++ b/core/include/visona/AudioDeviceWatchdog.h @@ -0,0 +1,50 @@ +#pragma once + +#include +#include + +namespace visona +{ + +/** Message-thread watchdog, polled every 500 ms. A stopped or stalled input gets two + seconds to recover before reopening. Device callbacks only supply an error flag. */ +class AudioDeviceWatchdog +{ +public: + [[nodiscard]] bool shouldRestart(bool inputSelected, bool playing, + std::optional frames, bool error) noexcept + { + if (!inputSelected) + { + reset(); + return false; + } + if (error) + { + reset(); + return true; + } + if (playing && frames && (!lastFrames_ || *frames != *lastFrames_)) + { + lastFrames_ = frames; + stalledPolls_ = 0; + return false; + } + if (++stalledPolls_ < 4) + return false; + reset(); + return true; + } + + void reset() noexcept + { + lastFrames_.reset(); + stalledPolls_ = 0; + } + +private: + std::optional lastFrames_; + int stalledPolls_ = 0; +}; + +} // namespace visona diff --git a/core/include/visona/AudioRingSizing.h b/core/include/visona/AudioRingSizing.h new file mode 100644 index 0000000..35ed70a --- /dev/null +++ b/core/include/visona/AudioRingSizing.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#include +#include + +namespace visona +{ + +/** One second of audio, or four maximum-sized blocks, whichever is larger. */ +inline std::size_t ringCapacityFrames(double sampleRate, int bufferSize) +{ + const auto oneSecond = static_cast(std::ceil(std::max(sampleRate, 1.0))); + return std::max(oneSecond, static_cast(std::max(bufferSize, 1)) * 4); +} + +/** Independent of the maximum block size: hosts may send much smaller actual blocks. */ +inline std::size_t ringTimingSlots(std::size_t capacityFrames) noexcept +{ + constexpr std::size_t framesPerTimingSlot = 16; + return std::max(capacityFrames / framesPerTimingSlot, 1); +} + +} // namespace visona diff --git a/core/include/visona/BarImpulseScheduler.h b/core/include/visona/BarImpulseScheduler.h index 0f23ac0..06a5049 100644 --- a/core/include/visona/BarImpulseScheduler.h +++ b/core/include/visona/BarImpulseScheduler.h @@ -2,9 +2,9 @@ #include +#include #include #include -#include namespace visona { @@ -21,14 +21,18 @@ class BarImpulseScheduler { public: /** - Appends sample offsets within `[0, numFrames)` where a bar impulse should fire. + Writes sample offsets within `[0, numFrames)` where a bar impulse should fire. `ppqAtBlockStart` is the host PPQ at the first frame of this block. Ableton Live reports playhead PPQ at block start; anchoring placement there keeps impulses on the - arrangement grid instead of one buffer late. + arrangement grid instead of one buffer late. Returns the number written. Storage for + numFrames offsets always suffices. With smaller storage, only the first offsets fit. + Non-finite inputs, invalid signatures and bar periods below one sample are ignored. */ - static void impulsesInBlock(std::uint64_t blockStartSample, std::uint32_t numFrames, - double ppqAtBlockStart, double bpm, TimeSignature timeSignature, - double sampleRate, std::vector& offsetsOut); + [[nodiscard]] static std::size_t impulsesInBlock(std::uint64_t blockStartSample, + std::uint32_t numFrames, + double ppqAtBlockStart, double bpm, + TimeSignature timeSignature, double sampleRate, + std::span offsetsOut) noexcept; /** The stream sample index of the bar boundary for `ppq`. */ [[nodiscard]] static double sampleIndexOfBarBoundary(double ppqAtReference, diff --git a/core/include/visona/BarPeaks.h b/core/include/visona/BarPeaks.h index 1f5a7c2..36d44af 100644 --- a/core/include/visona/BarPeaks.h +++ b/core/include/visona/BarPeaks.h @@ -23,7 +23,8 @@ struct BarPeak */ struct RecentBarPeaks { - static constexpr std::size_t capacity = 16; + // Covers the complete ten-second auto-gain hold at 100 ms per input window. + static constexpr std::size_t capacity = 128; /** How many bars have ended in all. */ std::uint64_t count = 0; diff --git a/core/include/visona/HostPlayheadReader.h b/core/include/visona/HostPlayheadReader.h new file mode 100644 index 0000000..1acabd1 --- /dev/null +++ b/core/include/visona/HostPlayheadReader.h @@ -0,0 +1,38 @@ +#pragma once + +#include + +#include +#include +#include + +namespace visona +{ + +/** Validates host data shared by both plugins. Audio thread only; no allocation. */ +class HostPlayheadReader +{ +public: + /** Missing or invalid tempo/signature retains the last usable value. A finite PPQ + position is required: a missing position must never masquerade as a frozen one. */ + [[nodiscard]] HostTransport::Playhead read(bool playing, std::optional ppq, + std::optional bpm, + std::optional signature) noexcept + { + if (bpm && std::isfinite(*bpm) && *bpm > 0.0) + bpm_ = *bpm; + if (signature && signature->isValid()) + signature_ = *signature; + // Leave headroom for the transport's conversion to integral MIDI ticks. + constexpr auto maxPpq = static_cast(std::numeric_limits::max()) / + (2.0 * TimeSignature::ticksPerQuarterNote); + const bool valid = ppq && std::isfinite(*ppq) && std::abs(*ppq) < maxPpq; + return {valid, playing, valid ? *ppq : 0.0, bpm_, signature_, true}; + } + +private: + double bpm_ = 120.0; + TimeSignature signature_{}; +}; + +} // namespace visona diff --git a/core/include/visona/HostTransport.h b/core/include/visona/HostTransport.h index b34ca82..8afd831 100644 --- a/core/include/visona/HostTransport.h +++ b/core/include/visona/HostTransport.h @@ -34,6 +34,8 @@ class HostTransport double ppqPosition = 0.0; double bpm = 0.0; TimeSignature timeSignature{}; + /** A partial host report may carry play/stop even when its PPQ is missing. */ + bool hasTransportState = false; }; /** Throws std::invalid_argument if `spanCapacity` is less than 2. */ diff --git a/core/include/visona/TimeSignature.h b/core/include/visona/TimeSignature.h index 775859f..f1a7b95 100644 --- a/core/include/visona/TimeSignature.h +++ b/core/include/visona/TimeSignature.h @@ -15,6 +15,13 @@ struct TimeSignature int numerator = 4; int denominator = 4; + /** Supported signatures have whole MIDI ticks per beat and a bounded numerator. */ + [[nodiscard]] constexpr bool isValid() const noexcept + { + return numerator >= 1 && numerator <= 64 && denominator >= 1 && denominator <= 32 && + (denominator & (denominator - 1)) == 0; + } + /** 96 in 4/4, 72 in 3/4 and 6/8. */ [[nodiscard]] constexpr int ticksPerBar() const noexcept { diff --git a/core/src/AutoGain.cpp b/core/src/AutoGain.cpp index 4276c1d..7e686df 100644 --- a/core/src/AutoGain.cpp +++ b/core/src/AutoGain.cpp @@ -49,6 +49,16 @@ bool AutoGain::follow(const RecentBarPeaks& recent) noexcept } else { + if (seenBars_ + 1 < recent.oldest()) + { + // Some peaks were overwritten while the UI stalled. Their levels are unknown: + // return to unity and rebuild a complete hold interval before allowing a rise. + changed = gainDb_ != DisplayGain::minDb; + gainDb_ = DisplayGain::minDb; + historySize_ = historyNext_ = 0; + heldSeconds_ = 0.0; + seenBars_ = recent.count; + } for (auto number = std::max(seenBars_ + 1, recent.oldest()); number <= recent.count; ++number) changed = addBar(recent.bar(number)) || changed; diff --git a/core/src/BarImpulseScheduler.cpp b/core/src/BarImpulseScheduler.cpp index 4b8f070..ef04278 100644 --- a/core/src/BarImpulseScheduler.cpp +++ b/core/src/BarImpulseScheduler.cpp @@ -23,47 +23,50 @@ double samplesPerQuarterNote(double bpm, double sampleRate) noexcept } // namespace double BarImpulseScheduler::sampleIndexOfBarBoundary(double ppqAtReference, - std::uint64_t referenceSample, - double barPpq, double bpm, - double sampleRate) noexcept + std::uint64_t referenceSample, double barPpq, + double bpm, double sampleRate) noexcept { return static_cast(referenceSample) + (barPpq - ppqAtReference) * samplesPerQuarterNote(bpm, sampleRate); } -void BarImpulseScheduler::impulsesInBlock(std::uint64_t blockStartSample, - std::uint32_t numFrames, double ppqAtBlockStart, - double bpm, TimeSignature timeSignature, - double sampleRate, std::vector& offsetsOut) +std::size_t BarImpulseScheduler::impulsesInBlock(std::uint64_t /*blockStartSample*/, + std::uint32_t numFrames, double ppqAtBlockStart, + double bpm, TimeSignature timeSignature, + double sampleRate, + std::span offsetsOut) noexcept { - if (numFrames == 0 || bpm <= 0.0 || sampleRate <= 0.0) - return; + if (numFrames == 0 || offsetsOut.empty() || !std::isfinite(ppqAtBlockStart) || + !std::isfinite(bpm) || bpm <= 0.0 || !std::isfinite(sampleRate) || sampleRate <= 0.0 || + !timeSignature.isValid()) + return 0; - const auto blockEndSample = blockStartSample + numFrames; - const auto ppqAtBlockEnd = - ppqAtBlockStart + static_cast(numFrames) / samplesPerQuarterNote(bpm, sampleRate); + const auto framesPerQuarter = samplesPerQuarterNote(bpm, sampleRate); const auto barLength = quarterNotesPerBar(timeSignature); + const auto framesPerBar = framesPerQuarter * barLength; + if (!std::isfinite(framesPerBar) || framesPerBar < 1.0) + return 0; - const auto firstBar = - static_cast(std::floor(ppqAtBlockStart / barLength + 1.0e-12)); - const auto lastBar = - static_cast(std::floor(ppqAtBlockEnd / barLength + 1.0e-12)); + auto phase = std::fmod(ppqAtBlockStart, barLength); + if (phase < 0.0) + phase += barLength; + auto sample = -phase * framesPerQuarter; + // Decide ownership after rounding. In particular, a boundary just before this block + // can round to its first sample. Work locally to avoid rounding large stream indices. + constexpr double roundingTolerance = 1.0e-7; + if (sample < -0.5 - roundingTolerance) + sample += framesPerBar; - for (auto bar = firstBar; bar <= lastBar; ++bar) + std::size_t count = 0; + for (; count < offsetsOut.size(); sample += framesPerBar) { - const auto barPpq = static_cast(bar) * barLength; - const auto sample = sampleIndexOfBarBoundary(ppqAtBlockStart, blockStartSample, barPpq, - bpm, sampleRate); - if (sample < static_cast(blockStartSample) || - sample >= static_cast(blockEndSample)) - continue; - const auto boundarySample = static_cast(std::llround(sample)); - if (boundarySample < blockStartSample) - continue; - const auto offset = static_cast(boundarySample - blockStartSample); - if (offset < numFrames) - offsetsOut.push_back(offset); + const auto rounded = std::floor(sample + 0.5 + roundingTolerance); + if (rounded >= static_cast(numFrames)) + break; + if (rounded >= 0.0) + offsetsOut[count++] = static_cast(rounded); } + return count; } } // namespace visona diff --git a/core/src/HostAnalysisPipeline.cpp b/core/src/HostAnalysisPipeline.cpp index 653f08d..68f8492 100644 --- a/core/src/HostAnalysisPipeline.cpp +++ b/core/src/HostAnalysisPipeline.cpp @@ -197,6 +197,15 @@ void HostAnalysisPipeline::syncPlayheads() noexcept playhead.ppqPosition += static_cast(next->sampleIndex - lastPlayhead_.sampleIndex) / sampleRate_ * playhead.bpm / 60.0; + if (next->playhead.hasTransportState) + { + playhead.isPlaying = next->playhead.isPlaying; + playhead.bpm = next->playhead.bpm; + playhead.timeSignature = next->playhead.timeSignature; + } + // Retain the extrapolated anchor as well, so a stop without PPQ freezes time + // instead of extrapolating across the entire stopped interval on resume. + lastPlayhead_ = {next->sampleIndex, playhead}; } else { @@ -204,7 +213,15 @@ void HostAnalysisPipeline::syncPlayheads() noexcept } // The audio of this playhead reaches the plugin `offset_` frames later. + const auto previousSignature = transport_.timeSignature(); transport_.syncTo(static_cast(next->sampleIndex) + offset_, playhead); + if (transport_.timeSignature() != previousSignature) + { + analyzer_.startMusical(windowTicks()); + barPeaks_.restart(); + followsStart_ = false; + changed_ = true; + } } } diff --git a/core/src/HostTransport.cpp b/core/src/HostTransport.cpp index e76b9e1..71e1ea2 100644 --- a/core/src/HostTransport.cpp +++ b/core/src/HostTransport.cpp @@ -46,7 +46,7 @@ void HostTransport::reset(double sampleRate) noexcept void HostTransport::syncTo(double sampleTime, const Playhead& playhead) noexcept { - if (!playhead.valid) + if (!playhead.valid || !playhead.timeSignature.isValid()) return; sampleTime = clampToTimeline(sampleTime); diff --git a/core/src/SidechainSyncDetector.cpp b/core/src/SidechainSyncDetector.cpp index db042df..b4d6cf1 100644 --- a/core/src/SidechainSyncDetector.cpp +++ b/core/src/SidechainSyncDetector.cpp @@ -37,7 +37,9 @@ void SidechainSyncDetector::processBlock(std::span sidechain, doubl double bpm, TimeSignature timeSignature, double sampleRate, bool hostPlaying) noexcept { - if (!enabled_ || !hostPlaying || bpm <= 0.0 || sampleRate <= 0.0 || sidechain.empty()) + if (!enabled_ || !hostPlaying || !timeSignature.isValid() || !std::isfinite(ppqAtBlockStart) || + !std::isfinite(bpm) || bpm <= 0.0 || !std::isfinite(sampleRate) || sampleRate <= 0.0 || + sidechain.empty()) return; std::size_t peakIndex = 0; diff --git a/docs/plugins.md b/docs/plugins.md index d8a022e..a1ee702 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -84,6 +84,8 @@ In Ableton Live, turn on **Use Audio Units** under **Settings → Plug-Ins**, th ## Transport The plugin follows the **host playhead**: tempo, position, play/stop and time signature come from the DAW, as reported at the first frame of each audio block. There is no MIDI Clock input and no FREE mode in the plugin editor. The status bar shows **HOST RUN** while the DAW plays and **STOPPED** while it is stopped, which is also the state right after the plugin is loaded, before the first playback. +Both plugins reject missing or non-finite PPQ positions rather than treating an old position as current. Visona Sync emits no impulses for such a block; the scope's analysis can continue from its last valid playhead. Invalid tempo or time signatures retain the last valid value (initially 120 BPM and 4/4). Supported host time signatures have a numerator of 1–64 and a power-of-two denominator up to 32. + The standalone app still uses MIDI Clock and manual FREE tempo. ## Sidechain sync (Visona Sync) diff --git a/docs/technical-review.md b/docs/technical-review.md index 3a1d73a..fe0ee2d 100644 --- a/docs/technical-review.md +++ b/docs/technical-review.md @@ -48,6 +48,11 @@ Severity: **high** can crash, corrupt or silently break a promise; **medium** is ### 3.1 Bugs to fix now +**Follow-up (2026-10-18):** B1, B2 and B4–B18 are addressed by the correctness follow-up. The table below preserves the original findings against `8ad1301`. B3 is resolved by retaining the documented Trixie requirement for published Pi binaries; Bookworm compatibility remains separate work, with no release-build environment change. + +Validation includes core regression tests, optional offline checks of both actual plugin processors (`VISONA_BUILD_PLUGIN_CHECKS`), the analysis UI checks and macOS builds. The plugin checks exercise repeated preparation, destruction without release, malformed state, modified shortcuts, audio-thread allocation and concurrent Sync status reads. Device recovery logic is tested with a hardware-independent watchdog; physical device failures and DAW integration still require hardware smoke tests. + + | # | Severity | Where | What is wrong | Fix | | --- | --- | --- | --- | --- | | B1 | high, checked | `plugin/src/PluginProcessor.cpp:46-55` | `prepareToPlay` replaces `ring_`, freeing the old ring, before it detaches the analysis thread with `setStream`. A host that prepares twice without `releaseResources`, such as JUCE's AU wrapper when Logic toggles offline rendering, can have the analysis thread read freed memory. | Detach first (`analysis_.setStream(nullptr, 0.0)`, or call `releaseResources()`), then build the ring and writer, reset the offset, and attach last. | diff --git a/plugin/CMakeLists.txt b/plugin/CMakeLists.txt index a96696d..5e32165 100644 --- a/plugin/CMakeLists.txt +++ b/plugin/CMakeLists.txt @@ -126,3 +126,26 @@ clap_juce_extensions_plugin(TARGET VisonaSyncPlugin CLAP_SUPPORT_URL "https://github.com/stephanterning/visona/issues") visona_sign_plugin_formats(VisonaSyncPlugin) + +option(VISONA_BUILD_PLUGIN_CHECKS "Build offline plugin lifetime, state and realtime checks" OFF) +if(VISONA_BUILD_PLUGIN_CHECKS) + foreach(kind IN ITEMS effect sync) + set(check_target "visona_${kind}_checks") + add_executable(${check_target}) + target_sources(${check_target} PRIVATE ../tests/PluginChecks.cpp ../tests/support/AllocationCounter.cpp) + target_include_directories(${check_target} PRIVATE "${PROJECT_SOURCE_DIR}") + target_compile_definitions(${check_target} PRIVATE JUCE_WEB_BROWSER=0 JUCE_USE_CURL=0) + if(kind STREQUAL "sync") + target_compile_definitions(${check_target} PRIVATE VISONA_CHECK_SYNC=1) + target_link_libraries(${check_target} PRIVATE VisonaSyncPlugin) + else() + target_link_libraries(${check_target} PRIVATE VisonaPlugin) + endif() + target_link_libraries(${check_target} PRIVATE visona::core juce::juce_audio_utils + juce::juce_recommended_config_flags juce::juce_recommended_warning_flags) + if(VISONA_BUILD_TESTS) + add_test(NAME ${check_target} COMMAND ${check_target}) + set_tests_properties(${check_target} PROPERTIES TIMEOUT 120) + endif() + endforeach() +endif() diff --git a/plugin/src/HostPlayheadReader.h b/plugin/src/HostPlayheadReader.h new file mode 100644 index 0000000..44b1e9c --- /dev/null +++ b/plugin/src/HostPlayheadReader.h @@ -0,0 +1,29 @@ +#pragma once + +#include + +#include + +namespace visona +{ + +/** JUCE adapter; validation and retained defaults live in the testable core reader. */ +inline HostTransport::Playhead readHostPlayhead(juce::AudioPlayHead* head, + HostPlayheadReader& reader) noexcept +{ + if (head != nullptr) + if (const auto position = head->getPosition()) + { + std::optional signature; + if (const auto value = position->getTimeSignature()) + signature = TimeSignature{value->numerator, value->denominator}; + const auto ppq = position->getPpqPosition(); + const auto bpm = position->getBpm(); + return reader.read(position->getIsPlaying(), + ppq ? std::optional(*ppq) : std::nullopt, + bpm ? std::optional(*bpm) : std::nullopt, signature); + } + return {}; +} + +} // namespace visona diff --git a/plugin/src/PluginProcessor.cpp b/plugin/src/PluginProcessor.cpp index d689c74..d4a2830 100644 --- a/plugin/src/PluginProcessor.cpp +++ b/plugin/src/PluginProcessor.cpp @@ -1,8 +1,10 @@ #include "PluginProcessor.h" +#include "HostPlayheadReader.h" #include "PluginEditor.h" #include "ui/Palette.h" +#include #include #include @@ -12,20 +14,6 @@ namespace visona { -namespace -{ - -constexpr double ringSeconds = 1.0; - -std::size_t ringCapacityFrames(double sampleRate, int bufferSize) -{ - const auto oneSecond = - static_cast(std::ceil(std::max(sampleRate, 1.0) * ringSeconds)); - return std::max(oneSecond, static_cast(std::max(bufferSize, 1)) * 4); -} - -} // namespace - PluginProcessor::PluginProcessor() : juce::AudioProcessor(BusesProperties() .withInput("Input", juce::AudioChannelSet::stereo(), true) @@ -38,25 +26,28 @@ PluginProcessor::PluginProcessor() palette::defaultWaveformColour); } -PluginProcessor::~PluginProcessor() = default; +PluginProcessor::~PluginProcessor() +{ + releaseResources(); +} void PluginProcessor::prepareToPlay(double sampleRate, int samplesPerBlock) { + releaseResources(); // Detach before freeing a ring the analysis thread may still read. + playheadReader_ = {}; sampleRate_ = sampleRate; ring_ = std::make_unique( layout_.totalChannelCount(), ringCapacityFrames(sampleRate, samplesPerBlock), - std::max(ringCapacityFrames(sampleRate, samplesPerBlock) / - static_cast(std::max(samplesPerBlock, 1)), - 1)); + ringTimingSlots(ringCapacityFrames(sampleRate, samplesPerBlock))); writer_ = std::make_unique(*ring_); writer_->route(0, 0); writer_->route(1, 1); channelPointers_.assign(layout_.totalChannelCount(), nullptr); - analysis_.setStream(ring_.get(), sampleRate); analysis_.setWindow(instanceState_.window); analysis_.setBandSplitting(instanceState_.waveformMode == WaveformMode::dj); sidechainSync_.reset(); analysis_.setAnalysisOffset(0.0); + analysis_.setStream(ring_.get(), sampleRate); } void PluginProcessor::releaseResources() @@ -146,42 +137,9 @@ void PluginProcessor::updateSidechainSync(juce::AudioBuffer& buffer, syncImpulsePeak_.store(sidechainSync_.impulsePeak(), std::memory_order_relaxed); } -HostTransport::Playhead PluginProcessor::readPlayhead() const noexcept +HostTransport::Playhead PluginProcessor::readPlayhead() noexcept { - HostTransport::Playhead playhead; - if (auto* head = getPlayHead()) - { - if (auto position = head->getPosition()) - { - playhead.isPlaying = position->getIsPlaying(); - if (position->getPpqPosition()) - playhead.ppqPosition = *position->getPpqPosition(); - else - playhead.ppqPosition = lastKnownPpq_; - if (position->getBpm()) - playhead.bpm = *position->getBpm(); - else - playhead.bpm = lastKnownBpm_; - if (position->getTimeSignature()) - playhead.timeSignature = {position->getTimeSignature()->numerator, - position->getTimeSignature()->denominator}; - else - playhead.timeSignature = lastKnownTimeSignature_; - - playhead.valid = - playhead.bpm > 0.0 && (position->getPpqPosition().hasValue() || - position->getBpm().hasValue() || position->getIsPlaying()); - - if (playhead.valid) - { - lastKnownBpm_ = playhead.bpm; - lastKnownPpq_ = playhead.ppqPosition; - lastKnownPlaying_ = playhead.isPlaying; - lastKnownTimeSignature_ = playhead.timeSignature; - } - } - } - return playhead; + return readHostPlayhead(getPlayHead(), playheadReader_); } juce::AudioProcessorEditor* PluginProcessor::createEditor() diff --git a/plugin/src/PluginProcessor.h b/plugin/src/PluginProcessor.h index 73d9594..3ac20ac 100644 --- a/plugin/src/PluginProcessor.h +++ b/plugin/src/PluginProcessor.h @@ -6,7 +6,7 @@ #include #include #include -#include +#include #include #include @@ -109,7 +109,7 @@ class PluginProcessor final : public juce::AudioProcessor } private: - [[nodiscard]] HostTransport::Playhead readPlayhead() const noexcept; + [[nodiscard]] HostTransport::Playhead readPlayhead() noexcept; void updateSidechainSync(juce::AudioBuffer& buffer, const HostTransport::Playhead& playhead) noexcept; @@ -131,10 +131,7 @@ class PluginProcessor final : public juce::AudioProcessor std::atomic sidechainPeak_{0.0f}; std::atomic lastBlockSize_{0}; - mutable double lastKnownBpm_ = 120.0; - mutable double lastKnownPpq_ = 0.0; - mutable bool lastKnownPlaying_ = false; - mutable TimeSignature lastKnownTimeSignature_{}; + HostPlayheadReader playheadReader_; }; } // namespace visona diff --git a/plugin/src/PluginState.cpp b/plugin/src/PluginState.cpp index 86ac587..cf037d2 100644 --- a/plugin/src/PluginState.cpp +++ b/plugin/src/PluginState.cpp @@ -3,6 +3,7 @@ #include "ui/Palette.h" #include +#include namespace visona { @@ -92,6 +93,7 @@ void PluginInstanceState::writeTo(juce::XmlElement& root) const root.setAttribute("spectrumSettings", spectrumSettings); root.setAttribute("stereoSettings", stereoSettings); root.setAttribute("gainDb", gainDb); + root.setAttribute("version", 1); root.setAttribute("afterglow", afterglow); root.setAttribute("autoGain", autoGain); root.setAttribute("window", static_cast(window)); @@ -110,12 +112,18 @@ void PluginInstanceState::readFrom(const juce::XmlElement& root, PluginGlobalDef afterglow = juce::jlimit(0, 3, root.getIntAttribute("afterglow", 2)); gainDb = DisplayGain::clampDb(root.getIntAttribute("gainDb", gainDb)); autoGain = root.getBoolAttribute("autoGain", false); - window = static_cast(root.getIntAttribute("window", static_cast(window))); + window = static_cast( + juce::jlimit(0, static_cast(sweepWindowBars.size()) - 1, + root.getIntAttribute("window", static_cast(defaultSweepWindow)))); waveformMode = modeFromString( root.getStringAttribute("waveformMode", modeToString(defaults.waveformMode()))); - waveformColour = static_cast(root.getIntAttribute( + const auto colour = root.getIntAttribute( "waveformColour", static_cast(defaults.waveformColour( - palette::waveformColours.size(), palette::defaultWaveformColour)))); + palette::waveformColours.size(), palette::defaultWaveformColour))); + waveformColour = + colour >= 0 && static_cast(colour) < palette::waveformColours.size() + ? static_cast(colour) + : palette::defaultWaveformColour; hasInstanceAppearance = root.getBoolAttribute("hasInstanceAppearance", false); if (!hasInstanceAppearance) { diff --git a/plugin/src/ScopeEditor.cpp b/plugin/src/ScopeEditor.cpp index 83f7eaf..e93adeb 100644 --- a/plugin/src/ScopeEditor.cpp +++ b/plugin/src/ScopeEditor.cpp @@ -149,6 +149,8 @@ ScopeEditor::ScopeEditor(PluginProcessor& processor) controlBar_.setToggles(false, false, false); setWantsKeyboardFocus(true); setAnalysisView(state_.analysisView); + lastUpdateSeconds_ = juce::Time::getMillisecondCounterHiRes() * 0.001; + lastAnalysisBusyNs_ = analysis_.busyNanoseconds(); startTimerHz(idleRefreshHz); } @@ -238,7 +240,8 @@ bool ScopeEditor::keyPressed(const juce::KeyPress& key) return true; } } - if (key.getTextCharacter() == 'd' || key.getTextCharacter() == 'D') + if (!key.getModifiers().isAnyModifierKeyDown() && + (key.getTextCharacter() == 'd' || key.getTextCharacter() == 'D')) { showDiagnostics(!diagnostics_.isVisible()); return true; @@ -259,7 +262,10 @@ void ScopeEditor::timerCallback() void ScopeEditor::setAnalysisView(int view) { - analysisView_ = std::clamp(view, 0, 3); + view = std::clamp(view, 0, 3); + if (analysisView_ == view) + return; + analysisView_ = view; scope_.setVisible(analysisView_ == 0); spectrum_.setActive(analysisView_ == 1); bandSpectrum_.setActive(analysisView_ == 2); @@ -455,15 +461,13 @@ void ScopeEditor::updateZoom() void ScopeEditor::updateDiagnostics() { - static double lastUpdateSeconds = juce::Time::getMillisecondCounterHiRes() * 0.001; - static std::uint64_t lastAnalysisBusyNs = 0; const auto now = juce::Time::getMillisecondCounterHiRes() * 0.001; - const auto elapsed = std::max(now - lastUpdateSeconds, 1.0e-3); - lastUpdateSeconds = now; + const auto elapsed = std::max(now - lastUpdateSeconds_, 1.0e-3); + lastUpdateSeconds_ = now; const auto busyNs = analysis_.busyNanoseconds(); - const auto analysisLoad = static_cast(busyNs - lastAnalysisBusyNs) * 1.0e-9 / elapsed; - lastAnalysisBusyNs = busyNs; + const auto analysisLoad = static_cast(busyNs - lastAnalysisBusyNs_) * 1.0e-9 / elapsed; + lastAnalysisBusyNs_ = busyNs; const auto& snapshot = scope_.snapshot(); DiagnosticsOverlay::Values values; @@ -475,22 +479,11 @@ void ScopeEditor::updateDiagnostics() values.overruns = snapshot.overruns; values.droppedFrames = snapshot.droppedFrames; values.analysisLoad = analysisLoad; - values.rendering = scope_.stats(); - if (analysisView_ != 0) - { - const auto stats = analysisView_ == 3 ? stereo_.stats() - : analysisView_ == 2 ? bandSpectrum_.stats() - : spectrum_.stats(); - values.rendering = {}; - values.rendering.framesPerSecond = stats.framesPerSecond; - values.rendering.renderMsAverage = stats.renderMsAverage; - values.rendering.renderMsMax = stats.renderMsMax; - values.rendering.paintMsAverage = stats.paintMsAverage; - values.rendering.paintMsMax = stats.paintMsMax; - values.rendering.imageWidth = stats.imageWidth; - values.rendering.imageHeight = stats.imageHeight; - values.rendering.scale = stats.scale; - } + values.scopeRendering = analysisView_ == 0; + values.rendering = analysisView_ == 3 ? stereo_.stats() + : analysisView_ == 2 ? bandSpectrum_.stats() + : analysisView_ == 1 ? spectrum_.stats() + : scope_.stats(); values.transportState = snapshot.transportState; values.nextTick = snapshot.nextTick; values.timeSignature = snapshot.timeSignature; diff --git a/plugin/src/ScopeEditor.h b/plugin/src/ScopeEditor.h index 20f9870..cd42bb5 100644 --- a/plugin/src/ScopeEditor.h +++ b/plugin/src/ScopeEditor.h @@ -44,7 +44,7 @@ class ScopeEditor final : public juce::Component, private juce::Timer /** Sets the gain by hand, which turns auto gain off. */ void setAnalysisView(int view); - int analysisView_ = 0; + int analysisView_ = -1; void setGainDb(int gainDb); /** The gain on screen: auto gain's while it is on, otherwise the one set by hand. */ [[nodiscard]] int shownGainDb(); @@ -92,6 +92,8 @@ class ScopeEditor final : public juce::Component, private juce::Timer std::size_t window_ = 2; std::vector peaks_; + double lastUpdateSeconds_ = 0.0; + std::uint64_t lastAnalysisBusyNs_ = 0; }; } // namespace visona diff --git a/plugin/src/SyncProcessor.cpp b/plugin/src/SyncProcessor.cpp index e9744e8..69fee3b 100644 --- a/plugin/src/SyncProcessor.cpp +++ b/plugin/src/SyncProcessor.cpp @@ -1,9 +1,13 @@ #include "SyncProcessor.h" +#include "HostPlayheadReader.h" #include "SyncEditor.h" #include +#include +#include + namespace visona { @@ -21,6 +25,7 @@ SyncProcessor::~SyncProcessor() = default; void SyncProcessor::prepareToPlay(double sampleRate, int samplesPerBlock) { juce::ignoreUnused(samplesPerBlock); + playheadReader_ = {}; sampleRate_ = sampleRate; streamSample_ = 0; } @@ -41,59 +46,31 @@ void SyncProcessor::processBlock(juce::AudioBuffer& buffer, juce::MidiBuf const auto blockStartSample = streamSample_; streamSample_ += numSamples; - const auto playhead = readPlayhead(static_cast(numSamples)); - lastPlayhead_ = playhead; + const auto playhead = readHostPlayhead(getPlayHead(), playheadReader_); + hostValid_.store(playhead.valid, std::memory_order_relaxed); + hostPlaying_.store(playhead.isPlaying, std::memory_order_relaxed); + hostBpm_.store(playhead.bpm, std::memory_order_relaxed); if (!playhead.valid || !playhead.isPlaying || sampleRate_ <= 0.0) return; - std::vector offsets; - BarImpulseScheduler::impulsesInBlock(blockStartSample, numSamples, playhead.ppqPosition, - playhead.bpm, playhead.timeSignature, sampleRate_, - offsets); - for (const auto offset : offsets) - { - for (int channel = 0; channel < buffer.getNumChannels(); ++channel) - buffer.setSample(channel, static_cast(offset), syncImpulseAmplitude); - } -} - -HostTransport::Playhead SyncProcessor::readPlayhead(int numSamples) noexcept -{ - HostTransport::Playhead playhead; - if (auto* head = getPlayHead()) + // At most one impulse per sample. Chunking bounds stack storage even if the host + // exceeds its advertised maximum block size, without dropping any impulses. + std::array offsets{}; + for (std::uint32_t first = 0; first < numSamples;) { - if (auto position = head->getPosition()) - { - playhead.isPlaying = position->getIsPlaying(); - if (position->getPpqPosition()) - playhead.ppqPosition = *position->getPpqPosition(); - else - playhead.ppqPosition = lastKnownPpq_; - if (position->getBpm()) - playhead.bpm = *position->getBpm(); - else - playhead.bpm = lastKnownBpm_; - if (position->getTimeSignature()) - playhead.timeSignature = {position->getTimeSignature()->numerator, - position->getTimeSignature()->denominator}; - else - playhead.timeSignature = lastKnownTimeSignature_; - - playhead.valid = playhead.bpm > 0.0 && - (position->getPpqPosition().hasValue() || - position->getBpm().hasValue() || position->getIsPlaying()); - - if (playhead.valid) - { - lastKnownBpm_ = playhead.bpm; - lastKnownPpq_ = playhead.ppqPosition; - lastKnownPlaying_ = playhead.isPlaying; - lastKnownTimeSignature_ = playhead.timeSignature; - } - } + const auto frames = + std::min(numSamples - first, static_cast(offsets.size())); + const auto ppq = + playhead.ppqPosition + static_cast(first) / sampleRate_ * playhead.bpm / 60.0; + const auto count = BarImpulseScheduler::impulsesInBlock( + blockStartSample + first, frames, ppq, playhead.bpm, playhead.timeSignature, + sampleRate_, offsets); + for (std::size_t i = 0; i < count; ++i) + for (int channel = 0; channel < buffer.getNumChannels(); ++channel) + buffer.setSample(channel, static_cast(first + offsets[i]), + syncImpulseAmplitude); + first += frames; } - juce::ignoreUnused(numSamples); - return playhead; } juce::AudioProcessorEditor* SyncProcessor::createEditor() @@ -177,8 +154,7 @@ bool SyncProcessor::isBusesLayoutSupported(const BusesLayout& layouts) const if (layouts.inputBuses.size() > 0) { const auto& input = layouts.getMainInputChannelSet(); - if (input != juce::AudioChannelSet::disabled() && - input != juce::AudioChannelSet::stereo()) + if (input != juce::AudioChannelSet::disabled() && input != juce::AudioChannelSet::stereo()) return false; } diff --git a/plugin/src/SyncProcessor.h b/plugin/src/SyncProcessor.h index 2890caf..68717f2 100644 --- a/plugin/src/SyncProcessor.h +++ b/plugin/src/SyncProcessor.h @@ -1,9 +1,11 @@ #pragma once -#include +#include #include +#include + namespace visona { @@ -39,20 +41,21 @@ class SyncProcessor final : public juce::AudioProcessor [[nodiscard]] HostTransport::Playhead lastPlayhead() const noexcept { - return lastPlayhead_; + HostTransport::Playhead result; + result.valid = hostValid_.load(std::memory_order_relaxed); + result.isPlaying = hostPlaying_.load(std::memory_order_relaxed); + result.bpm = hostBpm_.load(std::memory_order_relaxed); + return result; } private: - [[nodiscard]] HostTransport::Playhead readPlayhead(int numSamples) noexcept; - double sampleRate_ = 0.0; std::uint64_t streamSample_ = 0; - HostTransport::Playhead lastPlayhead_; - double lastKnownBpm_ = 120.0; - double lastKnownPpq_ = 0.0; - bool lastKnownPlaying_ = false; - TimeSignature lastKnownTimeSignature_{}; + // Independent display values; the editor never reads the audio thread's mutable playhead. + std::atomic hostValid_{false}, hostPlaying_{false}; + std::atomic hostBpm_{0.0}; + HostPlayheadReader playheadReader_; }; } // namespace visona diff --git a/site/static/manual/index.html b/site/static/manual/index.html index 5d459a8..72e71ab 100644 --- a/site/static/manual/index.html +++ b/site/static/manual/index.html @@ -178,7 +178,7 @@

6First start of the app

View
Only in a very small window, where they do not fit in the control bar: buttons for the diagnostics overlay and full screen.
-

Close the panel with Done or Esc. Audio interfaces and MIDI ports can be unplugged and plugged in again while Visona runs: it shows NO AUDIO INPUT while the device is missing and carries on a few seconds after it returns.

+

Close the panel with Done or Esc. Settings changes are saved after one second without further changes and when the app closes normally. Audio interfaces and MIDI ports can be unplugged and plugged in again while Visona runs: it shows NO AUDIO INPUT while the device is missing and carries on a few seconds after it returns. An input device that stops or fails to start is reopened automatically; the banner explains that it stopped.

Visona is developed and tested with an RME Babyface Pro FS, but works with any professional USB audio interface.

Running Visona on a separate device

@@ -268,7 +268,7 @@

14Tempo

15Gain and auto gain

GAIN and AUTO are shared by all visualizations and always appear in the bottom control bar. Gain ranges from 0 to +64 dB in 1 dB steps. It scales waveform amplitudes and stereo radii, and moves both FFT curves and Band bars and markers by the same number of dB. Spectrum scales continue to label actual signal levels: at +6 dB gain the top is −6 dBFS. Gain affects presentation only, never audio, correlation or signal validity. Drag or scroll on it, use its buttons, or use +/− and ↑/↓ in the standalone app. Double-click or double-tap resets it to 0 dB.

-

AUTO uses the same incoming channel peaks in every view, whether or not MIDI Clock or the DAW is playing. It lowers gain immediately when a peak would exceed the display, and once peaks have stayed low for 10 seconds it raises it, in 3 dB steps, as far as the loudest of them allows, up to +63 dB. Silence below the detection threshold does not cause gain to rise. Switching views does not restart Auto. Setting gain manually turns Auto off; switching Auto off retains its current gain. Auto follows the audio level, so each individual spectrum curve or stereo profile need not fill the plot.

+

AUTO uses the same incoming channel peaks in every view, whether or not MIDI Clock or the DAW is playing. It lowers gain immediately when a peak would exceed the display, and once peaks have stayed low for 10 seconds it raises it, in 3 dB steps, as far as the loudest of them allows, up to +63 dB. Silence below the detection threshold does not cause gain to rise. Switching views does not restart Auto. After a UI interruption long enough to lose the retained peak history, Auto returns to 0 dB and waits for a new ten-second history before raising gain. Setting gain manually turns Auto off; switching Auto off retains its current gain. Auto follows the audio level, so each individual spectrum curve or stereo profile need not fill the plot.

Afterglow is shared by FFT, Band and Stereo and hidden in Scope. Select Off, 0.5 s, 1 s (default) or 2 s. For FFT it sets the time for the white history line to fall 12 dB, without a hold: 0.5 s gives 24 dB/s, 1 s gives 12 dB/s, and 2 s gives 6 dB/s. For Band it sets peak-marker hold time, followed by a fall of 12 dB/s; an equal or higher peak restarts the hold. In Stereo it sets the fade to 1% brightness for sample points or 1% radius for Polar Level. Off hides the FFT history line and Band markers and removes stereo display history. The shared gain and afterglow are remembered in the app and per plugin instance.

In Scope, faint reference lines mark signal levels every 3 dB after gain, without a fixed lower dB limit. Right-hand labels continue as far as screen space allows; lines continue to pixel resolution near the zero-amplitude centre. A peak beyond a lane is cut off with a grey display-overshoot marker. In Stereo, retained visible history follows gain changes; history moved outside the plot may be discarded.

@@ -383,7 +383,7 @@

24Visona Sync with the app

25Diagnostics overlay

-

Press D, or the Diagnostics button, for a panel of technical readings: the audio device, sample rate, block size and level per input, overruns and device xruns, MIDI Clock messages and timing, the Visona Sync measurement, analysis load, frame rate and render times, and Visona's CPU use. Frame rate and render times follow the selected analysis view. Stereo aims at 60 frames per second or more: Polar Sample polls at 240 Hz and Polar Level at 120 Hz to allow for timer delays, and only fresh 120 Hz analysis snapshots produce frames. Band targets 30, and FFT 30 (25 on ARM64 Linux); both slow down on slower hardware to keep the controls responsive. Include a screenshot of it when you report a problem. For Raspberry Pi development, the local deployment script accepts --profile to log FPS, render/paint times and CPU over SSH even with this overlay closed; see the performance measurement guide.

+

Press D, or the Diagnostics button, for a panel of technical readings: the audio device, sample rate, block size and level per input, overruns and device xruns, MIDI Clock messages and timing, the Visona Sync measurement, analysis load, frame rate and render times, and Visona's CPU use. Frame rate and render times follow the selected analysis view. Display refresh rate, full redraws and tile counts appear only for Scope; Stereo reports its physical display scale and timing maxima for the latest reporting interval. Stereo aims at 60 frames per second or more: Polar Sample polls at 240 Hz and Polar Level at 120 Hz to allow for timer delays, and only fresh 120 Hz analysis snapshots produce frames. Band targets 30, and FFT 30 (25 on ARM64 Linux); both slow down on slower hardware to keep the controls responsive. Include a screenshot of it when you report a problem. For Raspberry Pi development, the local deployment script accepts --profile to log FPS, render/paint times and CPU over SSH even with this overlay closed; see the performance measurement guide.

Visona's diagnostics overlay
diff --git a/tests/AnalysisSelectorUiChecks.cpp b/tests/AnalysisSelectorUiChecks.cpp index 9bd6546..08c432b 100644 --- a/tests/AnalysisSelectorUiChecks.cpp +++ b/tests/AnalysisSelectorUiChecks.cpp @@ -43,7 +43,7 @@ void runAnalysisSelectorUiChecks() host.addAndMakeVisible(selector); selector.setBounds(0, 430, 190, 50); selector.setTouchMode(true); - int selected = -1; + int selected = 0; int picks = 0; selector.onSelect = [&](int view) { @@ -64,6 +64,7 @@ void runAnalysisSelectorUiChecks() check(dynamic_cast(button) != nullptr, "Selector button missing"); const auto event = eventFor(*button, button->getLocalBounds().toFloat().getCentre()); const auto before = picks; + const bool changesView = index < 4 && index != selected; button->mouseUp(event); check(panel->isVisible() && picks == before, @@ -77,7 +78,7 @@ void runAnalysisSelectorUiChecks() button->mouseExit(event); button->mouseUp(event); check(!panel->isVisible(), "Pointer exit swallowed selector tap"); - check(picks == before + (index < 4 ? 1 : 0), "Selector callback count incorrect"); + check(picks == before + (changesView ? 1 : 0), "Selector callback count incorrect"); if (index < 4) check(selected == index, "Selector picked wrong view"); } diff --git a/tests/AutoGainTests.cpp b/tests/AutoGainTests.cpp index fdd18d5..0115ca8 100644 --- a/tests/AutoGainTests.cpp +++ b/tests/AutoGainTests.cpp @@ -179,12 +179,11 @@ TEST_CASE("Auto gain follows the bars that ended since it last looked", "[autoga CHECK_FALSE(autoGain.follow(recent)); CHECK(autoGain.gainDb() == 0); - // More bars than the snapshot holds: only those still held are added, so the loud bar that - // was missed does not keep the gain down. + // Missing peaks are unknown. Do not raise gain from an incomplete history. for (std::size_t bar = 0; bar < RecentBarPeaks::capacity + 4; ++bar) end(bar == 0 ? 1.0f : 0.1f); - CHECK(autoGain.follow(recent)); - CHECK(autoGain.gainDb() == 18); + CHECK_FALSE(autoGain.follow(recent)); + CHECK(autoGain.gainDb() == 0); } TEST_CASE("BarPeakMeter ends a bar when the next one starts", "[autogain][bars]") @@ -256,3 +255,42 @@ TEST_CASE("Global auto gain follows input time without musical transport", "[aut feed(); CHECK(gain.gainDb() == 0); } + +TEST_CASE("Auto gain retains a loud input window across a multi-second UI stall", "[autogain]") +{ + AutoGain gain; + gain.reset(18); + BarPeakMeter meter; + std::vector input(4800, 0.1f); + std::array channels{input.data()}; + gain.follow(meter.recent()); + for (std::uint64_t window = 0; window < 51; ++window) + { + std::fill(input.begin(), input.end(), window == 1 ? 1.0f : 0.1f); + meter.processInput(channels, input.size(), window * input.size(), 48000); + } + gain.follow(meter.recent()); + CHECK(gain.gainDb() == 0); +} + +TEST_CASE("Auto gain returns to unity and rebuilds its hold after history is overwritten", + "[autogain]") +{ + AutoGain gain; + gain.reset(18); + RecentBarPeaks peaks; + gain.follow(peaks); + peaks.count = RecentBarPeaks::capacity + 1; + peaks.bars.fill({0.1f, 0.1}); + CHECK(gain.follow(peaks)); + CHECK(gain.gainDb() == 0); + for (int window = 0; window < 99; ++window) + { + ++peaks.count; + gain.follow(peaks); + CHECK(gain.gainDb() == 0); + } + ++peaks.count; + gain.follow(peaks); + CHECK(gain.gainDb() == 18); +} diff --git a/tests/BarImpulseSchedulerTests.cpp b/tests/BarImpulseSchedulerTests.cpp index 26b6cd3..77f056d 100644 --- a/tests/BarImpulseSchedulerTests.cpp +++ b/tests/BarImpulseSchedulerTests.cpp @@ -1,52 +1,127 @@ +#include "support/AllocationCounter.h" + #include #include #include -using Catch::Matchers::WithinAbs; +#include +#include +#include +#include +#include using visona::BarImpulseScheduler; using visona::TimeSignature; TEST_CASE("BarImpulseScheduler places one impulse per bar boundary", "[sync]") { - constexpr double sampleRate = 48'000.0; - constexpr double bpm = 120.0; - const TimeSignature timeSignature{4, 4}; - const auto samplesPerBar = static_cast(sampleRate * 60.0 / bpm * 4.0); - - std::vector offsets; - BarImpulseScheduler::impulsesInBlock(0, samplesPerBar, 0.0, bpm, timeSignature, sampleRate, - offsets); - REQUIRE(offsets.size() == 1); - CHECK(offsets.front() == 0); - - offsets.clear(); - BarImpulseScheduler::impulsesInBlock(samplesPerBar, samplesPerBar, 4.0, bpm, timeSignature, - sampleRate, offsets); - REQUIRE(offsets.size() == 1); - CHECK(offsets.front() == 0); + std::array offsets{}; + for (const auto start : {0u, 96000u}) + { + const auto count = BarImpulseScheduler::impulsesInBlock( + start, 96000, static_cast(start) / 24000.0, 120, {4, 4}, 48000, offsets); + REQUIRE(count == 1); + CHECK(offsets[0] == 0); + } + CHECK(BarImpulseScheduler::impulsesInBlock(100000, 1024, 0, 120, {4, 4}, 48000, offsets) == 1); + CHECK(offsets[0] == 0); +} + +TEST_CASE("BarImpulseScheduler rounds boundary ownership across adjacent blocks", "[sync]") +{ + for (int tenth = -15; tenth <= 15; ++tenth) + { + const double boundary = 512.0 + static_cast(tenth) / 10.0; + const auto expected = static_cast(std::floor(boundary + 0.5)); + for (const double barPpq : {-4.0, 0.0, 4.0}) + { + CAPTURE(boundary, barPpq); + std::array offsets{}; + unsigned total = 0; + for (std::uint32_t start : {0u, 512u}) + { + const double ppq = barPpq + (static_cast(start) - boundary) / 24000.0; + const auto count = BarImpulseScheduler::impulsesInBlock(start, 512, ppq, 120, + {4, 4}, 48000, offsets); + for (std::size_t i = 0; i < count; ++i) + { + CHECK(start + offsets[i] == expected); + ++total; + } + } + CHECK(total == 1); + } + } +} + +TEST_CASE("BarImpulseScheduler bounds output and never allocates", "[sync][realtime]") +{ + std::array offsets{}; + visona::test::AllocationCounter allocations; + // One sample per bar, the densest supported timeline. + const auto count = BarImpulseScheduler::impulsesInBlock(0, 128, 0, 60, {1, 4}, 1, offsets); + const auto allocated = allocations.count(); + REQUIRE(allocated == 0); + REQUIRE(count == offsets.size()); + for (std::size_t i = 0; i < count; ++i) + CHECK(offsets[i] == i); + CHECK(BarImpulseScheduler::impulsesInBlock(0, 128, 0, 60, {1, 4}, 1, + std::span(offsets).first(3)) == 3); + CHECK(BarImpulseScheduler::impulsesInBlock(0, 128, 0, 60, {1, 4}, 1, {}) == 0); } -TEST_CASE("BarImpulseScheduler places bar start at block start for Live playhead", "[sync]") +TEST_CASE("BarImpulseScheduler rejects malformed host values", "[sync]") { - constexpr double sampleRate = 48'000.0; - constexpr double bpm = 120.0; - const TimeSignature timeSignature{4, 4}; - constexpr std::uint32_t blockSize = 1024; - - std::vector offsets; - BarImpulseScheduler::impulsesInBlock(100'000, blockSize, 0.0, bpm, timeSignature, sampleRate, - offsets); - REQUIRE(offsets.size() == 1); - CHECK(offsets.front() == 0); + std::array offsets{}; + for (const auto signature : {TimeSignature{0, 4}, TimeSignature{4, 0}, TimeSignature{5, 64}, + TimeSignature{-1, 4}, TimeSignature{4, 3}}) + CHECK(BarImpulseScheduler::impulsesInBlock(0, 512, 0, 120, signature, 48000, offsets) == 0); + for (const double invalid : + {std::numeric_limits::quiet_NaN(), std::numeric_limits::infinity()}) + { + CHECK(BarImpulseScheduler::impulsesInBlock(0, 512, invalid, 120, {}, 48000, offsets) == 0); + CHECK(BarImpulseScheduler::impulsesInBlock(0, 512, 0, invalid, {}, 48000, offsets) == 0); + CHECK(BarImpulseScheduler::impulsesInBlock(0, 512, 0, 120, {}, invalid, offsets) == 0); + } } TEST_CASE("BarImpulseScheduler matches sampleIndexOfBarBoundary", "[sync]") { - constexpr double sampleRate = 48'000.0; - constexpr double bpm = 120.0; - const auto expected = BarImpulseScheduler::sampleIndexOfBarBoundary(8.0, 96000, 8.0, bpm, - sampleRate); - CHECK_THAT(expected, WithinAbs(96000.0, 1.0)); + CHECK_THAT(BarImpulseScheduler::sampleIndexOfBarBoundary(8, 96000, 8, 120, 48000), + Catch::Matchers::WithinAbs(96000, 1)); +} + +TEST_CASE("Bar impulses are independent of host block partitioning", "[sync]") +{ + for (const double bpm : {97.0, 120.0, 137.3}) + { + constexpr std::uint32_t totalFrames = 200000; + const double framesPerQuarter = 48000.0 * 60.0 / bpm; + std::vector expected; + for (int bar = 0; bar < 5; ++bar) + { + const auto frame = + std::floor((static_cast(bar) * 4.0 + 0.25) * framesPerQuarter + 0.5); + if (frame < totalFrames) + expected.push_back(static_cast(frame)); + } + for (const std::uint32_t blockSize : {1u, 64u, 127u, 512u, 4096u}) + { + CAPTURE(bpm, blockSize); + std::vector actual; + std::array offsets{}; + for (std::uint32_t start = 0; start < totalFrames;) + { + const auto frames = std::min(blockSize, totalFrames - start); + const auto count = BarImpulseScheduler::impulsesInBlock( + start, frames, -0.25 + static_cast(start) / framesPerQuarter, bpm, + {4, 4}, 48000, offsets); + for (std::size_t i = 0; i < count; ++i) + actual.push_back(start + offsets[i]); + start += frames; + } + CHECK(actual == expected); + } + } } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 3d67243..6928f3f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -20,6 +20,7 @@ add_executable(visona_core_tests BarImpulseSchedulerTests.cpp HostAnalysisPipelineTests.cpp HostTransportTests.cpp + HostPlayheadReaderTests.cpp SidechainSyncDetectorTests.cpp ColumnReductionTests.cpp LaneMappingTests.cpp diff --git a/tests/HostAnalysisPipelineTests.cpp b/tests/HostAnalysisPipelineTests.cpp index 7039680..8652911 100644 --- a/tests/HostAnalysisPipelineTests.cpp +++ b/tests/HostAnalysisPipelineTests.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -97,7 +98,7 @@ class LiveHost std::vector sidechain(blockSize_); // Visona Sync's output on its own track, before the host delays it. std::vector syncOutput(end + blockSize_, 0.0f); - std::vector impulses; + std::vector impulses(blockSize_); const std::array inputs{main.data(), main.data()}; detector_.setSidechainEnabled(withSidechain); @@ -114,11 +115,11 @@ class LiveHost if (playhead.isPlaying) { - impulses.clear(); - BarImpulseScheduler::impulsesInBlock(blockStart, blockSize_, playhead.ppqPosition, - bpm_, fourFour, sampleRate, impulses); - for (const auto offset : impulses) - syncOutput[blockStart + offset] = visona::syncImpulseAmplitude; + const auto count = BarImpulseScheduler::impulsesInBlock( + blockStart, blockSize_, playhead.ppqPosition, bpm_, fourFour, sampleRate, + impulses); + for (std::size_t i = 0; i < count; ++i) + syncOutput[blockStart + impulses[i]] = visona::syncImpulseAmplitude; } for (std::uint32_t index = 0; index < blockSize_; ++index) @@ -372,3 +373,55 @@ TEST_CASE("Global gain input peaks continue while host transport is stopped", "[ REQUIRE(snapshot.inputPeaks.currentPeak == 0.75f); REQUIRE(snapshot.barPeaks.count == 0); } + +TEST_CASE("Host pipeline updates window ticks on a time signature change", "[host]") +{ + AudioRingBuffer ring(2, 48000, 128); + AudioInputWriter writer(ring); + writer.route(0, 0); + writer.route(1, 1); + HostAnalysisPipeline pipeline(2); + pipeline.setStream(&ring, sampleRate); + playSilence(writer, pipeline, 4); + while (pipeline.poll() > 0) + { + } + pipeline.snapshots().fetch(); + CHECK(pipeline.snapshots().readBuffer().windowTicks == 96); + + const auto start = writer.nextSampleIndex(); + auto head = playingAt(static_cast(start) / 24000.0); + head.timeSignature = {3, 4}; + pipeline.pushPlayhead(start, head); + pipeline.poll(); + pipeline.snapshots().fetch(); + CHECK(pipeline.snapshots().readBuffer().timeSignature == TimeSignature{3, 4}); + CHECK(pipeline.snapshots().readBuffer().windowTicks == 72); +} + +TEST_CASE("Host pipeline observes stop and resume in partial reports without PPQ", "[host]") +{ + AudioRingBuffer ring(2, 48000, 128); + AudioInputWriter writer(ring); + writer.route(0, 0); + writer.route(1, 1); + HostAnalysisPipeline pipeline(2); + pipeline.setStream(&ring, sampleRate); + visona::HostPlayheadReader reader; + pipeline.pushPlayhead(0, reader.read(true, 0, 120, {})); + pipeline.pushPlayhead(512, reader.read(true, {}, 120, {})); + pipeline.pushPlayhead(1024, reader.read(false, {}, 120, {})); + pipeline.poll(); + pipeline.snapshots().fetch(); + CHECK(pipeline.snapshots().readBuffer().transportState == TransportState::stopped); + const auto stoppedTick = pipeline.snapshots().readBuffer().nextTick; + pipeline.pushPlayhead(48000, reader.read(false, {}, 120, {})); + pipeline.poll(); + pipeline.snapshots().fetch(); + CHECK(pipeline.snapshots().readBuffer().nextTick == stoppedTick); + pipeline.pushPlayhead(96000, reader.read(true, {}, 120, {})); + pipeline.poll(); + pipeline.snapshots().fetch(); + CHECK(pipeline.snapshots().readBuffer().transportState == TransportState::running); + CHECK(pipeline.snapshots().readBuffer().nextTick == stoppedTick); +} diff --git a/tests/HostPlayheadReaderTests.cpp b/tests/HostPlayheadReaderTests.cpp new file mode 100644 index 0000000..0e69311 --- /dev/null +++ b/tests/HostPlayheadReaderTests.cpp @@ -0,0 +1,86 @@ +#include +#include +#include +#include + +#include + +#include +#include + +TEST_CASE("Host playhead reader validates signatures and retains the last good value", "[host]") +{ + visona::HostPlayheadReader reader; + CHECK(reader.read(true, 0, 123, visona::TimeSignature{7, 8}).timeSignature == + visona::TimeSignature{7, 8}); + for (const auto signature : + {visona::TimeSignature{0, 4}, visona::TimeSignature{4, 0}, visona::TimeSignature{5, 64}, + visona::TimeSignature{65, 4}, visona::TimeSignature{4, 3}}) + { + CHECK_FALSE(signature.isValid()); + const auto head = reader.read(true, 4, 123, signature); + CHECK(head.valid); + CHECK(head.timeSignature == visona::TimeSignature{7, 8}); + } + CHECK(visona::TimeSignature{64, 32}.isValid()); +} + +TEST_CASE("Host playhead reader never treats a missing position as frozen valid transport", + "[host]") +{ + visona::HostPlayheadReader reader; + CHECK(reader.read(true, 10, 123, {}).valid); + CHECK_FALSE(reader.read(true, {}, 123, {}).valid); + CHECK_FALSE(reader.read(false, {}, {}, {}).valid); + for (const double bad : {std::numeric_limits::quiet_NaN(), + std::numeric_limits::infinity(), 1.0e100}) + CHECK_FALSE(reader.read(true, bad, 123, {}).valid); + for (const double bad : {0.0, -1.0, std::numeric_limits::quiet_NaN(), + std::numeric_limits::infinity()}) + CHECK(reader.read(true, 11, bad, {}).bpm == 123); +} + +TEST_CASE("Ring timings retain small host blocks even with a large advertised maximum", "[host]") +{ + const auto capacity = visona::ringCapacityFrames(48000, 4096); + visona::AudioRingBuffer ring(2, capacity, visona::ringTimingSlots(capacity)); + visona::AudioInputWriter writer(ring); + std::array audio{}; + std::array channels{audio.data(), audio.data()}; + writer.route(0, 0); + writer.route(1, 1); + // Buffer 0.8 seconds of 64-frame callbacks without any analysis-side draining. + for (int block = 0; block < 600; ++block) + writer.write(channels, 64, 0); + CHECK(ring.overrunCount() == 0); + CHECK(ring.droppedFrameCount() == 0); +} + +TEST_CASE("Audio device watchdog recovers stopped, failed and stalled inputs", "[device]") +{ + visona::AudioDeviceWatchdog watchdog; + SECTION("An open input that never starts has no stream") + { + for (int i = 0; i < 3; ++i) + CHECK_FALSE(watchdog.shouldRestart(true, false, {}, false)); + CHECK(watchdog.shouldRestart(true, false, {}, false)); + } + SECTION("An error requests recovery without waiting") + { + CHECK(watchdog.shouldRestart(true, true, 100, true)); + } + SECTION("A stalled stream recovers but changing frame counts do not") + { + for (std::uint64_t frames = 0; frames < 10; ++frames) + CHECK_FALSE(watchdog.shouldRestart(true, true, frames, false)); + for (int i = 0; i < 3; ++i) + CHECK_FALSE(watchdog.shouldRestart(true, true, 9, false)); + CHECK(watchdog.shouldRestart(true, true, 9, false)); + CHECK_FALSE(watchdog.shouldRestart(true, true, 0, false)); + } + SECTION("No selected input never triggers a reopen") + { + for (int i = 0; i < 10; ++i) + CHECK_FALSE(watchdog.shouldRestart(false, false, {}, true)); + } +} diff --git a/tests/PluginChecks.cpp b/tests/PluginChecks.cpp new file mode 100644 index 0000000..6cb654d --- /dev/null +++ b/tests/PluginChecks.cpp @@ -0,0 +1,126 @@ +#include "support/AllocationCounter.h" + +#ifdef VISONA_CHECK_SYNC +#include "plugin/src/SyncProcessor.h" +#else +#include "plugin/src/PluginProcessor.h" +#include "plugin/src/ScopeEditor.h" +#include "ui/Palette.h" + +#include +#endif + +#include +#include +#include +#include +#include +#include + +namespace +{ +void check(bool condition, const char* message) +{ + if (!condition) + throw std::runtime_error(message); +} + +struct Playhead : juce::AudioPlayHead +{ + PositionInfo position; + juce::Optional getPosition() const override + { + return position; + } +}; +} // namespace + +int main() +{ + juce::ScopedJuceInitialiser_GUI gui; + try + { + Playhead head; + head.position.setBpm(120); + head.position.setPpqPosition(0); + head.position.setIsPlaying(true); +#ifdef VISONA_CHECK_SYNC + visona::SyncProcessor processor; +#else + visona::PluginProcessor processor; +#endif + processor.setPlayHead(&head); + juce::AudioBuffer audio(2, 1024); + juce::MidiBuffer midi; + audio.clear(); + for (int prepare = 0; prepare < 20; ++prepare) + { + // Exercise both repeated preparation and destruction without releaseResources. + processor.prepareToPlay(48000, 4096); + for (int block = 0; block < 16; ++block) + { + head.position.setPpqPosition(static_cast(block * 1024) / 24000.0); + visona::test::AllocationCounter counter; + processor.processBlock(audio, midi); + const auto allocations = counter.count(); + check(allocations == 0, "Plugin processBlock allocated"); + } + } +#ifdef VISONA_CHECK_SYNC + head.position.setPpqPosition(4.0 - 511.75 / 24000.0); + processor.processBlock(audio, midi); + check(audio.getSample(0, 512) > 0.5f, "Sync lost the rounded bar impulse"); + check(std::bit_cast(audio.getSample(1, 512)) == + std::bit_cast(audio.getSample(0, 512)), + "Sync channels differ"); + head.position.setPpqPosition({}); + processor.processBlock(audio, midi); + check(audio.getMagnitude(0, audio.getNumSamples()) == 0.0f, + "Missing PPQ produced impulses"); + + std::atomic finished{false}; + std::thread reader( + [&] + { + while (!finished.load(std::memory_order_acquire)) + static_cast(processor.lastPlayhead()); + }); + for (int i = 0; i < 10000; ++i) + processor.processBlock(audio, midi); + finished.store(true, std::memory_order_release); + reader.join(); +#else + auto& state = processor.instanceState(); + for (const int malformed : {-1, 8, 999999}) + { + juce::XmlElement xml("VisonaPlugin"); + xml.setAttribute("hasInstanceAppearance", true); + xml.setAttribute("waveformColour", malformed); + xml.setAttribute("window", malformed); + state.readFrom(xml, processor.globalDefaults()); + check(state.waveformColour < visona::palette::waveformColours.size(), + "Unbounded colour"); + check(state.window < visona::sweepWindowBars.size(), "Unbounded window"); + visona::ScopeEditor editor(processor); + check(!editor.keyPressed(juce::KeyPress('d', juce::ModifierKeys::commandModifier, 'd')), + "Plugin consumed the host's Cmd+D shortcut"); + check(!editor.keyPressed(juce::KeyPress('d', juce::ModifierKeys::ctrlModifier, 'd')), + "Plugin consumed the host's Ctrl+D shortcut"); + check(editor.keyPressed(juce::KeyPress('d', 0, 'd')), "D no longer opens diagnostics"); + } + state.waveformColour = 3; + state.window = 1; + juce::XmlElement saved("VisonaPlugin"); + state.writeTo(saved); + check(saved.getIntAttribute("version") == 1, "Missing state version"); + state.readFrom(saved, processor.globalDefaults()); + check(state.waveformColour == 3 && state.window == 1, "Valid state did not round trip"); +#endif + std::cout << "Plugin checks passed\n"; + } + catch (const std::exception& error) + { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/tests/SpectrumAnalyzerTests.cpp b/tests/SpectrumAnalyzerTests.cpp index d0d5deb..54555db 100644 --- a/tests/SpectrumAnalyzerTests.cpp +++ b/tests/SpectrumAnalyzerTests.cpp @@ -288,8 +288,12 @@ TEST_CASE("Spectrum publishes coherent snapshots during concurrent settings chan std::thread consumer( [&] { - while (!done.load(std::memory_order_acquire)) + bool finished = false; + do { + // Observe completion before fetching, so the final published frame is + // consumed even if the producer finished before this thread was scheduled. + finished = done.load(std::memory_order_acquire); if (analyzer.snapshots().fetch()) { const auto& snapshot = analyzer.snapshots().readBuffer(); @@ -303,7 +307,7 @@ TEST_CASE("Spectrum publishes coherent snapshots during concurrent settings chan } } std::this_thread::yield(); - } + } while (!finished); }); for (int i = 0; i < 20; ++i) { diff --git a/tests/StereoUiChecks.cpp b/tests/StereoUiChecks.cpp index 50f43d7..11cf261 100644 --- a/tests/StereoUiChecks.cpp +++ b/tests/StereoUiChecks.cpp @@ -99,6 +99,18 @@ struct StereoUiChecks view.timerCallback(); check(view.snapshot_->correlationValid(), "Stereo UI did not receive measurement"); check(view.status().isEmpty(), "Valid stereo shows a no-signal message"); + // Publishing a new interval must replace maxima, not retain a lifetime maximum. + view.stats_.renderMsMax = view.stats_.paintMsMax = 99.0; + view.renderMax_ = 2.0; + view.paintMax_ = 3.0; + view.start_ = juce::Time::getMillisecondCounterHiRes() - 1100.0; + view.timerCallback(); + check(view.stats().renderMsMax == 2.0 && view.stats().paintMsMax == 3.0, + "Stereo diagnostics retained an old interval's maximum"); + view.start_ -= 1100.0; + view.timerCallback(); + check(view.stats().renderMsMax == 0.0 && view.stats().paintMsMax == 0.0, + "Stereo diagnostics did not reset interval counters"); const auto correlation = view.snapshot_->correlation; for (int mode = 0; mode < 3; ++mode) for (int gain = 0; gain < view.gain_.getNumItems(); ++gain) @@ -414,6 +426,8 @@ struct StereoUiChecks { const auto screenshot = view.createComponentSnapshot(view.getLocalBounds(), true, scale); + check(std::abs(view.stats().scale - scale) < 0.001f, + "Stereo diagnostics scale is incorrect"); check(std::abs(view.renderScale_ - scale) < 0.001f, "Stereo cache ignored physical display scale"); check(view.density_.getWidth() == juce::roundToInt(view.plot().getWidth() * scale), diff --git a/ui/AnalysisSelector.cpp b/ui/AnalysisSelector.cpp index d253edb..faaec24 100644 --- a/ui/AnalysisSelector.cpp +++ b/ui/AnalysisSelector.cpp @@ -174,6 +174,8 @@ void AnalysisSelector::setView(int view) } void AnalysisSelector::choose(int view) { + if (view == selected_) + return; setView(view); if (onSelect) onSelect(view); diff --git a/ui/CMakeLists.txt b/ui/CMakeLists.txt index a8fd41b..a31170a 100644 --- a/ui/CMakeLists.txt +++ b/ui/CMakeLists.txt @@ -31,6 +31,7 @@ set(visona_ui_sources ControlText.h DiagnosticsOverlay.cpp DiagnosticsOverlay.h + RenderStats.h GainControl.cpp GainControl.h Palette.h diff --git a/ui/DiagnosticsOverlay.cpp b/ui/DiagnosticsOverlay.cpp index 42ef37d..e12247b 100644 --- a/ui/DiagnosticsOverlay.cpp +++ b/ui/DiagnosticsOverlay.cpp @@ -128,8 +128,8 @@ int DiagnosticsOverlay::numRows() const { return headingRows + audioRows + midiRows + static_cast(values_.channels.size()) + (values_.callbackAllocations.has_value() ? 1 : 0) + - (values_.sidechainSync.isNotEmpty() ? 1 : 0) + analysisRows + renderingRows + - processRows; + (values_.sidechainSync.isNotEmpty() ? 1 : 0) + analysisRows + renderingRows - + (values_.scopeRendering ? 0 : 1) + processRows; } juce::Rectangle DiagnosticsOverlay::preferredSize() const @@ -267,16 +267,19 @@ void DiagnosticsOverlay::paint(juce::Graphics& g) drawHeading("RENDERING"); const auto& rendering = values_.rendering; - drawRow("Frame rate", juce::String(juce::roundToInt(rendering.framesPerSecond)) + - " fps (display " + - juce::String(juce::roundToInt(rendering.vblanksPerSecond)) + " Hz)"); + auto rate = juce::String(juce::roundToInt(rendering.framesPerSecond)) + " fps"; + if (values_.scopeRendering) + rate += " (display " + juce::String(juce::roundToInt(rendering.vblanksPerSecond)) + " Hz)"; + drawRow("Frame rate", rate); drawRow("Render", formatMs(rendering.renderMsAverage, rendering.renderMsMax)); drawRow("Paint", formatMs(rendering.paintMsAverage, rendering.paintMsMax)); - drawRow("Full redraws", juce::String(rendering.fullRedrawsPerSecond, 1) + " per second"); - drawRow("Image", juce::String(rendering.imageWidth) + " x " + - juce::String(rendering.imageHeight) + " px at " + - juce::String(rendering.scale, 1) + "x, " + - juce::String(static_cast(rendering.tiles)) + " tiles"); + if (values_.scopeRendering) + drawRow("Full redraws", juce::String(rendering.fullRedrawsPerSecond, 1) + " per second"); + auto image = juce::String(rendering.imageWidth) + " x " + juce::String(rendering.imageHeight) + + " px at " + juce::String(rendering.scale, 1) + "x"; + if (values_.scopeRendering) + image += ", " + juce::String(static_cast(rendering.tiles)) + " tiles"; + drawRow("Image", image); drawHeading("PROCESS"); drawRow("Visona CPU", diff --git a/ui/DiagnosticsOverlay.h b/ui/DiagnosticsOverlay.h index aec71af..f83021c 100644 --- a/ui/DiagnosticsOverlay.h +++ b/ui/DiagnosticsOverlay.h @@ -67,7 +67,8 @@ class DiagnosticsOverlay final : public juce::Component /** Fraction of one CPU core. */ double analysisLoad = 0.0; - ScopeView::Stats rendering; + RenderStats rendering; + bool scopeRendering = true; /** Fraction of one CPU core, if known. */ std::optional processCpu; }; diff --git a/ui/RenderStats.h b/ui/RenderStats.h new file mode 100644 index 0000000..1c2e4ad --- /dev/null +++ b/ui/RenderStats.h @@ -0,0 +1,19 @@ +#pragma once + +#include + +namespace visona +{ + +/** Common display measurements. Scope-specific counters are hidden for timer-driven views. */ +struct RenderStats +{ + double framesPerSecond = 0.0, renderMsAverage = 0.0, renderMsMax = 0.0; + int imageWidth = 0, imageHeight = 0; + float scale = 1.0f; + double paintMsAverage = 0.0, paintMsMax = 0.0; + double vblanksPerSecond = 0.0, fullRedrawsPerSecond = 0.0; + std::size_t tiles = 0; +}; + +} // namespace visona diff --git a/ui/ScopeView.h b/ui/ScopeView.h index 8494945..7c43354 100644 --- a/ui/ScopeView.h +++ b/ui/ScopeView.h @@ -1,4 +1,5 @@ #pragma once +#include "RenderStats.h" #include #include @@ -129,20 +130,7 @@ class ScopeView final : public juce::Component std::function onFrame; /** Rendering statistics over the most recent whole second. */ - struct Stats - { - double framesPerSecond = 0.0; - double vblanksPerSecond = 0.0; - double fullRedrawsPerSecond = 0.0; - double renderMsAverage = 0.0; - double renderMsMax = 0.0; - double paintMsAverage = 0.0; - double paintMsMax = 0.0; - int imageWidth = 0; - int imageHeight = 0; - float scale = 1.0f; - std::size_t tiles = 0; - }; + using Stats = RenderStats; [[nodiscard]] Stats stats() const noexcept { diff --git a/ui/SpectrumView.h b/ui/SpectrumView.h index 2bddb92..e1c862b 100644 --- a/ui/SpectrumView.h +++ b/ui/SpectrumView.h @@ -1,5 +1,6 @@ #pragma once #include "ChoiceBox.h" +#include "RenderStats.h" #include @@ -19,13 +20,7 @@ class SpectrumView final : public juce::Component, private juce::Timer void setActive(bool active); void setDisplayGainDb(int db); void setAfterglow(int index); - struct Stats - { - double framesPerSecond = 0, renderMsAverage = 0, renderMsMax = 0; - int imageWidth = 0, imageHeight = 0; - float scale = 1; - double paintMsAverage = 0, paintMsMax = 0; - }; + using Stats = RenderStats; Stats stats() const noexcept { return stats_; diff --git a/ui/StereoView.cpp b/ui/StereoView.cpp index 81940b9..3960b33 100644 --- a/ui/StereoView.cpp +++ b/ui/StereoView.cpp @@ -190,7 +190,7 @@ void StereoView::setActive(bool active) stale_ = true; lastAudio_ = start_ = now(); frames_ = paints_ = 0; - renderTotal_ = paintTotal_ = 0; + renderTotal_ = paintTotal_ = renderMax_ = paintMax_ = 0; stats_ = {}; render(); startTimerHz(refreshRate()); @@ -539,11 +539,10 @@ void StereoView::render() const double duration = now() - start; renderTotal_ += duration; ++frames_; - stats_.renderMsAverage = renderTotal_ / frames_; - stats_.renderMsMax = std::max(stats_.renderMsMax, duration); + renderMax_ = std::max(renderMax_, duration); stats_.imageWidth = width; stats_.imageHeight = height; - stats_.scale = 1; + stats_.scale = renderScale_; } void StereoView::renderLevel() { @@ -710,8 +709,8 @@ void StereoView::paint(juce::Graphics& g) } const double duration = now() - start; paintTotal_ += duration; - stats_.paintMsAverage = paintTotal_ / ++paints_; - stats_.paintMsMax = std::max(stats_.paintMsMax, duration); + ++paints_; + paintMax_ = std::max(paintMax_, duration); } void StereoView::timerCallback() { @@ -738,8 +737,12 @@ void StereoView::timerCallback() if (time - start_ >= 1000) { stats_.framesPerSecond = 1000.0 * frames_ / (time - start_); + stats_.renderMsAverage = frames_ > 0 ? renderTotal_ / frames_ : 0.0; + stats_.paintMsAverage = paints_ > 0 ? paintTotal_ / paints_ : 0.0; + stats_.renderMsMax = renderMax_; + stats_.paintMsMax = paintMax_; frames_ = paints_ = 0; - renderTotal_ = paintTotal_ = 0; + renderTotal_ = paintTotal_ = renderMax_ = paintMax_ = 0; start_ = time; } if (changed) diff --git a/ui/StereoView.h b/ui/StereoView.h index 5acd7b1..48a75a2 100644 --- a/ui/StereoView.h +++ b/ui/StereoView.h @@ -84,6 +84,7 @@ class StereoView final : public juce::Component, private juce::Timer SpectrumView::Stats stats_; double lastReadout_ = 0; double lastAudio_ = 0, start_ = 0, renderTotal_ = 0, paintTotal_ = 0; + double renderMax_ = 0.0, paintMax_ = 0.0; int frames_ = 0, paints_ = 0; }; } // namespace visona From e9d7270e74e56edc0936bb3cda0eee83350c3e75 Mon Sep 17 00:00:00 2001 From: Stephan Terning Date: Sun, 18 Oct 2026 10:51:19 +0200 Subject: [PATCH 2/2] Preserve auto gain across missed peak history --- CHANGELOG.md | 2 +- core/include/visona/BarImpulseScheduler.h | 3 +- core/src/AutoGain.cpp | 5 ++-- core/src/BarImpulseScheduler.cpp | 3 +- plugin/src/SyncProcessor.cpp | 7 +---- plugin/src/SyncProcessor.h | 1 - site/static/manual/index.html | 2 +- tests/AutoGainTests.cpp | 36 ++++++++++++++++------- tests/BarImpulseSchedulerTests.cpp | 26 ++++++++-------- tests/HostAnalysisPipelineTests.cpp | 3 +- 10 files changed, 47 insertions(+), 41 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 96aac0b..178489e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,7 +28,7 @@ All notable changes to this project are documented here. The format is based on - Plugin preparation detaches the old audio stream before replacing it, including repeated host preparation and destruction without an explicit release. - Visona Sync schedules bar impulses without heap allocation and retains impulses that round across a block boundary. Missing PPQ positions no longer produce repeated bar impulses; invalid host tempo and time signatures retain valid defaults. - Plugin state clamps saved colour and window indices. Small host blocks retain enough timing slots, and time-signature changes update the scope's window length. -- Auto gain retains more than ten seconds of input peaks. If the UI misses the entire retained history, gain returns to unity and waits for a new ten-second history before rising. App settings writes are coalesced and flushed on shutdown. +- Auto gain retains more than ten seconds of input peaks. If the UI misses the entire retained history, gain is preserved and waits for a new ten-second history before rising; current peaks can still lower it immediately. App settings writes are coalesced and flushed on shutdown. - The app retries an input device that fails to start, stops or reports an error. Selecting the active view preserves its history, and plugin diagnostics no longer share timing counters between instances or consume modified D shortcuts. - Visona Sync's editor reads atomic transport display values. Stereo diagnostics report the physical display scale and recent timing maxima; scope-only counters are hidden in other views. The spectrum stress test consumes the final snapshot even when its producer finishes first. diff --git a/core/include/visona/BarImpulseScheduler.h b/core/include/visona/BarImpulseScheduler.h index 06a5049..170e3e5 100644 --- a/core/include/visona/BarImpulseScheduler.h +++ b/core/include/visona/BarImpulseScheduler.h @@ -28,8 +28,7 @@ class BarImpulseScheduler numFrames offsets always suffices. With smaller storage, only the first offsets fit. Non-finite inputs, invalid signatures and bar periods below one sample are ignored. */ - [[nodiscard]] static std::size_t impulsesInBlock(std::uint64_t blockStartSample, - std::uint32_t numFrames, + [[nodiscard]] static std::size_t impulsesInBlock(std::uint32_t numFrames, double ppqAtBlockStart, double bpm, TimeSignature timeSignature, double sampleRate, std::span offsetsOut) noexcept; diff --git a/core/src/AutoGain.cpp b/core/src/AutoGain.cpp index 7e686df..5515b38 100644 --- a/core/src/AutoGain.cpp +++ b/core/src/AutoGain.cpp @@ -52,9 +52,8 @@ bool AutoGain::follow(const RecentBarPeaks& recent) noexcept if (seenBars_ + 1 < recent.oldest()) { // Some peaks were overwritten while the UI stalled. Their levels are unknown: - // return to unity and rebuild a complete hold interval before allowing a rise. - changed = gainDb_ != DisplayGain::minDb; - gainDb_ = DisplayGain::minDb; + // keep the current gain and rebuild a complete hold interval before allowing a rise. + // The current peak below can still lower gain immediately. historySize_ = historyNext_ = 0; heldSeconds_ = 0.0; seenBars_ = recent.count; diff --git a/core/src/BarImpulseScheduler.cpp b/core/src/BarImpulseScheduler.cpp index ef04278..e984c7e 100644 --- a/core/src/BarImpulseScheduler.cpp +++ b/core/src/BarImpulseScheduler.cpp @@ -30,8 +30,7 @@ double BarImpulseScheduler::sampleIndexOfBarBoundary(double ppqAtReference, (barPpq - ppqAtReference) * samplesPerQuarterNote(bpm, sampleRate); } -std::size_t BarImpulseScheduler::impulsesInBlock(std::uint64_t /*blockStartSample*/, - std::uint32_t numFrames, double ppqAtBlockStart, +std::size_t BarImpulseScheduler::impulsesInBlock(std::uint32_t numFrames, double ppqAtBlockStart, double bpm, TimeSignature timeSignature, double sampleRate, std::span offsetsOut) noexcept diff --git a/plugin/src/SyncProcessor.cpp b/plugin/src/SyncProcessor.cpp index 69fee3b..b4b7b0f 100644 --- a/plugin/src/SyncProcessor.cpp +++ b/plugin/src/SyncProcessor.cpp @@ -27,13 +27,11 @@ void SyncProcessor::prepareToPlay(double sampleRate, int samplesPerBlock) juce::ignoreUnused(samplesPerBlock); playheadReader_ = {}; sampleRate_ = sampleRate; - streamSample_ = 0; } void SyncProcessor::releaseResources() { sampleRate_ = 0.0; - streamSample_ = 0; } void SyncProcessor::processBlock(juce::AudioBuffer& buffer, juce::MidiBuffer& midi) @@ -43,8 +41,6 @@ void SyncProcessor::processBlock(juce::AudioBuffer& buffer, juce::MidiBuf buffer.clear(); const auto numSamples = static_cast(buffer.getNumSamples()); - const auto blockStartSample = streamSample_; - streamSample_ += numSamples; const auto playhead = readHostPlayhead(getPlayHead(), playheadReader_); hostValid_.store(playhead.valid, std::memory_order_relaxed); @@ -63,8 +59,7 @@ void SyncProcessor::processBlock(juce::AudioBuffer& buffer, juce::MidiBuf const auto ppq = playhead.ppqPosition + static_cast(first) / sampleRate_ * playhead.bpm / 60.0; const auto count = BarImpulseScheduler::impulsesInBlock( - blockStartSample + first, frames, ppq, playhead.bpm, playhead.timeSignature, - sampleRate_, offsets); + frames, ppq, playhead.bpm, playhead.timeSignature, sampleRate_, offsets); for (std::size_t i = 0; i < count; ++i) for (int channel = 0; channel < buffer.getNumChannels(); ++channel) buffer.setSample(channel, static_cast(first + offsets[i]), diff --git a/plugin/src/SyncProcessor.h b/plugin/src/SyncProcessor.h index 68717f2..9795ecf 100644 --- a/plugin/src/SyncProcessor.h +++ b/plugin/src/SyncProcessor.h @@ -50,7 +50,6 @@ class SyncProcessor final : public juce::AudioProcessor private: double sampleRate_ = 0.0; - std::uint64_t streamSample_ = 0; // Independent display values; the editor never reads the audio thread's mutable playhead. std::atomic hostValid_{false}, hostPlaying_{false}; diff --git a/site/static/manual/index.html b/site/static/manual/index.html index 72e71ab..6be3251 100644 --- a/site/static/manual/index.html +++ b/site/static/manual/index.html @@ -268,7 +268,7 @@

14Tempo

15Gain and auto gain

GAIN and AUTO are shared by all visualizations and always appear in the bottom control bar. Gain ranges from 0 to +64 dB in 1 dB steps. It scales waveform amplitudes and stereo radii, and moves both FFT curves and Band bars and markers by the same number of dB. Spectrum scales continue to label actual signal levels: at +6 dB gain the top is −6 dBFS. Gain affects presentation only, never audio, correlation or signal validity. Drag or scroll on it, use its buttons, or use +/− and ↑/↓ in the standalone app. Double-click or double-tap resets it to 0 dB.

-

AUTO uses the same incoming channel peaks in every view, whether or not MIDI Clock or the DAW is playing. It lowers gain immediately when a peak would exceed the display, and once peaks have stayed low for 10 seconds it raises it, in 3 dB steps, as far as the loudest of them allows, up to +63 dB. Silence below the detection threshold does not cause gain to rise. Switching views does not restart Auto. After a UI interruption long enough to lose the retained peak history, Auto returns to 0 dB and waits for a new ten-second history before raising gain. Setting gain manually turns Auto off; switching Auto off retains its current gain. Auto follows the audio level, so each individual spectrum curve or stereo profile need not fill the plot.

+

AUTO uses the same incoming channel peaks in every view, whether or not MIDI Clock or the DAW is playing. It lowers gain immediately when a peak would exceed the display, and once peaks have stayed low for 10 seconds it raises it, in 3 dB steps, as far as the loudest of them allows, up to +63 dB. Silence below the detection threshold does not cause gain to rise. Switching views does not restart Auto. After a UI interruption long enough to lose the retained peak history, Auto keeps its current gain and waits for a new ten-second history before raising it. Current peaks can still lower gain immediately. Setting gain manually turns Auto off; switching Auto off retains its current gain. Auto follows the audio level, so each individual spectrum curve or stereo profile need not fill the plot.

Afterglow is shared by FFT, Band and Stereo and hidden in Scope. Select Off, 0.5 s, 1 s (default) or 2 s. For FFT it sets the time for the white history line to fall 12 dB, without a hold: 0.5 s gives 24 dB/s, 1 s gives 12 dB/s, and 2 s gives 6 dB/s. For Band it sets peak-marker hold time, followed by a fall of 12 dB/s; an equal or higher peak restarts the hold. In Stereo it sets the fade to 1% brightness for sample points or 1% radius for Polar Level. Off hides the FFT history line and Band markers and removes stereo display history. The shared gain and afterglow are remembered in the app and per plugin instance.

In Scope, faint reference lines mark signal levels every 3 dB after gain, without a fixed lower dB limit. Right-hand labels continue as far as screen space allows; lines continue to pixel resolution near the zero-amplitude centre. A peak beyond a lane is cut off with a grey display-overshoot marker. In Stereo, retained visible history follows gain changes; history moved outside the plot may be discarded.

diff --git a/tests/AutoGainTests.cpp b/tests/AutoGainTests.cpp index 0115ca8..05c1cae 100644 --- a/tests/AutoGainTests.cpp +++ b/tests/AutoGainTests.cpp @@ -273,24 +273,40 @@ TEST_CASE("Auto gain retains a loud input window across a multi-second UI stall" CHECK(gain.gainDb() == 0); } -TEST_CASE("Auto gain returns to unity and rebuilds its hold after history is overwritten", +TEST_CASE("Auto gain preserves gain and restarts its hold after history is overwritten", "[autogain]") { AutoGain gain; - gain.reset(18); + gain.reset(6); RecentBarPeaks peaks; gain.follow(peaks); - peaks.count = RecentBarPeaks::capacity + 1; peaks.bars.fill({0.1f, 0.1}); - CHECK(gain.follow(peaks)); - CHECK(gain.gainDb() == 0); - for (int window = 0; window < 99; ++window) + for (int window = 0; window < 90; ++window) + { + ++peaks.count; + CHECK_FALSE(gain.follow(peaks)); + } + + peaks.count += RecentBarPeaks::capacity + 1; + SECTION("A quiet current peak preserves gain and requires a fresh full hold") { + peaks.currentPeak = 0.1f; + CHECK_FALSE(gain.follow(peaks)); + CHECK(gain.gainDb() == 6); + for (int window = 0; window < 99; ++window) + { + ++peaks.count; + CHECK_FALSE(gain.follow(peaks)); + CHECK(gain.gainDb() == 6); + } ++peaks.count; - gain.follow(peaks); + CHECK(gain.follow(peaks)); + CHECK(gain.gainDb() == 18); + } + SECTION("A loud current peak still lowers gain immediately after the gap") + { + peaks.currentPeak = 0.9f; + CHECK(gain.follow(peaks)); CHECK(gain.gainDb() == 0); } - ++peaks.count; - gain.follow(peaks); - CHECK(gain.gainDb() == 18); } diff --git a/tests/BarImpulseSchedulerTests.cpp b/tests/BarImpulseSchedulerTests.cpp index 77f056d..a20191c 100644 --- a/tests/BarImpulseSchedulerTests.cpp +++ b/tests/BarImpulseSchedulerTests.cpp @@ -20,11 +20,11 @@ TEST_CASE("BarImpulseScheduler places one impulse per bar boundary", "[sync]") for (const auto start : {0u, 96000u}) { const auto count = BarImpulseScheduler::impulsesInBlock( - start, 96000, static_cast(start) / 24000.0, 120, {4, 4}, 48000, offsets); + 96000, static_cast(start) / 24000.0, 120, {4, 4}, 48000, offsets); REQUIRE(count == 1); CHECK(offsets[0] == 0); } - CHECK(BarImpulseScheduler::impulsesInBlock(100000, 1024, 0, 120, {4, 4}, 48000, offsets) == 1); + CHECK(BarImpulseScheduler::impulsesInBlock(1024, 0, 120, {4, 4}, 48000, offsets) == 1); CHECK(offsets[0] == 0); } @@ -42,8 +42,8 @@ TEST_CASE("BarImpulseScheduler rounds boundary ownership across adjacent blocks" for (std::uint32_t start : {0u, 512u}) { const double ppq = barPpq + (static_cast(start) - boundary) / 24000.0; - const auto count = BarImpulseScheduler::impulsesInBlock(start, 512, ppq, 120, - {4, 4}, 48000, offsets); + const auto count = + BarImpulseScheduler::impulsesInBlock(512, ppq, 120, {4, 4}, 48000, offsets); for (std::size_t i = 0; i < count; ++i) { CHECK(start + offsets[i] == expected); @@ -60,15 +60,15 @@ TEST_CASE("BarImpulseScheduler bounds output and never allocates", "[sync][realt std::array offsets{}; visona::test::AllocationCounter allocations; // One sample per bar, the densest supported timeline. - const auto count = BarImpulseScheduler::impulsesInBlock(0, 128, 0, 60, {1, 4}, 1, offsets); + const auto count = BarImpulseScheduler::impulsesInBlock(128, 0, 60, {1, 4}, 1, offsets); const auto allocated = allocations.count(); REQUIRE(allocated == 0); REQUIRE(count == offsets.size()); for (std::size_t i = 0; i < count; ++i) CHECK(offsets[i] == i); - CHECK(BarImpulseScheduler::impulsesInBlock(0, 128, 0, 60, {1, 4}, 1, + CHECK(BarImpulseScheduler::impulsesInBlock(128, 0, 60, {1, 4}, 1, std::span(offsets).first(3)) == 3); - CHECK(BarImpulseScheduler::impulsesInBlock(0, 128, 0, 60, {1, 4}, 1, {}) == 0); + CHECK(BarImpulseScheduler::impulsesInBlock(128, 0, 60, {1, 4}, 1, {}) == 0); } TEST_CASE("BarImpulseScheduler rejects malformed host values", "[sync]") @@ -76,13 +76,13 @@ TEST_CASE("BarImpulseScheduler rejects malformed host values", "[sync]") std::array offsets{}; for (const auto signature : {TimeSignature{0, 4}, TimeSignature{4, 0}, TimeSignature{5, 64}, TimeSignature{-1, 4}, TimeSignature{4, 3}}) - CHECK(BarImpulseScheduler::impulsesInBlock(0, 512, 0, 120, signature, 48000, offsets) == 0); + CHECK(BarImpulseScheduler::impulsesInBlock(512, 0, 120, signature, 48000, offsets) == 0); for (const double invalid : {std::numeric_limits::quiet_NaN(), std::numeric_limits::infinity()}) { - CHECK(BarImpulseScheduler::impulsesInBlock(0, 512, invalid, 120, {}, 48000, offsets) == 0); - CHECK(BarImpulseScheduler::impulsesInBlock(0, 512, 0, invalid, {}, 48000, offsets) == 0); - CHECK(BarImpulseScheduler::impulsesInBlock(0, 512, 0, 120, {}, invalid, offsets) == 0); + CHECK(BarImpulseScheduler::impulsesInBlock(512, invalid, 120, {}, 48000, offsets) == 0); + CHECK(BarImpulseScheduler::impulsesInBlock(512, 0, invalid, {}, 48000, offsets) == 0); + CHECK(BarImpulseScheduler::impulsesInBlock(512, 0, 120, {}, invalid, offsets) == 0); } } @@ -115,8 +115,8 @@ TEST_CASE("Bar impulses are independent of host block partitioning", "[sync]") { const auto frames = std::min(blockSize, totalFrames - start); const auto count = BarImpulseScheduler::impulsesInBlock( - start, frames, -0.25 + static_cast(start) / framesPerQuarter, bpm, - {4, 4}, 48000, offsets); + frames, -0.25 + static_cast(start) / framesPerQuarter, bpm, {4, 4}, + 48000, offsets); for (std::size_t i = 0; i < count; ++i) actual.push_back(start + offsets[i]); start += frames; diff --git a/tests/HostAnalysisPipelineTests.cpp b/tests/HostAnalysisPipelineTests.cpp index 8652911..1c78e46 100644 --- a/tests/HostAnalysisPipelineTests.cpp +++ b/tests/HostAnalysisPipelineTests.cpp @@ -116,8 +116,7 @@ class LiveHost if (playhead.isPlaying) { const auto count = BarImpulseScheduler::impulsesInBlock( - blockStart, blockSize_, playhead.ppqPosition, bpm_, fourFour, sampleRate, - impulses); + blockSize_, playhead.ppqPosition, bpm_, fourFour, sampleRate, impulses); for (std::size_t i = 0; i < count; ++i) syncOutput[blockStart + impulses[i]] = visona::syncImpulseAmplitude; }