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

Merge commit '141aee86f' into wip/rollup1111

Ka1-S пре 3 недеља
родитељ
комит
e49fd8a256

+ 1 - 0
CMakeLists.txt

@@ -433,6 +433,7 @@ if(LYNX_BUILD_APP)
         src/engine/PluginSandbox.cpp
         src/engine/PluginSandbox.cpp
         src/engine/SandboxWorker.cpp
         src/engine/SandboxWorker.cpp
         src/engine/Bridge32Test.cpp
         src/engine/Bridge32Test.cpp
+        src/engine/ClapTeardownTest.cpp
         src/engine/Exporter.cpp
         src/engine/Exporter.cpp
         src/engine/FlStudioExport.cpp
         src/engine/FlStudioExport.cpp
         src/engine/StreamPrefetcher.cpp
         src/engine/StreamPrefetcher.cpp

+ 2 - 0
scripts/build-windows-zig.sh

@@ -220,6 +220,8 @@ APP_SOURCES+=(src/core/LiveSession.cpp src/core/LiveCrypto.cpp src/engine/LiveLi
 APP_SOURCES+=(src/core/RemotePlugins.cpp src/engine/LiveRemotePlugins.cpp src/ui/LiveRemoteUi.cpp)
 APP_SOURCES+=(src/core/RemotePlugins.cpp src/engine/LiveRemotePlugins.cpp src/ui/LiveRemoteUi.cpp)
 # round 190c: the device-change and short-export self-tests (issues #134, #138)
 # round 190c: the device-change and short-export self-tests (issues #134, #138)
 APP_SOURCES+=(src/engine/DeviceChangeTest.cpp src/engine/ShortExportTest.cpp)
 APP_SOURCES+=(src/engine/DeviceChangeTest.cpp src/engine/ShortExportTest.cpp)
+# round 190az: a CLAP plugin deleted on another thread while the message thread is blocked
+APP_SOURCES+=(src/engine/ClapTeardownTest.cpp)
 # LYNX substitutes for missing third-party plugins (round 98)
 # LYNX substitutes for missing third-party plugins (round 98)
 APP_SOURCES+=(src/core/PluginSubstitutes.cpp)
 APP_SOURCES+=(src/core/PluginSubstitutes.cpp)
 # settings pages (General/Audio/MIDI), plugin manager, shortcut manager (round 82)
 # settings pages (General/Audio/MIDI), plugin manager, shortcut manager (round 82)

+ 15 - 0
src/Main.cpp

@@ -42,6 +42,8 @@
 #include "engine/PluginHost.h"
 #include "engine/PluginHost.h"
 #include "engine/PluginSandbox.h"
 #include "engine/PluginSandbox.h"
 #include "engine/Bridge32Test.h"
 #include "engine/Bridge32Test.h"
+#include "engine/ClapFormat.h"
+#include "engine/ClapTeardownTest.h"
 #include "engine/ProjectFile.h"
 #include "engine/ProjectFile.h"
 #include "core/Sha256.h"
 #include "core/Sha256.h"
 #include "engine/SessionPack.h"
 #include "engine/SessionPack.h"
@@ -1164,6 +1166,17 @@ public:
             return;
             return;
         }
         }
 
 
