Преглед изворни кода

Export plugin warm-up: silent pre-roll until hosted plugins settle (fresh instances / bridged plugins apply state late); PDC trim after it; Export window option; round 155 doc

Ka1-S пре 1 месец
родитељ
комит
cc2ff57ee0

+ 111 - 0
docs/analise/REA_rodada155.md

@@ -0,0 +1,111 @@
+# Round 155 (render155): exported files start with half-loaded plugins (yabridge)
+
+2026-10-24. Bug report from a Linux user: "VSTs over yabridge tend to not load properly at the render stage, thus
+creating a period at the start of the exported file that has half-loaded effects."
+
+Evidence markers: [CODE] read in LYNX's source (file named); [TEST] proven by a test in `tests/Render155Tests.inc`;
+[RUN] measured with the Windows build; [FL] FL Studio observed as a user / its binary's strings (no decompilation was
+needed this round, nothing copied); [model] LYNX's own design choice.
+
+## 1. Cause
+
+- [CODE] Every export builds its **own engine** (`ExportJob`, `src/engine/Exporter.cpp`): `setSong` creates a fresh
+  instance of every hosted plugin, prepares it and restores its saved state (`PluginHost.cpp`,
+  `setStateInformation` right after `preparePlugin`), all on the message thread. `run()` then starts the render on the
+  Export window's thread at once.
+- [CODE] `renderOffline` (`src/engine/AudioEngine.cpp`) then switches every plugin to the offline mode
+  (`setPluginRenderMode` → `setNonRealtime` + `prepareToPlay`, i.e. VST3 `setupProcessing` + re-activation) and renders
+  sample 0 in the next instant.
+- An offline render runs many times faster than real time: the first second of the file is rendered in a few tens of
+  milliseconds of wall time after the plugins were created and re-activated.
+- yabridge forwards the state, the re-activation and the parameter / latency notifications over IPC to the Windows
+  plugin running in Wine; several plugins apply a restored state, or load what it refers to (samples, impulse
+  responses, wavetables, oversampling buffers), on their own threads or GUI thread. The same happens natively with
+  samplers that stream in the background. Until that work is done the plugin processes with its defaults: the
+  "half-loaded effects" at the start of the file.
+- [CODE] Two smaller contributors: (1) FL's initial values (`Song::initialValues`) were pushed by `play()` at the
+  first rendered block, so a plugin started smoothing towards them inside the file; (2) the PDC trim was read from the
+  latencies *before* the render, so a latency reported late was not trimmed.
+- [FL] FL Studio renders from the project's live plugin instances (the ones that played; playback stops while the
+  render runs), so its plugins have long finished loading. A search of `FLEngine_x64.dll`'s strings found no separate
+  "wait for plugins" option ("Let the plugin know when rendering to audio file" is the "Notify about rendering mode"
+  LYNX already has). LYNX keeps its separate export engine (exports never touch what is playing), so it has to give
+  the fresh instances the time a real start would give them.
+
+## 2. Fix: plugin warm-up before the render
+
+`core/PluginWarmup.h` (policy, JUCE-free) + `AudioEngine::warmUpPlugins` (engine):
+
+1. [model] Only when the song has hosted plugins (channels, inserts, inside Patchers; crashed ones skipped).
+   Projects with only LYNX's own engines render exactly as before (they are ready when created).
+2. FL's initial values are applied **before** the warm-up (`resetToInitialValues`), so the plugins settle on them.
+3. Silent blocks are processed through the whole graph and thrown away, transport **stopped at the start
+   position**: no note plays, and the rack evaluates automation clips / pattern events at that position every block,
+   so the parameters the song starts with reach the plugins before the render.
+4. It stops when all of these hold:
+   - ≥ 0.5 s of audio processed (plugins that settle after a number of blocks),
+   - ≥ 0.5 s of real time passed (work on the plugins' / bridge's own threads),
+   - what the plugins report — latency and every parameter value (quantised to 1e-5) — has not changed for 0.3 s;
+   or after 10 s (a plugin whose values never stop moving). After the minimum audio the blocks are paced to real time
+   (sleeps of ≤ 10 ms when ahead), so the bridge gets wall time, not just blocks. The progress window's Cancel works
+   during the warm-up.
+5. A latency that changed gets its new PDC plan (`publishSong`, on the message thread as the 30 Hz timer does it; the
+   Export window renders on a thread of its own), and the PDC trim uses the latency reported **after** the warm-up
+   (`RenderOptions::trimPdc`).
+6. LYNX's own units are re-prepared (`ChannelRackProcessor::prepareToPlay`: free-running LFOs, the delay
+   compensation's lines, smart-disable counters), so they start the render as without the warm-up. The hosted plugins
+   are **not** reset: in JUCE's VST3 host a reset re-activates the plugin, which is exactly what they had to settle
+   from; they only received silence, so they carry no tail into the file.
+
+Setting: Export window › "Plugin warm-up" (on by default; saved with the other export options as `pluginWarmUp`;
+pt-BR "Aquecimento dos plugins"). `LYNX --export … --no-warmup` turns it off; the `--export` report prints
+`warmup_blocks`, `warmup_ms`, `warmup_changes`, `warmup_timed_out`, `pdc_trim`.
+
+Cost: an export with hosted plugins takes ~0.5–0.8 s longer (more only while a plugin is still changing, at most 10 s).
+
+## 3. Tests
+
+- [TEST] `render155_warm_up_waits_for_a_state_applied_after_n_blocks`: a fake plugin effect whose state (gain 0.5)
+  lands after 40 blocks, after a drone instrument, rendered through the real `RackRenderer`. Without the warm-up the
+  first sample is 2× the reference (half-loaded); with it every sample of the first block equals the reference (a
+  plugin whose state is in place from the start).
+- [TEST] `render155_warm_up_waits_for_a_state_applied_late_in_real_time`: the state lands 1.2 s of (simulated) wall
+  time after creation whatever the number of blocks — the yabridge case. The warm-up lasts ≥ 1.2 + 0.3 s, stays paced
+  to real time, and the first rendered samples are correct.
+- [TEST] `render155_warm_up_minimums_timeout_and_cancel`: minimums, the 10 s timeout for a plugin that never settles,
+  Cancel, parameter quantisation.
+- [TEST] `render155_export_option_plugin_warm_up`: default on, saved and read back.
+- [RUN] Windows, a real VST3 (see §4).
+
+yabridge itself cannot be run on this machine (WSL, no Wine); the fake plugins model its two behaviours (late by
+blocks, late by wall time).
+
+## 4. Real VST3 check (Windows build)
+
+[RUN] `LYNX.exe --export vst3.lynx out.wav [--no-warmup]` (Windows build of this branch, C:\Users\kauan\lynx-test\render155):
+LYNX's Demo song with ValhallaSupermassive (VST3, free) first on the Master insert, then LYNX's Parametric EQ and
+Limiter.
+
+| | warm-up on | `--no-warmup` |
+|---|---|---|
+| `warmup_blocks` / `warmup_ms` / `warmup_changes` | 45 / 505 ms / 0 | 0 / 0 / 0 |
+| render time (song 52 s) | 2058 ms | 1566 ms |
+| `pdc_trim` | 66 samples | 66 samples |
+| peak | 0.95787 | 0.95787 |
+| two runs bit-identical | yes | yes |
+
+- The warm-up costs half a second for a plugin that is ready at once (the minimums), and nothing changed during it.
+- Warm vs cold files: bit-identical for the first 0.30 s, then the reverb tail differs slightly — Supermassive's
+  free-running modulation has run 0.5 s longer (as it would in a real-time start). Expected; both are deterministic.
+- The CLI render runs on the message thread (no message pump available: JUCE_MODAL_LOOPS_PERMITTED is 0), so there
+  the warm-up only gives wall time to the plugins' own threads; the Export window renders on its own thread, so the
+  message thread (JUCE's VST3 host callbacks, yabridge's replies handled there) keeps running during the warm-up.
+
+## Where I stopped
+
+- Landed: see the commit list in the final report.
+- Not done: no per-plugin "needs longer warm-up" option (FL has none either); if a reporter still hears a bad start
+  with a specific plugin, the next step is a longer minimum for bridged plugins only (`PluginRef::separateProcess`
+  or a yabridge path in the plugin's file name) rather than for every export.
+- Not tested with yabridge itself (no Wine here): ask the reporter to try 0.1.16 and, if it persists, send the
+  `--export` report lines `warmup_*` for their project.

+ 4 - 0
resources/i18n/pt-BR.txt

@@ -4266,3 +4266,7 @@ countries: br
 "Group the selected notes" = "Agrupar as notas selecionadas"
 "Ungroup the selected notes" = "Desagrupar as notas selecionadas"
 "The clip's pan (left -100% ... right 100%), on top of the channel's" = "O pan do clipe (esquerda -100% ... direita 100%), somado ao do canal"
+
+# --- round 155: export plugin warm-up
+"Plugin warm-up" = "Aquecimento dos plugins"
+"Before the export starts, third-party plugins process a moment of silence until they have finished loading their settings (bridged plugins, samplers that load in the background), so the file does not start with half-loaded effects" = "Antes de a exportação começar, os plugins de terceiros processam um instante de silêncio até terminarem de carregar as suas configurações (plugins em ponte, samplers que carregam em segundo plano), para o arquivo não começar com efeitos carregados pela metade"

+ 8 - 0
src/Main.cpp

@@ -2321,6 +2321,9 @@ private:
                 const auto loaded = juce::Time::getMillisecondCounterHiRes();
                 // .mp3: the Export window's MP3 (320 kbps); everything else as before
                 auto options = settings.toOptions();
+                // --no-warmup: the export's plugin warm-up off (round 155: compare the start of the file)
+                if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-warmup"))
+                    options.pluginWarmUp = false;
                 if (output.hasFileExtension ("mp3"))
                 {
                     options.format = lynx::exportopts::Format::mp3;
@@ -2380,6 +2383,11 @@ private:
                        << "render_ms=" << juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - prepared) << "\n"
                        << "graph_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().graphMs) << "\n"
                        << "write_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().writeMs) << "\n"
+                       << "warmup_blocks=" << job.getEngine().getLastRenderStats().warmUp.blocks << "\n"
+                       << "warmup_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().warmUp.wallSeconds * 1000.0) << "\n"
+                       << "warmup_changes=" << job.getEngine().getLastRenderStats().warmUp.signatureChanges << "\n"
+                       << "warmup_timed_out=" << (job.getEngine().getLastRenderStats().warmUp.timedOut ? 1 : 0) << "\n"
+                       << "pdc_trim=" << job.getEngine().getLastRenderStats().trimmedSamples << "\n"
                        << "song_seconds=" << job.getMusicSeconds() << "\n"
                        << "peak=" << job.getPeak() << "\n"
                        << "final_progress=" << lastPercent << "\n"

+ 2 - 0
src/core/ExportOptions.cpp

@@ -252,6 +252,7 @@ std::string toText (const Options& o)
       << "masterEffects=" << (o.masterEffects ? 1 : 0) << "\n"
       << "trimPdc=" << (o.trimPdc ? 1 : 0) << "\n"
       << "hqAllPlugins=" << (o.hqAllPlugins ? 1 : 0) << "\n"
+      << "pluginWarmUp=" << (o.pluginWarmUp ? 1 : 0) << "\n"
       << "showWhenDone=" << (o.showWhenDone ? 1 : 0) << "\n"
       << "disableMaxPolyphony=" << (o.disableMaxPolyphony ? 1 : 0) << "\n"
       << "moreFormats=" << o.moreFormats << "\n"
@@ -282,6 +283,7 @@ Options fromText (const std::string& text)
     o.masterEffects = toInt (kv, "masterEffects", d.masterEffects ? 1 : 0) != 0;
     o.trimPdc = toInt (kv, "trimPdc", d.trimPdc ? 1 : 0) != 0;
     o.hqAllPlugins = toInt (kv, "hqAllPlugins", d.hqAllPlugins ? 1 : 0) != 0;
+    o.pluginWarmUp = toInt (kv, "pluginWarmUp", d.pluginWarmUp ? 1 : 0) != 0;
     o.showWhenDone = toInt (kv, "showWhenDone", d.showWhenDone ? 1 : 0) != 0;
     o.disableMaxPolyphony = toInt (kv, "disableMaxPolyphony", d.disableMaxPolyphony ? 1 : 0) != 0;
     o.moreFormats = (std::uint32_t) std::clamp (toInt (kv, "moreFormats", 0), 0, 15);

+ 4 - 0
src/core/ExportOptions.h

@@ -80,6 +80,10 @@ struct Options
     // FL's "HQ for all plugins" (REA round 134): engines with a separate render quality use it and HQ switches are
     // forced on; off = the export uses the same (draft) quality as playback, so it matches what was heard
     bool hqAllPlugins = true;
+    // "Plugin warm-up" (round 155): hosted plugins get silent, discarded audio before the render until they have
+    // settled (fresh instances: bridged plugins / background loading apply their state late), so the file does not
+    // start with half-loaded effects
+    bool pluginWarmUp = true;
     bool showWhenDone = false;       // FL's "Show file(s) when complete": the file manager opens on the result
     // FL's "Disable maximum polyphony" (on by default; REA round 139, FLEngine FUN_00d1a…: every channel's Max
     // polyphony is set to 0 for the render): the channels' polyphony limits are lifted in the exported song

+ 115 - 0
src/core/PluginWarmup.h

@@ -0,0 +1,115 @@
+#pragma once
+
+#include <algorithm>
+#include <cstdint>
+
+namespace lynx::warmup
+{
+// Export "Plugin warm-up" (round 155). An export builds its own engine: every hosted plugin is a fresh instance whose
+// saved state was just restored, then it is re-prepared for the offline render mode. Some plugins finish that work
+// later — bridged plugins (yabridge on Linux forwards state, parameter and latency changes over IPC, and the Windows
+// side applies some of them on its own GUI thread), samplers that stream their samples in the background, convolution
+// reverbs loading their impulse. An offline render runs much faster than real time, so without a wait the first
+// second of the file is rendered by half-loaded plugins.
+//
+// Before the render starts, the engine processes silent blocks that are thrown away (transport stopped at the start
+// position, so the plugins also get the song's values at that position) until:
+//   - at least `minAudioSeconds` of audio went through the plugins (plugins that settle after a number of blocks),
+//   - at least `minWallSeconds` of real time passed (work done on the plugins' own threads),
+//   - what the plugins report (latency, parameter values: `signature`) stayed the same for `stableWallSeconds`,
+// or `maxWallSeconds` passed (a plugin whose values never stop moving, e.g. a meter exposed as a parameter).
+struct Settings
+{
+    double minAudioSeconds = 0.5;
+    double minWallSeconds = 0.5;
+    double stableWallSeconds = 0.3;
+    double maxWallSeconds = 10.0;
+};
+
+struct Result
+{
+    int blocks = 0;
+    double audioSeconds = 0.0;
+    double wallSeconds = 0.0;
+    int signatureChanges = 0; // how many times what the plugins report changed during the warm-up
+    bool timedOut = false;
+    bool cancelled = false; // process() returned a negative length
+};
+
+// Runs the warm-up. `process()` renders one discarded silent block and returns its length in samples (negative:
+// cancel); `signature()`
+// is a hash of what the plugins report; `now()` is a clock in seconds; `idle (seconds)` lets other threads run (the
+// blocks are paced so the audio processed does not run ahead of real time by more than a block or so: plugins that
+// work on their own threads get the time a real-time start would give them).
+template <class Process, class Signature, class Now, class Idle>
+Result run (const Settings& settings, double sampleRate, Process&& process, Signature&& signature, Now&& now, Idle&& idle)
+{
+    Result r;
+    const auto start = now();
+    auto last = signature();
+    auto stableSince = start;
+    std::int64_t samples = 0;
+    const auto rate = std::max (1.0, sampleRate);
+
+    for (;;)
+    {
+        const auto t = now();
+        r.wallSeconds = t - start;
+        r.audioSeconds = (double) samples / rate;
+
+        if (r.wallSeconds >= settings.maxWallSeconds)
+        {
+            r.timedOut = true;
+            break;
+        }
+
+        const auto sig = signature();
+        if (sig != last)
+        {
+            last = sig;
+            stableSince = t;
+            ++r.signatureChanges;
+        }
+
+        if (r.audioSeconds >= settings.minAudioSeconds && r.wallSeconds >= settings.minWallSeconds
+            && t - stableSince >= settings.stableWallSeconds)
+            break;
+
+        // ahead of real time: give the plugins' threads (and the message thread) a moment instead of spinning
+        if (r.audioSeconds > r.wallSeconds + 0.02 && r.audioSeconds >= settings.minAudioSeconds)
+        {
+            idle (std::min (0.01, r.audioSeconds - r.wallSeconds));
+            continue;
+        }
+
+        const auto n = process();
+        if (n < 0)
+        {
+            r.cancelled = true;
+            break;
+        }
+        samples += std::max (1, n);
+        ++r.blocks;
+    }
+
+    return r;
+}
+
+// FNV-1a over the values that make up a signature (latency, quantised parameter values).
+struct Hash
+{
+    std::uint64_t value = 1469598103934665603ull;
+
+    void add (std::uint64_t v) noexcept
+    {
+        for (int i = 0; i < 8; ++i)
+        {
+            value ^= (v >> (i * 8)) & 0xffu;
+            value *= 1099511628211ull;
+        }
+    }
+
+    // parameter values are quantised so float noise in a plugin's cache does not count as a change
+    void addValue (float v) noexcept { add ((std::uint64_t) (std::int64_t) (v * 100000.0f)); }
+};
+} // namespace lynx::warmup

+ 130 - 4
src/engine/AudioEngine.cpp

@@ -307,19 +307,27 @@ float AudioEngine::renderOffline (const RenderOptions& options)
     if (rackProcessor != nullptr)
         rackProcessor->setMetering (false); // nobody looks at the meters during the render
 
+    lastRenderStats = {};
+    // FL's init list first (play() would do it at the first block), so the plugins settle on those values too
+    resetToInitialValues();
+    int latency = getLatencySamples();
+    if (options.pluginWarmUp)
+        lastRenderStats.warmUp = warmUpPlugins (options.warmUp, sampleRate, blockSize, progress, latency);
+
     play();
 
     juce::AudioBuffer<float> buffer (2, blockSize);
     juce::MidiBuffer midi;
     float peak = 0.0f;
-    const auto trim = (std::int64_t) juce::jmax (0, trimSamples);
+    // PDC trim with the latency the plugins report once they have settled
+    const auto trim = (std::int64_t) juce::jmax (0, trimSamples + (options.trimPdc ? latency : 0));
+    lastRenderStats.trimmedSamples = (int) trim;
     const auto musicSamples = (std::int64_t) (seconds * sampleRate) + trim;
     const auto totalSamples = musicSamples + (std::int64_t) (juce::jmax (0.0, tailSeconds) * sampleRate);
     std::int64_t quietSamples = 0;
-    bool cancelled = false;
-    lastRenderStats = {};
+    bool cancelled = lastRenderStats.warmUp.cancelled;
 
-    for (std::int64_t done = 0; done < totalSamples; done += blockSize)
+    for (std::int64_t done = 0; done < totalSamples && ! cancelled; done += blockSize)
     {
         const auto n = (int) juce::jmin<std::int64_t> (blockSize, totalSamples - done);
         juce::AudioBuffer<float> view (buffer.getArrayOfWritePointers(), 2, n);
@@ -381,6 +389,124 @@ float AudioEngine::renderOffline (const RenderOptions& options)
     return cancelled ? -1.0f : peak;
 }
 
+warmup::Result AudioEngine::warmUpPlugins (const warmup::Settings& settings, double sampleRate, int blockSize,
+                                           const std::function<bool (double)>& progress, int& latency)
+{
+    // the hosted plugins, collected once: the timer may republish the song meanwhile (the instances stay the same)
+    std::vector<juce::AudioPluginInstance*> hosted;
+    forEachHostedPlugin ([&hosted] (juce::AudioPluginInstance& p, bool) { hosted.push_back (&p); });
+    if (hosted.empty())
+        return {}; // LYNX's own engines are ready as soon as they are created: nothing to wait for
+
+    // keeps the units alive whatever the timer publishes during the warm-up
+    std::vector<std::shared_ptr<Instrument>> keepInstruments;
+    std::vector<std::shared_ptr<Effect>> keepEffects;
+    for (std::size_t i = 0; i < song.channels.size(); ++i)
+        keepInstruments.push_back (getChannelInstrument ((int) i));
+    for (std::size_t t = 0; t < song.mixer.size(); ++t)
+        for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
+            keepEffects.push_back (getEffect ((int) t, (int) s));
+
+    juce::AudioBuffer<float> buffer (2, blockSize);
+    juce::MidiBuffer midi;
+    int blocks = 0;
+
+    // transport stopped at the start position: no note plays, and the automation / pattern events at that position
+    // reach the plugins (the rack evaluates them every block), so they settle on the values the song starts with
+    const auto result = warmup::run (
+        settings, sampleRate,
+        [&]() -> int {
+            if (progress && ++blocks % 32 == 0 && ! progress (0.0))
+                return -1;
+            buffer.clear();
+            midi.clear();
+            graph.processBlock (buffer, midi);
+            return blockSize;
+        },
+        [&hosted] {
+            warmup::Hash h;
+            for (auto* p : hosted)
+            {
+                h.add ((std::uint64_t) (std::int64_t) p->getLatencySamples());
+                for (auto* param : p->getParameters())
+                    h.addValue (param->getValue());
+            }
+            return h.value;
+        },
+        [] { return juce::Time::getMillisecondCounterHiRes() * 0.001; },
+        [] (double s) { juce::Thread::sleep (juce::jlimit (1, 20, (int) std::lround (s * 1000.0))); });
+
+    // a latency that changed (reported late) gets its PDC plan before the render, on the message thread as the
+    // timer does it (renders from the Export window run on a thread of their own)
+    auto republish = [this] {
+        if (lastPublishedShape.currentLatencies() != lastPublishedShape.latencies)
+        {
+            ++latencyRepublishes;
+            publishSong();
+        }
+        return getLatencySamples();
+    };
+    auto* mm = juce::MessageManager::getInstanceWithoutCreating();
+    if (mm == nullptr || mm->isThisTheMessageThread())
+        latency = republish();
+    else
+    {
+        struct Reply
+        {
+            juce::WaitableEvent done;
+            std::atomic<int> latency { 0 };
+        };
+        auto reply = std::make_shared<Reply>();
+        reply->latency = getLatencySamples();
+        juce::MessageManager::callAsync ([this, reply, republish] {
+            reply->latency = republish();
+            reply->done.signal();
+        });
+        reply->done.wait (3000);
+        latency = reply->latency.load();
+    }
+
+    // LYNX's own units start the render from a clean state, as without the warm-up (free-running LFOs, the delay
+    // compensation's lines); the hosted plugins are not reset: they keep what they settled on (a reset re-activates
+    // them, which is what they had to settle from)
+    if (rackProcessor != nullptr)
+        rackProcessor->prepareToPlay (sampleRate, blockSize);
+    return result;
+}
+
+void AudioEngine::forEachHostedPlugin (const std::function<void (juce::AudioPluginInstance&, bool notifyRender)>& visit) const
+{
+    for (std::size_t i = 0; i < song.channels.size(); ++i)
+        if (auto* p = dynamic_cast<PluginInstrument*> (getChannelInstrument ((int) i).get()); p != nullptr && ! p->hasCrashed())
+            visit (p->getInstance(), song.channels[i].plugin.notifyRender);
+
+    for (std::size_t t = 0; t < song.mixer.size(); ++t)
+        for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
+            if (auto* p = dynamic_cast<PluginEffect*> (getEffect ((int) t, (int) s).get()); p != nullptr && ! p->hasCrashed())
+                visit (p->getInstance(), song.mixer[t].effects[s].plugin.notifyRender);
+
+    std::function<void (patcher::Graph*)> inGraph = [&] (patcher::Graph* graph) {
+        if (graph == nullptr)
+            return;
+        for (int n = 0; n < graph->nodeCount(); ++n)
+        {
+            auto effect = graph->effectAt (n);
+            auto instrument = graph->instrumentAt (n);
+            if (auto* p = dynamic_cast<PluginEffect*> (effect.get()); p != nullptr && ! p->hasCrashed())
+                visit (p->getInstance(), true);
+            if (auto* p = dynamic_cast<PluginInstrument*> (instrument.get()); p != nullptr && ! p->hasCrashed())
+                visit (p->getInstance(), true);
+            inGraph (patcher::graphOf (effect.get()));
+            inGraph (patcher::graphOf (instrument.get()));
+        }
+    };
+    for (std::size_t i = 0; i < song.channels.size(); ++i)
+        inGraph (patcher::graphOf (getChannelInstrument ((int) i).get()));
+    for (std::size_t t = 0; t < song.mixer.size(); ++t)
+        for (std::size_t s = 0; s < song.mixer[t].effects.size(); ++s)
+            inGraph (patcher::graphOf (getEffect ((int) t, (int) s).get()));
+}
+
 ProcessTimes* AudioEngine::getProcessTimes() noexcept
 {
     return rackProcessor != nullptr ? &rackProcessor->processTimes() : nullptr;

+ 17 - 0
src/engine/AudioEngine.h

@@ -21,6 +21,7 @@
 #include "core/FlpImport.h"
 #include "core/History.h"
 #include "core/NativeEngines.h"
+#include "core/PluginWarmup.h"
 #include "core/SnapshotExchange.h"
 #include "core/Song.h"
 #include "engine/PluginHost.h"
@@ -79,6 +80,14 @@ public:
     void capturePluginStates();
     // Offline render mode for the hosted plugins (setNonRealtime), around renderOffline.
     void setPluginsRenderMode (bool offline);
+    // Every hosted plugin of the song that has not crashed (channels, inserts, inside Patchers); `notifyRender` is the
+    // plugin's "Notify about rendering mode" option. Message thread or the render thread, while nothing else edits.
+    void forEachHostedPlugin (const std::function<void (juce::AudioPluginInstance&, bool notifyRender)>& visit) const;
+    // The render's plugin warm-up (renderOffline, round 155): silent discarded blocks until the hosted plugins settle,
+    // then a new PDC plan if a latency changed and LYNX's own units reset. Returns blocks == 0 when the song has no
+    // hosted plugin. `latency` receives the delay compensation's total afterwards.
+    warmup::Result warmUpPlugins (const warmup::Settings& settings, double sampleRate, int blockSize,
+                                  const std::function<bool (double)>& progress, int& latency);
 
     void play() noexcept;
     void stop() noexcept; // also cancels a count-in or a wait for the first note
@@ -351,6 +360,12 @@ public:
         bool hqAllPlugins = true;
         // receives every rendered block after the PDC trim (left, right, frames), like `output` does
         std::function<void (const float*, const float*, int)> capture;
+        // trim the delay compensation's latency as the plugins report it after the warm-up (adds to trimSamples)
+        bool trimPdc = false;
+        // Export "Plugin warm-up" (round 155, core/PluginWarmup.h): with hosted plugins in the song, silent blocks are
+        // processed and thrown away before the render until the plugins have settled
+        bool pluginWarmUp = true;
+        warmup::Settings warmUp;
     };
 
     float renderOffline (const RenderOptions& options);
@@ -359,6 +374,8 @@ public:
     struct RenderStats
     {
         double graphMs = 0.0, writeMs = 0.0;
+        warmup::Result warmUp; // the plugin warm-up before the render (blocks == 0: none ran)
+        int trimmedSamples = 0; // the PDC trim used
     };
     RenderStats getLastRenderStats() const noexcept { return lastRenderStats; }
     float renderOffline (double seconds, double sampleRate, juce::AudioFormatWriter* output = nullptr)

+ 2 - 1
src/engine/Exporter.cpp

@@ -103,8 +103,9 @@ bool ExportJob::run (const std::function<bool (double)>& progress, juce::String&
     render.sampleRate = options.sampleRate;
     render.progress = progress;
     render.tailSeconds = tailSecondsFor (options);
-    render.trimSamples = options.trimPdc ? engine->getLatencySamples() : 0;
+    render.trimPdc = options.trimPdc; // the latency as reported after the plugins' warm-up
     render.hqAllPlugins = options.hqAllPlugins;
+    render.pluginWarmUp = options.pluginWarmUp;
 
     // streaming straight into the file when nothing needs the whole render first (the classic WAV/FLAC/OGG export)
     const auto streaming = options.format != exportopts::Format::mp3 && options.channels == Channels::stereo && ! options.normalize

+ 12 - 4
src/ui/ExportDialog.cpp

@@ -295,7 +295,7 @@ public:
         combo (ditherLabel, tr ("Dither"), ditherBox, { tr ("Off"), tr ("TPDF"), tr ("TPDF + noise shaping") },
                tr ("Hides the rounding noise of 16 and 24 bit files (noise shaping moves it where the ear is least sensitive)"));
 
-        for (auto* t : { &normalizeToggle, &masterFxToggle, &trimToggle, &hqToggle, &showToggle, &polyToggle })
+        for (auto* t : { &normalizeToggle, &masterFxToggle, &trimToggle, &hqToggle, &showToggle, &polyToggle, &warmUpToggle })
         {
             t->onClick = [this] { readControls(); };
             addAndMakeVisible (t);
@@ -309,6 +309,10 @@ public:
         hqToggle.setButtonText (tr ("HQ for all plugins"));
         showToggle.setButtonText (tr ("Show the file(s) when complete"));
         polyToggle.setButtonText (tr ("Disable maximum polyphony"));
+        warmUpToggle.setButtonText (tr ("Plugin warm-up"));
+        warmUpToggle.setTooltip (tr ("Before the export starts, third-party plugins process a moment of silence until they have "
+                                     "finished loading their settings (bridged plugins, samplers that load in the background), "
+                                     "so the file does not start with half-loaded effects"));
         polyToggle.setTooltip (tr ("The channels' Max polyphony is lifted for the export, so no note is cut by the voice limit"));
         showToggle.setTooltip (tr ("Opens the file manager on the exported file when the export is done"));
         hqToggle.setTooltip (tr ("Plugins with a separate render quality use it, and HQ switches are turned on for the export. "
@@ -329,7 +333,7 @@ public:
         cancelButton.onClick = [this] { close(); };
 
         writeControls();
-        setSize (620, 460);
+        setSize (620, 486);
     }
 
     // --snapshot: the window with this format chosen (0 WAV, 1 MP3, 2 OGG, 3 FLAC) and a few options set
@@ -358,7 +362,7 @@ public:
         warningLabel.setBounds (buttons);
         area.removeFromBottom (8);
 
-        auto mix = area.removeFromBottom (84);
+        auto mix = area.removeFromBottom (110);
         optionsTitle.setBounds (mix.removeFromTop (26));
         mix.removeFromTop (4);
         auto mixRow = mix.removeFromTop (24);
@@ -372,6 +376,8 @@ public:
             polyToggle.setBounds (row2.removeFromLeft (200));
             showToggle.setBounds (row2);
         }
+        mix.removeFromTop (2);
+        warmUpToggle.setBounds (mix.removeFromTop (24).removeFromLeft (200));
         area.removeFromBottom (6);
 
         auto left = area.removeFromLeft ((area.getWidth() - 24) / 2);
@@ -478,6 +484,7 @@ private:
         masterFxToggle.setToggleState (options.masterEffects, n);
         trimToggle.setToggleState (options.trimPdc, n);
         hqToggle.setToggleState (options.hqAllPlugins, n);
+        warmUpToggle.setToggleState (options.pluginWarmUp, n);
         showToggle.setToggleState (options.showWhenDone, n);
         polyToggle.setToggleState (options.disableMaxPolyphony, n);
         for (int i = 0; i < 4; ++i)
@@ -515,6 +522,7 @@ private:
         options.masterEffects = masterFxToggle.getToggleState();
         options.trimPdc = trimToggle.getToggleState();
         options.hqAllPlugins = hqToggle.getToggleState();
+        options.pluginWarmUp = warmUpToggle.getToggleState();
         options.showWhenDone = showToggle.getToggleState();
         options.disableMaxPolyphony = polyToggle.getToggleState();
         options.moreFormats = 0;
@@ -635,7 +643,7 @@ private:
     Segmented formatButtons { { "WAV", "MP3", "OGG", "FLAC" } };
     juce::Label depthLabel, bitrateLabel, compressionLabel, rateLabel, channelsLabel, ditherLabel;
     juce::ComboBox depthBox, mp3Box, oggBox, flacLevelBox, rateBox, channelsBox, ditherBox;
-    juce::ToggleButton normalizeToggle, masterFxToggle, trimToggle, hqToggle, showToggle, polyToggle;
+    juce::ToggleButton normalizeToggle, masterFxToggle, trimToggle, hqToggle, showToggle, polyToggle, warmUpToggle;
     juce::Label alsoLabel;
     std::array<juce::ToggleButton, 4> alsoToggles;
     juce::Label infoLabel, warningLabel;

+ 211 - 0
tests/Render155Tests.inc

@@ -0,0 +1,211 @@
+// Round 155: the export's plugin warm-up (core/PluginWarmup.h, AudioEngine::renderOffline). A fresh plugin instance
+// whose restored state lands late (bridged over yabridge, background loading) must not be heard half-loaded at the
+// start of the exported file (docs/analise/REA_rodada155.md).
+
+#include "core/PluginWarmup.h"
+
+namespace render155
+{
+// A source that is always on (a hosted instrument holding a drone): 0.25 on both sides whatever the notes.
+struct Drone final : lynx::Instrument
+{
+    void prepare (double) noexcept override {}
+    void noteOn (int, float) noexcept override {}
+    void noteOff (int) noexcept override {}
+    void allNotesOff() noexcept override {}
+    void render (float* l, float* r, int n, float gl, float gr) noexcept override
+    {
+        for (int i = 0; i < n; ++i)
+        {
+            l[i] += 0.25f * gl;
+            r[i] += 0.25f * gr;
+        }
+    }
+};
+
+// An effect whose saved state (output gain 0.5) only takes effect after `blocks` processed blocks, or once a clock
+// reaches `atTime` — as a bridged plugin applies a state forwarded over IPC a few blocks / milliseconds later. Before
+// that it runs with its default gain (1.0): the "half-loaded effect".
+struct LateState final : lynx::Effect
+{
+    int blocks = 0;
+    double atTime = -1.0;
+    const double* clock = nullptr;
+    int processed = 0;
+    float gain = 1.0f; // what the plugin reports (its parameter)
+
+    void prepare (double) noexcept override {}
+    void reset() noexcept override {}
+    void process (float* l, float* r, int n, const lynx::EffectParams&, double) noexcept override
+    {
+        ++processed;
+        const auto landed = (blocks > 0 && processed > blocks) || (atTime >= 0.0 && clock != nullptr && *clock >= atTime) || (blocks == 0 && atTime < 0.0);
+        if (landed)
+            gain = 0.5f;
+        for (int i = 0; i < n; ++i)
+        {
+            l[i] *= gain;
+            r[i] *= gain;
+        }
+    }
+};
+
+lynx::Song droneSong()
+{
+    lynx::Song s;
+    s.mixer = lynx::Song::defaultMixer (1);
+    lynx::ChannelDef c;
+    c.instrument = lynx::InstrumentKind::plugin;
+    c.plugin.id = "drone";
+    c.mixerTrack = 1;
+    s.channels.push_back (c);
+    s.patterns.emplace_back();
+    lynx::EffectSlot fx;
+    fx.kind = lynx::EffectKind::plugin;
+    fx.plugin.id = "late-state";
+    s.mixer[1].effects.push_back (fx);
+    return s;
+}
+
+struct Rig
+{
+    std::shared_ptr<LateState> effect = std::make_shared<LateState>();
+    std::unique_ptr<const lynx::RackState> state;
+    lynx::RackRenderer renderer;
+    static constexpr int block = 512;
+    std::vector<float> l = std::vector<float> (block), r = std::vector<float> (block);
+
+    Rig()
+    {
+        lynx::RackState::Factories f;
+        f.pluginInstruments = [] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Instrument> { return std::make_shared<Drone>(); };
+        auto fx = effect;
+        f.pluginEffects = [fx] (const lynx::PluginRef&, double) -> std::shared_ptr<lynx::Effect> { return fx; };
+        state = lynx::RackState::build (droneSong(), nullptr, 48000.0, f);
+        renderer.prepare (48000.0, block);
+    }
+
+    // what the engine's warm-up does: stopped at the start, silent output thrown away
+    int discard()
+    {
+        renderer.process (state.get(), false, 0.0, block, l.data(), r.data());
+        return block;
+    }
+
+    // the render's first block (playing from the start)
+    float firstSample()
+    {
+        renderer.process (state.get(), true, 0.0, block, l.data(), r.data());
+        return l[0];
+    }
+};
+} // namespace render155
+
+TEST (render155_warm_up_waits_for_a_state_applied_after_n_blocks)
+{
+    using namespace render155;
+    // the reference: a plugin whose state is in place from the start
+    Rig ready;
+    ready.effect->blocks = 0;
+    const auto expected = ready.firstSample();
+    CHECK (expected > 0.01f);
+
+    // without the warm-up the file starts with the half-loaded effect (twice as loud here)
+    Rig cold;
+    cold.effect->blocks = 40;
+    const auto coldFirst = cold.firstSample();
+    CHECK (std::abs (coldFirst - 2.0f * expected) < 1.0e-4f);
+
+    // with it: the state has landed before the first rendered sample
+    Rig warm;
+    warm.effect->blocks = 40; // ~0.43 s at 48 kHz / 512
+    double clock = 0.0;
+    lynx::warmup::Settings settings;
+    const auto result = lynx::warmup::run (
+        settings, 48000.0, [&] { clock += 0.0005; return warm.discard(); }, [&] { lynx::warmup::Hash h; h.addValue (warm.effect->gain); return h.value; },
+        [&] { return clock; }, [&] (double s) { clock += s; });
+    CHECK (! result.timedOut && ! result.cancelled);
+    CHECK (result.blocks > 40);
+    CHECK (result.audioSeconds >= settings.minAudioSeconds);
+    CHECK (result.signatureChanges == 1);
+    warm.renderer.prepare (48000.0, Rig::block); // as the engine does: LYNX's own units start clean
+    const auto warmFirst = warm.firstSample();
+    CHECK (std::abs (warmFirst - expected) < 1.0e-6f);
+    // and every sample of the first block
+    for (int i = 0; i < Rig::block; ++i)
+        CHECK (std::abs (warm.l[(std::size_t) i] - expected) < 1.0e-6f);
+}
+
+TEST (render155_warm_up_waits_for_a_state_applied_late_in_real_time)
+{
+    using namespace render155;
+    // a bridged plugin: the state lands 1.2 s (wall time) after creation, whatever the number of blocks
+    Rig warm;
+    double clock = 0.0;
+    warm.effect->atTime = 1.2;
+    warm.effect->clock = &clock;
+    lynx::warmup::Settings settings;
+    const auto result = lynx::warmup::run (
+        settings, 48000.0, [&] { clock += 0.001; return warm.discard(); }, [&] { lynx::warmup::Hash h; h.addValue (warm.effect->gain); return h.value; },
+        [&] { return clock; }, [&] (double s) { clock += s; });
+    CHECK (! result.timedOut);
+    CHECK (result.wallSeconds >= 1.2 + settings.stableWallSeconds - 0.02);
+    // paced: the discarded audio does not run far ahead of real time once the minimum is processed
+    CHECK (result.audioSeconds <= result.wallSeconds + 0.05);
+    Rig ready;
+    const auto expected = ready.firstSample();
+    warm.renderer.prepare (48000.0, Rig::block);
+    CHECK (std::abs (warm.firstSample() - expected) < 1.0e-6f);
+}
+
+TEST (render155_warm_up_minimums_timeout_and_cancel)
+{
+    // nothing changes: it stops after the minimums (audio and real time)
+    {
+        double clock = 0.0;
+        int blocks = 0;
+        lynx::warmup::Settings s;
+        const auto r = lynx::warmup::run (
+            s, 48000.0, [&] { ++blocks; clock += 0.0001; return 512; }, [] { return std::uint64_t { 7 }; }, [&] { return clock; },
+            [&] (double d) { clock += d; });
+        CHECK (! r.timedOut && r.signatureChanges == 0);
+        CHECK (r.audioSeconds >= s.minAudioSeconds && r.wallSeconds >= s.minWallSeconds && r.wallSeconds < s.minWallSeconds + 0.1);
+        CHECK (r.blocks == blocks);
+    }
+    // a plugin that never stops changing (a meter exposed as a parameter): the timeout ends it
+    {
+        double clock = 0.0;
+        std::uint64_t n = 0;
+        lynx::warmup::Settings s;
+        s.maxWallSeconds = 2.0;
+        const auto r = lynx::warmup::run (
+            s, 48000.0, [&] { clock += 0.001; return 512; }, [&] { return ++n; }, [&] { return clock; }, [&] (double d) { clock += d; });
+        CHECK (r.timedOut && r.wallSeconds >= 2.0 && r.wallSeconds < 2.1);
+    }
+    // cancelled from the progress window
+    {
+        double clock = 0.0;
+        int blocks = 0;
+        const auto r = lynx::warmup::run (
+            lynx::warmup::Settings {}, 48000.0, [&] { clock += 0.001; return ++blocks > 5 ? -1 : 512; }, [] { return std::uint64_t { 1 }; },
+            [&] { return clock; }, [&] (double d) { clock += d; });
+        CHECK (r.cancelled && r.blocks == 5);
+    }
+    // quantised: float noise in a cached parameter value is not a change
+    lynx::warmup::Hash a, b, c;
+    a.addValue (0.5f);
+    b.addValue (0.5f + 1.0e-7f);
+    c.addValue (0.51f);
+    CHECK (a.value == b.value && a.value != c.value);
+}
+
+TEST (render155_export_option_plugin_warm_up)
+{
+    lynx::exportopts::Options o;
+    CHECK (o.pluginWarmUp); // on by default
+    CHECK (lynx::exportopts::fromText ("").pluginWarmUp);
+    o.pluginWarmUp = false;
+    CHECK (! lynx::exportopts::fromText (lynx::exportopts::toText (o)).pluginWarmUp);
+    o.pluginWarmUp = true;
+    CHECK (lynx::exportopts::fromText (lynx::exportopts::toText (o)).pluginWarmUp);
+}

+ 1 - 0
tests/tests.cpp

@@ -15821,3 +15821,4 @@ TEST (plugin_layout_options_match_the_engine_values)
 #include "Vox148Tests.inc"
 #include "Natives142Tests.inc"
 #include "Rea153Tests.inc"
+#include "Render155Tests.inc"