Procházet zdrojové kódy

Engine: Patcher racks and LYNX's own effects sleep while stopped and silent (round 190ts, 0.1.33 block E)

The 0.1.32 release notes' known issue "the stopped CPU of projects whose Patcher racks never sleep" (Patience 29-32 %,
Exoplanet 12-14 %). A Patcher graph ran every node at every block while stopped, and a generator Patcher holding an
effect never reported idle, so its channel, its insert and the insert's effects never stopped either.

- patcher::Graph::setStoppedSleep: only the live engine's renderers allow it (RackRenderer::setStoppedSleep, set in
  AudioEngine's device setup; LYNX_STOPPED_SLEEP=0 switches it off), and only while the transport is stopped. A node of
  LYNX's own devices whose input and output stayed below -96 dBFS past its tail (its declared Effect::tailSamples, else
  4 s) passes its input through without being called; an idle built-in instrument node is not rendered; once every node
  sleeps, nothing comes in (notes, VFX voices, audio) and the graph's delays have emptied, the whole graph is skipped and
  a generator Patcher reports idle (the rack skips its channel). A note, a MIDI message or audio wakes it in that block.
- The mixer: while stopped, LYNX's own effects on an insert sleep by the same rule whatever the slot's "Smart disable"
  (the sound is the same: their silence is known); FL's smart disable keeps its own rules.
- Never asleep: hosted plugins (an LFO, a host sync, an analyser may need their calls), what smart disable leaves out
  (Gross Beat, Edison, Newtone / Newtime, the Scratcher, hardware inserts, controllers, Wave Candy, the visualizer, the
  tuner, Facet EQ's target), side-chained nodes, sources of control cables, a slot with an editor open
  (ProcessTimes::editorsOpen), a Patcher an editor watches. Playing, exports and every offline render never sleep.
- Tests sleep190ts_* (4), the app check --round190tstest / --selftest "round190ts": playing renders the very samples of
  an engine that never sleeps, the tails ring on after the stop, the units sleep, Wave Candy keeps running, an editor
  keeps its slot awake, a live note while asleep plays at once, playing again runs everything.
- Bench tools: --hostmem190ts (N instances of one plugin through LYNX's wrapper or JUCE alone, in process or in plugin
  processes, the memory after each count); --stoppedbench190sp opens Live sets, reports the memory and the heaviest units,
  and plays the song with LYNX_BENCH_PLAY=1.

Measured (Linux, the stopped device callback, callgrind, 300 blocks after 8 s stopped, no workers; sleep off -> on):
Patience 12.05 M -> 5.33 M instructions a block (-56 %), Exoplanet 4.30 M -> 1.24 M (-71 %), Thief 355 k -> 274 k (-23 %).

(cherry picked from commit 0bdc62d435d4ff7aeca813f21de6fa94455e1258)
Ka1-S před 4 dny
rodič
revize
722af2b04d

+ 170 - 0
src/HostMem190ts.inc

@@ -0,0 +1,170 @@
+    // Round 190ts (0.1.33 block E, "hosted plugin memory [32]"): the memory N instances of one hosted plugin take, through
+    // LYNX's wrapper or through JUCE alone (the plugin's own memory: what any JUCE host pays), so LYNX's own share per
+    // instance can be told apart. Included in the app class of Main.cpp.
+    //   LYNX --hostmem190ts <plugin file> <report.txt> [--counts 1,8,16,32] [--how lynx|raw] [--blocks B] [--buffer N]
+    // For each count the instances are made (the first type of the file; an instrument gets a chord held), prepared at
+    // 44.1 kHz with the buffer, B blocks played through each, then the process's memory is read (Linux: smaps_rollup's
+    // Rss / private / anonymous; Windows: private bytes and the working set) and all are destroyed before the next count.
+    // "lynx" makes them as a project's plugin channel does (PluginHost::createInstrument: LYNX's PluginInstrument with its
+    // queues and buffers, the same block size LYNX prepares); "raw" with juce::AudioPluginFormatManager at the device's block.
+    static juce::String processMemory190ts()
+    {
+       #if JUCE_WINDOWS
+        PROCESS_MEMORY_COUNTERS_EX counters {};
+        if (GetProcessMemoryInfo (GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*) &counters, sizeof (counters)))
+            return "private_mb=" + juce::String ((double) counters.PrivateUsage / 1048576.0, 1) + " ws_mb="
+                   + juce::String ((double) counters.WorkingSetSize / 1048576.0, 1);
+        return "private_mb=? ws_mb=?";
+       #elif JUCE_LINUX
+        juce::StringArray lines;
+        lines.addLines (juce::File ("/proc/self/smaps_rollup").loadFileAsString());
+        auto kb = [&lines] (const char* key) {
+            for (const auto& l : lines)
+                if (l.startsWith (key))
+                    return l.fromFirstOccurrenceOf (":", false, false).trim().getLargeIntValue();
+            return (juce::int64) 0;
+        };
+        const auto mb = [] (juce::int64 k) { return juce::String ((double) k / 1024.0, 1); };
+        // the plugin processes (separate-process modes): their private memory, summed
+        juce::int64 kids = 0, kidCount = 0;
+        for (const auto& task : juce::File ("/proc/self/task").findChildFiles (juce::File::findDirectories, false))
+            for (const auto& pid : juce::StringArray::fromTokens (task.getChildFile ("children").loadFileAsString(), " \n", ""))
+                if (pid.getIntValue() > 0)
+                {
+                    juce::StringArray k;
+                    k.addLines (juce::File ("/proc/" + pid + "/smaps_rollup").loadFileAsString());
+                    for (const auto& l : k)
+                        if (l.startsWith ("Private_Clean:") || l.startsWith ("Private_Dirty:"))
+                            kids += l.fromFirstOccurrenceOf (":", false, false).trim().getLargeIntValue();
+                    ++kidCount;
+                }
+        return "rss_mb=" + mb (kb ("Rss:")) + " private_mb=" + mb (kb ("Private_Clean:") + kb ("Private_Dirty:")) + " anon_mb="
+               + mb (kb ("Anonymous:")) + " children=" + juce::String (kidCount) + " children_private_mb=" + mb (kids);
+       #else
+        return "memory=?";
+       #endif
+    }
+
+    void runHostMem190ts (const juce::File& pluginFile, const juce::File& report, const juce::String& countList, const juce::String& how,
+                          int blocks, int block)
+    {
+        auto text = std::make_shared<juce::String>();
+        auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
+        const auto rate = 44100.0;
+        step ("hostmem (round 190ts): " + pluginFile.getFullPathName() + ", how=" + how + ", buffer " + juce::String (block) + ", "
+              + juce::String (blocks) + " blocks each");
+        lynx::setPluginSandboxAlerts (false);
+        // "sandbox": as "lynx", each instance in a process of its own (Options › "Run plugins in a separate process")
+        lynx::setPluginSandboxMode (how == "sandbox" ? lynx::SandboxMode::perPlugin : lynx::SandboxMode::inProcess);
+        lynx::PluginHost host (false);
+        host.addPluginFile (pluginFile);
+        std::optional<juce::PluginDescription> type; // (a copy: getTypes() hands out a temporary list)
+        for (const auto& t : host.getKnownPlugins().getTypes())
+            if (juce::File (t.fileOrIdentifier) == pluginFile || t.fileOrIdentifier == pluginFile.getFullPathName())
+            {
+                type = t;
+                break;
+            }
+        if (! type)
+        {
+            step ("FAIL: no plugin type in the file");
+            setApplicationReturnValue (1);
+            quit();
+            return;
+        }
+        const auto description = *type;
+        step ("plugin " + description.name + " (" + description.pluginFormatName + ", " + (description.isInstrument ? "instrument" : "effect") + ")");
+        step ("before: " + processMemory190ts());
+        juce::AudioPluginFormatManager formats;
+        lynx::addPluginFormats (formats);
+        for (const auto& countText : juce::StringArray::fromTokens (countList, ",", ""))
+        {
+            const auto count = juce::jlimit (1, 256, countText.getIntValue());
+            std::vector<std::unique_ptr<juce::AudioPluginInstance>> raw;
+            std::vector<std::shared_ptr<lynx::Instrument>> wrapped;
+            std::vector<std::shared_ptr<lynx::Effect>> wrappedFx;
+            const auto t0 = juce::Time::getMillisecondCounterHiRes();
+            for (int k = 0; k < count; ++k)
+            {
+                if (how == "raw")
+                {
+                    juce::String error;
+                    auto instance = formats.createPluginInstance (description, rate, block, error);
+                    if (instance == nullptr)
+                    {
+                        step ("FAIL create " + juce::String (k) + ": " + error);
+                        break;
+                    }
+                    instance->enableAllBuses();
+                    instance->setRateAndBufferSizeDetails (rate, block);
+                    instance->prepareToPlay (rate, block);
+                    raw.push_back (std::move (instance));
+                }
+                else
+                {
+                    lynx::PluginRef ref;
+                    ref.id = description.createIdentifierString().toStdString();
+                    ref.name = description.name.toStdString();
+                    juce::String error;
+                    if (description.isInstrument)
+                    {
+                        if (auto i = host.makeInstrument (ref, rate, &error))
+                            wrapped.push_back (std::move (i));
+                        else
+                            step ("FAIL create " + juce::String (k) + ": " + error);
+                    }
+                    else if (auto e = host.makeEffect (ref, rate, &error))
+                        wrappedFx.push_back (std::move (e));
+                    else
+                        step ("FAIL create " + juce::String (k) + ": " + error);
+                }
+            }
+            const auto made = juce::Time::getMillisecondCounterHiRes();
+            // play: a chord held through the blocks (an instrument), a sine through an effect
+            juce::AudioBuffer<float> buffer (64, block);
+            std::vector<float> l ((std::size_t) block), r ((std::size_t) block);
+            for (auto& i : wrapped)
+                for (const int key : { 48, 55, 60, 64, 67 })
+                    i->noteOn (key, 0.8f);
+            juce::MidiBuffer midi;
+            for (int b = 0; b < blocks; ++b)
+            {
+                for (auto& p : raw)
+                {
+                    buffer.setSize (juce::jmax (2, juce::jmax (p->getTotalNumInputChannels(), p->getTotalNumOutputChannels())), block, false, false, true);
+                    buffer.clear();
+                    midi.clear();
+                    if (b == 0 && p->acceptsMidi())
+                        for (const int key : { 48, 55, 60, 64, 67 })
+                            midi.addEvent (juce::MidiMessage::noteOn (1, key, (juce::uint8) 100), 0);
+                    if (! p->acceptsMidi())
+                        for (int s = 0; s < block; ++s)
+                            buffer.setSample (0, s, 0.25f * std::sin ((float) (b * block + s) * 0.05f));
+                    p->processBlock (buffer, midi);
+                }
+                for (auto& i : wrapped)
+                {
+                    std::fill (l.begin(), l.end(), 0.0f);
+                    std::fill (r.begin(), r.end(), 0.0f);
+                    i->beginChunk (block);
+                    i->render (l.data(), r.data(), block, 1.0f, 1.0f);
+                }
+                for (auto& e : wrappedFx)
+                {
+                    for (int s = 0; s < block; ++s)
+                        l[(std::size_t) s] = r[(std::size_t) s] = 0.25f * std::sin ((float) (b * block + s) * 0.05f);
+                    lynx::EffectParams params {};
+                    e->process (l.data(), r.data(), block, params, 120.0);
+                }
+            }
+            step ("count " + juce::String (count) + ": made " + juce::String ((int) (raw.size() + wrapped.size() + wrappedFx.size())) + " in "
+                  + juce::String (made - t0, 0) + " ms; " + processMemory190ts());
+            raw.clear();
+            wrapped.clear();
+            wrappedFx.clear();
+            step ("  after release: " + processMemory190ts());
+        }
+        step ("result=OK");
+        setApplicationReturnValue (0);
+        quit();
+    }