+        if (args.contains ("--clapteardowntest"))
+        {
+            // LYNX.exe --clapteardowntest "LYNX Test Restart.clap" report.txt (round 190az, engine/ClapTeardownTest.cpp)
+            const auto i = args.indexOf ("--clapteardowntest");
+            lynx::runClapTeardownTest (args[i + 1].unquoted(), args[i + 2].unquoted(), [this] (int code) {
+                setApplicationReturnValue (code);
+                quit();
+            });
+            return;
+        }
+
         if (args.contains ("--editortest"))
         if (args.contains ("--editortest"))
         {
         {
             // LYNX.exe --editortest plugin.vst3 report.txt ["name"]: opens the plugin's own editor in a window for a few
             // LYNX.exe --editortest plugin.vst3 report.txt ["name"]: opens the plugin's own editor in a window for a few
@@ -2332,6 +2345,8 @@ public:
         lynx::updater::shutdown(); // (a check or download in flight stops)
         lynx::updater::shutdown(); // (a check or download in flight stops)
         crashEngine = nullptr;
         crashEngine = nullptr;
         engine = nullptr;
         engine = nullptr;
+        // CLAP plugins whose instance another thread deleted while this one was busy: deactivated and destroyed now
+        lynx::ClapPluginFormat::finishPendingTeardowns();
         juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
         juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
         heartbeat.stopTimer();
         heartbeat.stopTimer();
         lynx::crashreporter::shutdown(); // (an upload in flight gets a moment, never long)
         lynx::crashreporter::shutdown(); // (an upload in flight gets a moment, never long)

+ 317 - 209
src/engine/ClapFormat.cpp

@@ -241,6 +241,154 @@ private:
 // --- plugin UI window ----------------------------------------------------------------
 // --- plugin UI window ----------------------------------------------------------------
 class ClapEditor;
 class ClapEditor;
 
 
+// --- what outlives the instance ---------------------------------------------------------
+// CLAP's threading rules (issue #46): deactivate and destroy belong on the main thread, stop_processing on an audio
+// thread, and a strict plugin (u-he's) aborts the whole process when a host breaks them. A ClapInstance can be
+// deleted on any thread (an export's thread drops the last reference to its rack), and the message thread may be
+// busy or blocked just then, for as long as it likes: it may even be waiting for that very thread. So what the plugin
+// needs until it is destroyed lives here, not in the instance: the plugin, its module, the clap_host_t it was created
+// with (the plugin may call it from deactivate / destroy) and the processing handshake. The instance's destructor
+// hands this block to the message thread and waits a moment for it; when the message thread does not answer, the
+// instance goes anyway and the plugin is deactivated and destroyed whenever the message thread is free again, or by
+// finishPendingTeardowns() when the application closes. Nothing here is ever called on another thread instead.
+class ClapInstance;
+
+struct ClapLife
+{
+    const clap_plugin_t* plugin = nullptr;
+    std::shared_ptr<ClapModule> module; // (released after destroy, on the message thread: the DLL's deinit too)
+    clap_host_t host {};
+    std::atomic<ClapInstance*> owner { nullptr }; // nullptr once the instance is gone
+    std::atomic<bool> active { false };            // (atomic: prepareToPlay reads it on the export's thread)
+    std::atomic<std::thread::id> audioThread {};
+    // gate: held by the block in progress, or by the main thread while it (de)activates (holdProcessing);
+    // processing: start_processing succeeded and stop_processing was not called yet
+    std::atomic<bool> restartPending { false }, gate { false }, stopRequest { false }, processing { false };
+    std::atomic<juce::uint32> lastBlockMs { 0 };
+    juce::WaitableEvent tornDown { true };
+
+    static bool isMessageThread()
+    {
+        auto* mm = juce::MessageManager::getInstanceWithoutCreating();
+        return mm == nullptr || mm->isThisTheMessageThread();
+    }
+
+    // CLAP's threading rules (issue #46: u-he plugins abort when they are broken): activate / deactivate on the main
+    // thread, start_processing / stop_processing on the audio thread, and never deactivate while processing. Main
+    // thread side: holds every block off (they output silence), has the audio thread call stop_processing at its next
+    // block when blocks are flowing, and waits for the block in progress to end. When no block comes (playback
+    // stopped, the export finished, the plugin is being deleted), the audio thread is idle: a short-lived thread then
+    // stands in for it (thread_check reports it as the audio thread while it calls stop_processing). Returns false,
+    // still holding the blocks off, when a block never ends (the plugin crashed inside process).
+    bool holdProcessing()
+    {
+        restartPending.store (true);
+        if (processing.load())
+        {
+            const auto now = juce::Time::getMillisecondCounter();
+            // blocks are flowing (on another thread: an offline render on this one is over): the next one stops it
+            if (now - lastBlockMs.load() < 250 && audioThread.load() != std::this_thread::get_id())
+            {
+                stopRequest.store (true);
+                while (processing.load() && juce::Time::getMillisecondCounter() - now < 500)
+                    std::this_thread::yield();
+            }
+        }
+
+        const auto start = juce::Time::getMillisecondCounter();
+        while (gate.exchange (true))
+        {
+            if (juce::Time::getMillisecondCounter() - start > 2000)
+            {
+                stopRequest.store (false);
+                return false;
+            }
+            std::this_thread::yield();
+        }
+        stopRequest.store (false);
+
+        if (processing.load()) // no block came: stop it from a stand-in audio thread
+        {
+            const auto previous = audioThread.load();
+            std::thread standIn ([this] {
+                audioThread.store (std::this_thread::get_id());
+                plugin->stop_processing (plugin);
+            });
+            standIn.join();
+            audioThread.store (previous);
+            processing.store (false);
+        }
+        return true;
+    }
+
+    // The message thread: stop_processing (by the stand-in audio thread), deactivate, destroy, then the module.
+    // (A plugin stuck inside process is not deactivated, as before: it is left alone.)
+    void tearDown()
+    {
+        if (plugin != nullptr)
+        {
+            if (active.load() && holdProcessing())
+                plugin->deactivate (plugin);
+            active.store (false);
+            plugin->destroy (plugin);
+            plugin = nullptr;
+        }
+        module = nullptr;
+        tornDown.signal();
+    }
+
+    // --- the teardowns waiting for the message thread --------------------------------------
+    struct Pending
+    {
+        std::mutex lock;
+        std::vector<std::shared_ptr<ClapLife>> list;
+        std::atomic<int> waitMs { 10000 };
+        std::atomic<int> deferred { 0 }; // how many the instance's destructor did not see finished (diagnostics, tests)
+    };
+    static Pending& pending()
+    {
+        static auto* p = new Pending(); // (never destroyed: a teardown may be queued while the process ends)
+        return *p;
+    }
+
+    // Runs every queued teardown; on the message thread only (anywhere else it does nothing).
+    static void drain()
+    {
+        if (! isMessageThread())
+            return;
+        for (;;)
+        {
+            std::vector<std::shared_ptr<ClapLife>> now;
+            {
+                const std::lock_guard<std::mutex> l (pending().lock);
+                now.swap (pending().list);
+            }
+            if (now.empty())
+                return;
+            for (auto& life : now)
+                life->tearDown();
+        }
+    }
+
+    // The end of an instance, on whatever thread deletes it.
+    static void finish (std::shared_ptr<ClapLife> life)
+    {
+        life->owner.store (nullptr);
+        if (isMessageThread())
+        {
+            life->tearDown();
+            return;
+        }
+        {
+            const std::lock_guard<std::mutex> l (pending().lock);
+            pending().list.push_back (life);
+        }
+        // (not posted: the message loop has ended, the application is closing and finishPendingTeardowns() runs it)
+        if (! juce::MessageManager::callAsync ([] { drain(); }) || ! life->tornDown.wait (pending().waitMs.load()))
+            ++pending().deferred;
+    }
+};
+
 // --- instance ------------------------------------------------------------------------
 // --- instance ------------------------------------------------------------------------
 class ClapInstance final : public juce::AudioPluginInstance
 class ClapInstance final : public juce::AudioPluginInstance
 {
 {
@@ -248,14 +396,17 @@ public:
     ClapInstance (std::shared_ptr<ClapModule> m, const clap_plugin_t* p, const juce::PluginDescription& d)
     ClapInstance (std::shared_ptr<ClapModule> m, const clap_plugin_t* p, const juce::PluginDescription& d)
         : AudioPluginInstance (busesFor (d)),
         : AudioPluginInstance (busesFor (d)),
           plugin (p),
           plugin (p),
-          module (std::move (m)),
           description (d)
           description (d)
     {
     {
+        life->module = std::move (m);
+        life->owner.store (this);
+        life->host = makeHost();
     }
     }
 
 
     // Second phase (needs `this` ready as host_data): init + extensions + parameters.
     // Second phase (needs `this` ready as host_data): init + extensions + parameters.
     bool initialise()
     bool initialise()
     {
     {
+        life->plugin = plugin;
         if (! plugin->init (plugin))
         if (! plugin->init (plugin))
             return false;
             return false;
 
 
@@ -313,75 +464,15 @@ public:
        #endif
        #endif
 
 
         // (stop_processing on an audio thread, never here: issue #46; a plugin stuck inside process is left alone).
         // (stop_processing on an audio thread, never here: issue #46; a plugin stuck inside process is left alone).
-        // Deleted on another thread: deactivate and destroy go to the message thread, which this waits for (done
-        // here only when the message thread does not answer in 10 s: it is blocked, and the plugin can't wait).
-        auto teardown = [this] {
-            if (active && holdProcessing())
-                plugin->deactivate (plugin);
-            if (plugin != nullptr)
-                plugin->destroy (plugin);
-        };
-        if (isMessageThread())
-            teardown();
-        else if (auto call = MainCall::post (teardown); ! call->waitOrCancel (10000))
-            teardown();
+        // Deleted on another thread: deactivate and destroy go to the message thread, which this waits a moment for;
+        // they are never done here instead (see ClapLife).
+        life->plugin = plugin;
+        ClapLife::finish (std::move (life));
     }
     }
 
 
-    // A call made on the message thread for another thread, which waits for it (CLAP: activate / deactivate on the
-    // main thread, issue #46).
-    struct MainCall
-    {
-        std::mutex lock;
-        bool started = false, cancelled = false;
-        juce::WaitableEvent done;
-        std::function<void()> fn;
-
-        static std::shared_ptr<MainCall> post (std::function<void()> fn)
-        {
-            auto call = std::make_shared<MainCall>();
-            call->fn = std::move (fn);
-            if (! juce::MessageManager::callAsync ([call] { call->run(); }))
-                call->run(); // (no message loop any more: here)
-            return call;
-        }
-
-        void run()
-        {
-            {
-                const std::lock_guard<std::mutex> l (lock);
-                if (cancelled)
-                    return;
-                started = true;
-            }
-            fn();
-            done.signal();
-        }
-
-        // true when it ran within timeoutMs, or was running then (waited for); false when it was cancelled unrun
-        bool waitOrCancel (int timeoutMs)
-        {
-            if (done.wait (timeoutMs))
-                return true;
-            {
-                const std::lock_guard<std::mutex> l (lock);
-                if (! started)
-                {
-                    cancelled = true;
-                    return false;
-                }
-            }
-            done.wait (-1);
-            return true;
-        }
-    };
-
-    static bool isMessageThread()
-    {
-        auto* mm = juce::MessageManager::getInstanceWithoutCreating();
-        return mm == nullptr || mm->isThisTheMessageThread();
-    }
+    static bool isMessageThread() { return ClapLife::isMessageThread(); }
 
 
-    static const clap_host_t* hostFor (ClapInstance* self) { return &self->host; }
+    static const clap_host_t* hostFor (ClapInstance* self) { return &self->life->host; }
 
 
     // --- AudioProcessor -------------------------------------------------------------
     // --- AudioProcessor -------------------------------------------------------------
     const juce::String getName() const override { return description.name; }
     const juce::String getName() const override { return description.name; }
@@ -400,7 +491,9 @@ public:
 
 
     // Runs fn here on the message thread; from another thread (an export at another rate or block size) on the
     // Runs fn here on the message thread; from another thread (an export at another rate or block size) on the
     // message thread, waiting up to 5 s for it. A message thread that doesn't answer in time is busy: fn then runs
     // message thread, waiting up to 5 s for it. A message thread that doesn't answer in time is busy: fn then runs
-    // when it gets there; until then the plugin keeps its current activation.
+    // when it gets there; until then the plugin keeps its current activation. With no message loop any more (the
+    // application is closing) fn does not run at all: activate / deactivate are never called on another thread
+    // (issue #46), and the teardown deactivates the plugin on the message thread.
     void onMessageThreadFor (std::function<void()> fn)
     void onMessageThreadFor (std::function<void()> fn)
     {
     {
         if (isMessageThread())
         if (isMessageThread())
@@ -408,10 +501,13 @@ public:
             fn();
             fn();
             return;
             return;
         }
         }
-        MainCall::post ([alive = alive, fn = std::move (fn)] {
-            if (*alive)
-                fn();
-        })->done.wait (5000);
+        auto done = std::make_shared<juce::WaitableEvent>();
+        if (juce::MessageManager::callAsync ([alive = alive, fn = std::move (fn), done] {
+                if (*alive)
+                    fn();
+                done->signal();
+            }))
+            done->wait (5000);
     }
     }
 
 
     // deactivates (when active) and activates the plugin again
     // deactivates (when active) and activates the plugin again
@@ -451,53 +547,7 @@ public:
         });
         });
     }
     }
 
 
