-
-
Notifications
You must be signed in to change notification settings - Fork 136
Expand file tree
/
Copy pathpluginmanager.cpp
More file actions
1611 lines (1358 loc) · 48.4 KB
/
Copy pathpluginmanager.cpp
File metadata and controls
1611 lines (1358 loc) · 48.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014-2023 Kushview, LLC <info@kushview.net>
// SPDX-License-Identifier: GPL-3.0-or-later
#include <array>
#include <thread>
#include <element/datapath.hpp>
#include <element/node.hpp>
#include <element/nodefactory.hpp>
#include <element/plugins.hpp>
#include <element/settings.hpp>
#include "engine/clapprovider.hpp"
#include "engine/ionode.hpp"
#include "nodes/nodetypes.hpp"
#include "utils.hpp"
#define EL_DEAD_AUDIO_PLUGINS_FILENAME "scanner/crashed.txt"
#define EL_PLUGIN_SCANNER_SLAVE_LIST_PATH "scanner/list.xml"
#define EL_PLUGIN_SCANNER_WAITING_STATE "waiting"
#define EL_PLUGIN_SCANNER_READY_STATE "ready"
#define EL_PLUGIN_SCANNER_READY_ID "ready"
#define EL_PLUGIN_SCANNER_START_ID "start"
#define EL_PLUGIN_SCANNER_FINISHED_ID "finished"
#define EL_PLUGIN_SCANNER_PROGRESS_ID "progress"
#define EL_PLUGIN_SCANNER_DEFAULT_TIMEOUT 24000 // 24 Seconds
#include <errno.h>
extern char* program_invocation_name;
#if JUCE_WINDOWS
#define WIN32_LEAN_AND_MEAN
#include <process.h>
#include <windows.h>
#else
#include <signal.h>
#include <unistd.h>
#endif
namespace element {
using namespace juce;
namespace detail {
static const char* pluginListKey() { return Settings::pluginListKey; }
/* noop. prevent OS error dialogs from child process */
static void pluginScannerCrashHandler (void*) {}
static File pluginsXmlFile() { return DataPath::applicationDataDir().getChildFile ("plugins.xml"); }
static File pluginMetadataXmlFile() { return DataPath::applicationDataDir().getChildFile ("plugin-metadata.xml"); }
static FileSearchPath readSearchPath (const PropertiesFile& props, const String& f)
{
const auto key = String (Settings::lastPluginScanPathPrefix) + f;
FileSearchPath sp (props.getValue (key));
return sp;
}
static File scannerExeFullPath()
{
auto scannerExe = File::getSpecialLocation (File::currentExecutableFile);
#if JUCE_LINUX
if (! scannerExe.existsAsFile())
{
std::array<char, PATH_MAX> path {};
const ssize_t len = readlink ("/proc/self/exe", path.data(), PATH_MAX - 1);
if (len > 0)
{
path[static_cast<size_t> (len)] = '\0';
scannerExe = File (String (path.data()));
}
}
#endif
return scannerExe;
}
static juce::StringArray readDeadMansPedalFile()
{
const auto file = DataPath::applicationDataDir().getChildFile (EL_DEAD_AUDIO_PLUGINS_FILENAME);
StringArray lines;
file.readLines (lines);
lines.removeEmptyStrings();
return lines;
}
static void setDeadMansPedalFile (const StringArray& newContents)
{
auto deadMansPedalFile = DataPath::applicationDataDir().getChildFile (EL_DEAD_AUDIO_PLUGINS_FILENAME);
if (deadMansPedalFile.isDirectory())
deadMansPedalFile.deleteRecursively();
if (! deadMansPedalFile.exists())
deadMansPedalFile.create();
if (deadMansPedalFile.existsAsFile() && deadMansPedalFile.getFullPathName().isNotEmpty())
deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
}
static void applyBlacklistingsFromDeadMansPedal (KnownPluginList& list)
{
// If any plugins have crashed recently when being loaded, move them to the
// end of the list to give the others a chance to load correctly..
for (auto& crashedPlugin : readDeadMansPedalFile())
list.addToBlacklist (crashedPlugin);
}
static juce::int64 currentProcessId()
{
#if JUCE_WINDOWS
return static_cast<juce::int64> (_getpid());
#else
return static_cast<juce::int64> (getpid());
#endif
}
/** Forcibly terminates a process by ID. Used as a last resort on scanner
workers that a misbehaving plugin has left unable to exit on their own
(e.g. a load that never returns while holding the dynamic linker lock). */
static void terminateProcess (juce::int64 pid)
{
if (pid <= 0)
return;
#if JUCE_WINDOWS
if (auto handle = OpenProcess (PROCESS_TERMINATE, FALSE, static_cast<DWORD> (pid)))
{
TerminateProcess (handle, 1);
CloseHandle (handle);
}
#else
::kill (static_cast<pid_t> (pid), SIGKILL);
#endif
}
} // namespace detail
//==============================================================================
class PluginScannerCoordinator : public juce::ChildProcessCoordinator,
public std::enable_shared_from_this<PluginScannerCoordinator>
{
public:
explicit PluginScannerCoordinator (PluginScanner& o)
: owner (o) {}
~PluginScannerCoordinator() {}
bool isLaunched() const noexcept { return launched.load(); }
/** Launches the worker process. Must be called on a shared_ptr managed
instance. launchWorkerProcess uses ChildProcessManager on Linux which
is only safe on the message thread, so the launch is marshalled there
when called from the scan thread.
@param timeoutMs IPC ping timeout handed to the worker connection
@param abortCheck polled while waiting; return true to abandon
@return true if the worker process launched and connected
*/
bool launch (int timeoutMs, std::function<bool()> abortCheck)
{
auto scannerExe = owner.scannerExeFile();
if (! scannerExe.existsAsFile())
{
Logger::writeToLog ("Failed to launch plugin scanner: exe not found.");
return false;
}
auto doLaunch = [this, scannerExe, timeoutMs]() -> bool {
Logger::writeToLog (String ("launching plugin scanner: ") + scannerExe.getFullPathName());
return launchWorkerProcess (scannerExe, EL_PLUGIN_SCANNER_PROCESS_ID, timeoutMs, 0);
};
if (MessageManager::getInstance()->isThisTheMessageThread())
{
if (! doLaunch())
return false;
if (! waitForWorkerReady (timeoutMs, abortCheck))
{
killWorkerProcess();
return false;
}
return launched = true;
}
struct LaunchState
{
juce::WaitableEvent done;
std::atomic<bool> ok { false };
};
auto state = std::make_shared<LaunchState>();
MessageManager::callAsync ([state, weak = std::weak_ptr<PluginScannerCoordinator> (shared_from_this()), doLaunch]() {
if (auto self = weak.lock())
state->ok = doLaunch();
state->done.signal();
});
const auto deadline = Time::getMillisecondCounter() + static_cast<uint32> (timeoutMs) + 5000;
while (! state->done.wait (50))
if (abortCheck() || Time::getMillisecondCounter() > deadline)
return false;
if (! state->ok.load())
return false;
// The pipe exists as soon as the process starts, so wait for the
// worker's ready handshake to confirm it actually connected. A lost
// connection after this point means the scanned plugin took the
// worker down; before it, the scanner itself is unavailable.
if (! waitForWorkerReady (timeoutMs, abortCheck))
{
killWorkerProcess(); // safe: launchWorkerProcess has completed
return false;
}
return launched = true;
}
enum class State
{
timeout,
gotResult,
progress,
connectionLost,
};
struct Response
{
State state;
std::unique_ptr<XmlElement> xml;
};
Response getResponse()
{
std::unique_lock<std::mutex> lock { mutex };
if (! condvar.wait_for (lock, std::chrono::milliseconds { 50 }, [&] { return gotResult || gotProgress || connectionLost; }))
return { State::timeout, nullptr };
if (connectionLost)
{
connectionLost = false;
gotResult = gotProgress = false;
return { State::connectionLost, nullptr };
}
if (gotResult)
{
gotResult = gotProgress = false;
return { State::gotResult, std::move (pluginDescription) };
}
gotProgress = false;
return { State::progress, nullptr };
}
void handleMessageFromWorker (const MemoryBlock& mb) override
{
const std::lock_guard<std::mutex> lock { mutex };
const auto message = mb.toString();
if (message.startsWith (EL_PLUGIN_SCANNER_READY_ID))
{
// "ready:<pid>" — the pid enables force-killing a hung worker.
workerPid = message.fromFirstOccurrenceOf (":", false, false).getLargeIntValue();
workerReady = true;
condvar.notify_one();
return;
}
if (message.startsWith (EL_PLUGIN_SCANNER_PROGRESS_ID))
{
// Heartbeat sent while the worker is still inside a single,
// possibly slow findAllTypesForFile call (e.g. a VST3 shell
// plugin enumerating many housed sub-plugins).
gotProgress = true;
condvar.notify_one();
return;
}
pluginDescription = juce::parseXML (message);
gotResult = true;
condvar.notify_one();
}
/** Kills the worker connection and forcibly terminates the worker
process. A worker hung inside a plugin's load code cannot process the
kill message or exit on its own, so the OS process must be killed. */
void terminateWorkerProcess()
{
killWorkerProcess();
detail::terminateProcess (workerPid.exchange (0));
}
void handleConnectionLost() override
{
const std::lock_guard<std::mutex> lock { mutex };
connectionLost = true;
condvar.notify_one();
}
private:
PluginScanner& owner;
std::mutex mutex;
std::condition_variable condvar;
std::unique_ptr<XmlElement> pluginDescription;
bool connectionLost = false;
bool gotResult = false;
bool gotProgress = false;
bool workerReady = false;
std::atomic<bool> launched { false };
std::atomic<juce::int64> workerPid { 0 };
bool waitForWorkerReady (int timeoutMs, const std::function<bool()>& abortCheck)
{
const auto deadline = Time::getMillisecondCounter() + static_cast<uint32> (timeoutMs);
std::unique_lock<std::mutex> lock { mutex };
for (;;)
{
if (condvar.wait_for (lock, std::chrono::milliseconds { 50 }, [&] { return workerReady || connectionLost; }))
{
if (workerReady)
return true;
connectionLost = false; // consumed here: launch failure, not a crash
return false;
}
if (abortCheck() || Time::getMillisecondCounter() >= deadline)
return false;
}
}
};
//==============================================================================
class PluginScannerWorker : public juce::ChildProcessWorker,
public juce::AsyncUpdater
{
public:
PluginScannerWorker()
{
SystemStats::setApplicationCrashHandler (detail::pluginScannerCrashHandler);
auto logfile = DataPath::applicationDataDir().getChildFile ("log/scanner.log");
logfile.create();
logger = std::make_unique<juce::FileLogger> (logfile, "Plugin Scanner");
Logger::setCurrentLogger (logger.get());
}
~PluginScannerWorker()
{
Logger::setCurrentLogger (nullptr);
}
void handleMessageFromCoordinator (const MemoryBlock& mb) override
{
if (mb.isEmpty())
return;
const std::lock_guard<std::mutex> lock (mutex);
if (const auto results = doScan (mb); ! results.isEmpty())
{
sendResults (results);
}
else
{
pendingBlocks.emplace (mb);
triggerAsyncUpdate();
}
}
void handleAsyncUpdate() override
{
for (;;)
{
const std::lock_guard<std::mutex> lock (mutex);
if (pendingBlocks.empty())
return;
sendResults (doScan (pendingBlocks.front()));
pendingBlocks.pop();
}
}
OwnedArray<PluginDescription> doScan (const MemoryBlock& block)
{
MemoryInputStream stream { block, false };
const auto formatName = stream.readString();
const auto identifier = stream.readString();
String msg = "scan: ";
msg << formatName << ": " << identifier;
logger->logMessage (msg);
return nullptr == plugins->getAudioPluginFormat (formatName)
? scanProvider (formatName, identifier)
: scanJuce (formatName, identifier);
}
OwnedArray<PluginDescription> scanJuce (const String& formatName, const String& identifier)
{
PluginDescription pd;
pd.pluginFormatName = formatName;
pd.fileOrIdentifier = identifier;
pd.uniqueId = pd.deprecatedUid = 0;
const auto matchingFormat = plugins->getAudioPluginFormat (formatName);
OwnedArray<PluginDescription> results;
if (matchingFormat != nullptr
&& (MessageManager::getInstance()->isThisTheMessageThread()
|| matchingFormat->requiresUnblockedMessageThreadDuringCreation (pd)))
{
// findAllTypesForFile can block for a long time with no feedback
// in between (e.g. a VST3 shell plugin such as WaveShell
// enumerating many housed sub-plugins), so send heartbeats to
// let the coordinator tell a slow scan from a wedged one.
std::mutex hbMutex;
std::condition_variable hbCondvar;
bool scanning = true;
std::thread heartbeat ([this, &hbMutex, &hbCondvar, &scanning] {
std::unique_lock<std::mutex> lock { hbMutex };
while (! hbCondvar.wait_for (lock, std::chrono::seconds (1), [&] { return ! scanning; }))
{
const String msg (EL_PLUGIN_SCANNER_PROGRESS_ID);
sendMessageToCoordinator ({ msg.toRawUTF8(), msg.getNumBytesAsUTF8() });
}
});
matchingFormat->findAllTypesForFile (results, identifier);
{
const std::lock_guard<std::mutex> lock { hbMutex };
scanning = false;
}
hbCondvar.notify_one();
heartbeat.join();
}
return results;
}
OwnedArray<PluginDescription> scanProvider (const String& format, const String& ID)
{
auto& nodes = plugins->getNodeFactory();
OwnedArray<PluginDescription> results;
for (auto* p : nodes.providers())
{
if (p->format() != format)
continue;
#if 0
if (auto inst = p->create (ID))
{
auto d = results.add (new PluginDescription());
inst->getPluginDescription (*d);
}
#else
p->scan (ID, results);
#endif
break;
}
return results;
}
void sendResults (const OwnedArray<PluginDescription>& results)
{
XmlElement xml ("LIST");
for (const auto& desc : results)
xml.addChildElement (desc->createXml().release());
const auto str = xml.toString();
sendMessageToCoordinator ({ str.toRawUTF8(), str.getNumBytesAsUTF8() });
}
void handleConnectionMade() override
{
logger->logMessage ("[scanner] connection to coordinator established");
logger->logMessage ("[scanner] creating global objects");
settings = std::make_unique<Settings>();
plugins = std::make_unique<PluginManager>();
logger->logMessage ("[scanner] setting up formats");
auto& nf = plugins->getNodeFactory();
nf.add (new CLAPProvider());
plugins->addDefaultFormats();
plugins->setPlayConfig (48000.0, 1024);
logger->logMessage ("[scanner] ready");
const auto msg = String (EL_PLUGIN_SCANNER_READY_ID) + ":" + String (detail::currentProcessId());
sendMessageToCoordinator ({ msg.toRawUTF8(), msg.getNumBytesAsUTF8() });
}
void handleConnectionLost() override
{
logger->logMessage ("[scanner] connection lost");
logger.reset();
settings = nullptr;
plugins = nullptr;
JUCEApplication::quit();
}
private:
std::unique_ptr<Settings> settings;
std::unique_ptr<PluginManager> plugins;
std::mutex mutex;
std::queue<MemoryBlock> pendingBlocks;
std::unique_ptr<juce::FileLogger> logger;
};
//==============================================================================
PluginScanner::PluginScanner (PluginManager& manager)
: juce::Thread ("elscan"),
_manager (manager),
list (manager.getKnownPlugins()),
_scannerExe (detail::scannerExeFullPath()),
launchTimeoutMs (EL_PLUGIN_SCANNER_DEFAULT_TIMEOUT)
{
// Force-create the master weak reference on this thread so copies made
// from the scan thread never race its lazy initialization.
juce::WeakReference<PluginScanner> (this);
}
PluginScanner::~PluginScanner()
{
cancel();
stopThread (5000);
masterReference.clear();
listeners.clear();
superprocess.reset();
}
void PluginScanner::cancel()
{
cancelFlag = 1;
}
bool PluginScanner::isScanning() const { return scanning.load(); }
bool PluginScanner::shouldAbort() const noexcept
{
return cancelFlag.get() != 0 || threadShouldExit();
}
bool PluginScanner::waitForScanToFinish (int timeoutMs)
{
const auto deadline = Time::getMillisecondCounter() + static_cast<uint32> (timeoutMs);
const bool onMessageThread = MessageManager::getInstance()->isThisTheMessageThread();
while (isScanning())
{
if (Time::getMillisecondCounter() >= deadline)
return false;
if (onMessageThread)
MessageManager::getInstance()->runDispatchLoopUntil (20);
else
Thread::sleep (20);
}
// Deliver the queued audioPluginScanFinished callback.
if (onMessageThread)
MessageManager::getInstance()->runDispatchLoopUntil (20);
return true;
}
juce::String PluginScanner::getLastScanError() const
{
ScopedLock sl (stateLock);
return lastScanError;
}
void PluginScanner::resetWorker (bool alsoKill)
{
if (superprocess != nullptr && alsoKill && superprocess->isLaunched())
superprocess->terminateWorkerProcess();
superprocess.reset();
}
void PluginScanner::notifyOnMessageThread (std::function<void (PluginScanner&)> fn)
{
MessageManager::callAsync ([weak = juce::WeakReference<PluginScanner> (this), fn = std::move (fn)]() {
if (auto* self = weak.get())
fn (*self);
});
}
PluginScanner::ScanResult PluginScanner::retrieveDescriptions (const String& formatName,
const String& fileOrIdentifier,
OwnedArray<PluginDescription>& result)
{
if (superprocess == nullptr)
{
superprocess = std::make_shared<PluginScannerCoordinator> (*this);
if (! superprocess->launch (launchTimeoutMs, [this]() { return shouldAbort(); }))
{
// Don't kill: an abandoned launch may still be in flight on the
// message thread. Dropping the reference is enough.
resetWorker (false);
return shouldAbort() ? ScanResult::cancelled : ScanResult::unavailable;
}
}
MemoryBlock block;
MemoryOutputStream stream { block, true };
stream.writeString (formatName);
stream.writeString (fileOrIdentifier);
if (! superprocess->sendMessageToWorker (block))
{
resetWorker (true);
return ScanResult::unavailable;
}
using State = PluginScannerCoordinator::State;
auto deadline = Time::getMillisecondCounter() + static_cast<uint32> (perPluginTimeoutMs);
for (;;)
{
if (shouldAbort())
return ScanResult::cancelled;
const auto response = superprocess->getResponse();
if (response.state == State::timeout)
{
if (Time::getMillisecondCounter() >= deadline)
{
Logger::writeToLog (String ("plugin scan timed out: ") + fileOrIdentifier);
resetWorker (true);
return ScanResult::crashed;
}
continue;
}
if (response.state == State::progress)
{
// The worker is still alive and working on this plugin, so
// push the deadline out rather than treating it as wedged.
deadline = Time::getMillisecondCounter() + static_cast<uint32> (perPluginTimeoutMs);
notifyOnMessageThread ([name = File::createFileWithoutCheckingPath (fileOrIdentifier).getFileName()] (PluginScanner& s) {
s.listeners.call (&Listener::audioPluginScanStarted, name + "…");
});
continue;
}
if (response.state == State::connectionLost)
{
Logger::writeToLog (String ("plugin scanner crashed on: ") + fileOrIdentifier);
resetWorker (true);
return ScanResult::crashed;
}
if (response.xml != nullptr)
{
for (const auto* item : response.xml->getChildIterator())
{
auto desc = std::make_unique<PluginDescription>();
if (desc->loadFromXml (*item))
result.add (std::move (desc));
}
}
return ScanResult::ok;
}
}
File PluginScanner::scannerExeFile() const noexcept { return _scannerExe; }
void PluginScanner::scanAudioFormat (const String& formatName)
{
detail::applyBlacklistingsFromDeadMansPedal (list);
auto paths = _manager.props != nullptr
? detail::readSearchPath (*_manager.props, formatName)
: FileSearchPath();
StringArray identifiers;
std::function<String (const String&)> pluginName = [] (const String& ID) -> juce::String { return ID; };
if (auto* format = _manager.getAudioPluginFormat (formatName))
{
pluginName = [format] (const String& ID) {
return format->getNameOfPluginFromIdentifier (ID);
};
if (paths.getNumPaths() <= 0)
paths = format->getDefaultLocationsToSearch();
identifiers = format->searchPathsForPlugins (paths, true, false);
}
else if (auto* provider = _manager.getProvider (formatName))
{
if (paths.getNumPaths() <= 0)
paths = provider->defaultSearchPath();
identifiers = provider->findTypes (paths, true, false);
}
notifyOnMessageThread ([] (PluginScanner& s) {
s.listeners.call (&Listener::audioPluginScanProgress, 0.0f);
});
const auto total = static_cast<float> (identifiers.size());
for (int i = 0; i < identifiers.size(); ++i)
{
const auto& ID = identifiers.getReference (i);
const auto reportProgress = [this, i, total]() {
const float progress = static_cast<float> (i + 1) / total;
notifyOnMessageThread ([progress] (PluginScanner& s) {
s.listeners.call (&Listener::audioPluginScanProgress, progress);
});
};
if (shouldAbort())
return;
notifyOnMessageThread ([name = pluginName (ID)] (PluginScanner& s) {
s.listeners.call (&Listener::audioPluginScanStarted, name);
});
if (list.getTypeForFile (ID) || list.getBlacklistedFiles().contains (ID))
{
reportProgress();
continue;
}
OwnedArray<PluginDescription> descriptions;
// Add to the dead-man's-pedal before scanning so the entry survives
// if this plugin takes down the whole application.
auto crashed = detail::readDeadMansPedalFile();
crashed.removeString (ID);
crashed.add (ID);
detail::setDeadMansPedalFile (crashed);
const auto removeFromPedal = [&crashed, &ID]() {
crashed.removeString (ID);
detail::setDeadMansPedalFile (crashed);
};
switch (retrieveDescriptions (formatName, ID, descriptions))
{
case ScanResult::ok:
consecutiveFailures = 0;
for (auto* desc : descriptions)
list.addType (*desc);
// Managed to load without crashing, so remove it from the dead-man's-pedal..
removeFromPedal();
if (descriptions.size() == 0 && ! list.getBlacklistedFiles().contains (ID))
failedIdentifiers.add (ID);
break;
case ScanResult::crashed:
// Leave the ID on the dead-man's-pedal so it gets blacklisted.
consecutiveFailures = 0;
if (! list.getBlacklistedFiles().contains (ID))
failedIdentifiers.add (ID);
break;
case ScanResult::unavailable:
// The scanner process itself failed. Not the plugin's fault:
// never blacklist it.
removeFromPedal();
if (++consecutiveFailures >= maxConsecutiveFailures)
{
abortedByFailure = true;
{
ScopedLock sl (stateLock);
lastScanError = TRANS ("Plugin scanning stopped early because the "
"scanner process could not be started or "
"kept failing.");
}
return;
}
break;
case ScanResult::cancelled:
removeFromPedal();
return;
}
reportProgress();
}
}
void PluginScanner::scanForAudioPlugins (const juce::String& formatName)
{
const juce::StringArray identifiers { formatName };
scanForAudioPlugins (identifiers);
}
void PluginScanner::scanForAudioPlugins (const StringArray& formats)
{
if (isThreadRunning() || scanning.load())
return;
formatsToScan = formats;
cancelFlag = 0;
abortedByFailure = false;
consecutiveFailures = 0;
failedIdentifiers.clearQuick();
{
ScopedLock sl (stateLock);
lastScanError.clear();
}
// Set before startThread so isScanning() is true immediately.
scanning = true;
startThread();
}
void PluginScanner::run()
{
if (scannerExeFile().existsAsFile())
{
detail::setDeadMansPedalFile ({});
for (const auto& format : formatsToScan)
{
scanAudioFormat (format);
if (shouldAbort() || abortedByFailure)
break;
}
resetWorker (true);
auto crashed = detail::readDeadMansPedalFile();
for (const auto& c : failedIdentifiers)
crashed.add (c);
crashed.removeDuplicates (false);
crashed.removeEmptyStrings();
detail::setDeadMansPedalFile (crashed);
detail::applyBlacklistingsFromDeadMansPedal (list);
detail::setDeadMansPedalFile ({});
}
else
{
ScopedLock sl (stateLock);
lastScanError = TRANS ("The plugin scanner executable is missing.");
}
cancelFlag = 0;
scanning = false;
notifyOnMessageThread ([] (PluginScanner& s) {
s.listeners.call (&Listener::audioPluginScanFinished);
});
}
//==============================================================================
using UnverifiedPluginMap = HashMap<String, StringArray>;
using UnverifiedPluginPaths = HashMap<String, FileSearchPath>;
class UnverifiedPlugins : private Thread
{
public:
UnverifiedPlugins() : Thread ("euvpl") {}
~UnverifiedPlugins()
{
cancelFlag.set (1);
if (isThreadRunning())
stopThread (1000);
}
void searchForPlugins (PropertiesFile* props)
{
if (isThreadRunning())
return;
if (props)
{
for (const auto& f : Util::compiledAudioPluginFormats())
{
const auto key = String (Settings::lastPluginScanPathPrefix) + f;
paths.set (f, FileSearchPath (props->getValue (key)));
}
}
else
{
paths.clear();
}
startThread (Thread::Priority::background);
}
void getPlugins (OwnedArray<PluginDescription>& plugs,
const String& format,
KnownPluginList& list)
{
ScopedLock sl (lock);
if (plugins.contains (format))
{
const auto types = list.getTypes();
for (const auto& file : plugins.getReference (format))
{
bool known = nullptr != list.getTypeForFile (file);
// Provider formats (e.g. CLAP) store types as "pluginID:filePath".
for (int i = types.size(); --i >= 0 && ! known;)
{
const auto& d = types.getReference (i);
known = d.pluginFormatName == format
&& d.fileOrIdentifier.fromFirstOccurrenceOf (":", false, false) == file;
}
if (known)
continue;
auto* const desc = plugs.add (new PluginDescription());
desc->pluginFormatName = format;
desc->fileOrIdentifier = file;
}
}
}
private:
friend class Thread;
CriticalSection lock;
UnverifiedPluginMap plugins;
UnverifiedPluginPaths paths;
struct Item
{
String name;
String identifier;
};
Atomic<int> cancelFlag;
void run() override
{
cancelFlag.set (0);
PluginManager pluginManager;
pluginManager.getNodeFactory().add (new CLAPProvider());
pluginManager.addDefaultFormats();
auto& manager (pluginManager.getAudioPluginFormats());
// JUCE Formats.
for (int i = 0; i < manager.getNumFormats(); ++i)
{
if (threadShouldExit() || cancelFlag.get() != 0)
break;
auto* const format = manager.getFormat (i);
FileSearchPath path = paths[format->getName()];
path.addPath (format->getDefaultLocationsToSearch());
const auto found = format->searchPathsForPlugins (path, true, false);
ScopedLock sl (lock);
plugins.set (format->getName(), found);
}
// Element Node Providers
auto& factory = pluginManager.getNodeFactory();
for (auto* const provider : factory.providers())
{
if (threadShouldExit() || cancelFlag.get() != 0)
break;
const auto formatName = provider->format();
FileSearchPath path = paths[formatName];
path.addPath (provider->defaultSearchPath());
// Providers with no search path (e.g. internal nodes) aren't file-based.
if (path.getNumPaths() <= 0)
continue;
const auto found = provider->findTypes (path, true, false);
ScopedLock sl (lock);
plugins.set (formatName, found);
}
cancelFlag.set (0);
}
};
//==============================================================================
class PluginManager::Private : public PluginScanner::Listener
{
public:
Private (PluginManager& o)
: owner (o)
{
deadAudioPlugins = DataPath::applicationDataDir().getChildFile (EL_DEAD_AUDIO_PLUGINS_FILENAME);
}
~Private() {}
/** returns true if anything changed in the plugin list */
bool updateBlacklistedAudioPlugins()
{
bool didSomething = false;