plugexporttest.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. // plugexporttest <plugin.vst3 | plugin.clap | plugin.lv2 (Linux, rounds 190ov and 190pk)> <report.txt> [editor picture prefix]
  2. // Loads LYNX's exported plugins the way a host does (round 180b, docs/PLUGIN_EXPORT.md) and checks, with no window on screen:
  3. // the scan, the sound against the same engine run directly in this process (null test), automation, the state (a new
  4. // instance sounds the same; the state opens as a .lynx project), the editor, memory per instance and CPU.
  5. // Exit 0 = every check passed.
  6. #include <atomic>
  7. #include <cmath>
  8. #include <cstdio>
  9. #include <cstring>
  10. #include <juce_audio_processors/juce_audio_processors.h>
  11. #include <juce_gui_basics/juce_gui_basics.h>
  12. #include <clap/clap.h>
  13. #include "core/Effects.h"
  14. #include "core/LynxBanks.h"
  15. #include "core/ModelParams.h"
  16. #include "core/RackRenderer.h"
  17. #include "engine/ClapFormat.h"
  18. #include "engine/ProjectFile.h"
  19. #include "plugin/ExportProcessor.h"
  20. #if JUCE_WINDOWS
  21. #include <windows.h>
  22. #include <psapi.h>
  23. #endif
  24. using namespace lynx;
  25. using lynx::plugexport::Entry;
  26. namespace
  27. {
  28. constexpr double rate = 48000.0;
  29. constexpr int block = 512, blocks = 200;
  30. juce::String report;
  31. int failures = 0;
  32. void check (bool ok, const juce::String& what)
  33. {
  34. report << (ok ? "PASS " : "FAIL ") << what << "\n";
  35. failures += ok ? 0 : 1;
  36. }
  37. double memoryMb()
  38. {
  39. #if JUCE_WINDOWS
  40. PROCESS_MEMORY_COUNTERS c {};
  41. GetProcessMemoryInfo (GetCurrentProcess(), &c, sizeof (c));
  42. return (double) c.WorkingSetSize / 1048576.0;
  43. #else
  44. const auto fields = juce::StringArray::fromTokens (juce::File ("/proc/self/statm").loadFileAsString(), " ", "");
  45. return fields[1].getDoubleValue() * 4096.0 / 1048576.0;
  46. #endif
  47. }
  48. struct Audio
  49. {
  50. std::vector<float> l, r;
  51. double peak() const
  52. {
  53. double p = 0.0;
  54. for (auto v : l) p = std::max (p, (double) std::abs (v));
  55. for (auto v : r) p = std::max (p, (double) std::abs (v));
  56. return p;
  57. }
  58. // the first sample where the two differ by more than `tolerance` (-1 = none)
  59. long firstDifference (const Audio& o, double tolerance = 1.0e-5) const
  60. {
  61. for (std::size_t i = 0; i < std::min (l.size(), o.l.size()); ++i)
  62. if (std::abs (l[i] - o.l[i]) > tolerance || std::abs (r[i] - o.r[i]) > tolerance)
  63. return (long) i;
  64. return -1;
  65. }
  66. // round 190sh: FNV-1a over the samples' bits, so two builds of the plugins can be compared render for render (the
  67. // report's "fingerprint" lines: the same plugin file renders the same bytes run after run)
  68. juce::String fingerprint() const
  69. {
  70. std::uint64_t h = 1469598103934665603ull;
  71. for (const auto* channel : { &l, &r })
  72. for (const auto v : *channel)
  73. {
  74. std::uint32_t bits;
  75. std::memcpy (&bits, &v, sizeof bits);
  76. for (int b = 0; b < 4; ++b)
  77. h = (h ^ ((bits >> (8 * b)) & 0xffu)) * 1099511628211ull;
  78. }
  79. return juce::String::toHexString ((juce::int64) h).paddedLeft ('0', 16);
  80. }
  81. double difference (const Audio& o) const
  82. {
  83. double p = l.size() == o.l.size() ? 0.0 : 1e9;
  84. for (std::size_t i = 0; i < std::min (l.size(), o.l.size()); ++i)
  85. p = std::max ({ p, (double) std::abs (l[i] - o.l[i]), (double) std::abs (r[i] - o.r[i]) });
  86. return p;
  87. }
  88. };
  89. // test input: a decaying noise / sine mix (deterministic)
  90. void fillInput (float* l, float* r, int n, int start)
  91. {
  92. Noise noise;
  93. noise.state = 0x1234567u + (std::uint32_t) start;
  94. for (int i = 0; i < n; ++i)
  95. {
  96. const auto t = (double) (start + i) / rate;
  97. const auto v = 0.2f * (float) std::sin (2.0 * juce::MathConstants<double>::pi * 440.0 * t) + 0.1f * noise.next();
  98. l[i] = v;
  99. r[i] = 0.7f * v;
  100. }
  101. }
  102. juce::MidiBuffer notesFor (int b)
  103. {
  104. juce::MidiBuffer m;
  105. if (b == 2) m.addEvent (juce::MidiMessage::noteOn (1, 60, 0.8f), 100);
  106. if (b == 2) m.addEvent (juce::MidiMessage::noteOn (1, 67, 0.6f), 300);
  107. if (b == 100) m.addEvent (juce::MidiMessage::noteOff (1, 60), 50);
  108. if (b == 100) m.addEvent (juce::MidiMessage::noteOff (1, 67), 50);
  109. return m;
  110. }
  111. Audio render (juce::AudioProcessor& p, bool instrument, double* seconds = nullptr)
  112. {
  113. Audio out;
  114. p.setPlayConfigDetails (instrument ? 0 : 2, 2, rate, block);
  115. p.prepareToPlay (rate, block);
  116. juce::AudioBuffer<float> buffer (2, block);
  117. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  118. for (int b = 0; b < blocks; ++b)
  119. {
  120. buffer.clear();
  121. if (! instrument)
  122. fillInput (buffer.getWritePointer (0), buffer.getWritePointer (1), block, b * block);
  123. auto midi = instrument ? notesFor (b) : juce::MidiBuffer();
  124. p.processBlock (buffer, midi);
  125. out.l.insert (out.l.end(), buffer.getReadPointer (0), buffer.getReadPointer (0) + block);
  126. out.r.insert (out.r.end(), buffer.getReadPointer (1), buffer.getReadPointer (1) + block);
  127. }
  128. if (seconds != nullptr)
  129. *seconds = (juce::Time::getMillisecondCounterHiRes() - t0) / 1000.0;
  130. p.releaseResources();
  131. return out;
  132. }
  133. // Round 188b: an effect with its side-chain bus switched on (stereo), the side fed with `side` × a square wave; the main
  134. // input as in render(). Empty: the host couldn't switch the bus on.
  135. Audio renderWithSide (juce::AudioProcessor& p, float side)
  136. {
  137. Audio out;
  138. auto layout = p.getBusesLayout();
  139. if (layout.inputBuses.size() < 2)
  140. return out;
  141. layout.inputBuses.getReference (1) = juce::AudioChannelSet::stereo();
  142. if (! p.setBusesLayout (layout))
  143. return out;
  144. p.setRateAndBufferSizeDetails (rate, block);
  145. p.prepareToPlay (rate, block);
  146. const auto channels = juce::jmax (p.getTotalNumInputChannels(), p.getTotalNumOutputChannels());
  147. juce::AudioBuffer<float> buffer (channels, block);
  148. for (int b = 0; b < blocks; ++b)
  149. {
  150. buffer.clear();
  151. fillInput (buffer.getWritePointer (0), buffer.getWritePointer (1), block, b * block);
  152. for (int c = 2; c < juce::jmin (4, channels); ++c)
  153. for (int i = 0; i < block; ++i)
  154. buffer.setSample (c, i, side * (i % 64 < 32 ? 1.0f : -1.0f));
  155. juce::MidiBuffer midi;
  156. p.processBlock (buffer, midi);
  157. out.l.insert (out.l.end(), buffer.getReadPointer (0), buffer.getReadPointer (0) + block);
  158. out.r.insert (out.r.end(), buffer.getReadPointer (1), buffer.getReadPointer (1) + block);
  159. }
  160. p.releaseResources();
  161. // (back to the main buses only, as render() expects)
  162. layout.inputBuses.getReference (1) = juce::AudioChannelSet::disabled();
  163. p.setBusesLayout (layout);
  164. return out;
  165. }
  166. // The same engine with no plugin between: the effect itself / a rack with the channel
  167. Audio directEffect (EffectKind kind, const EffectParams& params)
  168. {
  169. const juce::ScopedNoDenormals noDenormals; // (as the plugin's processBlock: denormals flushed)
  170. Audio out;
  171. auto effect = makeEffect (kind);
  172. effect->prepare (rate);
  173. std::vector<float> l ((std::size_t) block), r ((std::size_t) block);
  174. for (int b = 0; b < blocks; ++b)
  175. {
  176. fillInput (l.data(), r.data(), block, b * block);
  177. effect->setSongPosition (0.0);
  178. effect->setPlaying (false);
  179. effect->process (l.data(), r.data(), block, params, 120.0);
  180. out.l.insert (out.l.end(), l.begin(), l.end());
  181. out.r.insert (out.r.end(), r.begin(), r.end());
  182. }
  183. return out;
  184. }
  185. Audio directInstrument (const Entry& entry)
  186. {
  187. Audio out;
  188. auto song = Song::makeDefault();
  189. song.channels.clear();
  190. song.mixer.resize (2);
  191. song.mixer[0].effects.clear();
  192. song.mixer[1].effects.clear();
  193. // the plugin's own starting channel (round 190pq): Tetra and Braid have no preset bank, and dereferencing the empty
  194. // banks::defaultChannel copied a ChannelDef from garbage (CI plugins run 44975814572: std::length_error in the CLAP)
  195. auto channel = plugexport::instrumentChannel (entry);
  196. channel.mixerTrack = 0;
  197. song.channels.push_back (std::move (channel));
  198. auto state = RackState::build (song, nullptr, rate);
  199. auto renderer = std::make_unique<RackRenderer>();
  200. renderer->prepare (rate, block);
  201. LiveEventQueue queue;
  202. std::vector<float> l ((std::size_t) block), r ((std::size_t) block);
  203. for (int b = 0; b < blocks; ++b)
  204. {
  205. auto done = 0;
  206. const auto upTo = [&] (int end) {
  207. if (end > done)
  208. renderer->process (state.get(), false, 0.0, end - done, l.data() + done, r.data() + done, &queue);
  209. done = std::max (done, end);
  210. };
  211. for (const auto m : notesFor (b))
  212. {
  213. upTo (m.samplePosition);
  214. const auto message = m.getMessage();
  215. NoteEvent e;
  216. e.channel = 0;
  217. e.key = message.getNoteNumber();
  218. e.type = message.isNoteOn() ? NoteEvent::Type::on : NoteEvent::Type::off;
  219. e.velocity = message.isNoteOn() ? message.getFloatVelocity() : 0.0f;
  220. queue.push (e);
  221. }
  222. upTo (block);
  223. out.l.insert (out.l.end(), l.begin(), l.end());
  224. out.r.insert (out.r.end(), r.begin(), r.end());
  225. }
  226. return out;
  227. }
  228. void writeEditorPicture (const Entry& entry, const juce::String& prefix)
  229. {
  230. std::unique_ptr<juce::AudioProcessor> p (plugexport::makeProcessor (entry));
  231. {
  232. juce::MemoryBlock state; // (in-process: a VST3 host sees it inside JUCE's own chunk)
  233. p->getStateInformation (state);
  234. juce::String parseError;
  235. check (ProjectFile::fromJson (juce::String::createStringFromData (state.getData(), (int) state.getSize()), parseError).has_value(),
  236. "the state opens as a .lynx project " + parseError);
  237. }
  238. const auto before = memoryMb();
  239. std::unique_ptr<juce::AudioProcessorEditor> editor (p->createEditorIfNeeded());
  240. check (editor != nullptr && editor->getWidth() > 100 && editor->getHeight() > 50,
  241. juce::String ("in-process editor of ") + entry.name + " " + juce::String (editor != nullptr ? editor->getWidth() : 0) + "x" + juce::String (editor != nullptr ? editor->getHeight() : 0));
  242. report << " editor open adds " << juce::String (memoryMb() - before, 1) << " MB\n";
  243. if (editor == nullptr)
  244. return;
  245. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  246. {
  247. juce::Graphics g (image);
  248. editor->paintEntireComponent (g, false);
  249. }
  250. const juce::File file (prefix + juce::String (entry.name).removeCharacters (" ") + ".png");
  251. file.deleteFile();
  252. juce::PNGImageFormat png;
  253. if (auto stream = file.createOutputStream())
  254. png.writeImageToStream (image, *stream);
  255. p->editorBeingDeleted (editor.get());
  256. editor.reset();
  257. }
  258. } // namespace
  259. #if JUCE_MAC
  260. #include <CoreFoundation/CoreFoundation.h>
  261. #else
  262. namespace juce::detail { bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages); } // (juce_events' native code)
  263. #endif
  264. namespace
  265. {
  266. // Lets the message loop (and a CLAP plugin's timer) run for a while
  267. void pump (int ms, const std::function<void()>& tick = {})
  268. {
  269. const auto end = juce::Time::getMillisecondCounter() + (juce::uint32) ms;
  270. while (juce::Time::getMillisecondCounter() < end)
  271. {
  272. #if JUCE_MAC
  273. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.005, false); // (JUCE's messages come through the main run loop)
  274. #else
  275. while (juce::detail::dispatchNextMessageOnSystemQueue (true)) {}
  276. juce::Thread::sleep (5);
  277. #endif
  278. if (tick)
  279. tick();
  280. }
  281. }
  282. // Counts what a host would take as an edit: parameter changes coming from the plugin
  283. struct EditCounter final : juce::AudioProcessorParameter::Listener
  284. {
  285. std::atomic<int> changes { 0 };
  286. void parameterValueChanged (int, float) override { ++changes; }
  287. void parameterGestureChanged (int, bool) override { ++changes; }
  288. };
  289. // A loaded state (a project being opened) is not an edit: the host must get no parameter changes from it, at once or
  290. // later from the editor's sync (round 180b: FL Studio asked to save a project it had only opened)
  291. void stateLoadIsSilent (juce::AudioPluginFormat& format, const juce::PluginDescription& description, const juce::MemoryBlock& state)
  292. {
  293. juce::String error;
  294. auto third = format.createInstanceFromDescription (description, rate, block, error);
  295. if (third == nullptr)
  296. return;
  297. third->prepareToPlay (rate, block);
  298. EditCounter counter;
  299. for (auto* p : third->getParameters())
  300. p->addListener (&counter);
  301. third->setStateInformation (state.getData(), (int) state.getSize());
  302. // (JUCE's VST3 host re-reads every value inside setStateInformation and tells its own listeners: that is the host
  303. // updating its view, not an edit from the plugin, whose wrapper sends none while a state loads; what comes later is)
  304. report << " host refreshed " << counter.changes.exchange (0) << " values inside the state load\n";
  305. pump (300);
  306. const auto afterLoad = counter.changes.load();
  307. std::unique_ptr<juce::AudioProcessorEditor> editor (third->createEditorIfNeeded());
  308. pump (600);
  309. const auto withEditor = counter.changes.load() - afterLoad;
  310. editor.reset();
  311. for (auto* p : third->getParameters())
  312. p->removeListener (&counter);
  313. check (afterLoad == 0 && withEditor == 0, "a loaded state sends the host no edits: " + juce::String (afterLoad)
  314. + " at load, " + juce::String (withEditor) + " with the editor open");
  315. }
  316. // The same for the CLAP, with a host of our own that sees what LYNX's CLAP host ignores: parameter events the plugin
  317. // sends out and host_state.mark_dirty ("project modified")
  318. struct RawClapHost
  319. {
  320. static inline std::atomic<int> dirty { 0 }, flushes { 0 };
  321. static inline clap_id timer = CLAP_INVALID_ID;
  322. clap_host_t host {};
  323. clap_host_params_t params { [] (const clap_host_t*, clap_param_rescan_flags) {}, [] (const clap_host_t*, clap_id, clap_param_clear_flags) {},
  324. [] (const clap_host_t*) { ++flushes; } };
  325. clap_host_state_t state { [] (const clap_host_t*) { ++dirty; } };
  326. clap_host_latency_t latency { [] (const clap_host_t*) {} };
  327. clap_host_timer_support_t timers { [] (const clap_host_t*, uint32_t, clap_id* id) { *id = timer = 1; return true; },
  328. [] (const clap_host_t*, clap_id) { timer = CLAP_INVALID_ID; return true; } };
  329. RawClapHost()
  330. {
  331. host.clap_version = CLAP_VERSION;
  332. host.host_data = this;
  333. host.name = "plugexporttest";
  334. host.vendor = "LYNX";
  335. host.url = "";
  336. host.version = "1";
  337. host.get_extension = [] (const clap_host_t* h, const char* id) -> const void* {
  338. auto* self = static_cast<RawClapHost*> (h->host_data);
  339. if (std::strcmp (id, CLAP_EXT_PARAMS) == 0) return &self->params;
  340. if (std::strcmp (id, CLAP_EXT_STATE) == 0) return &self->state;
  341. if (std::strcmp (id, CLAP_EXT_LATENCY) == 0) return &self->latency;
  342. if (std::strcmp (id, CLAP_EXT_TIMER_SUPPORT) == 0) return &self->timers;
  343. return nullptr;
  344. };
  345. host.request_restart = [] (const clap_host_t*) {};
  346. host.request_process = [] (const clap_host_t*) {};
  347. host.request_callback = [] (const clap_host_t*) {};
  348. }
  349. };
  350. void clapStateLoadIsSilent (const juce::File& file, const Entry& entry)
  351. {
  352. std::fprintf (stderr, "plugexporttest: CLAP state in a plain host: %s\n", entry.name); // (the report is written at the end; this says where a crash was)
  353. std::fflush (stderr);
  354. // a state with moved parameters, from the same engine in this process
  355. std::unique_ptr<juce::AudioProcessor> source (plugexport::makeProcessor (entry));
  356. for (auto* p : source->getParameters())
  357. p->setValueNotifyingHost (std::fmod (p->getDefaultValue() + 0.37f, 1.0f));
  358. juce::MemoryBlock saved;
  359. source->getStateInformation (saved);
  360. juce::DynamicLibrary library;
  361. auto binary = file; // (macOS: the executable inside the .clap bundle; clap_entry.init still gets the bundle)
  362. if (file.isDirectory())
  363. if (const auto inside = file.getChildFile ("Contents/MacOS").getChildFile (file.getFileNameWithoutExtension()); inside.existsAsFile())
  364. binary = inside;
  365. if (! library.open (binary.getFullPathName()))
  366. return check (false, "CLAP opens in a plain host");
  367. const auto* clapEntry = static_cast<const clap_plugin_entry_t*> (library.getFunction ("clap_entry"));
  368. if (clapEntry == nullptr || ! clapEntry->init (file.getFullPathName().toRawUTF8()))
  369. return check (false, "CLAP entry in a plain host");
  370. {
  371. RawClapHost host;
  372. const auto* factory = static_cast<const clap_plugin_factory_t*> (clapEntry->get_factory (CLAP_PLUGIN_FACTORY_ID));
  373. const auto* plugin = factory != nullptr ? factory->create_plugin (factory, &host.host, entry.clapId) : nullptr;
  374. if (plugin == nullptr || ! plugin->init (plugin))
  375. check (false, "CLAP instance in a plain host");
  376. else
  377. {
  378. const auto* state = static_cast<const clap_plugin_state_t*> (plugin->get_extension (plugin, CLAP_EXT_STATE));
  379. const auto* params = static_cast<const clap_plugin_params_t*> (plugin->get_extension (plugin, CLAP_EXT_PARAMS));
  380. const auto* gui = static_cast<const clap_plugin_gui_t*> (plugin->get_extension (plugin, CLAP_EXT_GUI));
  381. const auto* timer = static_cast<const clap_plugin_timer_support_t*> (plugin->get_extension (plugin, CLAP_EXT_TIMER_SUPPORT));
  382. int sentOut = 0;
  383. clap_input_events_t none { nullptr, [] (const clap_input_events_t*) -> uint32_t { return 0; },
  384. [] (const clap_input_events_t*, uint32_t) -> const clap_event_header_t* { return nullptr; } };
  385. clap_output_events_t out { &sentOut, [] (const clap_output_events_t* o, const clap_event_header_t*) { ++*static_cast<int*> (o->ctx); return true; } };
  386. auto tick = [&] {
  387. if (timer != nullptr && RawClapHost::timer != CLAP_INVALID_ID)
  388. timer->on_timer (plugin, RawClapHost::timer);
  389. if (params != nullptr)
  390. params->flush (plugin, &none, &out);
  391. };
  392. struct Reader { const juce::MemoryBlock* data; std::size_t at = 0; } reader { &saved };
  393. clap_istream_t in { &reader, [] (const clap_istream_t* s, void* buffer, uint64_t size) -> int64_t {
  394. auto* r = static_cast<Reader*> (s->ctx);
  395. const auto n = std::min<std::size_t> ((std::size_t) size, r->data->getSize() - r->at);
  396. std::memcpy (buffer, static_cast<const char*> (r->data->getData()) + r->at, n);
  397. r->at += n;
  398. return (int64_t) n;
  399. } };
  400. RawClapHost::dirty = 0;
  401. const auto loaded = state != nullptr && state->load (plugin, &in);
  402. check (loaded, "CLAP state loads in a plain host");
  403. pump (300, tick);
  404. const auto atLoad = RawClapHost::dirty.load() + sentOut;
  405. int withEditor = 0;
  406. #if JUCE_WINDOWS
  407. const char* api = CLAP_WINDOW_API_WIN32;
  408. #else
  409. const char* api = CLAP_WINDOW_API_X11;
  410. #endif
  411. if (gui != nullptr && gui->create (plugin, api, false))
  412. {
  413. const auto before = RawClapHost::dirty.load() + sentOut;
  414. pump (600, tick);
  415. withEditor = RawClapHost::dirty.load() + sentOut - before;
  416. gui->destroy (plugin);
  417. }
  418. check (atLoad == 0 && withEditor == 0, "a loaded CLAP state marks nothing dirty and sends no parameter events: "
  419. + juce::String (atLoad) + " at load, " + juce::String (withEditor) + " with the editor open");
  420. plugin->destroy (plugin);
  421. }
  422. }
  423. clapEntry->deinit();
  424. }
  425. const Entry* entryNamed (const juce::String& name)
  426. {
  427. for (const auto& e : plugexport::catalog)
  428. if (name == e.name)
  429. return &e;
  430. return nullptr;
  431. }
  432. void testPlugin (juce::AudioPluginFormat& format, const juce::PluginDescription& description, const juce::String& picturePrefix)
  433. {
  434. std::fprintf (stderr, "plugexporttest: %s (%s)\n", description.name.toRawUTF8(), format.getName().toRawUTF8());
  435. std::fflush (stderr);
  436. const auto* entry = entryNamed (description.name);
  437. check (entry != nullptr, "known name: " + description.name);
  438. if (entry == nullptr)
  439. return;
  440. report << "--- " << description.name << " (" << format.getName() << ", " << (description.isInstrument ? "instrument" : "effect") << ")\n";
  441. check (description.isInstrument == entry->instrument, "scan says instrument or effect correctly");
  442. juce::String error;
  443. const auto base = memoryMb();
  444. auto make = [&] { return format.createInstanceFromDescription (description, rate, block, error); };
  445. auto instance = make();
  446. check (instance != nullptr, "instance " + error);
  447. if (instance == nullptr)
  448. return;
  449. report << " first instance: +" << juce::String (memoryMb() - base, 1) << " MB\n";
  450. // the effect engine's parameter i in the host's list. JUCE's LV2 host lists the plugin's lv2:Parameter properties in
  451. // an order of its own and adds the lv2:enabled port as "Bypass": there it is the one whose id ends in ":p<i>" (the
  452. // plugin's parameter id, round 190pk); the VST3 and CLAP hosts keep the plugin's order
  453. const auto lv2 = format.getName() == "LV2";
  454. auto engineParameter = [&] (int i) -> juce::AudioProcessorParameter*
  455. {
  456. const auto& all = instance->getParameters();
  457. if (lv2)
  458. {
  459. for (auto* p : all)
  460. if (auto* hosted = dynamic_cast<juce::HostedAudioProcessorParameter*> (p))
  461. if (hosted->getParameterID().endsWith (":p" + juce::String (i)))
  462. return p;
  463. return nullptr;
  464. }
  465. return juce::isPositiveAndBelow (i, all.size()) ? all[i] : nullptr;
  466. };
  467. check (instance->getParameters().size() > 0, "parameters: " + juce::String (instance->getParameters().size()));
  468. double seconds = 0.0;
  469. const auto sound = render (*instance, entry->instrument, &seconds);
  470. report << " " << blocks << " blocks of " << block << ": " << juce::String (100.0 * seconds / (blocks * block / rate), 2) << " % of real time\n";
  471. check (sound.peak() > 1.0e-3, "makes sound, peak " + juce::String (sound.peak(), 4));
  472. report << " fingerprint defaults " << sound.fingerprint() << "\n";
  473. auto direct = entry->instrument ? directInstrument (*entry) : directEffect (entry->effect, makeEffectSlot (entry->effect).params);
  474. const auto nulled = sound.difference (direct);
  475. check (nulled < 1.0e-5, "null test at the defaults: peak difference " + juce::String (nulled, 8));
  476. // round 188b: the side-chain bus. Switched on and silent, nothing changes (at the defaults no effect listens to it)
  477. if (! entry->instrument)
  478. {
  479. const auto withSide = renderWithSide (*instance, 0.0f);
  480. if (withSide.l.empty())
  481. report << " side-chain bus: this host can't switch it on\n";
  482. else
  483. check (withSide.difference (sound) < 1.0e-5, "side-chain bus on and silent: peak difference " + juce::String (withSide.difference (sound), 8));
  484. if (entry->effect == EffectKind::crestCompressor && ! withSide.l.empty())
  485. {
  486. // its external side chain on: a loud side signal compresses the main input
  487. const auto& names = effectInfo (entry->effect).params;
  488. for (int i = 0; i < (int) names.size(); ++i)
  489. if (auto* p = engineParameter (i); p != nullptr && juce::String::fromUTF8 (names[(std::size_t) i].name) == "External SC")
  490. p->setValue (1.0f);
  491. const auto quiet = renderWithSide (*instance, 0.0f), loud = renderWithSide (*instance, 0.9f);
  492. const auto energy = [] (const Audio& a) { double e = 0.0; for (auto v : a.l) e += (double) v * v; return e; };
  493. check (energy (loud) < 0.7 * energy (quiet), "external side chain through the bus compresses: " + juce::String (energy (loud) / juce::jmax (1.0e-12, energy (quiet)), 3));
  494. for (int i = 0; i < (int) names.size(); ++i)
  495. if (auto* p = engineParameter (i); p != nullptr && juce::String::fromUTF8 (names[(std::size_t) i].name) == "External SC")
  496. p->setValue (0.0f);
  497. }
  498. }
  499. auto& parameters = instance->getParameters();
  500. if (! entry->instrument)
  501. {
  502. // every named parameter moved through the host, against the same values on the engine run directly. Facet EQ's
  503. // defaults are flat (its output is its input), so this is the null test that says something.
  504. auto params = makeEffectSlot (entry->effect).params;
  505. const auto named = (int) effectInfo (entry->effect).params.size();
  506. int found = 0;
  507. for (int i = 0; i < named; ++i)
  508. if (auto* p = engineParameter (i))
  509. {
  510. const auto v = 0.5f + 0.45f * (float) std::sin ((double) i * 0.7);
  511. p->setValue (v);
  512. params[(std::size_t) i] = p->getValue();
  513. ++found;
  514. }
  515. check (found == juce::jmin (named, parameters.size()), "the host lists the engine's parameters: " + juce::String (found) + " of " + juce::String (named));
  516. const auto wet = render (*instance, false);
  517. report << " fingerprint moved " << wet.fingerprint() << "\n";
  518. const auto d = wet.difference (direct = directEffect (entry->effect, params));
  519. check (d < 1.0e-5, "null test with " + juce::String (named) + " parameters moved by the host: peak difference " + juce::String (d, 8)
  520. + (d < 1.0e-5 ? juce::String() : ", first at sample " + juce::String (wet.firstDifference (direct))));
  521. check (wet.difference (sound) > 1.0e-3, "those settings change the sound, difference " + juce::String (wet.difference (sound), 5));
  522. }
  523. else
  524. {
  525. // the engine's first continuous parameter after its first one (VST3 / CLAP: the host's parameter 1, as before). JUCE's
  526. // LV2 host lists them in an order of its own: there it is found by its id (round 190pq: its parameter 1 was Fourfold's
  527. // stepped "A On" switch, which a move of 0.3 leaves as it was)
  528. juce::AudioProcessorParameter* moved = nullptr;
  529. if (const auto* table = modelparams::tableOf (entry->synth); table != nullptr && table->params != nullptr)
  530. for (std::size_t k = 1; moved == nullptr && k < table->params->size(); ++k)
  531. if (const auto& e = (*table->params)[k]; ! (e.stepped && e.high > e.low && e.high - e.low <= 4096.0f)) // (the plugin's rule for a discrete parameter)
  532. moved = lv2 ? engineParameter (e.index) : engineParameter ((int) k);
  533. check (moved != nullptr, "the host lists a continuous parameter of the engine");
  534. if (moved != nullptr)
  535. {
  536. const auto was = moved->getValue();
  537. moved->setValue (was < 0.5f ? was + 0.3f : was - 0.3f);
  538. report << " moved '" << moved->getName (64) << "' " << was << " -> " << moved->getValue() << "\n";
  539. const auto changed = render (*instance, true);
  540. report << " fingerprint moved " << changed.fingerprint() << "\n";
  541. check (changed.difference (sound) > 1.0e-3, "the moved parameter changes the sound, difference " + juce::String (changed.difference (sound), 5));
  542. }
  543. }
  544. // state: a new instance of what we just heard sounds the same
  545. juce::MemoryBlock state;
  546. instance->getStateInformation (state);
  547. report << " state: " << (int) state.getSize() << " bytes\n";
  548. auto second = make();
  549. check (second != nullptr, "second instance");
  550. if (second != nullptr)
  551. {
  552. second->setStateInformation (state.getData(), (int) state.getSize());
  553. const auto first = render (*instance, entry->instrument), restored = render (*second, entry->instrument);
  554. report << " fingerprint restored " << restored.fingerprint() << "\n";
  555. const auto d = restored.difference (first);
  556. check (d < 1.0e-3, "state restores the sound: peak difference " + juce::String (d, 8)
  557. + (d < 1.0e-3 ? juce::String() : ", first at sample " + juce::String (restored.firstDifference (first, 1.0e-3))));
  558. }
  559. stateLoadIsSilent (format, description, state);
  560. // round 190pq: every parameter moved (as a host's randomizer does), the state loaded into a new instance saves back
  561. // byte for byte (clap-validator's state-reproducibility-binary failed on Fourfold and Wavecoil: values written back
  562. // through their range moved by a float step)
  563. if (auto third = make())
  564. {
  565. for (int i = 0; i < parameters.size(); ++i)
  566. parameters[i]->setValue (0.5f + 0.49f * (float) std::sin ((double) i * 1.37 + 0.3));
  567. juce::MemoryBlock saved, again;
  568. instance->getStateInformation (saved);
  569. third->setStateInformation (saved.getData(), (int) saved.getSize());
  570. third->getStateInformation (again);
  571. auto at = -1;
  572. for (size_t i = 0; at < 0 && i < juce::jmin (again.getSize(), saved.getSize()); ++i)
  573. if (again[i] != saved[i])
  574. at = (int) i;
  575. if (at < 0 && again.getSize() != saved.getSize())
  576. at = (int) juce::jmin (again.getSize(), saved.getSize());
  577. check (at < 0, "a loaded state saves back byte for byte with " + juce::String (parameters.size()) + " parameters moved"
  578. + (at < 0 ? juce::String() : ": " + juce::String ((int) again.getSize()) + " vs " + juce::String ((int) saved.getSize())
  579. + " bytes, first difference at byte " + juce::String (at)));
  580. }
  581. else
  582. check (false, "third instance");
  583. // hosted editor object (never put on the screen)
  584. if (auto* editor = instance->createEditorIfNeeded())
  585. {
  586. check (editor->getWidth() > 100, "hosted editor created, " + juce::String (editor->getWidth()) + "x" + juce::String (editor->getHeight()));
  587. delete editor;
  588. }
  589. else
  590. check (false, "hosted editor created");
  591. const auto oneMore = memoryMb();
  592. std::vector<std::unique_ptr<juce::AudioPluginInstance>> many;
  593. for (int i = 0; i < 8; ++i)
  594. many.push_back (make());
  595. report << " 8 more instances: +" << juce::String ((memoryMb() - oneMore) / 8.0, 1) << " MB each\n";
  596. many.clear();
  597. instance.reset();
  598. if (picturePrefix.isNotEmpty())
  599. writeEditorPicture (*entry, picturePrefix);
  600. }
  601. } // namespace
  602. int main (int argc, char** argv)
  603. {
  604. if (argc < 3)
  605. return 2;
  606. juce::ScopedJuceInitialiser_GUI gui;
  607. const juce::File plugin (juce::String::fromUTF8 (argv[1]));
  608. const juce::String picturePrefix = argc > 3 ? juce::String::fromUTF8 (argv[3]) : juce::String();
  609. juce::VST3PluginFormat vst3;
  610. ClapPluginFormat clap;
  611. juce::AudioPluginFormat* chosen = &vst3;
  612. if (plugin.hasFileExtension ("clap"))
  613. chosen = &clap;
  614. #if JUCE_PLUGINHOST_LV2 && JUCE_LINUX
  615. juce::LV2PluginFormat lv2; // (round 190ov: a bundle folder; JUCE's LV2 host loads it with lilv)
  616. if (plugin.hasFileExtension ("lv2"))
  617. chosen = &lv2;
  618. #endif
  619. juce::AudioPluginFormat& format = *chosen;
  620. juce::OwnedArray<juce::PluginDescription> found;
  621. format.findAllTypesForFile (found, plugin.getFullPathName());
  622. report << "plugin " << plugin.getFileName() << ": " << found.size() << " found\n";
  623. check (found.size() > 0, "scan finds plugins");
  624. for (auto* d : found)
  625. testPlugin (format, *d, picturePrefix);
  626. if (plugin.hasFileExtension ("clap"))
  627. for (auto* d : found)
  628. if (const auto* entry = entryNamed (d->name))
  629. clapStateLoadIsSilent (plugin, *entry);
  630. report << "result=" << (failures == 0 ? "OK" : "FAIL (" + juce::String (failures) + ")") << "\n";
  631. juce::File (juce::String::fromUTF8 (argv[2])).replaceWithText (report);
  632. std::fputs (report.toRawUTF8(), stdout);
  633. return failures == 0 ? 0 : 1;
  634. }