+ 31 - 1
src/Main.cpp

@@ -1288,6 +1288,20 @@ public:
             return;
         }
 
+        if (args.contains ("--hostmem190ts"))
+        {
+            // LYNX --hostmem190ts plugin report [--counts 1,8,16,32] [--how lynx|raw] [--blocks B] [--buffer N] (round 190ts,
+            // src/HostMem190ts.inc): the memory of N instances of one hosted plugin
+            const auto i = args.indexOf ("--hostmem190ts");
+            const auto option = [&args] (const char* name, const char* fallback) {
+                return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String (fallback);
+            };
+            runHostMem190ts (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), option ("--counts", "1,8,16,32"),
+                             option ("--how", "lynx"), juce::jlimit (1, 100000, option ("--blocks", "400").getIntValue()),
+                             juce::jlimit (16, 4096, option ("--buffer", "256").getIntValue()));
+            return;
+        }
+
         if (args.contains ("--renderaheadtest"))
         {
             // LYNX --renderaheadtest report.txt [project.flp|.lynx ...] [--buffer N] [--seconds S] (round 190gq): the engine's
@@ -2621,6 +2635,16 @@ public:
             quit();
             return;
         }
+        if (args.contains ("--round190tstest"))
+        {
+            // LYNX --round190tstest report.txt (round 190ts: sleep while stopped; also in --selftest): src/Round190tsCheck.inc
+            juce::String log;
+            const auto result = round190tsCheck (log);
+            juce::File (args[args.indexOf ("--round190tstest") + 1].unquoted()).replaceWithText (log + "round190ts=" + result + "\n");
+            setApplicationReturnValue (result == "OK" ? 0 : 1);
+            quit();
+            return;
+        }
         if (args.contains ("--round190tetest"))
         {
             // LYNX --round190tetest report.txt (round 190te: #356 effects told their own audio's position, item 58 XDND drops
@@ -11283,6 +11307,9 @@ private:
         // the Playlist's Time markers › Delete (src/Round190teCheck.inc)
         juce::String round190teLog;
         const auto round190teResult = round190teCheck (round190teLog);
+        // round 190ts: sleep while stopped (Patcher graphs and built-in effects; src/Round190tsCheck.inc)
+        juce::String round190tsLog;
+        const auto round190tsResult = round190tsCheck (round190tsLog);
 
         // round 190rb (0.1.32 quality release): the crash / memory fixes of the crash reports, the sanitizer build and the
         // UI monkey test (src/Qa190rbCheck.inc)
@@ -12733,7 +12760,7 @@ private:
                         && sidechainResult == "OK" && lanesResult == "OK" && arrange190cgResult == "OK" && livescr190drResult == "OK" && livewf190efResult == "OK" && livewf190emResult == "OK" && trackclips190neResult == "OK" && tracker190nwResult == "OK" && tracker190obResult == "OK" && rackauto190ooResult == "OK" && tracker190omResult == "OK" && rackauto190owResult == "OK" && versionsResult == "OK" && pluginsOffResult == "OK" && missingFilesResult == "OK"
                         && midigen190fmResult == "OK" && clipenv190giResult == "OK" && beatslaw190gxResult == "OK" && warplaw190ikResult == "OK" && editorScale190heResult == "OK" && sfModBase190heResult == "OK" && trackauto190gzResult == "OK" && community190hqResult == "OK" && rollup030Result == "OK" && rollup031Result == "OK" && rollup031s2Result == "OK"
                         && keys190nuResult == "OK" && rollup031s3Result == "OK"
-                        && helix4khs190ocResult == "OK" && rollup031s4Result == "OK" && sections190olResult == "OK" && rollup031s5Result == "OK" && simpleDuck190otResult == "OK" && tracks190peResult == "OK" && issue258Result == "OK" && issues190qrResult == "OK" && backlog190rcResult == "OK" && community190riResult == "OK" && flParity190tcResult == "OK" && q1a190rwResult == "OK" && iox190rmResult == "OK" && issues190rtResult == "OK" && perf190rnResult == "OK" && perf190sbResult == "OK" && cachecheck190tgResult == "OK" && undo190spResult == "OK" && menuwindows190skResult == "OK" && issues330skResult == "OK" && audioedit190stResult == "OK" && drumsynth190syResult == "OK" && smallbugs190srResult == "OK" && quickwins190srResult == "OK" && batch292_190swResult == "OK" && round190teResult == "OK" && yannik190sqResult == "OK" && rea190taResult == "OK" && round190tiResult == "OK" && round190tnResult == "OK" && round190trResult == "OK" && round190tpResult == "OK" && round190tkResult == "OK" && round190tmResult == "OK" && round190toResult == "OK" && batch334svResult == "OK" && details190tdResult == "OK" && qa190rbResult == "OK" && bugs190rvResult == "OK" && q6190saResult == "OK" && issue325Result == "OK" && keysheet190sjResult == "OK" && details190tbResult == "OK" && notes190tjResult == "OK" && children190thResult == "OK" && stab190rpResult == "OK" && repeats190pmResult == "OK" && mixerqol190qhResult == "OK" && autolive190qpResult == "OK" && issue282Result == "OK" && feel190qeResult == "OK" && toolbar190qgResult == "OK" && extras190qkResult == "OK" && extras190roResult == "OK" && playlistview190soResult == "OK" && custom190ssResult == "OK" && discord190quResult == "OK" && trialmark190qtResult == "OK" && optionsux190qxResult == "OK" && chordlane190pfResult == "OK" && nofl190rhResult == "OK" && downgrade0132Result == "OK" && autolinks190ovResult == "OK"
+                        && helix4khs190ocResult == "OK" && rollup031s4Result == "OK" && sections190olResult == "OK" && rollup031s5Result == "OK" && simpleDuck190otResult == "OK" && tracks190peResult == "OK" && issue258Result == "OK" && issues190qrResult == "OK" && backlog190rcResult == "OK" && community190riResult == "OK" && flParity190tcResult == "OK" && q1a190rwResult == "OK" && iox190rmResult == "OK" && issues190rtResult == "OK" && perf190rnResult == "OK" && perf190sbResult == "OK" && cachecheck190tgResult == "OK" && undo190spResult == "OK" && menuwindows190skResult == "OK" && issues330skResult == "OK" && audioedit190stResult == "OK" && drumsynth190syResult == "OK" && smallbugs190srResult == "OK" && quickwins190srResult == "OK" && batch292_190swResult == "OK" && round190teResult == "OK" && round190tsResult == "OK" && yannik190sqResult == "OK" && rea190taResult == "OK" && round190tiResult == "OK" && round190tnResult == "OK" && round190trResult == "OK" && round190tpResult == "OK" && round190tkResult == "OK" && round190tmResult == "OK" && round190toResult == "OK" && batch334svResult == "OK" && details190tdResult == "OK" && qa190rbResult == "OK" && bugs190rvResult == "OK" && q6190saResult == "OK" && issue325Result == "OK" && keysheet190sjResult == "OK" && details190tbResult == "OK" && notes190tjResult == "OK" && children190thResult == "OK" && stab190rpResult == "OK" && repeats190pmResult == "OK" && mixerqol190qhResult == "OK" && autolive190qpResult == "OK" && issue282Result == "OK" && feel190qeResult == "OK" && toolbar190qgResult == "OK" && extras190qkResult == "OK" && extras190roResult == "OK" && playlistview190soResult == "OK" && custom190ssResult == "OK" && discord190quResult == "OK" && trialmark190qtResult == "OK" && optionsux190qxResult == "OK" && chordlane190pfResult == "OK" && nofl190rhResult == "OK" && downgrade0132Result == "OK" && autolinks190ovResult == "OK"
                         && trackstates190opResult == "OK" && rollup031s6Result == "OK" // (round 190op's item, reported but not counted in its branch: rollup 0.1.31 step 6)
                         && rollup031s7Result == "OK" && rollup031s8Result == "OK" && rollup032Result == "OK" && headerGearResult == "OK" && perTab259Result == "OK" && slots260Result == "OK" && hotfixPlacesResult == "OK" && startPageScrollResult.startsWith ("OK") // (round 190qf: slots260) (rollup 0.1.31 step 7, round 190pw; and the three rounds' items its branches reported but did not count:)
                         && slides190piResult == "OK" && automodes190paResult == "OK" && heldSteps190ozResult == "OK"
@@ -12887,6 +12914,7 @@ private:
                << "drumsynth190sy=" << drumsynth190syResult << (drumsynth190syResult == "OK" ? juce::String() : " | " + drumsynth190syLog.replace ("\n", "; ")) << "\n"
                << "batch292_190sw=" << batch292_190swResult << (batch292_190swResult == "OK" ? juce::String() : " | " + batch292_190swLog.replace ("\n", "; ")) << "\n"
                << "round190te=" << round190teResult << (round190teResult == "OK" ? juce::String() : " | " + round190teLog.replace ("\n", "; ")) << "\n"
+               << "round190ts=" << round190tsResult << (round190tsResult == "OK" ? juce::String() : " | " + round190tsLog.replace ("\n", "; ")) << "\n"
                << "qa190rb=" << qa190rbResult << "\n"
                << "bugs190rv=" << bugs190rvResult << (bugs190rvResult == "OK" ? juce::String() : " | " + bugs190rvLog.replace ("\n", "; ")) << "\n"
                << "q6190sa=" << q6190saResult << (q6190saResult == "OK" ? juce::String() : " | " + q6190saLog.replace ("\n", "; ")) << "\n"
@@ -23337,6 +23365,7 @@ private:
 #include "Perf190sbCheck.inc" // round 190sb: FL's plugin database kept between starts
 #include "CacheCheck190tgCheck.inc" // round 190tg: the disk caches' integrity check
 #include "StoppedBench190sp.inc" // round 190sp: the device callback while stopped, for instruction-count compares
+#include "HostMem190ts.inc" // round 190ts: the memory of N instances of one hosted plugin (LYNX's wrapper vs JUCE alone)
 #include "Undo190spCheck.inc" // round 190sp: the undo history shares the song's big containers (core/CowVector.h)
 #include "MenuWindows190skCheck.inc" // round 190sk: the File menu's "..." items open their windows (DAWproject export did nothing)
 #include "Issues330skCheck.inc" // round 190sk: audio2000's Linux issues #330-#342
@@ -23354,6 +23383,7 @@ private:
 #include "SmallBugs190srCheck.inc" // round 190sr: #350, #349, QUEUE 0.1.33 items 42 / 43
 #include "QuickWins190srCheck.inc" // round 190sr: the quick wins (#318 ...)
 #include "Batch292Check190sw.inc" // round 190sw: #292 routing cables, #322 macOS's menu bar, #289 the hardware outputs export
+#include "Round190tsCheck.inc" // round 190ts: sleep while stopped (Patcher graphs, built-in effects)
 #include "Round190teCheck.inc" // round 190te: #356 latency-compensated transport (LYNX extra), item 58 XDND finished accepted, item 82 Time markers Delete
 #include "Backlog190rcCheck.inc" // round 190rc: #288 native presets, #287 MIDI drop, #283 #285 #286, PR #284, Discord 11-24
 #include "Bugs190rvCheck.inc" // round 190rv: 0.1.32 open bug issues (#317 header LED, #319 pin)

+ 247 - 0
src/Round190tsCheck.inc

@@ -0,0 +1,247 @@
+    // Round 190ts (0.1.33 block E): sleep while stopped (core/Patcher.h Graph::setStoppedSleep, RackRenderer::setStoppedSleep).
+    // Two engines play the same song through a stand-in device driven block by block: A sleeps while stopped (as the app),
+    // B never (LYNX_STOPPED_SLEEP=0's way). The song: a generator Patcher (LYNX's synth -> a Reeverb 2 node) on insert 1,
+    // which holds a Reeverb 2, a Patcher effect (a Fruity Delay 3 node) and Wave Candy. Checked: playing, A renders the
+    // very samples of B; after the stop the tails ring on in A exactly as in B; then A's reverb and Patchers sleep (their
+    // units stop being run) while Wave Candy keeps running; an editor open on the reverb keeps it awake; a live note while
+    // stopped and asleep sounds at once (as loud as in B); playing again renders as B. Included in the app class of Main.cpp;
+    // --round190tstest <report> and --selftest "round190ts".
+    juce::String round190tsCheck (juce::String& log)
+    {
+        using namespace lynx;
+        juce::String result = "OK";
+        const auto check = [&] (const juce::String& what, bool ok, const juce::String& detail = {}) {
+            log << (ok ? "ok   " : "FAIL ") << what << (detail.isNotEmpty() ? " (" + detail + ")" : juce::String()) << "\n";
+            if (! ok && result == "OK")
+                result = "ERROR " + what;
+        };
+        struct StandIn final : juce::AudioIODevice
+        {
+            StandIn() : juce::AudioIODevice ("round190ts", "test") {}
+            juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
+            juce::StringArray getInputChannelNames() override { return {}; }
+            juce::Array<double> getAvailableSampleRates() override { return { 44100.0 }; }
+            juce::Array<int> getAvailableBufferSizes() override { return { 256 }; }
+            int getDefaultBufferSize() override { return 256; }
+            juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
+            void close() override {}
+            bool isOpen() override { return true; }
+            void start (juce::AudioIODeviceCallback*) override {}
+            void stop() override {}
+            bool isPlaying() override { return true; }
+            juce::String getLastError() override { return {}; }
+            int getCurrentBufferSizeSamples() override { return 256; }
+            double getCurrentSampleRate() override { return 44100.0; }
+            int getCurrentBitDepth() override { return 32; }
+            juce::BigInteger getActiveOutputChannels() const override
+            {
+                juce::BigInteger b;
+                b.setRange (0, 2, true);
+                return b;
+            }
+            juce::BigInteger getActiveInputChannels() const override { return {}; }
+            int getOutputLatencyInSamples() override { return 0; }
+            int getInputLatencyInSamples() override { return 0; }
+        };
+
+        // the song
+        Song song = Song::makeDefault();
+        song.channels.resize (1);
+        auto& ch = song.channels[0];
+        ch = ChannelDef {};
+        ch.name = "Rack";
+        ch.instrument = InstrumentKind::patcher;
+        ch.mixerTrack = 1;
+        {
+            PatchNode gen;
+            gen.generator = true;
+            gen.channel.instrument = InstrumentKind::synth;
+            const auto g = patcher::addNode (ch.patcher, gen);
+            PatchNode fx;
+            fx.effect = makeEffectSlot (EffectKind::reeverb2);
+            const auto f = patcher::addNode (ch.patcher, fx);
+            PatchWire notes;
+            notes.kind = PatchWire::Kind::midi;
+            notes.from = patchFromHost;
+            notes.to = g;
+            ch.patcher.wires.push_back (notes);
+            PatchWire a;
+            a.from = g;
+            a.to = f;
+            ch.patcher.wires.push_back (a);
+            PatchWire o;
+            o.from = f;
+            o.to = patchToHost;
+            ch.patcher.wires.push_back (o);
+        }
+        song.mixer = Song::defaultMixer (2);
+        auto delayRack = makeEffectSlot (EffectKind::patcher);
+        {
+            PatchNode d;
+            d.effect = makeEffectSlot (EffectKind::fruityDelay3);
+            const auto n = patcher::addNode (delayRack.patcher, d);
+            PatchWire in;
+            in.from = patchFromHost;
+            in.to = n;
+            delayRack.patcher.wires.push_back (in);
+            PatchWire out;
+            out.from = n;
+            out.to = patchToHost;
+            delayRack.patcher.wires.push_back (out);
+        }
+        song.mixer[1].effects = { makeEffectSlot (EffectKind::reeverb2), delayRack, makeEffectSlot (EffectKind::waveCandy) };
+        for (auto& e : song.mixer[1].effects)
+            e.smartDisable = false; // (FL's per-slot smart disable off, as in most FL projects: only the stopped sleep acts)
+        song.patterns.resize (1);
+        song.patterns[0].notes.clear();
+        {
+            Note n;
+            n.channel = 0;
+            n.start = 0;
+            n.length = ppq / 4;
+            n.key = 60;
+            n.velocity = 0.8f;
+            song.patterns[0].notes.push_back (n);
+        }
+        song.mode = PlayMode::pattern;
+
+        auto device = std::make_unique<StandIn>();
+        auto makeEngine = [&] (bool sleeps) {
+            auto e = std::make_unique<AudioEngine> (true, 0, false, true); // (ready to play, no device: driven by hand below)
+            e->setStoppedSleep (sleeps);
+            e->setSong (song);
+            e->dispatchPendingMessages();
+            e->deviceCallback().audioDeviceAboutToStart (device.get());
+            return e;
+        };
+        auto a = makeEngine (true), b = makeEngine (false);
+        std::vector<float> al (256), ar (256), bl (256), br (256);
+        juce::AudioIODeviceCallbackContext context;
+        auto block = [&] (AudioEngine& e, std::vector<float>& l, std::vector<float>& r) {
+            float* outs[] = { l.data(), r.data() };
+            e.deviceCallback().audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 256, context);
+        };
+        auto peak = [] (const std::vector<float>& l, const std::vector<float>& r) {
+            float p = 0.0f;
+            for (std::size_t i = 0; i < l.size(); ++i)
+                p = std::max (p, std::max (std::abs (l[i]), std::abs (r[i])));
+            return p;
+        };
+        auto both = [&] { block (*a, al, ar); block (*b, bl, br); };
+        auto settle = [&] { a->dispatchPendingMessages(); b->dispatchPendingMessages(); };
+
+        // 1. playing: the same samples (1.5 s, the note every bar)
+        a->play();
+        b->play();
+        settle();
+        bool same = true;
+        float loudest = 0.0f;
+        for (int k = 0; k < 260; ++k)
+        {
+            both();
+            same = same && al == bl && ar == br;
+            loudest = std::max (loudest, peak (bl, br));
+        }
+        check ("playing: the engine that sleeps when stopped renders the very samples of one that never does", same && loudest > 0.01f,
+               "peak " + juce::String (loudest, 4));
+
+        // 2. stopped: the tails ring on, the same samples, until they have fallen below -96 dBFS
+        a->stop();
+        b->stop();
+        settle();
+        int ringing = 0, firstDiff = -1, lastLoudB = -1;
+        float largest = 0.0f;
+        for (int k = 0; k < 2600; ++k) // (15 s: the delay's echoes fall below -96 dBFS, then its 4 s hold)
+        {
+            both();
+            if (peak (bl, br) >= 1.0e-4f)
+                lastLoudB = k;
+            if (peak (al, ar) > 1.0e-4f)
+                ++ringing;
+            if (firstDiff < 0 && ! (al == bl && ar == br))
+                firstDiff = k;
+            for (std::size_t i = 0; i < 256; ++i)
+                largest = std::max (largest, std::max (std::abs (al[i] - bl[i]), std::abs (ar[i] - br[i])));
+            if (k % 100 == 0)
+                settle();
+        }
+        check ("after the stop the reverbs and the delay ring on (tails)", ringing > 40, juce::String (ringing) + " blocks above -80 dBFS");
+        // (each unit sleeps once its own input and output stayed below -96 dBFS past its tail: the output may differ from the
+        // one of the engine that never sleeps by those residues, never by more)
+        check ("... the same samples as without the sleep but for residues below -96 dBFS", largest < 1.5849e-5f,
+               "first difference at block " + juce::String (firstDiff) + ", last above -80 dBFS " + juce::String (lastLoudB) + ", largest difference "
+                   + juce::String (largest, 8));
+
+        // 3. asleep: the reverb slot and the channel's Patcher are no longer run, Wave Candy is
+        auto unitsNow = [] (AudioEngine& e) {
+            return std::array<std::uint64_t, 4> { e.effectUnitNanoseconds (1, 0), e.effectUnitNanoseconds (1, 1), e.effectUnitNanoseconds (1, 2),
+                                                  e.channelUnitNanoseconds (0) };
+        };
+        const auto a0 = unitsNow (*a), b0 = unitsNow (*b);
+        for (int k = 0; k < 200; ++k)
+            both();
+        const auto a1 = unitsNow (*a), b1 = unitsNow (*b);
+        const auto detail = "A reverb " + juce::String ((juce::int64) (a1[0] - a0[0])) + " ns, Patcher slot " + juce::String ((juce::int64) (a1[1] - a0[1]))
+                            + " ns, Wave Candy " + juce::String ((juce::int64) (a1[2] - a0[2])) + " ns, channel " + juce::String ((juce::int64) (a1[3] - a0[3]))
+                            + " ns; B reverb " + juce::String ((juce::int64) (b1[0] - b0[0])) + " ns";
+        check ("stopped and silent: the built-in reverb sleeps, the Patcher slot's graph and the generator Patcher sleep",
+               a1[0] == a0[0] && a1[3] == a0[3] && (a1[1] - a0[1]) * 4 < (b1[1] - b0[1]) + 1, detail);
+        check ("... Wave Candy (an analyser) keeps running, and B runs everything", a1[2] > a0[2] && b1[0] > b0[0] && b1[3] > b0[3], detail);
+        // an editor open on the reverb keeps it awake
+        if (auto* times = a->getProcessTimes())
+        {
+            const auto key = (std::size_t) maxEffectSlots;
+            times->editorsOpen[key].fetch_add (1);
+            const auto e0 = a->effectUnitNanoseconds (1, 0);
+            for (int k = 0; k < 20; ++k)
+                both();
+            check ("an editor open on the slot keeps it awake while stopped", a->effectUnitNanoseconds (1, 0) > e0);
+            times->editorsOpen[key].fetch_sub (1);
+            for (int k = 0; k < 900; ++k) // (asleep again after its hold)
+                both();
+        }
+        else
+            check ("the engine's process times", false);
+
+        // 4. a live note while stopped and asleep: it sounds at once, as loud as in B
+        a->sendLiveNote (0, 67, 0.8f, true);
+        b->sendLiveNote (0, 67, 0.8f, true);
+        float pa = 0.0f, pb = 0.0f, diff = 0.0f;
+        for (int k = 0; k < 40; ++k)
+        {
+            both();
+            pa = std::max (pa, peak (al, ar));
+            pb = std::max (pb, peak (bl, br));
+            for (std::size_t i = 0; i < 256; ++i)
+                diff = std::max (diff, std::max (std::abs (al[i] - bl[i]), std::abs (ar[i] - br[i])));
+            if (k == 2)
+                check ("a live note while asleep: heard in its first blocks", pa > 0.01f, "peak " + juce::String (pa, 4));
+        }
+        a->sendLiveNote (0, 67, 0.0f, false);
+        b->sendLiveNote (0, 67, 0.0f, false);
+        check ("... as in the engine that never sleeps (the slept reverb's residue below -96 dBFS only)", pb > 0.01f && diff < 1.0e-3f,
+               "peak " + juce::String (pa, 4) + " / " + juce::String (pb, 4) + ", largest difference " + juce::String (diff, 7));
+        for (int k = 0; k < 1900; ++k)
+            both();
+
+        // 5. playing again: the units run again
+        const auto p0 = unitsNow (*a);
+        a->play();
+        b->play();
+        settle();
+        float again = 0.0f;
+        for (int k = 0; k < 120; ++k)
+        {
+            both();
+            again = std::max (again, peak (al, ar));
+        }
+        const auto p1 = unitsNow (*a);
+        check ("playing again: everything runs and sounds", p1[0] > p0[0] && p1[1] > p0[1] && p1[3] > p0[3] && again > 0.01f);
+        a->stop();
+        b->stop();
+        a->deviceCallback().audioDeviceStopped();
+        b->deviceCallback().audioDeviceStopped();
+        a.reset();
+        b.reset();
+        return result;
+    }