-    // CLAP's threading rules (issue #46: u-he plugins abort when they are broken): activate / deactivate on the main
-    // thread, start_processing / stop_processing on the audio thread, and never deactivate while processing. Main
-    // thread side: holds every block off (they output silence), has the audio thread call stop_processing at its next
-    // block when blocks are flowing, and waits for the block in progress to end. When no block comes (playback
-    // stopped, the export finished, the plugin is being deleted), the audio thread is idle: a short-lived thread then
-    // stands in for it (thread_check reports it as the audio thread while it calls stop_processing). Returns false,
-    // still holding the blocks off, when a block never ends (the plugin crashed inside process).
-    bool holdProcessing()
-    {
-        restartPending.store (true);
-        if (processing.load())
-        {
-            const auto now = juce::Time::getMillisecondCounter();
-            // blocks are flowing (on another thread: an offline render on this one is over): the next one stops it
-            if (now - lastBlockMs.load() < 250 && audioThread.load() != std::this_thread::get_id())
-            {
-                stopRequest.store (true);
-                while (processing.load() && juce::Time::getMillisecondCounter() - now < 500)
-                    std::this_thread::yield();
-            }
-        }
-
-        const auto start = juce::Time::getMillisecondCounter();
-        while (gate.exchange (true))
-        {
-            if (juce::Time::getMillisecondCounter() - start > 2000)
-            {
-                stopRequest.store (false);
-                return false;
-            }
-            std::this_thread::yield();
-        }
-        stopRequest.store (false);
-
-        if (processing.load()) // no block came: stop it from a stand-in audio thread
-        {
-            const auto previous = audioThread.load();
-            std::thread standIn ([this] {
-                audioThread.store (std::this_thread::get_id());
-                plugin->stop_processing (plugin);
-            });
-            standIn.join();
-            audioThread.store (previous);
-            processing.store (false);
-        }
-        return true;
-    }
+    bool holdProcessing() { return life->holdProcessing(); } // (the handshake itself: ClapLife)
 
 
     void releaseProcessing()
     void releaseProcessing()
     {
     {
@@ -780,7 +830,10 @@ private:
     }
     }
 
 
     // --- the host as seen by the plugin -----------------------------------------------------
     // --- the host as seen by the plugin -----------------------------------------------------