+ 15 - 3
src/StoppedBench190sp.inc

@@ -63,7 +63,7 @@
         juce::String error;
         auto loaded = true;
         const auto t0 = juce::Time::getMillisecondCounterHiRes();
-        if (project.hasFileExtension ("flp"))
+        if (project.hasFileExtension ("flp") || project.hasFileExtension ("als")) // (round 190ts: a Live set too)
             loaded = engine->importFlpFile (project, error);
         else if (auto song = lynx::ProjectFile::load (project, error))
             engine->setSong (std::move (*song));
@@ -82,6 +82,10 @@
         auto device = std::make_shared<StandIn> (block, rate);
         engine->deviceCallback().audioDeviceAboutToStart (device.get());
         engine->stop();
+        // round 190ts: LYNX_BENCH_PLAY=1 plays the song instead (the memory of a project while it plays)
+        const auto playing = juce::SystemStats::getEnvironmentVariable ("LYNX_BENCH_PLAY", "0") == "1";
+        if (playing)
+            engine->play();
         struct State
         {
             std::vector<float> l, r;
@@ -128,8 +132,16 @@
             step ("measured: " + juce::String (blocks) + " blocks in " + juce::String (ms, 1) + " ms = " + juce::String (1000.0 * ms / blocks, 2)
                   + " us per block (" + juce::String (100.0 * ms / (blocks * block * 1000.0 / rate), 2) + " % of the device's time); output peak "
                   + juce::String (peak, 6));
-            engine->deviceCallback().audioDeviceStopped();
-            finish (true);
+            step ("memory (round 190ts): " + processMemory190ts()); // (the engine, its plugins and the app around them)
+            // round 190ts: the heaviest units of the engine's next 2 s window (its CPU meter's list), the measured blocks in it
+            juce::Timer::callAfterDelay (2300, [this, step, finish, device] {
+                if (engine == nullptr)
+                    return;
+                for (const auto& u : engine->getHeaviestUnits())
+                    step ("unit: " + u.name + " " + juce::String (100.0 * u.load, 2) + " %");
+                engine->deviceCallback().audioDeviceStopped();
+                finish (true);
+            });
         };
         juce::Timer::callAfterDelay (200, [tick] { (*tick)(); });
     }

+ 3 - 0
src/core/Effects.h

@@ -235,6 +235,9 @@ public:
     // (1 s for built-ins), never later. −1 = not declared: the fixed hold. Audio thread; cheap (worked out when the
     // settings change).
     virtual int tailSamples() const noexcept { return -1; }
+    // Round 190ts: the live engine's renderer, before each block: the transport is stopped and silent units may sleep
+    // (a Patcher's graph, patcher::Graph::setStoppedSleep). Never on for playing, exports or any offline render.
+    virtual void setStoppedSleep (bool /*on*/) noexcept {}
     // The hardware insert (round 164d): the device's input of the current callback piece and the device-output buses,
     // with where the next process() starts within that piece. `out` is null when no device plays live (an export).
     virtual void setHardwareIo (const LiveInput* /*in*/, HardwareOutput* /*out*/, int /*offset*/) noexcept {}

+ 2 - 0
src/core/Instruments.h

@@ -207,6 +207,8 @@ public:
     virtual void setTempoRatio (double /*ratio*/, bool /*moves*/) noexcept {}
     // No voice sounding: render would only produce silence (the mixer skips the channel until a note arrives).
     virtual bool idle() const noexcept { return false; }
+    // Round 190ts: as Effect::setStoppedSleep (a generator Patcher's graph may sleep; asleep, idle() says so)
+    virtual void setStoppedSleep (bool /*on*/) noexcept {}
     // The notes it sent out in its renders since the last call (a hosted plugin's MIDI output, FL's wrapper "Output
     // port", round 149): fills `out` with up to `max` and returns how many.
     struct MidiOutNote

+ 168 - 4
src/core/Patcher.cpp

@@ -14,6 +14,7 @@
 #include <map>
 #include <tuple>
 
+#include "core/FacetEq.h"
 #include "core/FlSynths.h"
 #include "core/FrequencySplitter.h"
 #include "core/HardwareInsert.h"
@@ -218,6 +219,40 @@ bool sameStructure (const PatcherDoc& a, const PatcherDoc& b)
 
 // ---------------------------------------------------------------------------------------------------------------
 
+namespace
+{
+// Round 190ts: a built-in device whose silence LYNX can tell (Graph::setStoppedSleep): not a hosted plugin or a nested
+// Patcher (that one sleeps by itself), nor what the mixer's smart disable leaves out (RackState::planSlot): Gross Beat and
+// Edison record the silence, Newtone / Newtime / the Scratcher play whatever the input, a hardware insert has outboard
+// tails, controllers move whatever the sound, analysers and the tuner follow the signal into silence, Facet EQ playing
+// its comparative target.
+bool sleepableDevice (const EffectSlot& slot) noexcept
+{
+    switch (slot.kind)
+    {
+        case EffectKind::plugin: case EffectKind::patcher: case EffectKind::grossBeat: case EffectKind::newtone:
+        case EffectKind::newtime: case EffectKind::scratcher: case EffectKind::edison: case EffectKind::hardwareInsert:
+        case EffectKind::formulaController: case EffectKind::xyController: case EffectKind::xyzController:
+        case EffectKind::controlSurface: case EffectKind::peakController: case EffectKind::waveCandy:
+        case EffectKind::visualizer: case EffectKind::tuner:
+            return false;
+        default:
+            break;
+    }
+    return ! (slot.kind == EffectKind::facetEq && facet::listensToTarget (slot.params));
+}
+
+constexpr float sleepLevel = 1.5849e-5f; // -96 dBFS (RackRenderer::silenceLevel)
+
+bool quietBlock (const float* l, const float* r, int n) noexcept
+{
+    float peak = 0.0f;
+    for (int k = 0; k < n; ++k)
+        peak = std::max (peak, std::max (std::abs (l[k]), std::abs (r[k])));
+    return peak < sleepLevel;
+}
+} // namespace
+
 struct Graph::Node
 {
     bool generator = false;
@@ -246,6 +281,12 @@ struct Graph::Node
     std::vector<int> mainInputs, sideInputs; // wire indices
     std::atomic<float> peak { 0.0f };       // round 190ld: main-output peak and process time while watched (Graph::watch)
     std::atomic<std::uint64_t> ns { 0 };
+    // round 190ts (Graph::setStoppedSleep): may sleep while stopped (LYNX's own devices / an instrument that says idle);
+    // a nested Patcher sleeps by itself (its graph), and counts as asleep when it is
+    bool sleeps = false;
+    Graph* nested = nullptr;
+    int silentSamples = 0; // input and output silent that long (effect nodes)
+    bool asleep = false;   // not called in the last piece
 };
 
 struct Graph::AudioWire
@@ -655,6 +696,37 @@ Graph::Graph (const PatcherDoc& doc, double sampleRate, const Factories& factori
         if (wires[k].to == patchToHost && wires[k].toBus < (int) outputs.size())
             outputs[(std::size_t) wires[k].toBus].push_back ((int) k);
 
+    // round 190ts (setStoppedSleep): which nodes may sleep while stopped
+    canWholeSleep = ! hardwareNodes;
+    for (int i = 0; i < count; ++i)
+    {
+        auto& node = *nodes[(std::size_t) i];
+        const auto& src = doc.nodes[(std::size_t) i];
+        if (node.generator)
+        {
+            // (a hosted generator keeps running: its idle() is FL's smart disable, which the rack asks itself)
+            node.nested = graphOf (node.instrument.get());
+            node.sleeps = node.instrument != nullptr && node.vfx == nullptr && ! node.plugin && node.nested == nullptr;
+            if (node.nested != nullptr)
+                nestedGraphs.push_back (node.nested);
+            else if (! node.sleeps && node.vfx == nullptr)
+                canWholeSleep = false;
+            continue;
+        }
+        node.nested = src.effect.kind == EffectKind::patcher ? graphOf (node.effect.get()) : nullptr;
+        if (node.nested != nullptr)
+        {
+            nestedGraphs.push_back (node.nested);
+            if (node.sidechain)
+                canWholeSleep = false;
+            continue;
+        }
+        const auto drivesControls = std::any_of (controls.begin(), controls.end(), [i] (const ControlWire& c) { return c.from == i; });
+        node.sleeps = node.effect != nullptr && ! node.sidechain && ! node.hardware && ! drivesControls && sleepableDevice (src.effect)
+                      && std::all_of (node.heads.begin(), node.heads.end(), [] (const Node::Head& h) { return h.effect == nullptr || sleepableDevice (h.slot); });
+        canWholeSleep = canWholeSleep && node.sleeps;
+    }
+
     for (auto& s : scratch)
         s.assign ((std::size_t) capacity, 0.0f);
     zeros.assign ((std::size_t) capacity, 0.0f);
@@ -838,6 +910,39 @@ void Graph::setPlaying (bool on) noexcept
             n->effect->setPlaying (on);
 }
 