-    static ClapInstance* from (const clap_host_t* h) { return static_cast<ClapInstance*> (h->host_data); }
+    // host_data is the ClapLife: the plugin may call its host until it is destroyed, which can be after the instance
+    // is gone (from: nullptr then; what needs no instance, the extension tables and thread_check, keeps answering)
+    static ClapLife* lifeOf (const clap_host_t* h) { return static_cast<ClapLife*> (h->host_data); }
+    static ClapInstance* from (const clap_host_t* h) { return lifeOf (h)->owner.load(); }
 
 
     void onMainThread (std::function<void()> fn)
     void onMainThread (std::function<void()> fn)
     {
     {
@@ -794,29 +847,30 @@ private:
     {
     {
         clap_host_t h {};
         clap_host_t h {};
         h.clap_version = CLAP_VERSION;
         h.clap_version = CLAP_VERSION;
-        h.host_data = this;
+        h.host_data = life.get();
         h.name = "LYNX";
         h.name = "LYNX";
         h.vendor = "LYNX";
         h.vendor = "LYNX";
         h.url = "";
         h.url = "";
         h.version = JUCE_APPLICATION_VERSION_STRING;
         h.version = JUCE_APPLICATION_VERSION_STRING;
-        h.get_extension = [] (const clap_host_t* hh, const char* id) -> const void* {
-            auto* self = from (hh);
-
-            if (std::strcmp (id, CLAP_EXT_LOG) == 0) return &self->hostLog;
-            if (std::strcmp (id, CLAP_EXT_THREAD_CHECK) == 0) return &self->hostThreadCheck;
-            if (std::strcmp (id, CLAP_EXT_PARAMS) == 0) return &self->hostParams;
-            if (std::strcmp (id, CLAP_EXT_STATE) == 0) return &self->hostState;
-            if (std::strcmp (id, CLAP_EXT_LATENCY) == 0) return &self->hostLatency;
-            if (std::strcmp (id, CLAP_EXT_GUI) == 0) return &self->hostGui;
-            if (std::strcmp (id, CLAP_EXT_TIMER_SUPPORT) == 0) return &self->hostTimers;
+        // (the tables belong to no instance: a plugin keeps the pointers it got for as long as it lives)
+        h.get_extension = [] (const clap_host_t*, const char* id) -> const void* {
+            if (std::strcmp (id, CLAP_EXT_LOG) == 0) return &hostLog();
+            if (std::strcmp (id, CLAP_EXT_THREAD_CHECK) == 0) return &hostThreadCheck();
+            if (std::strcmp (id, CLAP_EXT_PARAMS) == 0) return &hostParams();
+            if (std::strcmp (id, CLAP_EXT_STATE) == 0) return &hostState();
+            if (std::strcmp (id, CLAP_EXT_LATENCY) == 0) return &hostLatency();
+            if (std::strcmp (id, CLAP_EXT_GUI) == 0) return &hostGui();
+            if (std::strcmp (id, CLAP_EXT_TIMER_SUPPORT) == 0) return &hostTimers();
            #if JUCE_LINUX || JUCE_BSD
            #if JUCE_LINUX || JUCE_BSD
-            if (std::strcmp (id, CLAP_EXT_POSIX_FD_SUPPORT) == 0) return &self->hostFds;
+            if (std::strcmp (id, CLAP_EXT_POSIX_FD_SUPPORT) == 0) return &hostFds();
            #endif
            #endif
             return nullptr;
             return nullptr;
         };
         };
         h.request_restart = [] (const clap_host_t* hh) {
         h.request_restart = [] (const clap_host_t* hh) {
             // restart on the UI thread with the same settings (new latency, ports...)
             // restart on the UI thread with the same settings (new latency, ports...)
             auto* self = from (hh);
             auto* self = from (hh);
+            if (self == nullptr)
+                return;
             self->onMainThread ([self] {
             self->onMainThread ([self] {
                 // the rack calls processBlock directly (no callback lock), so suspendProcessing alone would not
                 // the rack calls processBlock directly (no callback lock), so suspendProcessing alone would not
                 // stop it: reactivate holds new blocks off, has the audio thread stop processing and waits for the
                 // stop it: reactivate holds new blocks off, has the audio thread stop processing and waits for the
@@ -827,20 +881,16 @@ private:
         };
         };
         h.request_process = [] (const clap_host_t*) {};
         h.request_process = [] (const clap_host_t*) {};
         h.request_callback = [] (const clap_host_t* hh) {
         h.request_callback = [] (const clap_host_t* hh) {
-            auto* self = from (hh);
-            self->onMainThread ([self] { self->plugin->on_main_thread (self->plugin); });
+            if (auto* self = from (hh))
+                self->onMainThread ([self] { self->plugin->on_main_thread (self->plugin); });
         };
         };
         return h;
         return h;
     }
     }
 
 
-    std::shared_ptr<ClapModule> module;
     juce::PluginDescription description;
     juce::PluginDescription description;
     std::shared_ptr<std::atomic<bool>> alive = std::make_shared<std::atomic<bool>> (true);
     std::shared_ptr<std::atomic<bool>> alive = std::make_shared<std::atomic<bool>> (true);
+    std::shared_ptr<ClapLife> life = std::make_shared<ClapLife>(); // (the host the plugin sees: outlives this)
 
 
-public:
-    clap_host_t host = makeHost();
-
-private:
     const clap_plugin_params_t* params = nullptr;
     const clap_plugin_params_t* params = nullptr;
     const clap_plugin_state_t* state = nullptr;
     const clap_plugin_state_t* state = nullptr;
     const clap_plugin_latency_t* latency = nullptr;
     const clap_plugin_latency_t* latency = nullptr;
@@ -848,8 +898,8 @@ private:
     bool midiDialect = false;
     bool midiDialect = false;
     bool initialised = false;
     bool initialised = false;
 
 
-    std::atomic<bool> active { false }; // (atomic: prepareToPlay reads them on the export's thread)
-    std::atomic<double> activeRate { 0.0 };
+    std::atomic<bool>& active = life->active;
+    std::atomic<double> activeRate { 0.0 }; // (atomic: prepareToPlay reads them on the export's thread)
     std::atomic<int> maxBlock { 0 };
     std::atomic<int> maxBlock { 0 };
     int inputChannels = 0, outputChannels = 2;
     int inputChannels = 0, outputChannels = 2;
     int64_t steadyTime = 0;
     int64_t steadyTime = 0;
@@ -858,23 +908,41 @@ private:
     ParamQueue pendingParams;
     ParamQueue pendingParams;
     std::unordered_map<clap_id, ClapParameter*> byId;
     std::unordered_map<clap_id, ClapParameter*> byId;
     std::array<bool, 16 * 128> heldNotes {};
     std::array<bool, 16 * 128> heldNotes {};
-    std::atomic<std::thread::id> audioThread {};
-    // gate: held by the block in progress, or by the main thread while it (de)activates (holdProcessing);
-    // processing: start_processing succeeded and stop_processing was not called yet
-    std::atomic<bool> restartPending { false }, gate { false }, stopRequest { false }, processing { false };
-    std::atomic<juce::uint32> lastBlockMs { 0 };
-
-    clap_host_log_t hostLog { [] (const clap_host_t*, clap_log_severity, const char* msg) { juce::ignoreUnused (msg); DBG ("CLAP: " << msg); } };
-    clap_host_thread_check_t hostThreadCheck {
-        [] (const clap_host_t*) { return juce::MessageManager::existsAndIsCurrentThread(); },
-        [] (const clap_host_t* hh) { return from (hh)->audioThread.load() == std::this_thread::get_id(); }
-    };
-    clap_host_params_t hostParams {
-        [] (const clap_host_t*, clap_param_rescan_flags) {},
-        [] (const clap_host_t*, clap_id, clap_param_clear_flags) {},
-        [] (const clap_host_t*) {}
-    };
-    clap_host_state_t hostState { [] (const clap_host_t*) {} };
+    // the processing handshake (ClapLife: the teardown needs it after this instance)
+    std::atomic<std::thread::id>& audioThread = life->audioThread;
+    std::atomic<bool>& restartPending = life->restartPending;
+    std::atomic<bool>& gate = life->gate;
+    std::atomic<bool>& stopRequest = life->stopRequest;
+    std::atomic<bool>& processing = life->processing;
+    std::atomic<juce::uint32>& lastBlockMs = life->lastBlockMs;
+
+    static const clap_host_log_t& hostLog()
+    {
+        static const clap_host_log_t e { [] (const clap_host_t*, clap_log_severity, const char* msg) { juce::ignoreUnused (msg); DBG ("CLAP: " << msg); } };
+        return e;
+    }
+    static const clap_host_thread_check_t& hostThreadCheck()
+    {
+        static const clap_host_thread_check_t e {
+            [] (const clap_host_t*) { return juce::MessageManager::existsAndIsCurrentThread(); },
+            [] (const clap_host_t* hh) { return lifeOf (hh)->audioThread.load() == std::this_thread::get_id(); }
+        };
+        return e;
+    }
+    static const clap_host_params_t& hostParams()
+    {
+        static const clap_host_params_t e {
+            [] (const clap_host_t*, clap_param_rescan_flags) {},
+            [] (const clap_host_t*, clap_id, clap_param_clear_flags) {},
+            [] (const clap_host_t*) {}
+        };
+        return e;
+    }
+    static const clap_host_state_t& hostState()
+    {
+        static const clap_host_state_t e { [] (const clap_host_t*) {} };
+        return e;
+    }
     // timer-support: plugin GUIs (on Linux above all) repaint and poll from host timers, on the main thread
     // timer-support: plugin GUIs (on Linux above all) repaint and poll from host timers, on the main thread
     struct PluginTimer final : juce::Timer
     struct PluginTimer final : juce::Timer
     {
     {
@@ -889,22 +957,27 @@ private:
     };
     };
     std::map<clap_id, std::unique_ptr<PluginTimer>> timers;
     std::map<clap_id, std::unique_ptr<PluginTimer>> timers;
     clap_id nextTimer = 1;
     clap_id nextTimer = 1;
-    clap_host_timer_support_t hostTimers {
-        [] (const clap_host_t* hh, uint32_t periodMs, clap_id* timerId) {
-            auto* self = from (hh);
-            if (timerId == nullptr || ! juce::MessageManager::existsAndIsCurrentThread())
-                return false;
-            const auto id = self->nextTimer++;
-            auto timer = std::make_unique<PluginTimer> (*self, id);
-            timer->startTimer ((int) juce::jlimit<uint32_t> (1, 10000, periodMs));
-            self->timers[id] = std::move (timer);
-            *timerId = id;
-            return true;
-        },
-        [] (const clap_host_t* hh, clap_id timerId) {
-            return from (hh)->timers.erase (timerId) > 0;
-        }
-    };
+    static const clap_host_timer_support_t& hostTimers()
+    {
+        static const clap_host_timer_support_t e {
+            [] (const clap_host_t* hh, uint32_t periodMs, clap_id* timerId) {
+                auto* self = from (hh);
+                if (self == nullptr || timerId == nullptr || ! juce::MessageManager::existsAndIsCurrentThread())
+                    return false;
+                const auto id = self->nextTimer++;
+                auto timer = std::make_unique<PluginTimer> (*self, id);
+                timer->startTimer ((int) juce::jlimit<uint32_t> (1, 10000, periodMs));
+                self->timers[id] = std::move (timer);
+                *timerId = id;
+                return true;
+            },
+            [] (const clap_host_t* hh, clap_id timerId) {
+                auto* self = from (hh); // (gone: its timers went with it)
+                return self != nullptr && self->timers.erase (timerId) > 0;
+            }
+        };
+        return e;
+    }
    #if JUCE_LINUX || JUCE_BSD
    #if JUCE_LINUX || JUCE_BSD
     // posix-fd-support: X11/Wayland plugin GUIs watch their own sockets through the host's event loop
     // posix-fd-support: X11/Wayland plugin GUIs watch their own sockets through the host's event loop
     std::vector<int> fds;
     std::vector<int> fds;
@@ -915,6 +988,8 @@ private:
     }
     }
     static bool watchFd (ClapInstance* self, int fd, clap_posix_fd_flags_t flags)
     static bool watchFd (ClapInstance* self, int fd, clap_posix_fd_flags_t flags)
     {
     {
+        if (self == nullptr)
+            return false;
         juce::LinuxEventLoop::unregisterFdCallback (fd);
         juce::LinuxEventLoop::unregisterFdCallback (fd);
         juce::LinuxEventLoop::registerFdCallback (fd, [self, flags] (int f) {
         juce::LinuxEventLoop::registerFdCallback (fd, [self, flags] (int f) {
             if (const auto* ext = static_cast<const clap_plugin_posix_fd_support_t*> (self->plugin->get_extension (self->plugin, CLAP_EXT_POSIX_FD_SUPPORT)))
             if (const auto* ext = static_cast<const clap_plugin_posix_fd_support_t*> (self->plugin->get_extension (self->plugin, CLAP_EXT_POSIX_FD_SUPPORT)))
@@ -924,45 +999,63 @@ private:
             self->fds.push_back (fd);
             self->fds.push_back (fd);
         return true;
         return true;
     }
     }
-    clap_host_posix_fd_support_t hostFds {
-        [] (const clap_host_t* hh, int fd, clap_posix_fd_flags_t flags) { return watchFd (from (hh), fd, flags); },
-        [] (const clap_host_t* hh, int fd, clap_posix_fd_flags_t flags) { return watchFd (from (hh), fd, flags); },
-        [] (const clap_host_t* hh, int fd) {
-            auto* self = from (hh);
-            juce::LinuxEventLoop::unregisterFdCallback (fd);
-            const auto it = std::find (self->fds.begin(), self->fds.end(), fd);
-            if (it == self->fds.end())
-                return false;
-            self->fds.erase (it);
-            return true;
-        }
-    };
+    static const clap_host_posix_fd_support_t& hostFds()
+    {
+        static const clap_host_posix_fd_support_t e {
+            [] (const clap_host_t* hh, int fd, clap_posix_fd_flags_t flags) { return watchFd (from (hh), fd, flags); },
+            [] (const clap_host_t* hh, int fd, clap_posix_fd_flags_t flags) { return watchFd (from (hh), fd, flags); },
+            [] (const clap_host_t* hh, int fd) {
+                auto* self = from (hh);
+                if (self == nullptr) // (gone: its descriptors were unregistered with it)
+                    return false;
+                juce::LinuxEventLoop::unregisterFdCallback (fd);
+                const auto it = std::find (self->fds.begin(), self->fds.end(), fd);
+                if (it == self->fds.end())
+                    return false;
+                self->fds.erase (it);
+                return true;
+            }
+        };
+        return e;
+    }
    #endif
    #endif
 
 
-    clap_host_latency_t hostLatency { [] (const clap_host_t* hh) {
-        auto* self = from (hh);
-        self->onMainThread ([self] {
-            if (self->latency != nullptr && self->active)
-                self->setLatencySamples ((int) self->latency->get (self->plugin));
-        });
-    } };
-    clap_host_gui_t hostGui {
-        [] (const clap_host_t*) {},
-        [] (const clap_host_t* hh, uint32_t w, uint32_t h) {
+    static const clap_host_latency_t& hostLatency()
+    {
+        static const clap_host_latency_t e { [] (const clap_host_t* hh) {
             auto* self = from (hh);
             auto* self = from (hh);
-            self->onMainThread ([self, w, h] {
-                if (auto* e = self->editor.getComponent())
-                {
-                    const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
-                    e->setSize (juce::roundToInt (w / scale), juce::roundToInt (h / scale));
-                }
+            if (self == nullptr)
+                return;
+            self->onMainThread ([self] {
+                if (self->latency != nullptr && self->active)
+                    self->setLatencySamples ((int) self->latency->get (self->plugin));
             });
             });
-            return true;
-        },
-        [] (const clap_host_t*) { return false; },
-        [] (const clap_host_t*) { return false; },
-        [] (const clap_host_t*, bool) {}
-    };
+        } };
+        return e;
+    }
+    static const clap_host_gui_t& hostGui()
+    {
+        static const clap_host_gui_t e {
+            [] (const clap_host_t*) {},
+            [] (const clap_host_t* hh, uint32_t w, uint32_t h) {
+                auto* self = from (hh);
+                if (self == nullptr)
+                    return false;
+                self->onMainThread ([self, w, h] {
+                    if (auto* e = self->editor.getComponent())
+                    {
+                        const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
+                        e->setSize (juce::roundToInt (w / scale), juce::roundToInt (h / scale));
+                    }
+                });
+                return true;
+            },
+            [] (const clap_host_t*) { return false; },
+            [] (const clap_host_t*) { return false; },
+            [] (const clap_host_t*, bool) {}
+        };
+        return e;
+    }
 };
 };
 
 
 void ClapParameter::setValue (float v)
 void ClapParameter::setValue (float v)
@@ -1166,6 +1259,21 @@ void ClapPluginFormat::createPluginInstance (const juce::PluginDescription& d, d
     callback (nullptr, juce::String::fromUTF8 ("plugin not found in file ") + d.fileOrIdentifier);
     callback (nullptr, juce::String::fromUTF8 ("plugin not found in file ") + d.fileOrIdentifier);
 }
 }
 
 
+// (a format goes with its plugin host: when that is on the message thread, nothing stays queued behind it)
+ClapPluginFormat::~ClapPluginFormat() { finishPendingTeardowns(); }
+
+void ClapPluginFormat::finishPendingTeardowns() { ClapLife::drain(); }
+
+int ClapPluginFormat::pendingTeardowns()
+{
+    const std::lock_guard<std::mutex> l (ClapLife::pending().lock);
+    return (int) ClapLife::pending().list.size();
+}
+
+int ClapPluginFormat::deferredTeardowns() { return ClapLife::pending().deferred.load(); }
+
+void ClapPluginFormat::setTeardownWaitMs (int ms) { ClapLife::pending().waitMs.store (juce::jmax (0, ms)); }
+
 void addPluginFormats (juce::AudioPluginFormatManager& manager)
 void addPluginFormats (juce::AudioPluginFormatManager& manager)
 {
 {
     manager.addDefaultFormats();
     manager.addDefaultFormats();

+ 13 - 0
src/engine/ClapFormat.h

@@ -31,6 +31,19 @@ public:
     juce::FileSearchPath getDefaultLocationsToSearch() override;
     juce::FileSearchPath getDefaultLocationsToSearch() override;
     bool requiresUnblockedMessageThreadDuringCreation (const juce::PluginDescription&) const override { return false; }
     bool requiresUnblockedMessageThreadDuringCreation (const juce::PluginDescription&) const override { return false; }
 
 
+    ~ClapPluginFormat() override;
+
+    // A CLAP instance deleted on another thread has its plugin deactivated and destroyed by the message thread (CLAP's
+    // threading rules, issue #46); the deleting thread waits a moment for that and then goes on. Teardowns the message
+    // thread has not run yet wait in a queue: it runs them when it is free again, and this runs them now. Call it on
+    // the message thread when the application closes, after the threads that may still hold plugins have ended (from
+    // any other thread it does nothing).
+    static void finishPendingTeardowns();
+    static int pendingTeardowns();  // how many wait for the message thread now
+    static int deferredTeardowns(); // how many the deleting thread ever went on without (diagnostics, tests)
+    // how long the deleting thread waits for the message thread (default 10 s; the tests shorten it)
+    static void setTeardownWaitMs (int ms);
+
 private:
 private:
     void createPluginInstance (const juce::PluginDescription&, double initialSampleRate, int initialBufferSize,
     void createPluginInstance (const juce::PluginDescription&, double initialSampleRate, int initialBufferSize,
                                PluginCreationCallback) override;
                                PluginCreationCallback) override;

+ 240 - 0
src/engine/ClapTeardownTest.cpp

@@ -0,0 +1,240 @@
+#include "engine/ClapTeardownTest.h"
+
+#include <atomic>
+#include <cstdlib>
+#include <memory>
+#include <optional>
+#include <thread>
+#include <vector>
+
+#include "engine/AudioEngine.h"
+#include "engine/ClapFormat.h"
+#include "engine/PluginHost.h"
+
+namespace lynx
+{
+namespace
+{
+struct TeardownTest : std::enable_shared_from_this<TeardownTest>
+{
+    // what the message thread does while the worker drops the plugin, and how the queued teardown then gets to run
+    enum class Kind
+    {
+        free,            // it runs its loop: the teardown is done while the worker waits for it
+        blockedThenLoop, // it joins the worker; afterwards it goes back to its loop, which runs the teardown
+        blockedThenExit  // it joins the worker; then what the application's shutdown calls runs the teardown
+    };
+    struct Round
+    {
+        Kind kind;
+        int waitMs; // how long the deleting thread waits for the message thread
+    };
+
+    juce::String pluginPath, reportPath, report;
+    juce::File counters;
+    std::function<void (int)> done;
+    std::vector<Round> rounds { { Kind::free, 10000 }, { Kind::blockedThenLoop, 300 }, { Kind::blockedThenExit, 300 }, { Kind::blockedThenLoop, 10000 } };
+    std::size_t next = 0;
+    bool ok = true;
+
+    // the round in progress
+    std::thread worker;
+    std::atomic<bool> dropped { false };
+    std::atomic<int> pendingAfterDrop { -1 };
+    std::atomic<double> dropMs { 0.0 };
+    int linesBefore = 0, deferredBefore = 0;
+    double loopSince = 0.0;
+
+    void fail (const juce::String& why)
+    {
+        report << "FAILED: " << why << "\n";
+        ok = false;
+    }
+
+    juce::StringArray lines() const
+    {
+        juce::StringArray out;
+        for (const auto& line : juce::StringArray::fromLines (counters.loadFileAsString()))
+            if (line.contains ("="))
+                out.add (line);
+        return out;
+    }
+
+    // A CLAP effect that is active and processing, held by this reference only: made and played by an engine (on the
+    // message thread), which is then closed; then prepared and given one more block, as a rack does.
+    std::shared_ptr<PluginEffect> runningPlugin()
+    {
+        auto engine = std::make_unique<AudioEngine> (false);
+        auto& host = engine->getPluginHost();
+        host.addPluginFile (juce::File (pluginPath));
+        std::optional<juce::PluginDescription> clap;
+        for (const auto& type : host.getKnownPlugins().getTypes())
+            if (type.pluginFormatName == ClapPluginFormat::formatName
+                && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
+                clap = type;
+        if (! clap)
+            return nullptr;
+        auto song = Song::makeDefault();
+        EffectSlot slot;
+        slot.kind = EffectKind::plugin;
+        slot.plugin.id = clap->createIdentifierString().toStdString();
+        slot.plugin.name = clap->name.toStdString();
+        slot.smartDisable = false;
+        song.mixer[0].effects = { slot };
+        engine->setSong (song);
+        engine->renderOffline (0.1, 48000.0);
+        auto effect = std::dynamic_pointer_cast<PluginEffect> (engine->getEffect (0, 0));
+        engine.reset();
+        if (effect == nullptr)
+            return nullptr;
+        auto& instance = effect->getInstance();
+        instance.prepareToPlay (48000.0, 512);
+        juce::AudioBuffer<float> buffer (2, 512);
+        juce::MidiBuffer midi;
+        buffer.clear();
+        instance.processBlock (buffer, midi);
+        return effect;
+    }
+
+    void start()
+    {
+        counters = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
+        counters.deleteFile();
+       #if JUCE_WINDOWS
+        _putenv_s ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8());
+       #else
+        setenv ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8(), 1);
+       #endif
+        runRound();
+    }
+
+    void runRound()
+    {
+        if (next >= rounds.size() || ! ok)
+            return finish();
+        const auto round = rounds[next];
+        auto effect = runningPlugin();
+        if (effect == nullptr)
+        {
+            fail ("no CLAP effect was loaded from the file");
+            return finish();
+        }
+        // (the engine that made it is closed: every instance but this one has written its line)
+        linesBefore = lines().size();
+        deferredBefore = ClapPluginFormat::deferredTeardowns();
+        ClapPluginFormat::setTeardownWaitMs (round.waitMs);
+        dropped = false;
+        pendingAfterDrop = -1;
+        worker = std::thread ([this, effect = std::move (effect)]() mutable {
+            const auto start = juce::Time::getMillisecondCounterHiRes();
+            effect.reset(); // the last reference: the plugin's instance is deleted here, on this thread
+            dropMs = juce::Time::getMillisecondCounterHiRes() - start;
+            pendingAfterDrop = ClapPluginFormat::pendingTeardowns();
+            dropped = true;
+        });
+
+        if (round.kind == Kind::free)
+            return waitForWorker();
+
+        // blocked on the thread that deletes the plugin: it can't have the message thread, however long it waits
+        worker.join();
+        const auto pendingNow = ClapPluginFormat::pendingTeardowns();
+        const auto linesNow = lines().size();
+        report << "round=" << (int) next + 1 << " kind=" << (round.kind == Kind::blockedThenLoop ? "blocked_then_loop" : "blocked_then_exit")
+               << " wait_ms=" << round.waitMs << " drop_ms=" << juce::String (dropMs.load(), 0) << " pending_after_drop=" << pendingAfterDrop.load()
+               << " pending_after_join=" << pendingNow << " destroyed_before_message_thread=" << linesNow - linesBefore << "\n";
+        if (pendingAfterDrop != 1 || pendingNow != 1)
+            fail ("the teardown was not left to the message thread");
+        if (linesNow != linesBefore)
+            fail ("the plugin was destroyed while the message thread was blocked");
+        if (ClapPluginFormat::deferredTeardowns() != deferredBefore + 1)
+            fail ("the deleting thread did not go on without the teardown");
+        if (round.kind == Kind::blockedThenExit)
+        {
+            ClapPluginFormat::finishPendingTeardowns(); // (what the application's shutdown calls)
+            return endRound();
+        }
+        loopSince = juce::Time::getMillisecondCounterHiRes();
+        waitForLoop();
+    }
+
+    // back in the message loop, which runs the queued teardown among whatever else piled up while it was blocked (a
+    // timer may well come first): it must be gone within 5 s
+    void waitForLoop()
+    {
+        const auto waited = juce::Time::getMillisecondCounterHiRes() - loopSince;
+        if (ClapPluginFormat::pendingTeardowns() != 0 && waited < 5000.0)
+        {
+            juce::Timer::callAfterDelay (10, [self = shared_from_this()] { self->waitForLoop(); });
+            return;
+        }
+        report << "torn_down_by_loop_after_ms=" << juce::String (waited, 0) << "\n";
+        endRound();
+    }
+
+    void waitForWorker()
+    {
+        if (! dropped)
+        {
+            juce::Timer::callAfterDelay (20, [self = shared_from_this()] { self->waitForWorker(); });
+            return;
+        }
+        worker.join();
+        report << "round=" << (int) next + 1 << " kind=free wait_ms=" << rounds[next].waitMs << " drop_ms=" << juce::String (dropMs.load(), 0)
+               << " pending_after_drop=" << pendingAfterDrop.load() << "\n";
+        if (pendingAfterDrop != 0 || ClapPluginFormat::deferredTeardowns() != deferredBefore)
+            fail ("a free message thread did not run the teardown while the deleting thread waited");
+        endRound();
+    }
+
+    // the teardown has run: one more instance line, written by a plugin that was stopped, deactivated and destroyed
+    // in order and on the right threads (it would have aborted the process otherwise)
+    void endRound()
+    {
+        const auto now = lines();
+        if (ClapPluginFormat::pendingTeardowns() != 0)
+            fail ("a teardown is still queued");
+        if (now.size() != linesBefore + 1)
+            fail ("the plugin was not destroyed (instance lines: " + juce::String (now.size()) + ", expected " + juce::String (linesBefore + 1) + ")");
+        else
+        {
+            const auto line = now[now.size() - 1];
+            report << "instance: " << line << "\n";
+            juce::StringPairArray values;
+            for (const auto& token : juce::StringArray::fromTokens (line, " ", ""))
+                if (token.contains ("="))
+                    values.set (token.upToFirstOccurrenceOf ("=", false, false), token.fromFirstOccurrenceOf ("=", false, false));
+            if (values["wrong_thread"].getIntValue() != 0 || values["misordered"].getIntValue() != 0)
+                fail ("a call on the wrong thread or out of order");
+            if (values["starts"].getIntValue() < 1 || values["starts"].getIntValue() != values["stops"].getIntValue())
+                fail ("start_processing without its stop_processing");
+            if (values["activations"].getIntValue() < 1 || values["activations"].getIntValue() != values["deactivations"].getIntValue())
+                fail ("activate without its deactivate");
+        }
+        ++next;
+        juce::Timer::callAfterDelay (10, [self = shared_from_this()] { self->runRound(); });
+    }
+
+    void finish()
+    {
+        ClapPluginFormat::setTeardownWaitMs (10000);
+        report << "instances=" << lines().size() << "\nplugin_crashes=" << pluginCrashCount() << "\n";
+        if (pluginCrashCount() != 0)
+            ok = false;
+        report << "result=" << (ok ? "OK" : "FAILED") << "\n";
+        juce::File (reportPath).replaceWithText (report);
+        if (done)
+            done (ok ? 0 : 1);
+    }
+};
+} // namespace
+
+void runClapTeardownTest (const juce::String& pluginPath, const juce::String& reportPath, std::function<void (int)> done)
+{
+    auto test = std::make_shared<TeardownTest>();
+    test->pluginPath = pluginPath;
+    test->reportPath = reportPath;
+    test->done = std::move (done);
+    juce::Timer::callAfterDelay (10, [test] { test->start(); });
+}
+} // namespace lynx

+ 16 - 0
src/engine/ClapTeardownTest.h

@@ -0,0 +1,16 @@
+#pragma once
+
+#include <functional>
+
+#include <juce_core/juce_core.h>
+
+namespace lynx
+{
+// LYNX.exe --clapteardowntest "LYNX Test Restart.clap" report.txt (round 190az, tools/testplugin/lynx_test_restart.c):
+// the last reference to a running CLAP plugin is dropped on a worker thread while the message thread is blocked on
+// that very thread (what an export's thread and the thread that joins it do), and while it is free. The plugin aborts
+// the process when deactivate or destroy reach it off the main thread, or stop_processing off an audio thread, so the
+// host must leave the teardown to the message thread however long that takes, and nothing may be left over when the
+// application closes. Runs on the message loop; done (exit code, 0 = OK) is called when it has ended.
+void runClapTeardownTest (const juce::String& pluginPath, const juce::String& reportPath, std::function<void (int)> done);
+} // namespace lynx

+ 6 - 1
tools/testplugin/lynx_test_restart.c

@@ -11,7 +11,9 @@
  * stop_processing run on the audio thread and activate / deactivate on the main thread, and aborts the process
  * stop_processing run on the audio thread and activate / deactivate on the main thread, and aborts the process
  * when they don't ("Host called the method clap_plugin.stop_processing() on wrong thread!"). Deactivate while
  * when they don't ("Host called the method clap_plugin.stop_processing() on wrong thread!"). Deactivate while
  * processing and start / stop out of order are counted (misordered). The last activation's rate and block size
  * processing and start / stop out of order are counted (misordered). The last activation's rate and block size
- * are reported (last_rate, last_block).
+ * are reported (last_rate, last_block). destroy must come on the main thread too (round 190az,
+ * LYNX.exe --clapteardowntest "LYNX Test Restart.clap" report.txt): the checks ask the host it was created with, so
+ * that host must still answer when the plugin is torn down after the host's own instance object.
  */
  */
 #include <clap/clap.h>
 #include <clap/clap.h>
 #include <stdatomic.h>
 #include <stdatomic.h>
@@ -88,6 +90,9 @@ static bool p_init (const clap_plugin_t* p)
 static void p_destroy (const clap_plugin_t* p)
 static void p_destroy (const clap_plugin_t* p)
 {
 {
     Restart* r = self (p);
     Restart* r = self (p);
+    if (! on_thread (r, 1))
+        atomic_fetch_add (&r->wrongThread, 1);
+    must_be_on (r, 1, "destroy"); /* (round 190az: [main-thread & !active], also when the host's instance is long gone) */
     if (atomic_load (&r->processing) != 0 || atomic_load (&r->active) != 0)
     if (atomic_load (&r->processing) != 0 || atomic_load (&r->active) != 0)
         atomic_fetch_add (&r->misordered, 1); /* destroyed while active or processing */
         atomic_fetch_add (&r->misordered, 1); /* destroyed while active or processing */
     const char* path = getenv ("LYNX_TEST_RESTART_REPORT");
     const char* path = getenv ("LYNX_TEST_RESTART_REPORT");