+void Graph::setStoppedSleep (bool on) noexcept
+{
+    if (on == sleepOk)
+        return;
+    sleepOk = on;
+    wholeAsleep = allNodesAsleep = false;
+    quietSamples = 0;
+    for (auto& n : nodes)
+    {
+        n->silentSamples = 0;
+        n->asleep = false;
+    }
+    for (auto* g : nestedGraphs)
+        g->setStoppedSleep (on);
+}
+
+int Graph::sleepHold (const Node& node) const noexcept
+{
+    // (as the mixer's smart disable takes a built-in's declared tail, round 190gp; an undeclared one waits 4 s of silence:
+    // the plugins' hold, longer than the mixer's 1 s for built-ins, so a long echo or reverb never stops early)
+    const auto fixed = (int) (rate * 4.0);
+    if (! declaredTails() || node.effect == nullptr)
+        return fixed;
+    auto tail = node.effect->tailSamples();
+    for (const auto& h : node.heads)
+        if (h.effect != nullptr)
+        {
+            const auto t = h.effect->tailSamples();
+            tail = tail < 0 || t < 0 ? -1 : std::max (tail, t);
+        }
+    return tail < 0 ? fixed : std::clamp (tail, 1, fixed);
+}
+
 void Graph::setHeldNotes (const NoteMask* channels, int count) noexcept
 {
     for (auto& n : nodes)
@@ -994,6 +1099,8 @@ bool Graph::zoneGate (int zone, bool on, int& key, int midiChannel, float& veloc
 
 void Graph::deliver (int pin, bool on, int key, float velocityIn, int midiChannel) noexcept
 {
+    wholeAsleep = false; // (round 190ts: something comes in: awake, idle() says so at once)
+    quietSamples = 0;
     if (pin < 0 || pin >= (int) pinTargets.size())
         return;
     forLayeredTargets (pinTargets[(std::size_t) pin], on ? 1 : 0, key, [&] (const MidiTarget& t, int k, float gain, float pan, float cents, bool viaLayer) {
@@ -1058,6 +1165,8 @@ void Graph::noteOffPort (int port, int key, int midiChannel) noexcept
 
 void Graph::queueTimed (int pin, int key, float velocity, int midiChannel, int offset) noexcept
 {
+    wholeAsleep = false; // (round 190ts: something comes in: awake, idle() says so at once)
+    quietSamples = 0;
     if (pin < 0 || pin >= (int) pinTargets.size() || pinTargets[(std::size_t) pin].empty() || timedCount >= timedCapacity)
         return;
     timed[(std::size_t) timedCount++] = { pin, key, midiChannel, std::max (0, offset), velocity };
@@ -1120,6 +1229,8 @@ void Graph::forNoteTargets (F&& f) noexcept
 
 void Graph::midiMessage (const std::uint8_t* bytes, int size) noexcept
 {
+    wholeAsleep = false; // (round 190ts: something comes in: awake, idle() says so at once)
+    quietSamples = 0;
     forNoteTargets ([&] (Instrument& i) { i.midiMessage (bytes, size); });
 }
 void Graph::pitchBend (float semitones) noexcept
@@ -1458,6 +1569,26 @@ void Graph::processPiece (const float* inL, const float* inR, const float* scL,
     }
     if (hasVfx)
         runVfx (n, bpm);
+    // round 190ts (setStoppedSleep): every node asleep, nothing coming in and the delays emptied: the graph is skipped
+    // (not while an editor watches its nodes: View › Activity / Performance)
+    if (sleepOk && watchLeft.load (std::memory_order_relaxed) > 0)
+        setStoppedSleep (false);
+    if (sleepOk && canWholeSleep)
+    {
+        const auto quiet = allNodesAsleep && noteOuts.empty() && timedCount == 0 && quietBlock (inL, inR, n)
+                           && (scL == nullptr || scR == nullptr || quietBlock (scL, scR, n)) && instrumentsIdle();
+        quietSamples = quiet ? quietSamples + n : 0;
+        wholeAsleep = quiet && quietSamples > latency;
+        if (wholeAsleep)
+        {
+            std::fill (outL, outL + n, 0.0f);
+            std::fill (outR, outR + n, 0.0f);
+            for (auto& a : aux)
+                for (auto& side : a)
+                    std::fill (side.begin(), side.begin() + n, 0.0f);
+            return;
+        }
+    }
     if (noteOuts.empty())
     {
         renderNodes (inL, inR, scL, scR, outL, outR, 0, n, bpm);
@@ -1672,7 +1803,10 @@ void Graph::renderNodes (const float* inL, const float* inR, const float* scL, c
         {
             std::fill (oL, oL + n, 0.0f);
             std::fill (oR, oR + n, 0.0f);
-            if (node.instrument != nullptr)
+            // (round 190ts, stopped: an idle instrument is not rendered, as the rack skips an idle channel)
+            node.asleep = sleepOk && (node.nested != nullptr ? node.nested->asleep() || node.instrument->idle()
+                                                             : node.sleeps && node.instrument->idle());
+            if (node.instrument != nullptr && ! node.asleep)
                 node.instrument->render (oL, oR, n, 1.0f, 1.0f);
             if (watched)
                 measured (node, oL, oR);
@@ -1682,7 +1816,19 @@ void Graph::renderNodes (const float* inL, const float* inR, const float* scL, c
         gather (node.mainInputs, inBufL, inBufR);
         std::copy (inBufL, inBufL + n, oL);
         std::copy (inBufR, inBufR + n, oR);
-        if (v.enabled && v.mix > 0.0f)
+        // round 190ts (setStoppedSleep): stopped, a device whose input and output stayed silent past its tail passes its
+        // input through without being called
+        auto quietIn = false, skip = false;
+        if (sleepOk && node.sleeps)
+        {
+            quietIn = quietBlock (inBufL, inBufR, n);
+            if (! quietIn)
+                node.silentSamples = 0;
+            else if (node.silentSamples >= sleepHold (node))
+                skip = true;
+        }
+        node.asleep = skip;
+        if (v.enabled && v.mix > 0.0f && ! skip)
         {
             if (node.sidechain)
             {
@@ -1705,7 +1851,7 @@ void Graph::renderNodes (const float* inL, const float* inR, const float* scL, c
             auto* hR = node.out[1 + h][1].data() + start;
             std::copy (inBufL, inBufL + n, hL);
             std::copy (inBufR, inBufR + n, hR);
-            if (node.heads[h].effect != nullptr)
+            if (node.heads[h].effect != nullptr && ! skip)
                 node.heads[h].effect->process (hL, hR, n, v.heads[h], bpm);
             const auto g = v.headGains[h];
             if (g != 1.0f)
@@ -1715,9 +1861,21 @@ void Graph::renderNodes (const float* inL, const float* inR, const float* scL, c
                     hR[k] *= g;
                 }
         }
+        if (sleepOk && node.sleeps && ! skip)
+        {
+            // (its tail: silent input and silent outputs count towards the hold)
+            auto quietOut = quietIn && quietBlock (oL, oR, n);
+            for (std::size_t h = 0; h < node.heads.size() && quietOut; ++h)
+                quietOut = quietBlock (node.out[1 + h][0].data() + start, node.out[1 + h][1].data() + start, n);
+            node.silentSamples = quietOut ? node.silentSamples + n : 0;
+        }
+        else if (sleepOk && node.nested != nullptr)
+            node.asleep = node.nested->asleep();
         if (watched)
             measured (node, oL, oR);
     }
+    if (sleepOk)
+        allNodesAsleep = std::all_of (nodes.begin(), nodes.end(), [] (const auto& x) { return x->asleep || x->vfx != nullptr; });
 
     // "To LYNX SHARE": the main output and the extra ones
     gather (outputs[0], inBufL, inBufR);
@@ -1776,6 +1934,7 @@ public:
     void setParameter (int index, float value) noexcept override { graph.setPublished (index, value); }
     void setSongPosition (double ticks) noexcept override { graph.setSongPosition (ticks); }
     void setPlaying (bool playing) noexcept override { graph.setPlaying (playing); }
+    void setStoppedSleep (bool on) noexcept override { graph.setStoppedSleep (on); } // (round 190ts)
     void setSidechain (const float* l, const float* r) noexcept override
     {
         sideL = l;
@@ -1842,7 +2001,12 @@ public:
     void setSongPosition (double ticks) noexcept override { graph.setSongPosition (ticks); }
     void setParameter (int index, float value) noexcept override { graph.setPublished (index, value); }
     int latencySamples() const noexcept override { return graph.latencySamples(); }
-    bool idle() const noexcept override { return idleWhenQuiet.load (std::memory_order_relaxed) && graph.instrumentsIdle(); }
+    // (round 190ts: or its graph sleeps while stopped, Graph::setStoppedSleep)
+    bool idle() const noexcept override
+    {
+        return (idleWhenQuiet.load (std::memory_order_relaxed) && graph.instrumentsIdle()) || graph.asleep();
+    }
+    void setStoppedSleep (bool on) noexcept override { graph.setStoppedSleep (on); }
 
     // (UI thread, while the audio thread renders: only atomics change here; the graph swaps its values itself)
     void configure (const ChannelDef& channel, double bpm) noexcept override

+ 22 - 0
src/core/Patcher.h

@@ -136,6 +136,20 @@ public:
     bool hasInstruments() const noexcept;
     bool instrumentsIdle() const noexcept;
 
+    // Round 190ts (0.1.33 block E, "Patcher racks use CPU while stopped"): sleep while stopped. Only the live engine's
+    // renderer allows it, and only while the transport is stopped (RackRenderer::setStoppedSleep -> setStoppedSleep here,
+    // before each block). Then a node made of LYNX's own devices whose input has been silent (below -96 dBFS) and whose
+    // output has stayed silent past its tail (its declared Effect::tailSamples, else 4 s) is not called: its input passes
+    // through, as FL's smart disable does; an idle instrument node (Instrument::idle) is not rendered. Once every node
+    // sleeps, nothing comes in (notes, VFX voices, audio above -96 dBFS) and the graph's delays have emptied, the whole
+    // graph is skipped (asleep(): a generator Patcher then reports idle, so the rack skips its channel and its insert).
+    // Never asleep: hosted plugins (an LFO, a host sync, an analyser may need their calls; FL keeps calling them), the
+    // nodes FL's smart disable leaves out (analysers, controllers, Gross Beat, Edison, hardware inserts...), side-chained
+    // nodes, the sources of control cables, VFX nodes. Playing, exports and every offline render never sleep: what they
+    // render is the same to the bit. Audio thread.
+    void setStoppedSleep (bool on) noexcept;
+    bool asleep() const noexcept { return sleepOk && wholeAsleep; }
+
     // The delay the graph adds (its longest path to "To LYNX SHARE"). If a node's latency moved since the graph planned
     // its compensation (latencyStale), the latency it will have once built again. UI thread (allocates when stale).
     int latencySamples() const;
@@ -283,6 +297,14 @@ private:
     HardwareOutput* hwOut = nullptr;
     int hwOffset = 0, pieceOffset = 0; // (pieceOffset: the current piece's first sample in the callback piece)
     bool hardwareNodes = false;
+    // round 190ts: sleep while stopped (setStoppedSleep)
+    bool sleepOk = false;          // allowed now (the live engine, stopped)
+    bool wholeAsleep = false;      // the last piece skipped every node
+    bool allNodesAsleep = false;   // every node slept in the last piece rendered
+    bool canWholeSleep = false;    // every node may sleep (nothing that never does)
+    int quietSamples = 0;          // the whole graph quiet that long
+    std::vector<Graph*> nestedGraphs;
+    int sleepHold (const Node& node) const noexcept;
     std::atomic<std::int64_t> watchLeft { 0 };          // round 190ld: frames still measured (watch())
     std::atomic<std::uint64_t> graphNs { 0 }, framesWatched { 0 };
     std::atomic<float> inputPeak { 0.0f };

+ 36 - 4
src/core/RackRenderer.cpp

@@ -4564,7 +4564,10 @@ void RackRenderer::renderChannel (const RackState& state, int i, int n) noexcept
     // (round 173d: + the controller's pitch wheel, which FL's generators follow through the channel's pitch)
     instrument.setChannelPitchNow (channelKnobCents (state, i), c.misc.fineTune + (c.misc.mainPitch ? state.song.masterPitch : 0.0f) + instrument.wheelCents());
     if (c.instrument == InstrumentKind::patcher) // its Hardware Insert nodes: this chunk's device buses (round 165c)
+    {
         instrument.setHardwareIo (liveInput, hwOut != nullptr && hwOut->active.load (std::memory_order_relaxed) ? hwOut : nullptr, liveInputOffset);
+        instrument.setStoppedSleep (sleepNow()); // (round 190ts: before idle() is asked below)
+    }
 
     // idle channel, no notes in this chunk and no PDC: nothing to do (neither clear nor sum into the mixer)
     const auto hasDelay = (std::size_t) i < state.channelDelays.size() && state.channelDelays[(std::size_t) i] != nullptr
@@ -5056,6 +5059,17 @@ RackState::SlotPlan RackState::planSlot (const RackState& state, int track, std:
     // side input (what it hears there moves its state while its own input is silent)
     // (round 190jg: a hosted plugin too, when it declares its tail — CLAP's clap.tail, PluginEffect::tailSamples)
     p.tailHold = (! p.longHold || p.isPlugin) && slot.sidechain < 0 && slot.sidechain2 < 0;
+    // round 190ts: sleep while stopped (RackRenderer::setStoppedSleep): LYNX's own devices only, whatever the slot's
+    // "Smart disable" says (the sound is the same: their silence is known), with the kinds smart disable leaves out still
+    // out, no side input and no Patcher (its graph sleeps by itself, Graph::setStoppedSleep); never a hosted plugin
+    p.stoppedSleep = ! p.isPlugin && slot.kind != EffectKind::patcher && slot.sidechain < 0 && slot.sidechain2 < 0
+                     && slot.kind != EffectKind::grossBeat && slot.kind != EffectKind::newtone && slot.kind != EffectKind::newtime
+                     && slot.kind != EffectKind::scratcher && slot.kind != EffectKind::edison && slot.kind != EffectKind::hardwareInsert
+                     && slot.kind != EffectKind::formulaController && slot.kind != EffectKind::xyController
+                     && slot.kind != EffectKind::xyzController && slot.kind != EffectKind::controlSurface
+                     && slot.kind != EffectKind::peakController && slot.kind != EffectKind::waveCandy
+                     && slot.kind != EffectKind::visualizer && slot.kind != EffectKind::tuner
+                     && ! (slot.kind == EffectKind::facetEq && facet::listensToTarget (slot.params));
     p.used = (int) std::min (slot.params.size(), effectInfo (slot.kind).params.size());
     // round 190pt: a Vocodex with liveControls has FL's 20 controls as hidden parameters that automation moves
     if (slot.kind == EffectKind::vocodex && slot.params[(std::size_t) vocodex::liveControls] >= 0.5f)
@@ -5315,16 +5329,27 @@ void RackRenderer::runEffects (const RackState& state, int track, int n) noexcep
         const auto key = (std::size_t) track * maxEffectSlots + i;
         const auto isPlugin = plan.isPlugin;
         const auto* connections = plan.routed ? &state.slotConnections[(std::size_t) track][i] : nullptr; // (round 189j: a hosted effect's routed Connections)
-        const auto hold = (int) (sampleRate * (plan.longHold ? 4.0 : 1.0)); // (a Patcher may hold plugins)
+        const auto smartHold = (int) (sampleRate * (plan.longHold ? 4.0 : 1.0)); // (a Patcher may hold plugins)
 
         // (not the slots RackState::planSlot lists, made with the snapshot; round 190gp — nor anything while FL's
         // Settings › Audio › CPU › "Smart disable" is off: the global switch, round 190bx)
-        if (key < smartDisable.size() && plan.smartEligible && flsettings::options().smartDisable.load (std::memory_order_relaxed))
+        const auto smartOn = key < smartDisable.size() && plan.smartEligible && flsettings::options().smartDisable.load (std::memory_order_relaxed);
+        // round 190ts: stopped, LYNX's own devices sleep by the same rule (their declared tail, else 4 s of silence), unless
+        // an editor is open on the slot; the count starts at the stop (stopSerial)
+        const auto sleepOn = ! smartOn && plan.stoppedSleep && key < smartDisable.size() && sleepNow()
+                             && times->editorsOpen[std::min (key, times->editorsOpen.size() - 1)].load (std::memory_order_relaxed) == 0;
+        if (smartOn || sleepOn)
         {
             auto& sd = smartDisable[key];
 
             if (sd.effect != effects[i].get())
-                sd = { effects[i].get(), 0 };
+                sd = { effects[i].get(), 0, stopSerial };
+            if (sleepOn && sd.stop != stopSerial)
+            {
+                sd.stop = stopSerial;
+                sd.silentSamples = 0;
+            }
+            const auto hold = sleepOn ? (int) (sampleRate * 4.0) : smartHold;
 
             if (audible < 0)
                 audible = ! trackZeros (track) && anyAbove (l, r, n, silenceLevel) ? 1 : 0;
@@ -5334,7 +5359,7 @@ void RackRenderer::runEffects (const RackState& state, int track, int n) noexcep
             // input keeps it on. silent ≥ min (hold, t) ⇔ silent ≥ hold or silent ≥ t; the call was a cache miss on the
             // effect object of every waiting slot at every block)
             auto pastTail = [&] {
-                const auto tail = plan.tailHold && declaredTails() ? effects[i]->tailSamples() : -1;
+                const auto tail = (plan.tailHold || sleepOn) && declaredTails() ? effects[i]->tailSamples() : -1;
                 return tail >= 0 && sd.silentSamples >= std::max (tail, 1);
             };
             if (audible == 1)
@@ -5389,6 +5414,8 @@ void RackRenderer::runEffects (const RackState& state, int track, int n) noexcep
         // the hardware insert (round 164d): this piece's device input and output buses (none during an export)
         if (slots[i].kind == EffectKind::hardwareInsert || slots[i].kind == EffectKind::patcher) // (a Patcher hands them to its nodes, round 165c)
             effects[i]->setHardwareIo (liveInput, hwOut != nullptr && hwOut->active.load (std::memory_order_relaxed) ? hwOut : nullptr, liveInputOffset);
+        if (slots[i].kind == EffectKind::patcher) // (round 190ts: stopped, its graph may sleep — not while an editor is open on it)
+            effects[i]->setStoppedSleep (sleepNow() && times->editorsOpen[std::min (key, times->editorsOpen.size() - 1)].load (std::memory_order_relaxed) == 0);
 
         // Fruity Send / Patcher / Transmitter / Transporter: what it sends goes to its own buffer, pulled by the destination insert
         // (processed later)
@@ -6632,6 +6659,11 @@ void RackRenderer::chunkPrelude (const RackState& state, bool playing, double st
 {
     chunkTick = startTick;
     chunkPlaying = playing;
+    if (const auto sleeping = sleepNow(); sleeping != sleptLast) // (round 190ts: a stop starts the slots' stopped-sleep counts again)
+    {
+        stopSerial += sleeping ? 1u : 0u;
+        sleptLast = sleeping;
+    }
     latencyTransport = playing && latencytransport::enabled(); // (issue #356; stopped: nothing to shift)
     const auto playedBefore = releaseWasPlaying; // (issue #356: this renderer's own last chunk played)
     // FL: playback starting puts every control the user moved back under its automation (issue #125)

+ 14 - 0
src/core/RackRenderer.h

@@ -479,6 +479,7 @@ struct RackState
         bool sends = false;         // it sends into its own buffers (Fruity Send, Patcher, Transmitter, Transporter, Equo, routed)
         bool hasMixAuto = false;    // effectMixAuto has its entry (mixAuto)
         bool tailHold = false;      // smart disable may take the effect's declared tail (a built-in with no side input)
+        bool stoppedSleep = false;  // round 190ts: a built-in that may sleep while stopped (RackRenderer::setStoppedSleep)
         int mixAuto = -1;
         float mix = 1.0f;
         int used = 0;               // the parameters its kind has (and the slot holds)
@@ -576,6 +577,9 @@ struct ProcessTimes
     // Round 190gp: the editors showing a slot's live meters (effectMeters) count themselves here; the renderer tells the
     // slot's effect before each block (Effect::setMetersShown), so a costly meter runs only while one is open.
     std::array<std::atomic<std::uint16_t>, (std::size_t) maxMixerTracks * maxEffectSlots> metersWanted {};
+    // Round 190ts: the editors open on a slot (a built-in's: its live displays, LFO positions, meters) count themselves
+    // here; while one is, the slot (or the Patcher holding the edited node) never sleeps while stopped.
+    std::array<std::atomic<std::uint16_t>, (std::size_t) maxMixerTracks * maxEffectSlots> editorsOpen {};
     std::array<std::atomic<float>, (std::size_t) maxMixerTracks * maxEffectSlots * 2> slotLevels {};
     // round 190lr (DL-87, Live's stereo meter after each device): the same peaks per side, [key * 2 + side], input and output
     std::array<std::atomic<float>, (std::size_t) maxMixerTracks * maxEffectSlots * 2> slotInputSides {}, slotOutputSides {};
@@ -752,6 +756,11 @@ public:
         return channel >= 0 && channel < maxChannels ? strikes[(std::size_t) channel].load (std::memory_order_relaxed) : 0u;
     }
     void setProfiling (bool on) noexcept { profiling.store (on, std::memory_order_relaxed); }
+    // Round 190ts (0.1.33 block E): the live engine's renderers only (off by default: exports, tools and tests never sleep).
+    // While the transport is stopped, the Patcher graphs of channels and inserts may put their silent built-in devices to
+    // sleep and skip themselves once all sleep (patcher::Graph::setStoppedSleep). LYNX_STOPPED_SLEEP=0 switches it off.
+    void setStoppedSleep (bool on) noexcept { stoppedSleep.store (on, std::memory_order_relaxed); }
+    bool stoppedSleepOn() const noexcept { return stoppedSleep.load (std::memory_order_relaxed); }
     bool isProfiling() const noexcept { return profiling.load (std::memory_order_relaxed); }
     const UnitTimes& unitTimes() const noexcept { return *units; }
     // Round 190gg: the slowest channel / effect call since the last take (core/Dropouts.h pack(); 0 = none). Audio thread,
@@ -1433,6 +1442,8 @@ private:
     bool runTaskGraph (const RackState& state, bool playing, int channels, int numSamples, MeterBank* meters) noexcept;
     void sumChannelsInto (const RackState& state, int track, int channels, int n) noexcept;
     std::atomic<bool> profiling { false };
+    std::atomic<bool> stoppedSleep { false }; // round 190ts (setStoppedSleep)
+    bool sleepNow() const noexcept { return ! chunkPlaying && stoppedSleep.load (std::memory_order_relaxed); }
     std::unique_ptr<UnitTimes> ownUnits = std::make_unique<UnitTimes>();
     std::unique_ptr<ProcessTimes> ownTimes = std::make_unique<ProcessTimes>();
     UnitTimes* units = ownUnits.get();
@@ -1442,7 +1453,10 @@ private:
     {
         const Effect* effect = nullptr;
         int silentSamples = 0;
+        std::uint32_t stop = 0; // round 190ts: the stop its stopped-sleep count belongs to (stopSerial)
     };
+    std::uint32_t stopSerial = 0; // round 190ts: +1 at each stop (a slot's stopped-sleep count starts again)
+    bool sleptLast = false;
     std::vector<SmartDisableState> smartDisable; // [track * maxEffectSlots + slot]
     // Round 190qh (D2-MX9): an effect slot switched off or on while the audio runs crossfades between its input and its
     // output over switchFade samples (Pdc.h switchFadeSamples: no click) instead of stepping. `gain` is where the slot is

+ 6 - 0
src/core/RenderAhead.cpp

@@ -253,6 +253,12 @@ void RenderAhead::setProfiling (bool on) noexcept
     ahead->setProfiling (on);
 }
 
+void RenderAhead::setStoppedSleep (bool on) noexcept
+{
+    live.setStoppedSleep (on);
+    ahead->setStoppedSleep (on);
+}
+
 const RackRenderer& RenderAhead::rendererOf (int channel) const noexcept
 {
     if (engagedNow.load (std::memory_order_relaxed) && channel >= 0 && channel < RackRenderer::maxChannels

+ 1 - 0
src/core/RenderAhead.h

@@ -234,6 +234,7 @@ public:
     void setReleasedSlots (const std::vector<int>& slots) noexcept;
     void setKeepReleasedOnPlay (bool keep) noexcept; // (round 190oa, DL-58: both renderers)
     void setProfiling (bool on) noexcept;
+    void setStoppedSleep (bool on) noexcept; // round 190ts: both renderers (RackRenderer::setStoppedSleep)
     // The render-ahead thread renders nothing more (the engine is going away: its snapshots are about to be freed);
     // returns once it is idle. prepare() lets it work again.
     void halt() noexcept;

+ 25 - 0
src/engine/AudioEngine.cpp

@@ -762,7 +762,11 @@ AudioEngine::AudioEngine (bool openAudioDevice, int workerThreads, bool userPlug
         player.setProcessor (&graph);
         // the settings that do not need the device (the window reads them; round 190go: built before the device opens)
         if (rackProcessor != nullptr)
+        {
             rackProcessor->setProfiling (true); // per-unit CPU for the CPU meter and the glitch log (both renderers: 190gq)
+            // round 190ts: the live engine's Patcher graphs sleep while stopped (LYNX_STOPPED_SLEEP=0: never, for A/B runs)
+            rackProcessor->setStoppedSleep (juce::SystemStats::getEnvironmentVariable ("LYNX_STOPPED_SLEEP", "1") != "0");
+        }
         midiPrefs = midiPrefsShared = prefs::MidiPrefs::fromText (midiSettingsFile().loadFileAsString().toStdString());
         performanceMidiChannel.store (midiPrefs.performanceChannel);
         controllerIo.loadProfiles (controllerProfilesFolder());
@@ -5593,6 +5597,27 @@ bool AudioEngine::finishFlpImport (PreparedFlp&& prepared, bool asEdit)
     return true;
 }
 
+void AudioEngine::setStoppedSleep (bool on) noexcept
+{
+    if (rackProcessor != nullptr)
+        rackProcessor->setStoppedSleep (on);
+}
+
+std::uint64_t AudioEngine::channelUnitNanoseconds (int channel) const noexcept
+{
+    if (rackProcessor == nullptr || channel < 0 || channel >= RackRenderer::maxChannels)
+        return 0;
+    return rackProcessor->getRenderer().unitTimes().channelNs[(std::size_t) channel].load (std::memory_order_relaxed);
+}
+
+std::uint64_t AudioEngine::effectUnitNanoseconds (int track, int slot) const noexcept
+{
+    const auto key = (std::size_t) track * maxEffectSlots + (std::size_t) slot;
+    if (rackProcessor == nullptr || track < 0 || slot < 0 || slot >= maxEffectSlots || key >= rackProcessor->getRenderer().unitTimes().effectNs.size())
+        return 0;
+    return rackProcessor->getRenderer().unitTimes().effectNs[key].load (std::memory_order_relaxed);
+}
+
 bool AudioEngine::importFlpFile (const juce::File& file, juce::String& error, const std::map<std::string, std::string>& relocations, bool asEdit)
 {
     // a slow plugin module (a Waves shell) starts on its own thread while the samples decode (round 121)

+ 5 - 0
src/engine/AudioEngine.h

@@ -1352,6 +1352,11 @@ public:
         double longestMs = 0.0; // the longest single call in the window
     };
     const std::vector<UnitLoad>& getHeaviestUnits() const noexcept { return heaviestUnits; }
+    // Round 190ts: sleep while stopped (RackRenderer::setStoppedSleep; on by default in an engine with a device, unless
+    // LYNX_STOPPED_SLEEP=0), and the CPU time a channel / an insert slot took so far (the renderer's unit profile, ns)
+    void setStoppedSleep (bool on) noexcept;
+    std::uint64_t channelUnitNanoseconds (int channel) const noexcept;
+    std::uint64_t effectUnitNanoseconds (int track, int slot) const noexcept;
 
     // Round 190gg (B5): the dropouts (buffer underruns) since the start, when the last one was and why (core/Dropouts.h):
     // the processing (with the slowest channel / effect of that block) or the driver / system (late while the load was

+ 1 - 0
src/engine/ChannelRackProcessor.h

@@ -78,6 +78,7 @@ public:
     void setReleasedSlots (const std::vector<int>& slots) noexcept { ahead->setReleasedSlots (slots); }
     void setKeepReleasedOnPlay (bool keep) noexcept { ahead->setKeepReleasedOnPlay (keep); } // (round 190oa, DL-58)
     void setProfiling (bool on) noexcept { ahead->setProfiling (on); }
+    void setStoppedSleep (bool on) noexcept { ahead->setStoppedSleep (on); } // round 190ts (RackRenderer::setStoppedSleep)
     bool renderAheadOwnsWorkers() const noexcept { return ahead->ownsWorkers(); }
     void haltRenderAhead() noexcept { ahead->halt(); }
     // round 190px: render-ahead paces its catch-up while the UI starves (core/RenderAhead.h setUiGuard)

+ 6 - 0
src/ui/PluginEditors.cpp

@@ -232,6 +232,9 @@ public:
         if ((kind == EffectKind::vocoder || kind == EffectKind::fruityMultiband || kind == EffectKind::maximus) && ! node.locate) // round 190ld (DP-32) / 190mf (DP-29) / 190oa (DP-27): live band levels
             if (auto* times = engine.getProcessTimes(); times != nullptr && levelKey() < times->metersWanted.size())
                 times->metersWanted[levelKey()].fetch_add (1, std::memory_order_relaxed);
+        if (! node.locate && track >= 0) // round 190ts: the slot stays awake while stopped (its live displays move)
+            if (auto* times = engine.getProcessTimes(); times != nullptr && levelKey() < times->editorsOpen.size())
+                times->editorsOpen[levelKey()].fetch_add (1, std::memory_order_relaxed);
         if (! node.locate)
             startTimerHz (30); // live displays, and the controls following their automation (cheap while nothing moves)
         else if (liveDisplays || kind == EffectKind::grossBeat) // (round 190ih: Gross Beat's locator, in a Patcher too)
@@ -248,6 +251,9 @@ public:
     ~NativeEffectEditor() override
     {
         stopTimer();
+        if (! node.locate && track >= 0) // (round 190ts)
+            if (auto* times = engine.getProcessTimes(); times != nullptr && levelKey() < times->editorsOpen.size())
+                times->editorsOpen[levelKey()].fetch_sub (1, std::memory_order_relaxed);
         if (levelMeter && ! node.locate)
             if (auto* times = engine.getProcessTimes(); times != nullptr && levelKey() < times->levelWanted.size())
                 times->levelWanted[levelKey()].fetch_sub (1, std::memory_order_relaxed);

+ 263 - 0
tests/Sleep190tsTests.inc

@@ -0,0 +1,263 @@
+// Round 190ts (0.1.33 block E, "Patcher racks use CPU while stopped"): sleep while stopped (patcher::Graph::setStoppedSleep,
+// RackRenderer::setStoppedSleep). Only the live engine allows it, only while stopped; LYNX's own devices sleep once their
+// input and output stayed silent past their tail, hosted plugins and analysers never do, a note wakes everything at once.
+
+namespace sleep190ts
+{
+// a hosted plugin stand-in (an effect slot of kind `plugin`) that counts its calls
+struct CountingPlugin final : lynx::Effect
+{
+    long processed = 0;
+    void prepare (double) noexcept override {}
+    void reset() noexcept override {}
+    void process (float*, float*, int n, const lynx::EffectParams&, double) noexcept override { processed += n; }
+};
+
+// host -> Fruity Reeverb 2 -> host, and (withPlugin) host -> a hosted plugin -> host beside it
+lynx::PatcherDoc reverbDoc (bool withPlugin, int* reverbNode = nullptr, int* pluginNode = nullptr)
+{
+    using namespace lynx;
+    PatcherDoc d;
+    auto chain = [&d] (EffectSlot slot) {
+        PatchNode n;
+        n.effect = std::move (slot);
+        const auto node = patcher::addNode (d, n);
+        PatchWire in;
+        in.from = patchFromHost;
+        in.to = node;
+        d.wires.push_back (in);
+        PatchWire out;
+        out.from = node;
+        out.to = patchToHost;
+        d.wires.push_back (out);
+        return node;
+    };
+    const auto rv = chain (makeEffectSlot (EffectKind::reeverb2));
+    if (reverbNode != nullptr)
+        *reverbNode = rv;
+    if (withPlugin)
+    {
+        auto p = makeEffectSlot (EffectKind::plugin);
+        p.plugin.id = "VST3-Counting";
+        p.plugin.name = "Counting";
+        const auto pn = chain (p);
+        if (pluginNode != nullptr)
+            *pluginNode = pn;
+    }
+    return d;
+}
+
+lynx::patcher::Factories factories (std::shared_ptr<CountingPlugin>& plugin)
+{
+    auto f = lynx::patcher::builtInFactories (44100.0);
+    auto builtIn = f.effect;
+    f.effect = [builtIn, &plugin] (const lynx::EffectSlot& slot) -> std::shared_ptr<lynx::Effect> {
+        if (slot.kind == lynx::EffectKind::plugin)
+            return plugin = std::make_shared<CountingPlugin>();
+        return builtIn (slot);
+    };
+    return f;
+}
+
+float peakOf (const std::vector<float>& l, const std::vector<float>& r)
+{
+    float p = 0.0f;
+    for (std::size_t i = 0; i < l.size(); ++i)
+        p = std::max (p, std::max (std::abs (l[i]), std::abs (r[i])));
+    return p;
+}
+} // namespace sleep190ts
+
+// stopped, the reverb's tail rings out bit for bit as without the sleep; once it has been silent long enough the graph is
+// skipped (asleep), never before the tail has fallen below -96 dBFS; a hosted plugin node keeps the graph awake and keeps
+// being called; a loud input wakes the graph in the same block
+TEST (sleep190ts_patcher_graph_sleeps_after_the_tail_and_wakes_at_once)
+{
+    using namespace lynx;
+    std::shared_ptr<sleep190ts::CountingPlugin> plugin, unused;
+    const auto doc = sleep190ts::reverbDoc (false);
+    patcher::Graph sleeping (doc, 44100.0, sleep190ts::factories (unused)), reference (doc, 44100.0, sleep190ts::factories (unused));
+    sleeping.setStoppedSleep (true);
+    std::vector<float> a (256), b (256), c (256), d (256);
+    int lastLoud = -1, asleepAt = -1, firstDiff = -1;
+    for (int block = 0; block < 1400 && asleepAt < 0; ++block) // (~8 s)
+    {
+        for (int i = 0; i < 256; ++i)
+            a[(std::size_t) i] = b[(std::size_t) i] = c[(std::size_t) i] = d[(std::size_t) i]
+                = block < 20 ? 0.5f * std::sin (0.07f * (float) (block * 256 + i)) : 0.0f; // a burst, then silence
+        sleeping.process (a.data(), b.data(), nullptr, nullptr, a.data(), b.data(), 256, 120.0);
+        reference.process (c.data(), d.data(), nullptr, nullptr, c.data(), d.data(), 256, 120.0);
+        if (sleep190ts::peakOf (c, d) >= 1.5849e-5f)
+            lastLoud = block;
+        if (sleeping.asleep())
+            asleepAt = block;
+        if (firstDiff < 0 && ! (a == c && b == d))
+            firstDiff = block;
+    }
+    CHECK (firstDiff < 0 || firstDiff > lastLoud); // the very same samples while the tail can be heard
+    CHECK (lastLoud > 40);                 // the reverb's tail rang after the burst
+    CHECK (asleepAt > lastLoud);           // asleep only after it
+    CHECK (asleepAt >= 0 && asleepAt < 1400);
+    // a loud input: awake in that block, and it sounds
+    for (int i = 0; i < 256; ++i)
+        a[(std::size_t) i] = b[(std::size_t) i] = 0.5f * std::sin (0.07f * (float) i);
+    sleeping.process (a.data(), b.data(), nullptr, nullptr, a.data(), b.data(), 256, 120.0);
+    CHECK (! sleeping.asleep());
+    CHECK (sleep190ts::peakOf (a, b) > 0.01f);
+
+    // with a hosted plugin beside it: never asleep, and the plugin is called at every block
+    const auto withPlugin = sleep190ts::reverbDoc (true);
+    patcher::Graph g (withPlugin, 44100.0, sleep190ts::factories (plugin));
+    g.setStoppedSleep (true);
+    std::fill (a.begin(), a.end(), 0.0f);
+    std::fill (b.begin(), b.end(), 0.0f);
+    for (int block = 0; block < 1400; ++block)
+    {
+        g.process (a.data(), b.data(), nullptr, nullptr, a.data(), b.data(), 256, 120.0);
+        CHECK (! g.asleep());
+    }
+    CHECK (plugin != nullptr && plugin->processed == 1400L * 256);
+}
+
+// not allowed (playing, an export, any renderer that never says so): no node ever sleeps, the samples are the ones of a
+// graph that never heard of it, also after the sleep was allowed and taken back
+TEST (sleep190ts_patcher_graph_never_sleeps_unless_allowed)
+{
+    using namespace lynx;
+    std::shared_ptr<sleep190ts::CountingPlugin> unused;
+    const auto doc = sleep190ts::reverbDoc (false);
+    patcher::Graph g (doc, 44100.0, sleep190ts::factories (unused)), reference (doc, 44100.0, sleep190ts::factories (unused));
+    g.setStoppedSleep (true);
+    g.setStoppedSleep (false); // (playing again before anything slept)
+    std::vector<float> a (256), b (256), c (256), d (256);
+    bool identical = true;
+    for (int block = 0; block < 1400; ++block)
+    {
+        for (int i = 0; i < 256; ++i)
+            a[(std::size_t) i] = b[(std::size_t) i] = c[(std::size_t) i] = d[(std::size_t) i]
+                = block % 400 < 10 ? 0.4f * std::sin (0.03f * (float) (block * 256 + i)) : 0.0f;
+        g.process (a.data(), b.data(), nullptr, nullptr, a.data(), b.data(), 256, 120.0);
+        reference.process (c.data(), d.data(), nullptr, nullptr, c.data(), d.data(), 256, 120.0);
+        identical = identical && a == c && b == d;
+        CHECK (! g.asleep());
+    }
+    CHECK (identical);
+}
+
+// a generator Patcher (an instrument and a reverb inside): stopped, it reports idle once its notes and the reverb's tail
+// have ended (the rack then skips its channel); a note wakes it and plays
+TEST (sleep190ts_generator_patcher_idles_after_its_tail_and_a_note_plays)
+{
+    using namespace lynx;
+    ChannelDef ch;
+    ch.instrument = InstrumentKind::patcher;
+    PatchNode gen;
+    gen.generator = true;
+    gen.channel.instrument = InstrumentKind::synth; // (LYNX's own instrument: says idle when no voice sounds)
+    const auto g = patcher::addNode (ch.patcher, gen);
+    PatchNode fx;
+    fx.effect = makeEffectSlot (EffectKind::reeverb2);
+    const auto f = patcher::addNode (ch.patcher, fx);
+    PatchWire notes;
+    notes.kind = PatchWire::Kind::midi;
+    notes.from = patchFromHost;
+    notes.to = g;
+    ch.patcher.wires.push_back (notes);
+    PatchWire a;
+    a.from = g;
+    a.to = f;
+    ch.patcher.wires.push_back (a);
+    PatchWire o;
+    o.from = f;
+    o.to = patchToHost;
+    ch.patcher.wires.push_back (o);
+    auto inst = patcher::makeInstrument (ch, 44100.0, patcher::builtInFactories (44100.0));
+    CHECK (inst != nullptr);
+    if (inst == nullptr)
+        return;
+    inst->prepare (44100.0);
+    std::vector<float> l (256), r (256);
+    auto render = [&] {
+        std::fill (l.begin(), l.end(), 0.0f);
+        std::fill (r.begin(), r.end(), 0.0f);
+        inst->beginChunk (256);
+        inst->render (l.data(), r.data(), 256, 1.0f, 1.0f);
+        return sleep190ts::peakOf (l, r);
+    };
+    inst->setStoppedSleep (true);
+    inst->noteOn (60, 0.8f);
+    float loud = 0.0f;
+    for (int b = 0; b < 20; ++b)
+        loud = std::max (loud, render());
+    CHECK (loud > 0.01f);
+    inst->noteOff (60);
+    int idleAt = -1;
+    for (int b = 0; b < 1600 && idleAt < 0; ++b)
+    {
+        CHECK (! inst->idle() || b > 0);
+        render();
+        if (inst->idle())
+            idleAt = b;
+    }
+    CHECK (idleAt > 0);
+    inst->noteOn (64, 0.8f);
+    CHECK (! inst->idle());
+    loud = 0.0f;
+    for (int b = 0; b < 8; ++b)
+        loud = std::max (loud, render());
+    CHECK (loud > 0.01f);
+    // not allowed (the transport plays): never idle while the reverb rings, as before
+    inst->noteOff (64);
+    inst->setStoppedSleep (false);
+    for (int b = 0; b < 1600; ++b)
+    {
+        render();
+        CHECK (! inst->idle());
+    }
+}
+
+// the mixer: stopped, a silent insert's built-in effect stops being run after its hold; an analyser (Wave Candy) and a
+// hosted plugin keep running; playing (or a renderer never told to sleep) runs them all
+TEST (sleep190ts_mixer_built_ins_sleep_while_stopped_plugins_and_analysers_do_not)
+{
+    using namespace lynx;
+    Song song;
+    song.mixer = Song::defaultMixer (1);
+    auto plug = makeEffectSlot (EffectKind::plugin);
+    plug.plugin.id = "VST3-Counting";
+    song.mixer[1].effects = { makeEffectSlot (EffectKind::reeverb2), makeEffectSlot (EffectKind::waveCandy), plug };
+    for (auto& e : song.mixer[1].effects)
+        e.smartDisable = false; // (FL's per-slot smart disable off, as in most FL projects: only the stopped sleep acts)
+    std::shared_ptr<sleep190ts::CountingPlugin> plugin;
+    RackState::Factories f;
+    f.pluginEffects = [&] (const PluginRef&, double) -> std::shared_ptr<Effect> { return plugin = std::make_shared<sleep190ts::CountingPlugin>(); };
+    auto state = RackState::build (song, nullptr, 44100.0, f);
+    auto run = [&] (bool sleepAllowed, bool playing, std::array<std::uint64_t, 3>& late) {
+        RackRenderer renderer;
+        renderer.prepare (44100.0, 2048);
+        renderer.setProfiling (true);
+        renderer.setStoppedSleep (sleepAllowed);
+        std::vector<float> l (256), r (256);
+        const auto key = (std::size_t) 1 * maxEffectSlots;
+        std::array<std::uint64_t, 3> at6 {};
+        for (int block = 0; block < 1400; ++block) // (~8 s)
+        {
+            renderer.process (state.get(), playing, block * 256.0 * 0.01, 256, l.data(), r.data());
+            if (block == 1000)
+                for (std::size_t s = 0; s < 3; ++s)
+                    at6[s] = renderer.unitTimes().effectNs[key + s].load();
+        }
+        for (std::size_t s = 0; s < 3; ++s)
+            late[s] = renderer.unitTimes().effectNs[key + s].load() - at6[s]; // the last ~2.3 s
+    };
+    std::array<std::uint64_t, 3> stopped {}, notAllowed {}, playing {};
+    const auto calls0 = plugin->processed;
+    run (true, false, stopped);
+    CHECK (plugin->processed - calls0 == 1400L * 256); // the hosted plugin: every block
+    CHECK (stopped[0] == 0u);                          // the reverb: asleep
+    CHECK (stopped[1] > 0u);                           // Wave Candy: runs
+    run (false, false, notAllowed);
+    CHECK (notAllowed[0] > 0u && notAllowed[1] > 0u);
+    run (true, true, playing);
+    CHECK (playing[0] > 0u && playing[1] > 0u);
+}

+ 1 - 0
tests/tests.cpp

@@ -18254,5 +18254,6 @@ TEST (fl_low_lifter_matches_fl_engine)
 #include "CacheCheck190tgTests.inc" // round 190tg (0.1.33, QUEUE item 85): the disk caches' integrity check (core/CacheCheck.h)
 #include "Notes358_190tjTests.inc" // round 190tj (issue #358): the Notes window's texts (core/ItemNotes.h)
 #include "AutoTime190tkTests.inc" // round 190tk (0.1.33, QUEUE item 92): FL's automation timing for imported FL projects; the NewTick fix
+#include "Sleep190tsTests.inc" // round 190ts (0.1.33 block E): sleep while stopped (Patcher graphs, built-in effects)
 #include "MixFx190toTests.inc" // round 190to (0.1.33, QUEUE item 96): FL's per-insert effects switch; the Master's arm tap
 #include "UxTracks190tpTests.inc" // round 190tp (issues #365 / #366): the header drag that moves a track, Ctrl+V of copied files